@chainingintention/pi-web-cn 1.202606.10 → 1.202606.11
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-YNyWxbqH.js → CodeViewer-DzeGsHZ5.js} +1 -1
- package/dist/client/assets/{TerminalPanel-B9UStXy9.js → TerminalPanel-BghODb4T.js} +1 -1
- package/dist/client/assets/{index-BH7nkPuT.js → index-DATsMV4H.js} +206 -175
- package/dist/client/index.html +1 -1
- package/dist/server/sessions/piSessionService.js +61 -13
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/sessions/sessionRoutes.js +5 -2
- package/dist/server/sessions/sessionRoutes.js.map +1 -1
- package/dist/shared/apiTypes.d.ts +11 -0
- package/package.json +1 -1
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-
|
|
2
|
-
import{Q as
|
|
3
|
-
\f\r]`,ht=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g
|
|
4
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Po=/'/g,Co=/"/g,Qr=/^(?:script|style|textarea|title)$/i,Xr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Xr(1),st=Xr(2),Fe=Symbol.for("lit-noChange"),_=Symbol.for("lit-nothing"),Io=new WeakMap,He=Ke.createTreeWalker(Ke,129);function Yr(e,t){if(!Es(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return So!==void 0?So.createHTML(t):t}const Ja=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ht;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===ht?u[1]==="!--"?n=ko:u[1]!==void 0?n=$o:u[2]!==void 0?(Qr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Ne):u[3]!==void 0&&(n=Ne):n===Ne?u[0]===">"?(n=o??ht,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Ne:u[3]==='"'?Co:Po):n===Co||n===Po?n=Ne:n===ko||n===$o?n=ht:(n=Ne,o=void 0);const b=n===Ne&&e[a+1].startsWith("/>")?" ":"";r+=n===ht?c+Va:h>=0?(s.push(p),c.slice(0,h)+Jr+c.slice(h)+je+b):c+je+(h===-2?a:b)}return[Yr(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ct{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Ja(t,i);if(this.el=Ct.createElement(p,s),He.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=He.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Jr)){const f=u[n++],b=o.getAttribute(h).split(je),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:b,ctor:P[1]==="."?Qa:P[1]==="?"?Xa:P[1]==="@"?Ya:$i}),o.removeAttribute(h)}else h.startsWith(je)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Qr.test(o.tagName)){const h=o.textContent.split(je),f=h.length-1;if(f>0){o.textContent=si?si.emptyScript:"";for(let b=0;b<f;b++)o.append(h[b],$t()),He.nextNode(),c.push({type:2,index:++r});o.append(h[f],$t())}}}else if(o.nodeType===8)if(o.data===Zr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(je,h+1))!==-1;)c.push({type:7,index:r}),h+=je.length-1}r++}}static createElement(t,i){const s=Ke.createElement("template");return s.innerHTML=t,s}}function rt(e,t,i=e,s){if(t===Fe)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Pt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=rt(e,o._$AS(e,t.values),o,s)),t}class Za{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ke).importNode(i,!0);He.currentNode=o;let r=He.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new at(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new el(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=He.nextNode(),n++)}return He.currentNode=Ke,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class at{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=rt(this,t,i),Pt(t)?t===_||t==null||t===""?(this._$AH!==_&&this._$AR(),this._$AH=_):t!==this._$AH&&t!==Fe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ga(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==_&&Pt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ke.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ct.createElement(Yr(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Za(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Io.get(t.strings);return i===void 0&&Io.set(t.strings,i=new Ct(t)),i}k(t){Es(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new at(this.O($t()),this.O($t()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=xo(t).nextSibling;xo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let $i=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=_,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=_}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=rt(this,t,i,0),n=!Pt(t)||t!==this._$AH&&t!==Fe,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=rt(this,a[s+c],i,c),p===Fe&&(p=this._$AH[c]),n||=!Pt(p)||p!==this._$AH[c],p===_?t=_:t!==_&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Qa=class extends $i{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===_?void 0:t}},Xa=class extends $i{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==_)}},Ya=class extends $i{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=rt(this,t,i,0)??_)===Fe)return;const s=this._$AH,o=t===_&&s!==_||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==_&&(s===_||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class el{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){rt(this,t)}}const tl={I:at},il=As.litHtmlPolyfillSupport;il?.(Ct,at),(As.litHtmlVersions??=[]).push("3.3.2");const sl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new at(t.insertBefore($t(),r),r,void 0,i??{})}return o._$AI(e),o};const Ds=globalThis;let T=class extends it{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=sl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};T._$litElement$=!0,T.finalized=!0,Ds.litElementHydrateSupport?.({LitElement:T});const ol=Ds.litElementPolyfillSupport;ol?.({LitElement:T});(Ds.litElementVersions??=[]).push("4.2.2");const R=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const rl={attribute:!0,type:String,converter:ii,reflect:!1,hasChanged:Rs},nl=(e=rl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?nl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const al=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function F(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return al(i,s,{get(){return r(this)}})}}function Pi(e,t=tn()){if(t===void 0)return e;const i=en(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function Ws(e,t=tn()){if(t===void 0)return e;const i=en(t);if(i===void 0)return e;const s=new URL(e);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),s.toString()}function en(e){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 tn(){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}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(Pi(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(ll(n)??o.statusText)}const r=await o.json();return t(r)}function ll(e){if(cl(e))return typeof e.error=="string"?e.error:void 0}function cl(e){return typeof e=="object"&&e!==null}function St(e){return typeof e=="object"&&e!==null}function y(e){if(!St(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 C(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 ne(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function dl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function pl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function hl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:dl(t.messages),start:ne(t,"start"),total:ne(t,"total")}}function ul(e){const t=y(e);return j(sn)(t.machines)}function sn(e){const t=y(e),i=gl(t,"kind"),s=C(t,"baseUrl"),o=on(t,"status"),r=C(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function fl(e){const t=y(e),i=on(t,"status"),s=C(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:oi(t.web)},...t.sessiond===void 0?{}:{sessiond:oi(t.sessiond)},...s===void 0?{}:{error:s}}}function gl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function on(e,t){const i=C(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function To(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function ml(e){const t=y(e),i=C(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function ds(e){const t=y(e),i=C(t,"name"),s=C(t,"parentSessionPath"),o=C(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:ne(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function ut(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:ne(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(vl)(t.queuedMessages),...x("messageCount",Te(t,"messageCount")),tokens:bl(t.tokens),cost:ne(t,"cost"),...wl(t.model),...El(t.contextUsage),...x("thinkingLevel",C(t,"thinkingLevel"))}}function vl(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 bl(e){const t=y(e);return{input:ne(t,"input"),output:ne(t,"output"),cacheRead:ne(t,"cacheRead"),cacheWrite:ne(t,"cacheWrite"),total:ne(t,"total")}}function rn(e){const t=y(e);return{...x("provider",C(t,"provider")),...x("id",C(t,"id")),...x("name",C(t,"name")),...x("contextWindow",Te(t,"contextWindow")),...x("reasoning",t.reasoning)}}function wl(e){return e===void 0?{}:{model:rn(e)}}function yl(e){const t=y(e);return{models:j(rn)(t.models)}}function xl(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Sl(e){const t=y(e);return{levels:j(xl)(t.levels)}}function kl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function $l(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 Pl(e){const t=y(e),i=t.source===void 0?void 0:$l(t.source);return{configured:E(t,"configured"),...x("source",i),...x("label",C(t,"label"))}}function Cl(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:kl(t.authType),status:Pl(t.status)}}function Il(e){const t=y(e);return{providers:j(Cl)(t.providers)}}function jt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Tl(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...x("error",C(t,"error")),...x("auth",Ml(t.auth)),...x("prompt",Rl(t.prompt)),...x("select",Al(t.select))}}function Tl(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ml(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...x("instructions",C(t,"instructions"))}}function Rl(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,...x("placeholder",C(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Al(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(an)(t.options)}}function El(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Oo(t,"tokens"),contextWindow:ne(t,"contextWindow"),percent:Oo(t,"percent")}}}function Dl(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,...x("description",C(t,"description"))}}function nn(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Wl(e){const t=y(e);return{path:m(t,"path"),entries:j(Ol)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function Ol(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,...x("size",Te(t,"size")),...x("modifiedAt",C(t,"modifiedAt"))}}function _l(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...x("language",C(t,"language")),...x("mediaType",Ll(t.mediaType)),...x("mimeType",C(t,"mimeType")),encoding:i,size:ne(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function ps(e){const t=y(e);return{path:m(t,"path"),size:ne(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Ni(e){const t=y(e);return{path:m(t,"path")}}function Mo(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Ll(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function jl(e){const t=y(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...x("branch",C(t,"branch")),...x("upstream",C(t,"upstream")),...x("ahead",Te(t,"ahead")),...x("behind",Te(t,"behind")),files:j(Fl)(t.files)}}function Fl(e){const t=y(e);return{path:m(t,"path"),...x("oldPath",C(t,"oldPath")),index:Ro(t.index),workingTree:Ro(t.workingTree)}}function Ro(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 Nl(e){const t=y(e);return{...x("path",C(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function zi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...x("exitCode",Te(t,"exitCode")),...x("commandRunId",C(t,"commandRunId"))}}function kt(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:zl(t.status),...x("exitCode",Te(t,"exitCode")),createdAt:m(t,"createdAt"),...x("startedAt",C(t,"startedAt")),...x("completedAt",C(t,"completedAt")),metadata:Bl(t.metadata,"metadata")}}function zl(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Bl(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Ul(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Hl(e){const t=y(e);return{workspaces:j(Ul)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Ao(e){const t=y(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Eo(t.config),effectiveConfig:Eo(t.effectiveConfig),envOverrides:Gl(t.envOverrides)}}function Eo(e){const t=y(e);return{...x("host",C(t,"host")),...x("port",Te(t,"port")),...x("allowedHosts",ql(t.allowedHosts)),...x("shortcuts",Kl(t.shortcuts)),...x("plugins",Vl(t.plugins))}}function ql(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function Kl(e){if(e!==void 0){if(!St(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 Vl(e){if(e!==void 0){if(!St(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!St(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!St(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Gl(e){const t=y(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts")}}function Jl(e){const t=y(e);return{plugins:j(Zl)(t.plugins)}}function Zl(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Ql(t.scope),enabled:E(t,"enabled")}}function Ql(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Xl(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Yl(t.components),release:tc(t.release),commands:ic(t.commands),messages:j(sc)(t.messages)}}function Yl(e){const t=y(e);return{web:oi(t.web),sessiond:oi(t.sessiond)}}function oi(e){const t=y(e);return{component:oc(t.component),label:m(t,"label"),...x("runtimeVersion",C(t,"runtimeVersion")),...x("installedVersion",C(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...x("installation",ec(t.installation)),...x("error",C(t,"error"))}}function ec(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...x("path",C(t,"path")),...x("source",C(t,"source")),...s===void 0?{}:{scope:s},...x("npmRoot",C(t,"npmRoot"))}}function tc(e){const t=y(e);return{packageName:m(t,"packageName"),...x("latestVersion",C(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...x("checkedAt",C(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...x("error",C(t,"error"))}}function ic(e){const t=y(e);return{...x("update",C(t,"update")),...x("restart",C(t,"restart")),...x("restartWeb",C(t,"restartWeb")),...x("restartSessiond",C(t,"restartSessiond")),...x("status",C(t,"status"))}}function sc(e){const t=y(e);return{id:m(t,"id"),severity:rc(t.severity),title:m(t,"title"),body:m(t,"body"),...x("command",C(t,"command"))}}function oc(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function rc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Do(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(an)(t.options)};if(i==="done")return{type:i,...x("message",C(t,"message")),...nc(t.session),...x("promptDraft",C(t,"promptDraft"))};throw new Error("Invalid command result type")}function an(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...x("description",C(t,"description"))}}function nc(e){return e===void 0?{}:{session:ds(e)}}function Ft(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function hs(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function ac(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function lc(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Wo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:pl(t.sessionIds,"sessionIds"),s=Te(t,"archivedCount"),o=Te(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function cc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function dc(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Te(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Oo(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 x(e,t){return t===void 0?{}:{[e]:t}}function pc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function hc(e,t,i="local"){const s=new URLSearchParams;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/${e}/messages${o?`?${o}`:""}`}function uc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function ln(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Pi(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const S=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,cn={piWebStatus:()=>v("/api/pi-web/status",Xl)},fc={machines:()=>v("/api/machines",ul),addMachine:e=>v("/api/machines",sn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,fl)},ri={config:()=>v("/api/config",Ao),saveConfig:e=>v("/api/config",Ao,{method:"PUT",body:JSON.stringify({config:e})})},us={plugins:()=>v("/api/plugins",Jl)},dn={workspaceActivity:(e="local")=>v(`${S(e)}/activity`,Hl)},gc={projects:(e="local")=>v(`${S(e)}/projects`,j(To)),addProject:(e,t,i,s="local")=>v(`${S(s)}/projects`,To,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${S(t)}/projects/${encodeURIComponent(e)}`,hs,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${S(t)}/project-directories?q=${encodeURIComponent(e)}`,j(nn))},fs={workspaces:(e,t="local")=>v(`${S(t)}/projects/${e}/workspaces`,j(ml)),deleteWorkspace:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,kt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Wl),workspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,_l),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?vc(e,t,i,s):v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ps,{method:"POST",body:JSON.stringify({path:i,contentBase64:await mc(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ps,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ni,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Mo,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ni,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ni,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Mo,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>ln(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>wc(e,t,i,s)};async function mc(e){return bc(await e.arrayBuffer())}async function vc(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(Pi(`${S("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Os(n)??r.statusText)}return ps(await r.json())}function bc(e){const t=new Uint8Array(e),i=32768;let s="";for(let o=0;o<t.length;o+=i)s+=String.fromCharCode(...t.subarray(o,o+i));return btoa(s)}async function wc(e,t,i,s){const o=await fetch(ln(e,t,i,{machineId:s}));if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(Os(a)??o.statusText)}const r=URL.createObjectURL(await o.blob()),n=document.createElement("a");n.href=r,n.download=yc(i,o.headers.get("content-disposition")),document.body.append(n),n.click(),n.remove(),URL.revokeObjectURL(r)}function yc(e,t){const s=t?.match(/filename\*=UTF-8''([^;]+)/u)?.[1];if(s!==void 0)try{const n=decodeURIComponent(s).trim();if(n!=="")return n}catch{}const r=t?.match(/filename="([^"]+)"/u)?.[1]?.trim();return r!==void 0&&r!==""?r:e.split("/").filter(n=>n!=="").at(-1)??"download"}const xc={sessions:(e,t="local")=>v(`${S(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(ds)),startSession:(e,t="local")=>v(`${S(t)}/sessions`,ds,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(hc(e,t,i),hl),status:(e,t="local")=>v(`${S(t)}/sessions/${e}/status`,ut),models:(e,t="local")=>v(`${S(t)}/sessions/${e}/models`,yl),setModel:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/model`,ut,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/model/cycle`,ut,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-levels`,Sl),setThinkingLevel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/thinking-level`,ut,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-level/cycle`,ut,{method:"POST"}),commands:(e,t="local")=>v(`${S(t)}/sessions/${e}/commands`,j(Dl)),prompt:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/prompt`,Ft,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/shell`,Ft,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/commands/run`,Do,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/commands/respond`,Do,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>v(`${S(t)}/sessions/${e}/abort`,ac,{method:"POST"}),stop:(e,t="local")=>v(`${S(t)}/sessions/${e}/stop`,lc,{method:"POST"}),archive:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive`,Wo,{method:"POST"}),archiveWithDescendants:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive-tree`,Wo,{method:"POST"}),restore:(e,t="local")=>v(`${S(t)}/sessions/${e}/restore`,cc,{method:"POST"}),detachParent:(e,t="local")=>v(`${S(t)}/sessions/${e}/detach-parent`,dc,{method:"POST"}),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 v(`${S(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Il)},saveApiKey:(e,t,i="local")=>v(`${S(i)}/auth/api-key`,Ft,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${S(t)}/auth/logout`,Ft,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${S(t)}/auth/oauth`,jt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}`,jt),respondOAuthFlow:(e,t,i,s="local")=>v(`${S(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,jt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,jt,{method:"POST"})},ot={terminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(zi)),startTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,zi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,hs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,hs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,zi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,kt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${S(t)}/terminal-command-runs${kc(e)}`,j(kt)),getCommandRun:(e,t="local")=>Sc(e,t),cancelCommandRun:(e,t="local")=>v(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,kt,{method:"POST"})};async function Sc(e,t){const i=await fetch(Pi(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Os(s)??i.statusText)}return kt(await i.json())}}function kc(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 Os(e){if(!$c(e))return;const t=e.error;return typeof t=="string"?t:void 0}function $c(e){return typeof e=="object"&&e!==null}const Pc={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${S(i.machineId)}/files?${s.toString()}`,j(nn))}},Cc={gitStatus:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,jl),gitDiff:(e,t,i,s="local")=>v(pc(s,e,t,i),Nl)},B={...cn,...fc,...ri,...us,...dn,...gc,...fs,...xc,...ot,...Pc,...Cc};function Ic(e,t="local"){return new WebSocket(Ws(`${Ls()}${_s(t)}/sessions/${e}/events`))}function Rb(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(Ws(`${Ls()}${_s(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`))}function Tc(e="local"){return new WebSocket(Ws(`${Ls()}${_s(e)}/events`))}function _s(e){return`/api/machines/${encodeURIComponent(e)}`}function Ls(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Zt(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Mc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ci(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function pn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const hn="local";function Bi(e,t){return`${e}:${t}`}function un(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??hn}class Rc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??dn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Ac(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=Ec(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Ac(e){const t={};for(const i of e.workspaces)pn(i)&&(t[i.cwd]=i);return t}function Ec(e,t){const i={...e};return pn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Dc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??B,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Wc(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function Wc(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Mt(e){return e.replaceAll(":",".")}function Oc(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Ui(e,t){const i=Oc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function re(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));_c(o,s)}function _c(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Nt=Mt("core:workspace.files");class Lc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??B}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(_o(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:jc(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),re(Nt,"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"}),re(Nt,"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 o=await this.api.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(_o(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),re(Nt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=g(this.getState()),r=Fc(this.getState()),n=[];for(const c of t){const p=zc(r,Nc(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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,g(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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,g(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=g(this.getState());Hi(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}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 o=g(this.getState());Hi(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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===""||Hi(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,g(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),re(Nt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function _o(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function jc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Fc(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(fn(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function Hi(e){const t=e.selectedFilePath;return t===void 0?"file":fn(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function fn(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Nc(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function zc(e,t){return e===""?t:`${e}/${t}`}const Lo=Mt("core:workspace.git");class Bc{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 B.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),re(Lo,"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"}),re(Lo,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([B.gitDiff(i.id,s.id,{path:t},g(this.getState())),B.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Uc{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await B.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Hc(this.getState().machineActivities,o)}),this.refreshMachineHealthFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Zt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await B.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 B.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:jo(this.getState().machineStatuses,t.id),machineActivities:jo(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await B.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const o=await this.safeRemoteHealth(s);if(o.ok)return s;const r=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${r?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o}}),r??s}async safeRemoteHealth(t){try{return await B.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>B.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}}function jo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Hc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class qc{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await B.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await B.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await B.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const gs="pi-web:cached-new-sessions:v1",Kc="browserCachedNew",lt="local";function Rt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=lt,i=Rt()){if(e.messageCount!==0||e.archived===!0)return;const s=js(i).filter(o=>o.id!==e.id||o.machineId!==t);Fs([ms(e,t),...s],i)}function ms(e,t=lt){return{...e,browserCachedNew:!0,machineId:t}}function No(e,t=lt,i=Rt()){const s=js(i).filter(o=>o.id!==e||o.machineId!==t);Fs(s,i)}function Vc(e,t,i=lt,s=Rt()){const o=new Set(t.map(c=>c.id)),r=js(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Fs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Ce(e){return e===void 0?!1:Zc(e)&&e.browserCachedNew===!0}function Gc(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:lt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function js(e=Rt()){try{const t=e?.getItem(gs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Jc(s)):[]}catch{return[]}}function Fs(e,t=Rt()){try{e.length===0?t?.removeItem(gs):t?.setItem(gs,JSON.stringify(e))}catch{}}function Jc(e){if(!Qc(e))return[];const t=et(e,"id"),i=et(e,"path"),s=et(e,"cwd"),o=et(e,"created"),r=et(e,"modified"),n=et(e,"firstMessage"),a=Xc(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=qi(e,"name"),p=qi(e,"parentSessionPath"),u=qi(e,"machineId")??lt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Zc(e){return Kc in e}function Qc(e){return typeof e=="object"&&e!==null}function et(e,t){const i=e[t];return typeof i=="string"?i:void 0}function qi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Xc(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Yc(e){return fd(e.flatMap(Ns)).filter(t=>t.parts.length>0)}function Ie(e,t){return{role:e,parts:[{type:"text",text:t}]}}function zt(e,t){const i=nd(t);return i===void 0?e:{...e,meta:i}}function ed(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Ie(t,i)]}function td(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 Ns(e){if(id(e))return[e];if(W(e,"role")==="bashExecution")return[zt(cd(e),e)];const t=dd(W(e,"role")),i=pd(pe(e,"content"),e),s=t==="user"?sd(i):void 0;if(s!==void 0)return s.map(a=>zt(a,e));const o=rd(e);if(t==="tool")return[zt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(a=>a.type==="skillRead")?"skill":t;return r.length>0?[zt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[]}function id(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(pe(e,"parts"))}function sd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=od(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 od(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 rd(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function nd(e){const t=ad(pe(e,"timestamp")),i=ld(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function ad(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 ld(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function cd(e){const t=W(e,"command")??"",i=Qt(e,"excludeFromContext")===!0?["不加入上下文","",`$ ${t}`]:[`$ ${t}`],s=pe(e,"output");s!=null&&i.push("",ai(s));const o=pe(e,"exitCode");o!=null&&i.push("",`exit ${ai(o)}`),Qt(e,"cancelled")===!0&&i.push("","cancelled"),Qt(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`完整输出:${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
-
`)}]}}function
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-DzeGsHZ5.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BghODb4T.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as go,w as Ye,J as Ni,R as Ta,S as Ma,G as Ra,U as Aa,V as Ea,A as Da,W as Wa,X as Oa,Y as _a,Z as mo,x as vo,_ as La}from"./vendor-editor-core-B4Sq6exx.js";import{m as ja,i as Na,d as Fa}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const Zt=globalThis,Ms=Zt.ShadowRoot&&(Zt.ShadyCSS===void 0||Zt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Rs=Symbol(),bo=new WeakMap;let Jr=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Rs)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(Ms&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=bo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&bo.set(i,t))}return t}toString(){return this.cssText}};const za=e=>new Jr(typeof e=="string"?e:e+"",void 0,Rs),A=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new Jr(i,e,Rs)},Ba=(e,t)=>{if(Ms)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=Zt.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},wo=Ms?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return za(i)})(e):e;const{is:Ua,defineProperty:Ha,getOwnPropertyDescriptor:qa,getOwnPropertyNames:Ka,getOwnPropertySymbols:Va,getPrototypeOf:Ga}=Object,$i=globalThis,yo=$i.trustedTypes,Ja=yo?yo.emptyScript:"",Za=$i.reactiveElementPolyfillSupport,St=(e,t)=>e,si={toAttribute(e,t){switch(t){case Boolean:e=e?Ja: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}},As=(e,t)=>!Ua(e,t),xo={attribute:!0,type:String,converter:si,reflect:!1,useDefault:!1,hasChanged:As};Symbol.metadata??=Symbol("metadata"),$i.litPropertyMetadata??=new WeakMap;let it=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=xo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Ha(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=qa(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??xo}static _$Ei(){if(this.hasOwnProperty(St("elementProperties")))return;const t=Ga(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(St("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(St("properties"))){const i=this.properties,s=[...Ka(i),...Va(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(wo(o))}else t!==void 0&&i.push(wo(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 Ba(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:si).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:si;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??As)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};it.elementStyles=[],it.shadowRootOptions={mode:"open"},it[St("elementProperties")]=new Map,it[St("finalized")]=new Map,Za?.({ReactiveElement:it}),($i.reactiveElementVersions??=[]).push("2.1.2");const Es=globalThis,So=e=>e,oi=Es.trustedTypes,ko=oi?oi.createPolicy("lit-html",{createHTML:e=>e}):void 0,Zr="$lit$",je=`lit$${Math.random().toFixed(9).slice(2)}$`,Qr="?"+je,Qa=`<${Qr}>`,Ke=document,Pt=()=>Ke.createComment(""),It=e=>e===null||typeof e!="object"&&typeof e!="function",Ds=Array.isArray,Xa=e=>Ds(e)||typeof e?.[Symbol.iterator]=="function",Fi=`[
|
|
3
|
+
\f\r]`,ht=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,$o=/-->/g,Po=/>/g,Fe=RegExp(`>|${Fi}(?:([^\\s"'>=/]+)(${Fi}*=${Fi}*(?:[^
|
|
4
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Io=/'/g,Co=/"/g,Xr=/^(?:script|style|textarea|title)$/i,Yr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Yr(1),st=Yr(2),Ne=Symbol.for("lit-noChange"),_=Symbol.for("lit-nothing"),To=new WeakMap,He=Ke.createTreeWalker(Ke,129);function en(e,t){if(!Ds(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return ko!==void 0?ko.createHTML(t):t}const Ya=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ht;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===ht?u[1]==="!--"?n=$o:u[1]!==void 0?n=Po:u[2]!==void 0?(Xr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Fe):u[3]!==void 0&&(n=Fe):n===Fe?u[0]===">"?(n=o??ht,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Fe:u[3]==='"'?Co:Io):n===Co||n===Io?n=Fe:n===$o||n===Po?n=ht:(n=Fe,o=void 0);const b=n===Fe&&e[a+1].startsWith("/>")?" ":"";r+=n===ht?c+Qa:h>=0?(s.push(p),c.slice(0,h)+Zr+c.slice(h)+je+b):c+je+(h===-2?a:b)}return[en(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ct{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Ya(t,i);if(this.el=Ct.createElement(p,s),He.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=He.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Zr)){const f=u[n++],b=o.getAttribute(h).split(je),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:b,ctor:P[1]==="."?tl:P[1]==="?"?il:P[1]==="@"?sl:Pi}),o.removeAttribute(h)}else h.startsWith(je)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Xr.test(o.tagName)){const h=o.textContent.split(je),f=h.length-1;if(f>0){o.textContent=oi?oi.emptyScript:"";for(let b=0;b<f;b++)o.append(h[b],Pt()),He.nextNode(),c.push({type:2,index:++r});o.append(h[f],Pt())}}}else if(o.nodeType===8)if(o.data===Qr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(je,h+1))!==-1;)c.push({type:7,index:r}),h+=je.length-1}r++}}static createElement(t,i){const s=Ke.createElement("template");return s.innerHTML=t,s}}function rt(e,t,i=e,s){if(t===Ne)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=It(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=rt(e,o._$AS(e,t.values),o,s)),t}class el{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ke).importNode(i,!0);He.currentNode=o;let r=He.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new at(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new ol(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=He.nextNode(),n++)}return He.currentNode=Ke,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class at{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=rt(this,t,i),It(t)?t===_||t==null||t===""?(this._$AH!==_&&this._$AR(),this._$AH=_):t!==this._$AH&&t!==Ne&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Xa(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!==_&&It(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ke.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ct.createElement(en(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new el(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=To.get(t.strings);return i===void 0&&To.set(t.strings,i=new Ct(t)),i}k(t){Ds(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new at(this.O(Pt()),this.O(Pt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=So(t).nextSibling;So(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Pi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=_,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=_}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=rt(this,t,i,0),n=!It(t)||t!==this._$AH&&t!==Ne,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=rt(this,a[s+c],i,c),p===Ne&&(p=this._$AH[c]),n||=!It(p)||p!==this._$AH[c],p===_?t=_:t!==_&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},tl=class extends Pi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===_?void 0:t}},il=class extends Pi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==_)}},sl=class extends Pi{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=rt(this,t,i,0)??_)===Ne)return;const s=this._$AH,o=t===_&&s!==_||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==_&&(s===_||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class ol{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){rt(this,t)}}const rl={I:at},nl=Es.litHtmlPolyfillSupport;nl?.(Ct,at),(Es.litHtmlVersions??=[]).push("3.3.2");const al=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new at(t.insertBefore(Pt(),r),r,void 0,i??{})}return o._$AI(e),o};const Ws=globalThis;let T=class extends it{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=al(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ne}};T._$litElement$=!0,T.finalized=!0,Ws.litElementHydrateSupport?.({LitElement:T});const ll=Ws.litElementPolyfillSupport;ll?.({LitElement:T});(Ws.litElementVersions??=[]).push("4.2.2");const R=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const cl={attribute:!0,type:String,converter:si,reflect:!1,hasChanged:As},dl=(e=cl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?dl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const pl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function F(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return pl(i,s,{get(){return r(this)}})}}function Ii(e,t=sn()){if(t===void 0)return e;const i=tn(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function Os(e,t=sn()){if(t===void 0)return e;const i=tn(t);if(i===void 0)return e;const s=new URL(e);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),s.toString()}function tn(e){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 sn(){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}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(Ii(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(hl(n)??o.statusText)}const r=await o.json();return t(r)}function hl(e){if(ul(e))return typeof e.error=="string"?e.error:void 0}function ul(e){return typeof e=="object"&&e!==null}function kt(e){return typeof e=="object"&&e!==null}function x(e){if(!kt(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 I(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 ne(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function fl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function gl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function ml(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=x(e);return{messages:fl(t.messages),start:ne(t,"start"),total:ne(t,"total")}}function vl(e){const t=x(e);return j(on)(t.machines)}function on(e){const t=x(e),i=wl(t,"kind"),s=I(t,"baseUrl"),o=rn(t,"status"),r=I(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function bl(e){const t=x(e),i=rn(t,"status"),s=I(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ri(t.web)},...t.sessiond===void 0?{}:{sessiond:ri(t.sessiond)},...s===void 0?{}:{error:s}}}function wl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function rn(e,t){const i=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 Mo(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function yl(e){const t=x(e),i=I(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree")}}function ps(e){const t=x(e),i=I(t,"name"),s=I(t,"parentSessionPath"),o=I(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:ne(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function ut(e){const t=x(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:ne(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(xl)(t.queuedMessages),...y("messageCount",xe(t,"messageCount")),tokens:Sl(t.tokens),cost:ne(t,"cost"),...$l(t.model),...Ll(t.contextUsage),...y("thinkingLevel",I(t,"thinkingLevel"))}}function xl(e){const t=x(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...y("imageCount",xe(t,"imageCount"))}}function Sl(e){const t=x(e);return{input:ne(t,"input"),output:ne(t,"output"),cacheRead:ne(t,"cacheRead"),cacheWrite:ne(t,"cacheWrite"),total:ne(t,"total")}}function nn(e){const t=x(e);return{...y("provider",I(t,"provider")),...y("id",I(t,"id")),...y("name",I(t,"name")),...y("contextWindow",xe(t,"contextWindow")),...y("reasoning",t.reasoning),...y("input",kl(t.input))}}function kl(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Expected model input array");return e.filter(t=>t==="text"||t==="image")}}function $l(e){return e===void 0?{}:{model:nn(e)}}function Pl(e){const t=x(e);return{models:j(nn)(t.models)}}function Il(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Cl(e){const t=x(e);return{levels:j(Il)(t.levels)}}function Tl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Ml(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 Rl(e){const t=x(e),i=t.source===void 0?void 0:Ml(t.source);return{configured:D(t,"configured"),...y("source",i),...y("label",I(t,"label"))}}function Al(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),authType:Tl(t.authType),status:Rl(t.status)}}function El(e){const t=x(e);return{providers:j(Al)(t.providers)}}function Nt(e){const t=x(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Dl(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...y("error",I(t,"error")),...y("auth",Wl(t.auth)),...y("prompt",Ol(t.prompt)),...y("select",_l(t.select))}}function Dl(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Wl(e){if(e===void 0)return;const t=x(e);return{url:m(t,"url"),...y("instructions",I(t,"instructions"))}}function Ol(e){if(e===void 0)return;const t=x(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,...y("placeholder",I(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function _l(e){if(e===void 0)return;const t=x(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(ln)(t.options)}}function Ll(e){if(e===void 0)return{};const t=x(e);return{contextUsage:{tokens:_o(t,"tokens"),contextWindow:ne(t,"contextWindow"),percent:_o(t,"percent")}}}function jl(e){const t=x(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,...y("description",I(t,"description"))}}function an(e){const t=x(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 Nl(e){const t=x(e);return{path:m(t,"path"),entries:j(Fl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Fl(e){const t=x(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,...y("size",xe(t,"size")),...y("modifiedAt",I(t,"modifiedAt"))}}function zl(e){const t=x(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...y("language",I(t,"language")),...y("mediaType",Bl(t.mediaType)),...y("mimeType",I(t,"mimeType")),encoding:i,size:ne(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function hs(e){const t=x(e);return{path:m(t,"path"),size:ne(t,"size"),modifiedAt:m(t,"modifiedAt")}}function zi(e){const t=x(e);return{path:m(t,"path")}}function Ro(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Bl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Ul(e){const t=x(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...y("branch",I(t,"branch")),...y("upstream",I(t,"upstream")),...y("ahead",xe(t,"ahead")),...y("behind",xe(t,"behind")),files:j(Hl)(t.files)}}function Hl(e){const t=x(e);return{path:m(t,"path"),...y("oldPath",I(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function ql(e){const t=x(e);return{...y("path",I(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function Bi(e){const t=x(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...y("exitCode",xe(t,"exitCode")),...y("commandRunId",I(t,"commandRunId"))}}function $t(e){const t=x(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:Kl(t.status),...y("exitCode",xe(t,"exitCode")),createdAt:m(t,"createdAt"),...y("startedAt",I(t,"startedAt")),...y("completedAt",I(t,"completedAt")),metadata:Vl(t.metadata,"metadata")}}function Kl(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Vl(e,t){const i=x(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Gl(e){const t=x(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Jl(e){const t=x(e);return{workspaces:j(Gl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Eo(e){const t=x(e);return{path:m(t,"path"),exists:D(t,"exists"),config:Do(t.config),effectiveConfig:Do(t.effectiveConfig),envOverrides:Yl(t.envOverrides)}}function Do(e){const t=x(e);return{...y("host",I(t,"host")),...y("port",xe(t,"port")),...y("allowedHosts",Zl(t.allowedHosts)),...y("shortcuts",Ql(t.shortcuts)),...y("plugins",Xl(t.plugins))}}function Zl(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 Ql(e){if(e!==void 0){if(!kt(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 Xl(e){if(e!==void 0){if(!kt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!kt(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!kt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Yl(e){const t=x(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts")}}function ec(e){const t=x(e);return{plugins:j(tc)(t.plugins)}}function tc(e){const t=x(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:ic(t.scope),enabled:D(t,"enabled")}}function ic(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function sc(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:oc(t.components),release:nc(t.release),commands:ac(t.commands),messages:j(lc)(t.messages)}}function oc(e){const t=x(e);return{web:ri(t.web),sessiond:ri(t.sessiond)}}function ri(e){const t=x(e);return{component:cc(t.component),label:m(t,"label"),...y("runtimeVersion",I(t,"runtimeVersion")),...y("installedVersion",I(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...y("installation",rc(t.installation)),...y("error",I(t,"error"))}}function rc(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...y("path",I(t,"path")),...y("source",I(t,"source")),...s===void 0?{}:{scope:s},...y("npmRoot",I(t,"npmRoot"))}}function nc(e){const t=x(e);return{packageName:m(t,"packageName"),...y("latestVersion",I(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...y("checkedAt",I(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...y("error",I(t,"error"))}}function ac(e){const t=x(e);return{...y("update",I(t,"update")),...y("restart",I(t,"restart")),...y("restartWeb",I(t,"restartWeb")),...y("restartSessiond",I(t,"restartSessiond")),...y("status",I(t,"status"))}}function lc(e){const t=x(e);return{id:m(t,"id"),severity:dc(t.severity),title:m(t,"title"),body:m(t,"body"),...y("command",I(t,"command"))}}function cc(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function dc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Wo(e){const t=x(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(ln)(t.options)};if(i==="done")return{type:i,...y("message",I(t,"message")),...pc(t.session),...y("promptDraft",I(t,"promptDraft"))};throw new Error("Invalid command result type")}function ln(e){const t=x(e);return{value:m(t,"value"),label:m(t,"label"),...y("description",I(t,"description"))}}function pc(e){return e===void 0?{}:{session:ps(e)}}function Ft(e){if(x(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function us(e){if(x(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function hc(e){if(x(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function uc(e){if(x(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Oo(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:gl(t.sessionIds,"sessionIds"),s=xe(t,"archivedCount"),o=xe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function fc(e){if(x(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function gc(e){if(x(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function xe(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 _o(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 y(e,t){return t===void 0?{}:{[e]:t}}function mc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function vc(e,t,i="local"){const s=new URLSearchParams;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/${e}/messages${o?`?${o}`:""}`}function bc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function cn(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ii(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const S=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,dn={piWebStatus:()=>v("/api/pi-web/status",sc)},wc={machines:()=>v("/api/machines",vl),addMachine:e=>v("/api/machines",on,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,bl)},ni={config:()=>v("/api/config",Eo),saveConfig:e=>v("/api/config",Eo,{method:"PUT",body:JSON.stringify({config:e})})},fs={plugins:()=>v("/api/plugins",ec)},pn={workspaceActivity:(e="local")=>v(`${S(e)}/activity`,Jl)},yc={projects:(e="local")=>v(`${S(e)}/projects`,j(Mo)),addProject:(e,t,i,s="local")=>v(`${S(s)}/projects`,Mo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${S(t)}/projects/${encodeURIComponent(e)}`,us,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${S(t)}/project-directories?q=${encodeURIComponent(e)}`,j(an))},gs={workspaces:(e,t="local")=>v(`${S(t)}/projects/${e}/workspaces`,j(yl)),deleteWorkspace:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,$t,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Nl),workspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,zl),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?Sc(e,t,i,s):v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,hs,{method:"POST",body:JSON.stringify({path:i,contentBase64:await xc(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,hs,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Ro,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,zi,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Ro,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>cn(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>$c(e,t,i,s)};async function xc(e){return kc(await e.arrayBuffer())}async function Sc(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(Ii(`${S("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(_s(n)??r.statusText)}return hs(await r.json())}function kc(e){const t=new Uint8Array(e),i=32768;let s="";for(let o=0;o<t.length;o+=i)s+=String.fromCharCode(...t.subarray(o,o+i));return btoa(s)}async function $c(e,t,i,s){const o=await fetch(cn(e,t,i,{machineId:s}));if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(_s(a)??o.statusText)}const r=URL.createObjectURL(await o.blob()),n=document.createElement("a");n.href=r,n.download=Pc(i,o.headers.get("content-disposition")),document.body.append(n),n.click(),n.remove(),URL.revokeObjectURL(r)}function Pc(e,t){const s=t?.match(/filename\*=UTF-8''([^;]+)/u)?.[1];if(s!==void 0)try{const n=decodeURIComponent(s).trim();if(n!=="")return n}catch{}const r=t?.match(/filename="([^"]+)"/u)?.[1]?.trim();return r!==void 0&&r!==""?r:e.split("/").filter(n=>n!=="").at(-1)??"download"}const Ic={sessions:(e,t="local")=>v(`${S(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(ps)),startSession:(e,t="local")=>v(`${S(t)}/sessions`,ps,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(vc(e,t,i),ml),status:(e,t="local")=>v(`${S(t)}/sessions/${e}/status`,ut),models:(e,t="local")=>v(`${S(t)}/sessions/${e}/models`,Pl),setModel:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/model`,ut,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/model/cycle`,ut,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-levels`,Cl),setThinkingLevel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/thinking-level`,ut,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-level/cycle`,ut,{method:"POST"}),commands:(e,t="local")=>v(`${S(t)}/sessions/${e}/commands`,j(jl)),prompt:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/prompt`,Ft,{method:"POST",body:JSON.stringify(Mc(t,i))}),shell:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/shell`,Ft,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/commands/run`,Wo,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/commands/respond`,Wo,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>v(`${S(t)}/sessions/${e}/abort`,hc,{method:"POST"}),stop:(e,t="local")=>v(`${S(t)}/sessions/${e}/stop`,uc,{method:"POST"}),archive:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive`,Oo,{method:"POST"}),archiveWithDescendants:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive-tree`,Oo,{method:"POST"}),restore:(e,t="local")=>v(`${S(t)}/sessions/${e}/restore`,fc,{method:"POST"}),detachParent:(e,t="local")=>v(`${S(t)}/sessions/${e}/detach-parent`,gc,{method:"POST"}),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 v(`${S(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,El)},saveApiKey:(e,t,i="local")=>v(`${S(i)}/auth/api-key`,Ft,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${S(t)}/auth/logout`,Ft,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${S(t)}/auth/oauth`,Nt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}`,Nt),respondOAuthFlow:(e,t,i,s="local")=>v(`${S(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Nt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Nt,{method:"POST"})},ot={terminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Bi)),startTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Bi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,us,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,us,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Bi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,$t,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${S(t)}/terminal-command-runs${Tc(e)}`,j($t)),getCommandRun:(e,t="local")=>Cc(e,t),cancelCommandRun:(e,t="local")=>v(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,$t,{method:"POST"})};async function Cc(e,t){const i=await fetch(Ii(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(_s(s)??i.statusText)}return $t(await i.json())}}function Tc(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 _s(e){if(!Rc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Mc(e,t){const i=typeof e=="string"?{text:e}:e;return t===void 0?i:{...i,streamingBehavior:t}}function Rc(e){return typeof e=="object"&&e!==null}const Ac={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${S(i.machineId)}/files?${s.toString()}`,j(an))}},Ec={gitStatus:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ul),gitDiff:(e,t,i,s="local")=>v(mc(s,e,t,i),ql)},U={...dn,...wc,...ni,...fs,...pn,...yc,...gs,...Ic,...ot,...Ac,...Ec};function Dc(e,t="local"){return new WebSocket(Os(`${js()}${Ls(t)}/sessions/${e}/events`))}function Ub(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(Os(`${js()}${Ls(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`))}function Wc(e="local"){return new WebSocket(Os(`${js()}${Ls(e)}/events`))}function Ls(e){return`/api/machines/${encodeURIComponent(e)}`}function js(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Qt(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Oc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ci(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function hn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const un="local";function Ui(e,t){return`${e}:${t}`}function fn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??un}class _c{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??pn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Lc(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=jc(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Lc(e){const t={};for(const i of e.workspaces)hn(i)&&(t[i.cwd]=i);return t}function jc(e,t){const i={...e};return hn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Nc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??U,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Fc(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function Fc(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Rt(e){return e.replaceAll(":",".")}function zc(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Hi(e,t){const i=zc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function re(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Bc(o,s)}function Bc(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const zt=Rt("core:workspace.files");class Uc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??U}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(Lo(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Hc(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),re(zt,"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"}),re(zt,"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 o=await this.api.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(Lo(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),re(zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=g(this.getState()),r=qc(this.getState()),n=[];for(const c of t){const p=Vc(r,Kc(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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,g(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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,g(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=g(this.getState());qi(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}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 o=g(this.getState());qi(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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===""||qi(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,g(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),re(zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function Lo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Hc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qc(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(gn(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function qi(e){const t=e.selectedFilePath;return t===void 0?"file":gn(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function gn(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Kc(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Vc(e,t){return e===""?t:`${e}/${t}`}const jo=Rt("core:workspace.git");class Gc{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 U.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),re(jo,"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"}),re(jo,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([U.gitDiff(i.id,s.id,{path:t},g(this.getState())),U.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Jc{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await U.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Zc(this.getState().machineActivities,o)}),this.refreshMachineHealthFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Qt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await U.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 U.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:No(this.getState().machineStatuses,t.id),machineActivities:No(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await U.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const o=await this.safeRemoteHealth(s);if(o.ok)return s;const r=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${r?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o}}),r??s}async safeRemoteHealth(t){try{return await U.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>U.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}}function No(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Qc{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await U.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await U.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await U.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const ms="pi-web:cached-new-sessions:v1",Xc="browserCachedNew",lt="local";function At(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=lt,i=At()){if(e.messageCount!==0||e.archived===!0)return;const s=Ns(i).filter(o=>o.id!==e.id||o.machineId!==t);Fs([vs(e,t),...s],i)}function vs(e,t=lt){return{...e,browserCachedNew:!0,machineId:t}}function zo(e,t=lt,i=At()){const s=Ns(i).filter(o=>o.id!==e||o.machineId!==t);Fs(s,i)}function Yc(e,t,i=lt,s=At()){const o=new Set(t.map(c=>c.id)),r=Ns(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Fs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Ce(e){return e===void 0?!1:id(e)&&e.browserCachedNew===!0}function ed(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:lt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ns(e=At()){try{const t=e?.getItem(ms);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>td(s)):[]}catch{return[]}}function Fs(e,t=At()){try{e.length===0?t?.removeItem(ms):t?.setItem(ms,JSON.stringify(e))}catch{}}function td(e){if(!sd(e))return[];const t=et(e,"id"),i=et(e,"path"),s=et(e,"cwd"),o=et(e,"created"),r=et(e,"modified"),n=et(e,"firstMessage"),a=od(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Ki(e,"name"),p=Ki(e,"parentSessionPath"),u=Ki(e,"machineId")??lt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function id(e){return Xc in e}function sd(e){return typeof e=="object"&&e!==null}function et(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ki(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function od(e,t){const i=e[t];return typeof i=="number"?i:void 0}function rd(e){return yd(e.flatMap(zs)).filter(t=>t.parts.length>0)}function Te(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Bt(e,t){const i=hd(t);return i===void 0?e:{...e,meta:i}}function nd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Te(t,i)]}function ad(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 zs(e){if(ld(e))return[e];if(E(e,"role")==="bashExecution")return[Bt(gd(e),e)];const t=md(E(e,"role")),i=vd(pe(e,"content"),e),s=t==="user"?cd(i):void 0;if(s!==void 0)return s.map(a=>Bt(a,e));const o=pd(e);if(t==="tool")return[Bt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(a=>a.type==="skillRead")?"skill":t;return r.length>0?[Bt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[]}function ld(e){const t=E(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(pe(e,"parts"))}function cd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=dd(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 dd(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 pd(e){const t=E(e,"source");if(t==="compaction"||t==="branch_summary")return t}function hd(e){const t=ud(pe(e,"timestamp")),i=fd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function ud(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 fd(e){if(E(e,"role")!=="assistant")return;const t=E(e,"provider"),i=E(e,"model"),s=E(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 gd(e){const t=E(e,"command")??"",i=Xt(e,"excludeFromContext")===!0?["不加入上下文","",`$ ${t}`]:[`$ ${t}`],s=pe(e,"output");s!=null&&i.push("",li(s));const o=pe(e,"exitCode");o!=null&&i.push("",`exit ${li(o)}`),Xt(e,"cancelled")===!0&&i.push("","cancelled"),Xt(e,"truncated")===!0&&i.push("","output truncated");const r=E(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`完整输出:${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
+
`)}]}}function md(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function vd(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=E(i,"type"),o=E(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=E(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=E(i,"name")??"tool",n=pe(i,"arguments"),a=r==="read"?wd(E(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=E(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:r,summary:Et(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=E(i,"data"),n=E(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",data:r,mimeType:n}]:[{type:"text",text:"[image]"}]}return Bo(i)}).map(i=>i.type==="text"&&E(t,"role")==="toolResult"?bd(i.text,t):i):Bo(e)}function bd(e,t){const i=E(t,"toolCallId"),s=pe(t,"content"),o=pe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:E(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:Xt(t,"isError")===!0}}function wd(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 yd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=xd(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&Sd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function xd(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 Sd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=ai(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function ai(e){const t=pe(e,"preview");if(!Bs(t))return;const i=E(t,"diff"),s=E(t,"error"),o=$d(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Bo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Et(e)}]:[{type:"text",text:li(e)}]}function Et(e){if(!Bs(e))return li(e);const t=E(e,"command");if(t!==void 0)return t;const i=E(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)} 处编辑`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${kd(n)}`).join(" · ")}function kd(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)} 项`:typeof e=="object"&&e!==null?"object":""}function Bs(e){return typeof e=="object"&&e!==null}function pe(e,t){return Bs(e)?e[t]:void 0}function E(e,t){const i=pe(e,t);return typeof i=="string"?i:void 0}function Xt(e,t){const i=pe(e,t);return typeof i=="boolean"?i:void 0}function $d(e,t){const i=pe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function li(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Pd="pi-web:prompt-draft:";function ci(e){return`${Pd}${e}`}function Ti(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function mn(e,t=Ti()){try{return t?.getItem(ci(e))??""}catch{return""}}function di(e,t,i=Ti()){try{t?i?.setItem(ci(e),t):i?.removeItem(ci(e))}catch{}}function Us(e,t=Ti()){try{t?.removeItem(ci(e))}catch{}}function Id(e,t,i=Ti()){const s=mn(e,i);s!==""&&(di(t,s,i),Us(e,i))}function Cd(e,t){return Te("bash",`${t===!0?`不加入上下文
|
|
6
6
|
|
|
7
|
-
`:""}$ ${e}`)}function
|
|
7
|
+
`:""}$ ${e}`)}function Td(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Te("bash",t)];const o=Rd(s.text)?"":`
|
|
8
8
|
|
|
9
|
-
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function
|
|
9
|
+
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Md(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
|
|
10
10
|
|
|
11
11
|
`)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash 命令失败"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`完整输出:${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
|
|
12
12
|
|
|
13
13
|
${o.join(`
|
|
14
|
-
`)}`}]}]}function
|
|
14
|
+
`)}`}]}]}function Rd(e){const t=e.lastIndexOf(`
|
|
15
15
|
|
|
16
|
-
`),i=e.lastIndexOf("$ ");return t>i}function
|
|
17
|
-
`);if(typeof e=="object"&&e!==null){const t=qe(e,"text")??qe(e,"content")??qe(e,"output");if(t!==void 0)return t}return""}function
|
|
16
|
+
`),i=e.lastIndexOf("$ ");return t>i}function Ad(e,t){if(t.type==="message.append")return zd(e,t.message);if(t.type==="assistant.delta")return nd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return ad(e,t.text);if(t.type==="tool.start")return Od(e,t);if(t.type==="tool.update")return bn(e,t.toolCallId,i=>_d(i,t));if(t.type==="tool.end")return vn(e,t.toolCallId,t.toolName,Et(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Cd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Td(e,t.chunk);if(t.type==="shell.end")return Md(e,t);if(t.type==="command.output")return[...e,Te(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Te("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Ed(e,t.message)}function Ed(e,t){const i=Ld(t);if(i!==void 0)return vn(e,i.toolCallId,i.toolName,Et(i.content),i.text,i.isError,i.content,i.details);const s=zs(t)[0];if(s===void 0)return;const o=s.role==="assistant"?Dd(s):s;if(o.parts.length===0)return e;const r=jd(e,o);if(r>=0)return[...e.slice(0,r),o,...e.slice(r+1)];const n=e.at(-1);return n?.role!==o.role?[...e,o]:o.role==="assistant"||Fd(n,o)?[...e.slice(0,-1),o]:[...e,o]}function Dd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Wd(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 Od(e,t){const i=t.toolName==="read"?Wd(qe(t.args,"path")):void 0;if(i!==void 0)return Bd(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Et(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function _d(e,t){const i=ai(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 vn(e,t,i,s,o,r,n,a){const c=bn(e,t,h=>{const f=ai(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=ai(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function bn(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Ld(e){if(qe(e,"role")!=="toolResult")return;const t=qe(e,"toolCallId"),i=hi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:qe(e,"toolName")??"tool",text:wn(i),isError:Hd(e,"isError")===!0,content:i,details:hi(e,"details")}}function wn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(wn).filter(t=>t!=="").join(`
|
|
17
|
+
`);if(typeof e=="object"&&e!==null){const t=qe(e,"text")??qe(e,"content")??qe(e,"output");if(t!==void 0)return t}return""}function jd(e,t){const i=pi(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o?.role!=="skill")continue;const r=pi(o);if(yn(r,i))return s}return-1}function pi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function yn(e,t){return e.length===t.length&&e.every((i,s)=>Nd(i,t[s]))}function Nd(e,t){return t===void 0?!1:Uo(e.path)===Uo(t.path)||e.name===t.name}function Uo(e){return e.replace(/\\/g,"/")}function Fd(e,t){return Ho(e)===Ho(t)}function Ho(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
18
18
|
|
|
19
|
-
`)}function
|
|
20
|
-
`))+1;return e.slice(t)}function Qd(e){const t=yn(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const o=e.slice(0,s);return o.endsWith("@")||o.endsWith("@ ")||o.endsWith("!@")}class Xd{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.sessionId=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),Sn(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=Ic(this.sessionId,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await xn(t);Yd(i)&&this.onEvent?.(i)}}class Ko{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Sn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Tc(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await xn(t);tp(i)&&this.onEvent?.(i)}}function Yd(e){const t=Hs(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(t)}function ep(e){const t=Hs(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function tp(e){const t=Hs(e);return ep(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Hs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function xn(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 Sn(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 Et(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Ti{constructor(t,i,s=Et()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of ip(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function qs(e){return typeof e=="string"&&e!==""?e:void 0}function ip(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!sp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function sp(e){return!op(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 op(e){return typeof e=="object"&&e!==null}class rp{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 np="pi-web:session-selection:v1";class ap{constructor(t=Et()){this.sessionIdsByCwd=new Ti(np,qs,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function lp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return dp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function cp(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function dp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function pp(e,t,i){return kn(e,[t],i)}function kn(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function hp(e,t,i){return $n(e,t,[i])}function $n(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const ft=100;class up{constructor(t,i,s,o=new rp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Xd,this.api=r.api??B,this.transcripts=r.transcripts??new Jd}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();cp(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Fo(s,i);const o=ms(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return lp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t.id,{limit:ft},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:ft},g(this.getState())),this.api.status(t.id,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Ce(t)&&bp(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.id,{before:t.messagePageStart,limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(Zd(t))return this.runShell(t);const o=this.getState().selectedSession;if(!(!o||o.archived===!0))try{await this.api.prompt(o.id,t,i,g(this.getState())),this.markCachedNewSessionPersisted(o)}catch(r){this.setState({error:String(r)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ie("user",t)]});try{await this.api.shell(i.id,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ie("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ie("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ie("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Ce(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,g(this.getState()));const i=this.getState(),s=pp(i.sessions,t.id,new Date().toISOString()),o=hp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Ce(t)))try{const i=await this.api.archiveWithDescendants(t.id,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=kn(o.sessions,s,new Date().toISOString()),n=$n(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Ce(t))return;this.api.stop(t.id,g(this.getState())).catch(()=>{}),No(t.id,g(this.getState())),Bs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t.id,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t.id,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t.id,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t.id,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(t,{limit:ft},g(this.getState())),this.api.status(t,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return un(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);Fo(o,s),yd(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),No(t.id,s);const r=ms(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Ce(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Gc(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,Ie(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ci(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ci(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...gp(i,t.sessionId,t.messageCount),...s?{sessionActivities:fp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!t.isStreaming&&this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(mp(t))return}if(vp(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function fp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function mp(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function vp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function bp(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class wp{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 yp="pi-web:workspace-selection:v1";class xp{constructor(t=Et()){this.workspaceIdsByProject=new Ti(yp,qs,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Sp(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class kp{constructor(t,i,s,o,r=new wp,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??B}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Zt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Bi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Zt()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Sp(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Bi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Zt()});try{const o=Vc(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Pp(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function $p(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Pp(e){return e.find(t=>t.isMain)??e[0]}const Cp="pi-web:machine-navigation:v1";class Ip{constructor(t=Et()){this.snapshotsByMachine=new Ti(Cp,Mp,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Jo(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Jo(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Tp(e){return{machineId:e,surface:{}}}function Vo(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??hn,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 Go(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 Jo(e){return{...e,surface:{...e.surface}}}function Mp(e){if(!Cn(e))return;const t=Ee(e,"machineId");if(t===void 0)return;const i=Pn(Ee(e,"tool")),s=Ap(Ee(e,"view"));return{machineId:t,projectId:Ee(e,"projectId"),workspaceId:Ee(e,"workspaceId"),sessionId:Ee(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Rp(e.surface)}}function Rp(e){return Cn(e)?{selectedFilePath:Ee(e,"selectedFilePath"),selectedDiffPath:Ee(e,"selectedDiffPath"),selectedTerminalId:Ee(e,"selectedTerminalId")}:{}}function Ap(e){return e==="navigation"||e==="chat"?e:Pn(e)}function Pn(e){return Ep(e)?e:void 0}function Ep(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ee(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Cn(e){return typeof e=="object"&&e!==null}const Dp="pi-web:terminal-selection:v1";class Wp{constructor(t=Et()){this.terminalIdsByCwd=new Ti(Dp,qs,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 Ab(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Eb(e){return e.find(t=>!t.exited)??e[0]}const In=1200,Op=["mod","alt","shift"];class _p{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Mn(t);if(o===void 0)return!1;const r=Ks(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!It(o))return!1}else if(!It(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Kp(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Vs(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},In)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Ks(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Lp(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(ws)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Np),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=zp(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:Zo(u),b=h?[...a.get(p)??[]].sort(ws).map(Zo):[];return{...p,active:h,shadows:b,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Ki(e){return Rn(e,{requireFirstChordActivator:!0})}function Tn(e){const t=Rn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Xt(e){return Tn(e).map(t=>t.split("+").map(En).join("+")).join(" ")}function Mn(e){if(e.isComposing)return;const t=Hp(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 It(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Lp(e,t,i){const s=jp(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Tn(o),n=r[0];if(!(n===void 0||!It(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Fp(r),order:i}}function jp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Fp(e){return e.join("\0")}function Zo(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ws(e,t){return Qo(e.source)-Qo(t.source)||Xo(e.action.id,t.action.id)||Xo(e.action.title,t.action.title)||e.order-t.order}function Np(e,t){return e.tokens.length-t.tokens.length||ws(e,t)}function zp(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Vs(e.tokens,i.tokens))}function Qo(e){switch(e){case"custom":return 0;case"default":return 1}}function Xo(e,t){return e<t?-1:e>t?1:0}function Rn(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Bp(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!It(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Bp(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=Up(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${En(n)} modifiers.`};i.add(n);continue}const a=An(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...Op.filter(r=>i.has(r)),s].join("+")}}function Up(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 An(e){const t=qp(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 Hp(e){if(e===" ")return"space";const t=e.toLowerCase();return An(t)}function qp(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 En(e){return e==="mod"?Yo()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Yo()?"⌥":"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 Kp(e,t){return e.length===t.length&&Vs(e,t)}function Vs(e,t){return t.every((i,s)=>e[s]===i)}function Yo(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Gs="themes:classic",Vp="themes:pi-web-dark",Gp={themeId:Vp,auto:!0},Dn="pi-web-app-theme",Jp=["--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"],Zp=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Qp(){try{const e=window.localStorage.getItem(Dn);return e===null?void 0:ih(e)}catch{return}}function Xp(e){try{window.localStorage.setItem(Dn,JSON.stringify(e))}catch{}}function Yp(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Jp){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function eh(e){const t=th(e.themes,e.fallbackThemeId??Gs),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=Wn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function th(e,t=Gs){return e.find(i=>i.id===t)??e[0]}function Wn(e,t){return e.find(i=>i.light===t||i.dark===t)}function ih(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return sh(i)?i:void 0}catch{return}}function sh(e){if(!oh(e))return!1;const t=e.themeId,i=e.auto;return rh(t)&&typeof i=="boolean"}function oh(e){return typeof e=="object"&&e!==null}function rh(e){return typeof e=="string"&&Zp.test(e)}const nh="management";function ah(e){return lh(ch())===nh}function lh(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function ch(){return typeof window>"u"?void 0:window.location.search}const dh="workspace.delete",ph="pi.operation",hh="target.workspaceId";function uh(e){return{...e===void 0?{}:{projectId:e},metadata:{[ph]:dh}}}function fh(e){const t={};for(const i of e){const s=ys(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function gh(e){return Object.entries(e).filter(([,t])=>hi(t)).map(([t])=>t)}function On(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&hi(i)}function ys(e){return e.metadata[hh]}function hi(e){return e.status==="queued"||e.status==="running"}function er(){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:gt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:tr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:gt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:gt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:tr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:gt,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:mh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:gt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:vh,run:e=>e.archiveSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:bh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Ci(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function gt(e){return e.state.selectedWorkspace!==void 0}function tr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function mh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!On(e.state,t)}function vh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Ce(t)}function bh(e){return Ce(e.state.selectedSession)}const wh="modulepreload",yh=function(e){return"/"+e},ir={},_n=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=yh(p),p in ir)return;ir[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":wh,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((b,P)=>{f.addEventListener("load",b),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},xh=10*1024*1024,Sh="10 MB";function kh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Yt(e)}function Yt(e){switch(e){case"navigation":return st`
|
|
19
|
+
`)}function zd(e,t){const i=zs(t);return i.length===0?e:[...e,...i]}function Bd(e,t){const i=e.at(-1);return t.role==="skill"&&yn(pi(i),pi(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Ud(e){return typeof e=="object"&&e!==null}function hi(e,t){return Ud(e)?e[t]:void 0}function qe(e,t){const i=hi(e,t);return typeof i=="string"?i:void 0}function Hd(e,t){const i=hi(e,t);return typeof i=="boolean"?i:void 0}const qd="pi-web:chat-history:v2:",Kd=1800*1e3;function Vd(e){try{const t=sessionStorage.getItem(bs(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Xd(i))return;if(Date.now()-i.savedAt>Kd){sessionStorage.removeItem(bs(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Gd(e,t){try{sessionStorage.setItem(bs(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Jd(e,t){if(e===void 0||!ws(e))return t;if(!ws(t))return e;if(Zd(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return qo(o,i,e),qo(o,i,t),Qd(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Zd(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Qd(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function qo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function bs(e){return`${qd}${e}`}function Xd(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&ws({messages:t,start:i,total:s})}function ws(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(Yd)}function Yd(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 ep={read:Vd,write:Gd};class tp{constructor(t=ep){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Ko(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Jd(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Ko(s)}applyLiveEvent(t,i){return Ad(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Ko(e){const t=e?.start??0;return{messages:rd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Hs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:xn(e).startsWith("/")?{kind:"command"}:sp(e)?{kind:"file"}:{kind:"normal"}}function ip(e){return Hs(e).kind==="shell"}function xn(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
20
|
+
`))+1;return e.slice(t)}function sp(e){const t=xn(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const o=e.slice(0,s);return o.endsWith("@")||o.endsWith("@ ")||o.endsWith("!@")}class op{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.sessionId=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),kn(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=Dc(this.sessionId,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Sn(t);rp(i)&&this.onEvent?.(i)}}class Vo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),kn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Wc(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Sn(t);ap(i)&&this.onEvent?.(i)}}function rp(e){const t=qs(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(t)}function np(e){const t=qs(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function ap(e){const t=qs(e);return np(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function qs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Sn(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 kn(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 Dt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Mi{constructor(t,i,s=Dt()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of lp(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Ks(e){return typeof e=="string"&&e!==""?e:void 0}function lp(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!cp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function cp(e){return!dp(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 dp(e){return typeof e=="object"&&e!==null}class pp{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 hp="pi-web:session-selection:v1";class up{constructor(t=Dt()){this.sessionIdsByCwd=new Mi(hp,Ks,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function fp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return mp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function gp(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function mp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function vp(e,t,i){return $n(e,[t],i)}function $n(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function bp(e,t,i){return Pn(e,t,[i])}function Pn(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const ft=100;class wp{constructor(t,i,s,o=new pp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new op,this.api=r.api??U,this.transcripts=r.transcripts??new tp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();gp(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Fo(s,i);const o=vs(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return fp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t.id,{limit:ft},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:ft},g(this.getState())),this.api.status(t.id,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Ce(t)&&$p(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.id,{before:t.messagePageStart,limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(typeof t=="string"){if(t.trim().startsWith("/"))return this.runCommand(t);if(ip(t))return this.runShell(t)}const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{await this.api.prompt(s.id,t,i,g(this.getState())),this.markCachedNewSessionPersisted(s)}catch(o){this.setState({error:String(o)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{await this.api.shell(i.id,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Ce(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,g(this.getState()));const i=this.getState(),s=vp(i.sessions,t.id,new Date().toISOString()),o=bp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Ce(t)))try{const i=await this.api.archiveWithDescendants(t.id,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=$n(o.sessions,s,new Date().toISOString()),n=Pn(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Ce(t))return;this.api.stop(t.id,g(this.getState())).catch(()=>{}),zo(t.id,g(this.getState())),Us(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t.id,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t.id,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t.id,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t.id,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(t,{limit:ft},g(this.getState())),this.api.status(t,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return fn(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);Fo(o,s),Id(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),zo(t.id,s);const r=vs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Ce(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(ed(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Te(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&di(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ci(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...xp(i,t.sessionId,t.messageCount),...s?{sessionActivities:yp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!t.isStreaming&&this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Sp(t))return}if(kp(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function yp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function xp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function Sp(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 kp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function $p(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Pp{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 Ip="pi-web:workspace-selection:v1";class Cp{constructor(t=Dt()){this.workspaceIdsByProject=new Mi(Ip,Ks,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Tp(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Mp{constructor(t,i,s,o,r=new Pp,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??U}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Qt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Ui(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Qt()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Tp(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Ui(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Ui(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Qt()});try{const o=Yc(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Ap(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Rp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Ap(e){return e.find(t=>t.isMain)??e[0]}const Ep="pi-web:machine-navigation:v1";class Dp{constructor(t=Dt()){this.snapshotsByMachine=new Mi(Ep,Op,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Zo(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Zo(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Wp(e){return{machineId:e,surface:{}}}function Go(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??un,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 Jo(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 Zo(e){return{...e,surface:{...e.surface}}}function Op(e){if(!Cn(e))return;const t=Ee(e,"machineId");if(t===void 0)return;const i=In(Ee(e,"tool")),s=Lp(Ee(e,"view"));return{machineId:t,projectId:Ee(e,"projectId"),workspaceId:Ee(e,"workspaceId"),sessionId:Ee(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:_p(e.surface)}}function _p(e){return Cn(e)?{selectedFilePath:Ee(e,"selectedFilePath"),selectedDiffPath:Ee(e,"selectedDiffPath"),selectedTerminalId:Ee(e,"selectedTerminalId")}:{}}function Lp(e){return e==="navigation"||e==="chat"?e:In(e)}function In(e){return jp(e)?e:void 0}function jp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ee(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Cn(e){return typeof e=="object"&&e!==null}const Np="pi-web:terminal-selection:v1";class Fp{constructor(t=Dt()){this.terminalIdsByCwd=new Mi(Np,Ks,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 Hb(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function qb(e){return e.find(t=>!t.exited)??e[0]}const Tn=1200,zp=["mod","alt","shift"];class Bp{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Rn(t);if(o===void 0)return!1;const r=Vs(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Tt(o))return!1}else if(!Tt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Xp(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Gs(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Tn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Vs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Up(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(ys)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Kp),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Vp(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:Qo(u),b=h?[...a.get(p)??[]].sort(ys).map(Qo):[];return{...p,active:h,shadows:b,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Vi(e){return An(e,{requireFirstChordActivator:!0})}function Mn(e){const t=An(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Yt(e){return Mn(e).map(t=>t.split("+").map(Dn).join("+")).join(" ")}function Rn(e){if(e.isComposing)return;const t=Zp(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 Tt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Up(e,t,i){const s=Hp(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Mn(o),n=r[0];if(!(n===void 0||!Tt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:qp(r),order:i}}function Hp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function qp(e){return e.join("\0")}function Qo(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ys(e,t){return Xo(e.source)-Xo(t.source)||Yo(e.action.id,t.action.id)||Yo(e.action.title,t.action.title)||e.order-t.order}function Kp(e,t){return e.tokens.length-t.tokens.length||ys(e,t)}function Vp(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Gs(e.tokens,i.tokens))}function Xo(e){switch(e){case"custom":return 0;case"default":return 1}}function Yo(e,t){return e<t?-1:e>t?1:0}function An(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Gp(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Tt(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Gp(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=Jp(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Dn(n)} modifiers.`};i.add(n);continue}const a=En(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...zp.filter(r=>i.has(r)),s].join("+")}}function Jp(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function En(e){const t=Qp(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 Zp(e){if(e===" ")return"space";const t=e.toLowerCase();return En(t)}function Qp(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Dn(e){return e==="mod"?er()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?er()?"⌥":"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 Xp(e,t){return e.length===t.length&&Gs(e,t)}function Gs(e,t){return t.every((i,s)=>e[s]===i)}function er(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Js="themes:classic",Yp="themes:pi-web-dark",eh={themeId:Yp,auto:!0},Wn="pi-web-app-theme",th=["--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"],ih=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function sh(){try{const e=window.localStorage.getItem(Wn);return e===null?void 0:lh(e)}catch{return}}function oh(e){try{window.localStorage.setItem(Wn,JSON.stringify(e))}catch{}}function rh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of th){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function nh(e){const t=ah(e.themes,e.fallbackThemeId??Js),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=On(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function ah(e,t=Js){return e.find(i=>i.id===t)??e[0]}function On(e,t){return e.find(i=>i.light===t||i.dark===t)}function lh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return ch(i)?i:void 0}catch{return}}function ch(e){if(!dh(e))return!1;const t=e.themeId,i=e.auto;return ph(t)&&typeof i=="boolean"}function dh(e){return typeof e=="object"&&e!==null}function ph(e){return typeof e=="string"&&ih.test(e)}const hh="management";function uh(e){return fh(gh())===hh}function fh(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function gh(){return typeof window>"u"?void 0:window.location.search}const mh="workspace.delete",vh="pi.operation",bh="target.workspaceId";function wh(e){return{...e===void 0?{}:{projectId:e},metadata:{[vh]:mh}}}function yh(e){const t={};for(const i of e){const s=xs(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function xh(e){return Object.entries(e).filter(([,t])=>ui(t)).map(([t])=>t)}function _n(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&ui(i)}function xs(e){return e.metadata[bh]}function ui(e){return e.status==="queued"||e.status==="running"}function tr(){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:gt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:ir,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:gt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:gt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:ir,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:gt,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:Sh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:gt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:kh,run:e=>e.archiveSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:$h,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Ci(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function gt(e){return e.state.selectedWorkspace!==void 0}function ir(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Sh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!_n(e.state,t)}function kh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Ce(t)}function $h(e){return Ce(e.state.selectedSession)}const Ph="modulepreload",Ih=function(e){return"/"+e},sr={},Ln=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Ih(p),p in sr)return;sr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Ph,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((b,P)=>{f.addEventListener("load",b),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Ch=10*1024*1024,Th="10 MB";function Mh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ei(e)}function ei(e){switch(e){case"navigation":return st`
|
|
21
21
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
22
22
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
23
23
|
<path d="M10 7h8"></path>
|
|
@@ -51,53 +51,53 @@ ${o.join(`
|
|
|
51
51
|
<path d="m7 10 3 3-3 3"></path>
|
|
52
52
|
<path d="M12 16h5"></path>
|
|
53
53
|
</svg>
|
|
54
|
-
`}}function
|
|
54
|
+
`}}function or(){return[{id:"workspace.files",title:"文件",icon:ei("files"),order:10,render:Rh},{id:"workspace.git",title:"Git",icon:ei("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:zh},{id:"workspace.terminal",title:"终端",icon:ei("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Fh}]}function Rh(e){const t=e.machine.kind==="local";return l`
|
|
55
55
|
<section class="toolbar">
|
|
56
56
|
<strong>文件</strong>
|
|
57
57
|
${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
|
|
58
58
|
<div class="toolbar-actions">
|
|
59
59
|
<button @click=${e.onRefreshFiles}>刷新</button>
|
|
60
|
-
<button @click=${()=>{
|
|
61
|
-
<button @click=${()=>{
|
|
60
|
+
<button @click=${()=>{Eh(e)}}>新建文件</button>
|
|
61
|
+
<button @click=${()=>{Dh(e)}}>新建目录</button>
|
|
62
62
|
${e.selectedFilePath===void 0?null:l`
|
|
63
|
-
${
|
|
64
|
-
<button @click=${()=>{
|
|
65
|
-
<button class="danger" @click=${()=>{
|
|
63
|
+
${Wt(e)==="file"?l`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
|
|
64
|
+
<button @click=${()=>{Wh(e)}}>移动</button>
|
|
65
|
+
<button class="danger" @click=${()=>{Oh(e)}}>删除</button>
|
|
66
66
|
`}
|
|
67
67
|
${t?l`
|
|
68
68
|
<label class="file-upload-button">
|
|
69
69
|
上传
|
|
70
|
-
<input type="file" multiple @change=${i=>{
|
|
70
|
+
<input type="file" multiple @change=${i=>{Ah(e,i)}} />
|
|
71
71
|
</label>
|
|
72
72
|
`:l`<span class="file-upload-button disabled" title="远端机器暂不支持上传" aria-disabled="true">上传</span>`}
|
|
73
73
|
</div>
|
|
74
74
|
</section>
|
|
75
75
|
<section class="split">
|
|
76
76
|
<div class="list tree">
|
|
77
|
-
${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>
|
|
77
|
+
${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>jn(e,i,0))}
|
|
78
78
|
</div>
|
|
79
79
|
<div class="viewer">
|
|
80
|
-
${
|
|
80
|
+
${jh(e)}
|
|
81
81
|
</div>
|
|
82
82
|
</section>
|
|
83
|
-
`}function
|
|
84
|
-
<button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{
|
|
83
|
+
`}function Ah(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function Eh(e){const t=window.prompt("新建文件路径",Nn(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function Dh(e){const t=window.prompt("新建目录路径",Nn(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function Wh(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Wt(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function Oh(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Wt(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function jn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=e.selectedFilePath===t.path;return l`
|
|
84
|
+
<button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{_h(e,t)}}>
|
|
85
85
|
<span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
|
|
86
86
|
<span>${t.name}</span>
|
|
87
87
|
</button>
|
|
88
|
-
${o?s.map(n=>
|
|
89
|
-
`}function
|
|
88
|
+
${o?s.map(n=>jn(e,n,i+1)):null}
|
|
89
|
+
`}function _h(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Wt(e){const t=e.selectedFilePath;return t===void 0?"file":Lh(e,t)?.type??"file"}function Nn(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Wt(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Lh(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const o=s.find(r=>r.path===t);if(o!==void 0)return o}}function jh(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:Wt(e)==="directory"?l`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Nh(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Ss(t.size)}</p>`:(Fn(),l`
|
|
90
90
|
<div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
|
|
91
91
|
<code-viewer .content=${t.content} .language=${t.language}></code-viewer>
|
|
92
|
-
`)}function
|
|
92
|
+
`)}function Nh(e,t){const i=`${t.mimeType??"image"} · ${Ss(t.size)}`;if(t.size>Ch)return l`
|
|
93
93
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
94
|
-
<p class="muted">图片过大,无法预览:${
|
|
95
|
-
`;const s=
|
|
94
|
+
<p class="muted">图片过大,无法预览:${Ss(t.size)} · 限制 ${Th}</p>
|
|
95
|
+
`;const s=bc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
|
|
96
96
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
97
97
|
<div class="image-preview">
|
|
98
98
|
<img src=${s} alt=${t.path} decoding="async" />
|
|
99
99
|
</div>
|
|
100
|
-
`}function
|
|
100
|
+
`}function Fh(e){return Hh(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function zh(e){const t=e.gitStatus;return l`
|
|
101
101
|
<section class="toolbar">
|
|
102
102
|
<strong>Git</strong>
|
|
103
103
|
${e.gitStale?l`<span class="stale">过期</span>`:null}
|
|
@@ -106,29 +106,29 @@ ${o.join(`
|
|
|
106
106
|
<section class="split">
|
|
107
107
|
<div class="list">
|
|
108
108
|
${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
|
|
109
|
-
<p class="summary">${
|
|
109
|
+
<p class="summary">${qh(t)}</p>
|
|
110
110
|
${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
|
|
111
111
|
<button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
|
|
112
|
-
<span>${
|
|
112
|
+
<span>${Kh(i.index,i.workingTree)}</span>
|
|
113
113
|
<span>${i.path}</span>
|
|
114
114
|
</button>
|
|
115
115
|
`)}
|
|
116
116
|
`:l`<p class="muted">不是 Git 仓库。</p>`}
|
|
117
117
|
</div>
|
|
118
118
|
<div class="viewer">
|
|
119
|
-
${
|
|
119
|
+
${Bh(e)}
|
|
120
120
|
</div>
|
|
121
121
|
</section>
|
|
122
|
-
`}function
|
|
122
|
+
`}function Bh(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(o=>o.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
|
|
123
123
|
<div class=${s.length===1?"diffs single":"diffs"}>
|
|
124
|
-
${s.map(o=>
|
|
124
|
+
${s.map(o=>Uh(o))}
|
|
125
125
|
</div>
|
|
126
|
-
`}function
|
|
126
|
+
`}function Uh(e){return Fn(),l`
|
|
127
127
|
<section class="diff-section">
|
|
128
128
|
<div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
|
|
129
129
|
<code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
|
|
130
130
|
</section>
|
|
131
|
-
`}function Fn(){_n(()=>import("./CodeViewer-YNyWxbqH.js"),__vite__mapDeps([0,1,2,3]))}function jh(){_n(()=>import("./TerminalPanel-B9UStXy9.js"),__vite__mapDeps([4,5,6,1,2]))}function Fh(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 Nh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function xs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Vi(t)} KB`;const i=t/1024;return i<1024?`${Vi(i)} MB`:`${Vi(i/1024)} GB`}function Vi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const zh={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!ah();return{contributions:{actions:e?er():er().filter(t=>t.id!=="view.terminal"),workspacePanels:e?sr():sr().filter(t=>t.id!=="workspace.terminal")}}}},Bh={"--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"},Uh={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#3d4a78","--pi-selection-bg":"#151b31","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Hh={"--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"},qh={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Uh},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Hh},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Bh}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Kh=/^[a-z][a-z0-9.-]*$/u;function Vh(e){return Kh.test(e)}const Gh="machine.";function Jh(e,t){if(e==="")throw new Error("Machine id is required");if(!Vh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Gh}${Zh(e)}.${t}`}function Zh(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function or(e="/pi-web-plugins/manifest.json",t={}){const i=await Qh(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=Yh(n,r);s.push({id:t.machineId===void 0?o.id:Jh(t.machineId,o.id),plugin:a,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function Qh(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 Xh(await t.json())}}function Xh(e){if(!ui(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ui(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}})}}function Yh(e,t){if(!ui(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!eu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function eu(e){return ui(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ui(e){return typeof e=="object"&&e!==null}const tu=/^[a-z][a-z0-9.-]*$/u,iu=/^[a-z][a-z0-9.-]*$/u,Nn=new WeakMap,zn=new WeakMap;class su{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(au(t,this.gatewayPluginIds))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:st}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a));this.gatewayPluginIds.add(i)}}getActions(t){return this.actions.filter(i=>mt(i.machineId,cu(t),i.sourcePluginId,this.gatewayPluginIds)).map(i=>{const s=ou(t,i.pluginId),o=i.enabled?.(s),r={id:i.id,pluginId:i.pluginId,localId:i.localId,...i.machineId===void 0?{}:{machineId:i.machineId},title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(r.description=i.description),i.shortcut!==void 0&&(r.shortcut=i.shortcut),i.group!==void 0&&(r.group=i.group),o!==void 0&&(r.enabled=o),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(a?.(Gi(c,t))??!0),...n===void 0?{}:{badge:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?n(Gi(c,t)):void 0},render:c=>i.render(Gi(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(n?.(c)??!0),items:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}validatePluginId(t){if(!tu.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!iu.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function ou(e,t){return Nn.get(e)?.(t)??e}function Gi(e,t){return zn.get(e)?.(t)??e}function ru(e,t){return Nn.set(e,t),e}function nu(e,t){return zn.set(e,t),e}function au(e,t){return e.machineId!==void 0&&e.sourcePluginId!==void 0&&t.has(e.sourcePluginId)}function mt(e,t,i,s){return e===void 0||e===t&&!lu(i,s)}function lu(e,t){return e!==void 0&&t.has(e)}function cu(e){return e.state.selectedMachine?.id??"local"}const du=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function pu(){return typeof window>"u"||!("matchMedia"in window)?[]:du.map(e=>window.matchMedia(e))}function rr(e,t=hu()){return e.some(i=>i.matches)||uu(t)}function hu(){return typeof navigator>"u"?void 0:navigator}function uu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const fu=250;class gu{constructor(t=mu()){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()},fu)}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 mu(){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 vu="(max-width: 760px)";class bu{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=rr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??wu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??pu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new gu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=rr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function wu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(vu)}const fi=["machines","projects","workspaces","sessions"];function yu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Js(e,t){if(e!=="none")return e??yu(t)}function xu(e,t){return t.isMobileLayout?Js(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Su(e,t,i){return Js(e,i.state)===t?"none":t}function ku(e,t,i){return i?t:e}function $u(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Iu(i)}function Pu(e){return fi[fi.indexOf(e)+1]}class Cu{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Js(this.expanded,this.getState())}isCollapsed(t){return xu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Su(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections($u(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(ku(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Pu(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){Tu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Iu(e){const t=new Set(e);return fi.filter(i=>t.has(i))}function Tu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Mu{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Bn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Bn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ss="pi-web:panel-sizes:v1",Ru={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Au{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Zs(),this.panelSizes=Ou(this.storage)}hostConnected(){}constraints(t){return Wt(t)}panelWidth(t,i){return de(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=de(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=ju(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Fu(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(){_u(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${ar(de("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${ar(de("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Wt(e){return Ru[e]}function Eu(e,t,i){return e==="navigation"?i-t:t-i}function Du(e,t,i,s,o=Wt(e)){return de(e,t+Eu(e,i,s),o)}function Wu(e,t,i,s={}){const o=s.constraints??Wt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Nu(e,i,r);if(n!==void 0)return de(e,t+n,o)}function de(e,t,i=Wt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Ou(e=Zs()){try{const t=e?.getItem(Ss);if(t==null||t==="")return{};const i=JSON.parse(t);return Lu(i)}catch{return{}}}function _u(e,t=Zs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ss);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=de("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=de("workspace",e.workspacePanelWidth)),t.setItem(Ss,JSON.stringify(i))}catch{}}function Lu(e){if(!zu(e)||e.version!==1)return{};const t={},i=nr(e.navigationPanelWidth),s=nr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=de("navigation",i)),s!==void 0&&(t.workspacePanelWidth=de("workspace",s)),t}function nr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ju(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Fu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Nu(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 ar(e){return`${String(Math.round(e))}px`}function Zs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function zu(e){return typeof e=="object"&&e!==null}function lr(){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:Bu(e.get("tool")),view:Uu(e.get("view"))}}function Ji(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Bu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Uu(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Un(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function cr(){return Hu(new URLSearchParams(window.location.search).get("settings"))}function Zi(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function Hu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function qu(e,t){return t===void 0?e:e.map(i=>Vu(i,t))}function Ku(e,t){const i=new Set(Ks(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return qu(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Hn(s):s)}function Vu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Hn(e):{...e,shortcut:i}}function Hn(e){const t={...e};return delete t.shortcut,t}function Gu(e,t){const i=t.api??ot,s=t.pollIntervalMs??1e3,o=t.setTimeout??Zu(),r=t.clearTimeout??Qu();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:Ju(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Ju(e,t,i,s,o){return dr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&dr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function dr(e){return e.status==="succeeded"||e.status==="failed"}function Zu(){return(e,t)=>globalThis.setTimeout(e,t)}function Qu(){return e=>{globalThis.clearTimeout(e)}}function Xu(e,t){return t[e.path]}function Yu(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function ef(e,t,i){return Kn(tf(e,t,i))}function qn(e){return Kn(Object.values(e??{}))}function Kn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function tf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Bt=0,sf=120;function Ot(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Vn():of(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Bt,f=i.top-c-Bt;return[...h<sf&&f>h?[`bottom: ${tt(r-i.top+Bt)};`,`max-height: ${tt(Math.max(0,f))};`]:[`top: ${tt(i.bottom+Bt)};`,`max-height: ${tt(Math.max(0,h))};`],`right: ${tt(Math.max(0,o-u))};`,`max-width: ${tt(Math.max(0,u-n))};`].join(" ")}function of(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vn()}function Vn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function tt(e){return`${String(Math.round(e))}px`}function Gn(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Mi(e,t="Active"){const i=Gn(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const rf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Jn(e){return e.composedPath().some(t=>nf(t,rf))}function nf(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 Ri(e,t){Jn(e)||t()}function Ai(e,t){return Jn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?ze(e,()=>{pr(e.currentTarget,-1)}):e.key==="ArrowDown"?ze(e,()=>{pr(e.currentTarget,1)}):e.key==="Home"?ze(e,()=>{hr(e.currentTarget,0)}):e.key==="End"?ze(e,()=>{hr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?ze(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?ze(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?ze(e,t.cancel):!1}function Ei(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 ze(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function pr(e,t){const i=Qn(e),s=Xn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Zn(i,o+t)}function hr(e,t){const i=Qn(e);i.length!==0&&Zn(i,t<0?i.length-1:t)}function Zn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Qn(e){const t=Xn(e)?.getRootNode();return t===void 0||!af(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function af(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Xn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const lf=A`
|
|
131
|
+
`}function Fn(){Ln(()=>import("./CodeViewer-DzeGsHZ5.js"),__vite__mapDeps([0,1,2,3]))}function Hh(){Ln(()=>import("./TerminalPanel-BghODb4T.js"),__vite__mapDeps([4,5,6,1,2]))}function qh(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 Kh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Ss(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`${Gi(t)} KB`;const i=t/1024;return i<1024?`${Gi(i)} MB`:`${Gi(i/1024)} GB`}function Gi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Vh={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!uh();return{contributions:{actions:e?tr():tr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?or():or().filter(t=>t.id!=="workspace.terminal")}}}},Gh={"--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"},Jh={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#3d4a78","--pi-selection-bg":"#151b31","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Zh={"--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"},Qh={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Jh},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Zh},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Gh}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Xh=/^[a-z][a-z0-9.-]*$/u;function Yh(e){return Xh.test(e)}const eu="machine.";function tu(e,t){if(e==="")throw new Error("Machine id is required");if(!Yh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${eu}${iu(e)}.${t}`}function iu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function rr(e="/pi-web-plugins/manifest.json",t={}){const i=await su(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=ru(n,r);s.push({id:t.machineId===void 0?o.id:tu(t.machineId,o.id),plugin:a,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function su(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 ou(await t.json())}}function ou(e){if(!fi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!fi(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}})}}function ru(e,t){if(!fi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nu(e){return fi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function fi(e){return typeof e=="object"&&e!==null}const au=/^[a-z][a-z0-9.-]*$/u,lu=/^[a-z][a-z0-9.-]*$/u,zn=new WeakMap,Bn=new WeakMap;class cu{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(uu(t,this.gatewayPluginIds))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:st}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a));this.gatewayPluginIds.add(i)}}getActions(t){return this.actions.filter(i=>mt(i.machineId,gu(t),i.sourcePluginId,this.gatewayPluginIds)).map(i=>{const s=du(t,i.pluginId),o=i.enabled?.(s),r={id:i.id,pluginId:i.pluginId,localId:i.localId,...i.machineId===void 0?{}:{machineId:i.machineId},title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(r.description=i.description),i.shortcut!==void 0&&(r.shortcut=i.shortcut),i.group!==void 0&&(r.group=i.group),o!==void 0&&(r.enabled=o),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(a?.(Ji(c,t))??!0),...n===void 0?{}:{badge:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?n(Ji(c,t)):void 0},render:c=>i.render(Ji(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(n?.(c)??!0),items:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}validatePluginId(t){if(!au.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lu.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function du(e,t){return zn.get(e)?.(t)??e}function Ji(e,t){return Bn.get(e)?.(t)??e}function pu(e,t){return zn.set(e,t),e}function hu(e,t){return Bn.set(e,t),e}function uu(e,t){return e.machineId!==void 0&&e.sourcePluginId!==void 0&&t.has(e.sourcePluginId)}function mt(e,t,i,s){return e===void 0||e===t&&!fu(i,s)}function fu(e,t){return e!==void 0&&t.has(e)}function gu(e){return e.state.selectedMachine?.id??"local"}const mu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vu(){return typeof window>"u"||!("matchMedia"in window)?[]:mu.map(e=>window.matchMedia(e))}function nr(e,t=bu()){return e.some(i=>i.matches)||wu(t)}function bu(){return typeof navigator>"u"?void 0:navigator}function wu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yu=250;class xu{constructor(t=Su()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},yu)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Su(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const ku="(max-width: 760px)";class $u{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=nr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Pu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new xu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=nr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Pu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(ku)}const gi=["machines","projects","workspaces","sessions"];function Iu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Zs(e,t){if(e!=="none")return e??Iu(t)}function Cu(e,t){return t.isMobileLayout?Zs(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Tu(e,t,i){return Zs(e,i.state)===t?"none":t}function Mu(e,t,i){return i?t:e}function Ru(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Du(i)}function Au(e){return gi[gi.indexOf(e)+1]}class Eu{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Zs(this.expanded,this.getState())}isCollapsed(t){return Cu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Tu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Ru(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Mu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Au(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Wu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Du(e){const t=new Set(e);return gi.filter(i=>t.has(i))}function Wu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Ou{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",Un(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Un(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const ks="pi-web:panel-sizes:v1",_u={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Lu{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Qs(),this.panelSizes=zu(this.storage)}hostConnected(){}constraints(t){return Ot(t)}panelWidth(t,i){return de(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=de(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Hu(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=qu(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Bu(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${lr(de("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${lr(de("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ot(e){return _u[e]}function ju(e,t,i){return e==="navigation"?i-t:t-i}function Nu(e,t,i,s,o=Ot(e)){return de(e,t+ju(e,i,s),o)}function Fu(e,t,i,s={}){const o=s.constraints??Ot(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Ku(e,i,r);if(n!==void 0)return de(e,t+n,o)}function de(e,t,i=Ot(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function zu(e=Qs()){try{const t=e?.getItem(ks);if(t==null||t==="")return{};const i=JSON.parse(t);return Uu(i)}catch{return{}}}function Bu(e,t=Qs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ks);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=de("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=de("workspace",e.workspacePanelWidth)),t.setItem(ks,JSON.stringify(i))}catch{}}function Uu(e){if(!Vu(e)||e.version!==1)return{};const t={},i=ar(e.navigationPanelWidth),s=ar(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=de("navigation",i)),s!==void 0&&(t.workspacePanelWidth=de("workspace",s)),t}function ar(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hu(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function qu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ku(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function lr(e){return`${String(Math.round(e))}px`}function Qs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vu(e){return typeof e=="object"&&e!==null}function cr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Gu(e.get("tool")),view:Ju(e.get("view"))}}function Zi(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Gu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Hn(e)?e:void 0}function Ju(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Hn(e)?e:void 0}function Hn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function dr(){return Zu(new URLSearchParams(window.location.search).get("settings"))}function Qi(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function Zu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Qu(e,t){return t===void 0?e:e.map(i=>Yu(i,t))}function Xu(e,t){const i=new Set(Vs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Qu(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?qn(s):s)}function Yu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?qn(e):{...e,shortcut:i}}function qn(e){const t={...e};return delete t.shortcut,t}function ef(e,t){const i=t.api??ot,s=t.pollIntervalMs??1e3,o=t.setTimeout??sf(),r=t.clearTimeout??of();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:tf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function tf(e,t,i,s,o){return pr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&pr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function pr(e){return e.status==="succeeded"||e.status==="failed"}function sf(){return(e,t)=>globalThis.setTimeout(e,t)}function of(){return e=>{globalThis.clearTimeout(e)}}function rf(e,t){return t[e.path]}function nf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function af(e,t,i){return Vn(lf(e,t,i))}function Kn(e){return Vn(Object.values(e??{}))}function Vn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function lf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Ut=0,cf=120;function _t(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Gn():df(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ut,f=i.top-c-Ut;return[...h<cf&&f>h?[`bottom: ${tt(r-i.top+Ut)};`,`max-height: ${tt(Math.max(0,f))};`]:[`top: ${tt(i.bottom+Ut)};`,`max-height: ${tt(Math.max(0,h))};`],`right: ${tt(Math.max(0,o-u))};`,`max-width: ${tt(Math.max(0,u-n))};`].join(" ")}function df(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Gn()}function Gn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function tt(e){return`${String(Math.round(e))}px`}function Jn(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Ri(e,t="Active"){const i=Jn(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const pf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Zn(e){return e.composedPath().some(t=>hf(t,pf))}function hf(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Ai(e,t){Zn(e)||t()}function Ei(e,t){return Zn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?ze(e,()=>{hr(e.currentTarget,-1)}):e.key==="ArrowDown"?ze(e,()=>{hr(e.currentTarget,1)}):e.key==="Home"?ze(e,()=>{ur(e.currentTarget,0)}):e.key==="End"?ze(e,()=>{ur(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?ze(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?ze(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?ze(e,t.cancel):!1}function Di(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function ze(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function hr(e,t){const i=Xn(e),s=Yn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Qn(i,o+t)}function ur(e,t){const i=Xn(e);i.length!==0&&Qn(i,t<0?i.length-1:t)}function Qn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Xn(e){const t=Yn(e)?.getRootNode();return t===void 0||!uf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function uf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Yn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ff=A`
|
|
132
132
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
133
133
|
: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; }
|
|
134
134
|
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
@@ -226,7 +226,7 @@ ${o.join(`
|
|
|
226
226
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
227
227
|
.empty { margin: auto; color: var(--pi-muted); }
|
|
228
228
|
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
229
|
-
`,
|
|
229
|
+
`,gf=A`
|
|
230
230
|
: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; }
|
|
231
231
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
232
232
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -285,7 +285,7 @@ ${o.join(`
|
|
|
285
285
|
.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); }
|
|
286
286
|
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; }
|
|
287
287
|
p { margin: 10px; }
|
|
288
|
-
`,
|
|
288
|
+
`,Wi=A`
|
|
289
289
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
290
290
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
291
291
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -347,7 +347,7 @@ ${o.join(`
|
|
|
347
347
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
348
348
|
.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; }
|
|
349
349
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
350
|
-
`,
|
|
350
|
+
`,mf=A`
|
|
351
351
|
:host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
352
352
|
.chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
353
353
|
.chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
|
|
@@ -420,6 +420,8 @@ ${o.join(`
|
|
|
420
420
|
formatted-text.part { display: block; }
|
|
421
421
|
.part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
|
|
422
422
|
.part + .part { margin-top: 10px; }
|
|
423
|
+
.chat-image { margin: 0; }
|
|
424
|
+
.chat-image img { display: block; max-width: min(100%, 420px); max-height: 320px; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background: var(--pi-bg); }
|
|
423
425
|
.tool-line { color: var(--pi-warning); }
|
|
424
426
|
.summary { color: var(--pi-muted); margin-left: 6px; }
|
|
425
427
|
.part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
|
|
@@ -431,7 +433,7 @@ ${o.join(`
|
|
|
431
433
|
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
432
434
|
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
|
|
433
435
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
434
|
-
`,
|
|
436
|
+
`,vf=A`
|
|
435
437
|
:host { display: block; }
|
|
436
438
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
437
439
|
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -456,7 +458,7 @@ ${o.join(`
|
|
|
456
458
|
table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
|
|
457
459
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
458
460
|
th { background: var(--pi-surface); }
|
|
459
|
-
`,
|
|
461
|
+
`,bf=A`
|
|
460
462
|
:host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
|
|
461
463
|
.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; }
|
|
462
464
|
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -466,7 +468,7 @@ ${o.join(`
|
|
|
466
468
|
.activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
467
469
|
.muted { color: var(--pi-dim); }
|
|
468
470
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
469
|
-
`,
|
|
471
|
+
`,wf=A`
|
|
470
472
|
:host { display: block; }
|
|
471
473
|
.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); }
|
|
472
474
|
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; }
|
|
@@ -474,7 +476,7 @@ ${o.join(`
|
|
|
474
476
|
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
475
477
|
span { color: var(--pi-muted); font-size: 12px; }
|
|
476
478
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
477
|
-
`,
|
|
479
|
+
`,ea=A`
|
|
478
480
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
479
481
|
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
480
482
|
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; }
|
|
@@ -488,7 +490,7 @@ ${o.join(`
|
|
|
488
490
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
489
491
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
490
492
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
491
|
-
`,
|
|
493
|
+
`,yf=A`
|
|
492
494
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
493
495
|
.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; }
|
|
494
496
|
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; }
|
|
@@ -506,7 +508,7 @@ ${o.join(`
|
|
|
506
508
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
507
509
|
kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
|
|
508
510
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
509
|
-
`,
|
|
511
|
+
`,xf=A`
|
|
510
512
|
:host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
511
513
|
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
|
|
512
514
|
footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
@@ -514,6 +516,13 @@ ${o.join(`
|
|
|
514
516
|
.actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
|
|
515
517
|
.compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
|
|
516
518
|
.compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
519
|
+
.image-attachments { display: flex; gap: 8px; min-width: 0; overflow-x: auto; padding-bottom: 2px; }
|
|
520
|
+
.image-attachment { position: relative; flex: 0 0 auto; width: 116px; margin: 0; display: grid; grid-template-rows: 72px auto; gap: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 6px; box-sizing: border-box; }
|
|
521
|
+
.image-attachment img { width: 100%; height: 72px; object-fit: cover; border-radius: 5px; background: var(--pi-bg); }
|
|
522
|
+
.image-attachment figcaption { min-width: 0; display: grid; gap: 1px; color: var(--pi-muted); font-size: 11px; line-height: 1.2; }
|
|
523
|
+
.image-attachment figcaption span, .image-attachment figcaption small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
524
|
+
.image-attachment button { position: absolute; top: 3px; right: 3px; width: 22px; height: 22px; display: grid; place-items: center; padding: 0; border-radius: 999px; background: var(--pi-bg-overlay); }
|
|
525
|
+
.input-notice { color: var(--pi-warning); font-size: 12px; line-height: 1.3; }
|
|
517
526
|
.select-model { max-width: min(42vw, 320px); }
|
|
518
527
|
.select-thinking { max-width: 110px; }
|
|
519
528
|
textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
|
|
@@ -525,8 +534,10 @@ ${o.join(`
|
|
|
525
534
|
.markdown-editor .cm-focused { outline: none; }
|
|
526
535
|
.shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
|
|
527
536
|
.mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
|
|
528
|
-
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
529
|
-
button
|
|
537
|
+
button, .image-input-button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
538
|
+
.image-input-button { display: inline-flex; align-items: center; gap: 5px; }
|
|
539
|
+
.image-input-button input { display: none; }
|
|
540
|
+
button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor, .image-input-button.disabled { opacity: .5; cursor: not-allowed; }
|
|
530
541
|
@media (max-width: 640px) {
|
|
531
542
|
footer { gap: 8px; padding: 8px; }
|
|
532
543
|
.actions { gap: 6px; }
|
|
@@ -540,7 +551,7 @@ ${o.join(`
|
|
|
540
551
|
.select-thinking { max-width: 70px; }
|
|
541
552
|
button { padding: 5px 7px; }
|
|
542
553
|
}
|
|
543
|
-
`;var
|
|
554
|
+
`;var Sf=Object.defineProperty,kf=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?kf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sf(t,i,o),o};let J=class extends T{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
544
555
|
<section>
|
|
545
556
|
<h2>${this.renderHeading()}</h2>
|
|
546
557
|
${this.collapsed?null:l`
|
|
@@ -549,12 +560,12 @@ ${o.join(`
|
|
|
549
560
|
</div>
|
|
550
561
|
`}
|
|
551
562
|
</section>
|
|
552
|
-
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=
|
|
563
|
+
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=ta(e)&&this.onRemove!==void 0;return l`
|
|
553
564
|
<div
|
|
554
565
|
class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
|
|
555
566
|
tabindex="0"
|
|
556
567
|
title=${e.baseUrl??e.name}
|
|
557
|
-
@click=${o=>{
|
|
568
|
+
@click=${o=>{Ai(o,()=>this.onSelect?.(e))}}
|
|
558
569
|
@keydown=${o=>{this.handleMachineKeydown(o,e)}}
|
|
559
570
|
>
|
|
560
571
|
<div class="action-main">
|
|
@@ -562,7 +573,7 @@ ${o.join(`
|
|
|
562
573
|
</div>
|
|
563
574
|
${s?this.renderMachineMenu(e):null}
|
|
564
575
|
</div>
|
|
565
|
-
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=
|
|
576
|
+
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Kn(this.activities[e.id]);return Ri(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=$f(e.id);return l`
|
|
566
577
|
<div class="action-menu">
|
|
567
578
|
<button
|
|
568
579
|
class="action-menu-toggle"
|
|
@@ -578,13 +589,13 @@ ${o.join(`
|
|
|
578
589
|
</div>
|
|
579
590
|
`:null}
|
|
580
591
|
</div>
|
|
581
|
-
`}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>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=
|
|
592
|
+
`}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>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=_t(t),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Ei(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[Wi,A`
|
|
582
593
|
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
583
594
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
584
595
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
585
596
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
586
597
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
587
|
-
`];oe([d({attribute:!1})],J.prototype,"machines",2);oe([d({attribute:!1})],J.prototype,"selected",2);oe([d({attribute:!1})],J.prototype,"statuses",2);oe([d({attribute:!1})],J.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);oe([d({attribute:!1})],J.prototype,"onSelect",2);oe([d({attribute:!1})],J.prototype,"onRemove",2);oe([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);oe([d({attribute:!1})],J.prototype,"onFocusNextSection",2);oe([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);oe([w()],J.prototype,"openMenuMachineId",2);oe([w()],J.prototype,"menuStyle",2);J=oe([R("machine-list")],J);function
|
|
598
|
+
`];oe([d({attribute:!1})],J.prototype,"machines",2);oe([d({attribute:!1})],J.prototype,"selected",2);oe([d({attribute:!1})],J.prototype,"statuses",2);oe([d({attribute:!1})],J.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);oe([d({attribute:!1})],J.prototype,"onSelect",2);oe([d({attribute:!1})],J.prototype,"onRemove",2);oe([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);oe([d({attribute:!1})],J.prototype,"onFocusNextSection",2);oe([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);oe([w()],J.prototype,"openMenuMachineId",2);oe([w()],J.prototype,"menuStyle",2);J=oe([R("machine-list")],J);function ta(e){return e.kind==="remote"}function $f(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Pf=Object.defineProperty,If=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?If(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pf(t,i,o),o};let V=class extends T{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
588
599
|
<section>
|
|
589
600
|
<h2>${this.renderHeading()}</h2>
|
|
590
601
|
${this.collapsed?null:l`
|
|
@@ -599,7 +610,7 @@ ${o.join(`
|
|
|
599
610
|
class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
|
|
600
611
|
tabindex="0"
|
|
601
612
|
title=${e.path}
|
|
602
|
-
@click=${t=>{
|
|
613
|
+
@click=${t=>{Ai(t,()=>this.onSelect?.(e))}}
|
|
603
614
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
604
615
|
>
|
|
605
616
|
<div class="action-main">
|
|
@@ -619,19 +630,19 @@ ${o.join(`
|
|
|
619
630
|
</div>
|
|
620
631
|
`}
|
|
621
632
|
</section>
|
|
622
|
-
`}handleProjectKeydown(e,t){
|
|
633
|
+
`}handleProjectKeydown(e,t){Ei(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=af(e,this.workspacesByProjectId[e.id]??[],this.activities);return Ri(t,t==="terminal"?"项目终端活跃":"项目活跃")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=_t(t),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
|
|
623
634
|
|
|
624
|
-
这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};
|
|
635
|
+
这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};V.styles=Wi;Y([d({attribute:!1})],V.prototype,"projects",2);Y([d({attribute:!1})],V.prototype,"selected",2);Y([d({attribute:!1})],V.prototype,"activities",2);Y([d({attribute:!1})],V.prototype,"workspacesByProjectId",2);Y([d({type:Boolean,reflect:!0})],V.prototype,"collapsible",2);Y([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);Y([d({attribute:!1})],V.prototype,"onSelect",2);Y([d({attribute:!1})],V.prototype,"onClose",2);Y([d({attribute:!1})],V.prototype,"onToggleCollapsed",2);Y([d({attribute:!1})],V.prototype,"onFocusPreviousSection",2);Y([d({attribute:!1})],V.prototype,"onFocusNextSection",2);Y([d({attribute:!1})],V.prototype,"onCancelKeyboardNavigation",2);Y([w()],V.prototype,"openMenuProjectId",2);Y([w()],V.prototype,"menuStyle",2);V=Y([R("project-list")],V);function fr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Cf(t)}`)}function Cf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Tf(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 Tf(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Mf=Object.defineProperty,Rf=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mf(t,i,o),o};let q=class extends T{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
625
636
|
<section>
|
|
626
637
|
<h2>${this.renderHeading()}</h2>
|
|
627
638
|
${this.collapsed?null:l`
|
|
628
639
|
<div class="list-body">
|
|
629
|
-
${this.workspaces.map(e=>{const t=
|
|
640
|
+
${this.workspaces.map(e=>{const t=Af(e),i=this.workspaceLabelItems(e);return l`
|
|
630
641
|
<div
|
|
631
642
|
class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
|
|
632
643
|
tabindex="0"
|
|
633
644
|
title=${t}
|
|
634
|
-
@click=${s=>{
|
|
645
|
+
@click=${s=>{Ai(s,()=>this.onSelect?.(e))}}
|
|
635
646
|
@keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
|
|
636
647
|
>
|
|
637
648
|
<div class="action-main">
|
|
@@ -643,18 +654,18 @@ ${o.join(`
|
|
|
643
654
|
</div>
|
|
644
655
|
`}
|
|
645
656
|
</section>
|
|
646
|
-
`}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=
|
|
657
|
+
`}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=nf(rf(e,this.activities));return Ri(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
|
|
647
658
|
<span class="workspace-primary">
|
|
648
659
|
<span class="workspace-primary-label">${e}</span>
|
|
649
660
|
${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
|
|
650
661
|
</span>
|
|
651
662
|
${t.length===0?null:l`
|
|
652
663
|
<small class="workspace-secondary">
|
|
653
|
-
<span class="workspace-label">${
|
|
664
|
+
<span class="workspace-label">${fr(t)}</span>
|
|
654
665
|
</small>
|
|
655
666
|
`}
|
|
656
667
|
${this.renderActivity(i)}
|
|
657
|
-
`}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=
|
|
668
|
+
`}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Df(i.id);return l`
|
|
658
669
|
<div class="action-menu">
|
|
659
670
|
<button
|
|
660
671
|
class="action-menu-toggle"
|
|
@@ -671,7 +682,7 @@ ${o.join(`
|
|
|
671
682
|
</div>
|
|
672
683
|
`:null}
|
|
673
684
|
</div>
|
|
674
|
-
`}renderWorkspaceActions(e){if(!
|
|
685
|
+
`}renderWorkspaceActions(e){if(!Ef(e))return;const t=this.isDeleting(e);return l`
|
|
675
686
|
<div class="workspace-menu-actions">
|
|
676
687
|
<button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
|
|
677
688
|
</div>
|
|
@@ -688,11 +699,11 @@ ${o.join(`
|
|
|
688
699
|
${t.length===0?null:l`
|
|
689
700
|
<div class="workspace-detail-row">
|
|
690
701
|
<dt>详情</dt>
|
|
691
|
-
<dd><span class="workspace-label">${
|
|
702
|
+
<dd><span class="workspace-label">${fr(t)}</span></dd>
|
|
692
703
|
</div>
|
|
693
704
|
`}
|
|
694
705
|
</dl>
|
|
695
|
-
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=
|
|
706
|
+
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=_t(t),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Ei(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=Wi;Z([d({attribute:!1})],q.prototype,"workspaces",2);Z([d({attribute:!1})],q.prototype,"selected",2);Z([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);Z([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);Z([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);Z([d({attribute:!1})],q.prototype,"activities",2);Z([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);Z([d({attribute:!1})],q.prototype,"onSelect",2);Z([d({attribute:!1})],q.prototype,"onDelete",2);Z([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);Z([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);Z([d({attribute:!1})],q.prototype,"onFocusNextSection",2);Z([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);Z([w()],q.prototype,"openMenuWorkspaceId",2);Z([w()],q.prototype,"menuStyle",2);q=Z([R("workspace-list")],q);function Af(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Ef(e){return e.isGitWorktree&&!e.isMain}function Df(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Wf=Object.defineProperty,Of=Object.getOwnPropertyDescriptor,O=(e,t,i,s)=>{for(var o=s>1?void 0:s?Of(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wf(t,i,o),o};function Xi(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let W=class extends T{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(i=>i.archived===!0)&&(this.archivedExpanded=!1);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,Di(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Lf(this.sessions),t=new Set(e.map(o=>o.session.id)),i=ia(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),s=_f(this.sessions);return l`
|
|
696
707
|
<section>
|
|
697
708
|
${this.renderHeading(e.length+i.length)}
|
|
698
709
|
${this.collapsed?null:l`
|
|
@@ -705,7 +716,7 @@ ${o.join(`
|
|
|
705
716
|
</div>
|
|
706
717
|
`}
|
|
707
718
|
</section>
|
|
708
|
-
`}renderHeading(e){if(!this.collapsible)return l`<h2>会话 <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`;const t=this.selected===void 0?"未选择会话":
|
|
719
|
+
`}renderHeading(e){if(!this.collapsible)return l`<h2>会话 <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`;const t=this.selected===void 0?"未选择会话":Xi(this.selected),i=this.selected?.path??t;return l`
|
|
709
720
|
<h2>
|
|
710
721
|
<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=${i}>${t}</small>`:null}</span><small class="section-count">${e}</small></button>
|
|
711
722
|
<button ?disabled=${!this.canStart} @click=${s=>{s.stopPropagation(),this.onStart?.()}}>+</button>
|
|
@@ -716,11 +727,11 @@ ${o.join(`
|
|
|
716
727
|
style=${`--depth:${String(s)}`}
|
|
717
728
|
tabindex="0"
|
|
718
729
|
title=${i.path}
|
|
719
|
-
@click=${o=>{
|
|
730
|
+
@click=${o=>{Ai(o,()=>this.onSelect?.(i))}}
|
|
720
731
|
@keydown=${o=>{this.handleSessionKeydown(o,i)}}
|
|
721
732
|
>
|
|
722
733
|
<div class="action-main">
|
|
723
|
-
<span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${
|
|
734
|
+
<span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Xi(i)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(i)}${String(i.messageCount)} 条消息</small>
|
|
724
735
|
${this.renderActivity(i)}
|
|
725
736
|
</div>
|
|
726
737
|
<div class="action-menu">
|
|
@@ -736,7 +747,7 @@ ${o.join(`
|
|
|
736
747
|
`:null}
|
|
737
748
|
</div>
|
|
738
749
|
</div>
|
|
739
|
-
`}handleSessionKeydown(e,t){Ai(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?.()}})}confirmArchiveWithDescendants(e,t){confirm(`归档“${Qi(e)}”及 ${String(t)} 个子会话?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ot(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Ce(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){if(!(Ce(e)||e.archived===!0))return Mi(Ci(this.statuses[e.id],this.activities[e.id])?"session":void 0,"会话活跃")}};D.styles=Di;O([d({attribute:!1})],D.prototype,"sessions",2);O([d({attribute:!1})],D.prototype,"statuses",2);O([d({attribute:!1})],D.prototype,"activities",2);O([d({attribute:!1})],D.prototype,"selected",2);O([d({type:Boolean})],D.prototype,"canStart",2);O([d({type:Boolean,reflect:!0})],D.prototype,"collapsible",2);O([d({type:Boolean,reflect:!0})],D.prototype,"collapsed",2);O([d({attribute:!1})],D.prototype,"onSelect",2);O([d({attribute:!1})],D.prototype,"onStart",2);O([d({attribute:!1})],D.prototype,"onToggleCollapsed",2);O([d({attribute:!1})],D.prototype,"onArchivedCollapsed",2);O([d({attribute:!1})],D.prototype,"onFocusPreviousSection",2);O([d({attribute:!1})],D.prototype,"onFocusNextSection",2);O([d({attribute:!1})],D.prototype,"onCancelKeyboardNavigation",2);O([w()],D.prototype,"openMenuSessionId",2);O([w()],D.prototype,"menuStyle",2);O([w()],D.prototype,"archivedExpanded",2);O([d({attribute:!1})],D.prototype,"onArchive",2);O([d({attribute:!1})],D.prototype,"onArchiveWithDescendants",2);O([d({attribute:!1})],D.prototype,"onRestore",2);O([d({attribute:!1})],D.prototype,"onDelete",2);O([d({attribute:!1})],D.prototype,"onDetachParent",2);D=O([R("session-list")],D);function Rf(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Af(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return ta(e.filter(s=>i.has(s.id)))}function ta(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const Qs={CHILD:2,ELEMENT:6},Xs=e=>(...t)=>({_$litDirective$:e,values:t});let Ys=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:Ef}=tl,fr=e=>e,gr=()=>document.createComment(""),vt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(gr(),o),n=s.insertBefore(gr(),o);i=new Ef(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=fr(c).nextSibling;fr(s).insertBefore(c,o),c=p}}}return i},Be=(e,t,i=e)=>(e._$AI(t,i),e),Df={},Wf=(e,t=Df)=>e._$AH=t,Of=e=>e._$AH,Xi=e=>{e._$AR(),e._$AA.remove()};const mr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},_f=Xs(class extends Ys{constructor(e){if(super(e),e.type!==Qs.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=Of(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,b=0,P=r.length-1;for(;h<=f&&b<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[b])c[b]=Be(o[h],r[b]),h++,b++;else if(a[f]===n[P])c[P]=Be(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Be(o[h],r[P]),vt(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[b])c[b]=Be(o[f],r[b]),vt(e,o[h],o[f]),f--,b++;else if(p===void 0&&(p=mr(n,b,P),u=mr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const z=u.get(n[b]),Xe=z!==void 0?o[z]:null;if(Xe===null){const dt=vt(e,o[h]);Be(dt,r[b]),c[b]=dt}else c[b]=Be(Xe,r[b]),vt(e,o[h],Xe),o[z]=null;b++}else Xi(o[f]),f--;else Xi(o[h]),h++;for(;b<=P;){const z=vt(e,c[P+1]);Be(z,r[b]),c[b++]=z}for(;h<=f;){const z=o[h++];z!==null&&Xi(z)}return this.ut=n,Wf(e,c),Fe}}),Lf="pi-web:chat-groups:",jf={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(vr(e));return t===null||t===""?void 0:Nf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(vr(e),JSON.stringify(t))}catch{}}};class Ff{constructor(t=jf){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&br(r,this.openGroupKeys)&&br(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function vr(e){return`${Lf}${e}`}function Nf(e){if(Array.isArray(e))return{open:Yi(e),closedDefaultOpen:[]};if(zf(e))return{open:Array.isArray(e.open)?Yi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Yi(e.closedDefaultOpen):[]}}function Yi(e){return e.filter(t=>typeof t=="string")}function br(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function zf(e){return typeof e=="object"&&e!==null}function Bf(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>wr(a,b)),u=a.parts.filter(b=>!wr(a,b)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...f},index:h})}}),n(),i}function Uf(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,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${Hf(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Hf(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function wr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const qf=30;function Kf(e,t){const i=Gf(Qf(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Vf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Jf(s,t.markerOffset);return}e.scrollTop=Zf(e.scrollHeight,t.distanceFromBottom)}function Gf(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function Jf(e,t){return e-t}function Zf(e,t){return Math.max(0,e-t)}function Qf(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const Xf=600,Yf=1;function eg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:tg(e)||ig(e)}function tg(e){return e.scrollTop<(e.topThreshold??Math.max(Xf,e.clientHeight))}function ig(e){return e.scrollHeight<=e.clientHeight+Yf}const sg="pi-web:chat-scroll:",og=180,rg=48,ng=2,ag={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)}},lg={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class cg{constructor(t=ag,i=lg){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=og){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=ng){if(t===""||i===void 0||!ts(i))return"skipped";try{if(sa(i,o)){const a={mode:"bottom"};return this.storage.setItem(es(t),JSON.stringify(a)),"saved"}const r=hg(i,s);if(r===void 0)return"skipped";const n=pg(i,r);return this.storage.setItem(es(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ts(i))return{status:"skipped"};const r=ug(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(es(t));if(i===null||i==="")return;const s=JSON.parse(i);return dg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function es(e){return`${sg}${e}`}function dg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function ts(e){return e.clientHeight>0&&e.scrollHeight>0}function ia(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function sa(e,t=rg){return ia(e)<t}function pg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:eo(t)??"",offset:t.getBoundingClientRect().top-i}}function hg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(eo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function yr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function ug(e,t){return e.find(i=>eo(i)===t)}function eo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var fg=Object.defineProperty,gg=Object.getOwnPropertyDescriptor,to=(e,t,i,s)=>{for(var o=s>1?void 0:s?gg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&fg(t,i,o),o};let Tt=class extends T{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=xr(this.positionPercent),t=xr(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
|
|
750
|
+
`}handleSessionKeydown(e,t){Ei(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?.()}})}confirmArchiveWithDescendants(e,t){confirm(`归档“${Xi(e)}”及 ${String(t)} 个子会话?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=_t(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Ce(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){if(!(Ce(e)||e.archived===!0))return Ri(Ci(this.statuses[e.id],this.activities[e.id])?"session":void 0,"会话活跃")}};W.styles=Wi;O([d({attribute:!1})],W.prototype,"sessions",2);O([d({attribute:!1})],W.prototype,"statuses",2);O([d({attribute:!1})],W.prototype,"activities",2);O([d({attribute:!1})],W.prototype,"selected",2);O([d({type:Boolean})],W.prototype,"canStart",2);O([d({type:Boolean,reflect:!0})],W.prototype,"collapsible",2);O([d({type:Boolean,reflect:!0})],W.prototype,"collapsed",2);O([d({attribute:!1})],W.prototype,"onSelect",2);O([d({attribute:!1})],W.prototype,"onStart",2);O([d({attribute:!1})],W.prototype,"onToggleCollapsed",2);O([d({attribute:!1})],W.prototype,"onArchivedCollapsed",2);O([d({attribute:!1})],W.prototype,"onFocusPreviousSection",2);O([d({attribute:!1})],W.prototype,"onFocusNextSection",2);O([d({attribute:!1})],W.prototype,"onCancelKeyboardNavigation",2);O([w()],W.prototype,"openMenuSessionId",2);O([w()],W.prototype,"menuStyle",2);O([w()],W.prototype,"archivedExpanded",2);O([d({attribute:!1})],W.prototype,"onArchive",2);O([d({attribute:!1})],W.prototype,"onArchiveWithDescendants",2);O([d({attribute:!1})],W.prototype,"onRestore",2);O([d({attribute:!1})],W.prototype,"onDelete",2);O([d({attribute:!1})],W.prototype,"onDetachParent",2);W=O([R("session-list")],W);function _f(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Lf(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return ia(e.filter(s=>i.has(s.id)))}function ia(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const Xs={CHILD:2,ELEMENT:6},Ys=e=>(...t)=>({_$litDirective$:e,values:t});let eo=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:jf}=rl,gr=e=>e,mr=()=>document.createComment(""),vt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(mr(),o),n=s.insertBefore(mr(),o);i=new jf(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=gr(c).nextSibling;gr(s).insertBefore(c,o),c=p}}}return i},Be=(e,t,i=e)=>(e._$AI(t,i),e),Nf={},Ff=(e,t=Nf)=>e._$AH=t,zf=e=>e._$AH,Yi=e=>{e._$AR(),e._$AA.remove()};const vr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Bf=Ys(class extends eo{constructor(e){if(super(e),e.type!==Xs.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=zf(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,b=0,P=r.length-1;for(;h<=f&&b<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[b])c[b]=Be(o[h],r[b]),h++,b++;else if(a[f]===n[P])c[P]=Be(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Be(o[h],r[P]),vt(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[b])c[b]=Be(o[f],r[b]),vt(e,o[h],o[f]),f--,b++;else if(p===void 0&&(p=vr(n,b,P),u=vr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const B=u.get(n[b]),Xe=B!==void 0?o[B]:null;if(Xe===null){const dt=vt(e,o[h]);Be(dt,r[b]),c[b]=dt}else c[b]=Be(Xe,r[b]),vt(e,o[h],Xe),o[B]=null;b++}else Yi(o[f]),f--;else Yi(o[h]),h++;for(;b<=P;){const B=vt(e,c[P+1]);Be(B,r[b]),c[b++]=B}for(;h<=f;){const B=o[h++];B!==null&&Yi(B)}return this.ut=n,Ff(e,c),Ne}}),Uf="pi-web:chat-groups:",Hf={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(br(e));return t===null||t===""?void 0:Kf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(br(e),JSON.stringify(t))}catch{}}};class qf{constructor(t=Hf){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&wr(r,this.openGroupKeys)&&wr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function br(e){return`${Uf}${e}`}function Kf(e){if(Array.isArray(e))return{open:es(e),closedDefaultOpen:[]};if(Vf(e))return{open:Array.isArray(e.open)?es(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?es(e.closedDefaultOpen):[]}}function es(e){return e.filter(t=>typeof t=="string")}function wr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Vf(e){return typeof e=="object"&&e!==null}function Gf(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>yr(a,b)),u=a.parts.filter(b=>!yr(a,b)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...f},index:h})}}),n(),i}function Jf(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,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${Zf(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Zf(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function yr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Qf=30;function Xf(e,t){const i=eg(sg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Yf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=tg(s,t.markerOffset);return}e.scrollTop=ig(e.scrollHeight,t.distanceFromBottom)}function eg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function tg(e,t){return e-t}function ig(e,t){return Math.max(0,e-t)}function sg(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const og=600,rg=1;function ng(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ag(e)||lg(e)}function ag(e){return e.scrollTop<(e.topThreshold??Math.max(og,e.clientHeight))}function lg(e){return e.scrollHeight<=e.clientHeight+rg}const cg="pi-web:chat-scroll:",dg=180,pg=48,hg=2,ug={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)}},fg={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class gg{constructor(t=ug,i=fg){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=dg){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=hg){if(t===""||i===void 0||!is(i))return"skipped";try{if(oa(i,o)){const a={mode:"bottom"};return this.storage.setItem(ts(t),JSON.stringify(a)),"saved"}const r=bg(i,s);if(r===void 0)return"skipped";const n=vg(i,r);return this.storage.setItem(ts(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!is(i))return{status:"skipped"};const r=wg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(ts(t));if(i===null||i==="")return;const s=JSON.parse(i);return mg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!is(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ts(e){return`${cg}${e}`}function mg(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 is(e){return e.clientHeight>0&&e.scrollHeight>0}function sa(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function oa(e,t=pg){return sa(e)<t}function vg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:to(t)??"",offset:t.getBoundingClientRect().top-i}}function bg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(to(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function xr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function wg(e,t){return e.find(i=>to(i)===t)}function to(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var yg=Object.defineProperty,xg=Object.getOwnPropertyDescriptor,io=(e,t,i,s)=>{for(var o=s>1?void 0:s?xg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&yg(t,i,o),o};let Mt=class extends T{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Sr(this.positionPercent),t=Sr(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
|
|
740
751
|
<div
|
|
741
752
|
class="meter"
|
|
742
753
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -752,19 +763,19 @@ ${o.join(`
|
|
|
752
763
|
<div class="marker"></div>
|
|
753
764
|
</div>
|
|
754
765
|
</div>
|
|
755
|
-
`}};
|
|
766
|
+
`}};Mt.styles=A`
|
|
756
767
|
:host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
|
|
757
768
|
:host(:hover), :host(:focus-within) { opacity: .92; }
|
|
758
769
|
.meter { height: 100%; }
|
|
759
770
|
.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); }
|
|
760
771
|
.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)); }
|
|
761
772
|
.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%); }
|
|
762
|
-
`;
|
|
763
|
-
]`).replace("lheading",
|
|
773
|
+
`;io([d({type:Number})],Mt.prototype,"positionPercent",2);io([d({type:Number})],Mt.prototype,"loadedPercent",2);Mt=io([R("conversation-meter")],Mt);function Sr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class $s extends eo{constructor(t){if(super(t),this.it=_,t.type!==Xs.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===_||t==null)return this._t=void 0,this.it=t;if(t===Ne)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:[]}}}$s.directiveName="unsafeHTML",$s.resultType=1;const Sg=Ys($s);function so(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Je=so();function ra(e){Je=e}var Ue={exec:()=>null};function C(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var kg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={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:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},$g=/^(?:[ \t]*(?:\n|$))+/,Pg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ig=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Lt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,oo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,na=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,aa=C(na).replace(/bull/g,oo).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(),Tg=C(na).replace(/bull/g,oo).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(),ro=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Mg=/^[^\n]+/,no=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Rg=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",no).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ag=C(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,oo).getRegex(),Oi="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",ao=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Eg=C("^ {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",ao).replace("tag",Oi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),la=C(ro).replace("hr",Lt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Oi).getRegex(),Dg=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",la).getRegex(),lo={blockquote:Dg,code:Pg,def:Rg,fences:Ig,heading:Cg,hr:Lt,html:Eg,lheading:aa,list:Ag,newline:$g,paragraph:la,table:Ue,text:Mg},kr=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Lt).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",Oi).getRegex(),Wg={...lo,lheading:Tg,table:kr,paragraph:C(ro).replace("hr",Lt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",kr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Oi).getRegex()},Og={...lo,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ao).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:Ue,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(ro).replace("hr",Lt).replace("heading",` *#{1,6} *[^
|
|
774
|
+
]`).replace("lheading",aa).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_g=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Lg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ca=/^( {2,}|\\)\n(?!\s*$)/,jg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ct=/[\p{P}\p{S}]/u,_i=/[\s\p{P}\p{S}]/u,co=/[^\s\p{P}\p{S}]/u,Ng=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_i).getRegex(),da=/(?!~)[\p{P}\p{S}]/u,Fg=/(?!~)[\s\p{P}\p{S}]/u,zg=/(?:[^\s\p{P}\p{S}]|~)/u,Bg=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",kg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),pa=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ug=C(pa,"u").replace(/punct/g,ct).getRegex(),Hg=C(pa,"u").replace(/punct/g,da).getRegex(),ha="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",qg=C(ha,"gu").replace(/notPunctSpace/g,co).replace(/punctSpace/g,_i).replace(/punct/g,ct).getRegex(),Kg=C(ha,"gu").replace(/notPunctSpace/g,zg).replace(/punctSpace/g,Fg).replace(/punct/g,da).getRegex(),Vg=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,co).replace(/punctSpace/g,_i).replace(/punct/g,ct).getRegex(),Gg=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ct).getRegex(),Jg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Zg=C(Jg,"gu").replace(/notPunctSpace/g,co).replace(/punctSpace/g,_i).replace(/punct/g,ct).getRegex(),Qg=C(/\\(punct)/,"gu").replace(/punct/g,ct).getRegex(),Xg=C(/^<(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(),Yg=C(ao).replace("(?:-->|$)","-->").getRegex(),em=C("^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",Yg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),mi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,tm=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",mi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ua=C(/^!?\[(label)\]\[(ref)\]/).replace("label",mi).replace("ref",no).getRegex(),fa=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",no).getRegex(),im=C("reflink|nolink(?!\\()","g").replace("reflink",ua).replace("nolink",fa).getRegex(),$r=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,po={_backpedal:Ue,anyPunctuation:Qg,autolink:Xg,blockSkip:Bg,br:ca,code:Lg,del:Ue,delLDelim:Ue,delRDelim:Ue,emStrongLDelim:Ug,emStrongRDelimAst:qg,emStrongRDelimUnd:Vg,escape:_g,link:tm,nolink:fa,punctuation:Ng,reflink:ua,reflinkSearch:im,tag:em,text:jg,url:Ue},sm={...po,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",mi).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",mi).getRegex()},Ps={...po,emStrongRDelimAst:Kg,emStrongLDelim:Hg,delLDelim:Gg,delRDelim:Zg,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",$r).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:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",$r).getRegex()},om={...Ps,br:C(ca).replace("{2,}","*").getRegex(),text:C(Ps.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ht={normal:lo,gfm:Wg,pedantic:Og},bt={normal:po,gfm:Ps,breaks:om,pedantic:sm},rm={"&":"&","<":"<",">":">",'"':""","'":"'"},Pr=e=>rm[e];function Ie(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,Pr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,Pr);return e}function Ir(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Cr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(G.slashPipe,"|");return s}function Le(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Tr(e){let t=e.split(`
|
|
764
775
|
`),i=t.length-1;for(;i>=0&&G.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
|
|
765
|
-
`)}function
|
|
776
|
+
`)}function nm(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 am(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Mr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function lm(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
|
|
766
777
|
`).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
|
|
767
|
-
`)}var
|
|
778
|
+
`)}var vi=class{options;rules;lexer;constructor(e){this.options=e||Je}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]:Tr(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=lm(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=Le(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Le(t[0],`
|
|
768
779
|
`),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:Le(t[0],`
|
|
769
780
|
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Le(t[0],`
|
|
770
781
|
`).split(`
|
|
@@ -774,22 +785,22 @@ ${o.join(`
|
|
|
774
785
|
${p}`:p,o=o?`${o}
|
|
775
786
|
${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let b=f,P=b.raw+`
|
|
776
787
|
`+i.join(`
|
|
777
|
-
`),
|
|
788
|
+
`),B=this.blockquote(P);r[r.length-1]=B,s=s.substring(0,s.length-b.raw.length)+B.raw,o=o.substring(0,o.length-b.text.length)+B.text;break}else if(f?.type==="list"){let b=f,P=b.raw+`
|
|
778
789
|
`+i.join(`
|
|
779
|
-
`),
|
|
780
|
-
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=
|
|
790
|
+
`),B=this.list(P);r[r.length-1]=B,s=s.substring(0,s.length-f.raw.length)+B.raw,o=o.substring(0,o.length-b.raw.length)+B.raw,i=P.substring(r.at(-1).raw.length).split(`
|
|
791
|
+
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=am(t[2].split(`
|
|
781
792
|
`,1)[0],t[1].length),f=e.split(`
|
|
782
793
|
`,1)[0],b=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):b?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),b&&this.rules.other.blankLine.test(f)&&(p+=f+`
|
|
783
|
-
`,e=e.substring(f.length+1),c=!0),!c){let
|
|
784
|
-
`,1)[0],pt;if(f=
|
|
785
|
-
`+pt.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||dt.test(h)||
|
|
786
|
-
`+f}b=!f.trim(),p+=
|
|
787
|
-
`,e=e.substring(
|
|
794
|
+
`,e=e.substring(f.length+1),c=!0),!c){let B=this.rules.other.nextBulletRegex(P),Xe=this.rules.other.hrRegex(P),dt=this.rules.other.fencesBeginRegex(P),fo=this.rules.other.headingBeginRegex(P),Ia=this.rules.other.htmlBeginRegex(P),Ca=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ji=e.split(`
|
|
795
|
+
`,1)[0],pt;if(f=ji,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),pt=f):pt=f.replace(this.rules.other.tabCharGlobal," "),dt.test(f)||fo.test(f)||Ia.test(f)||Ca.test(f)||B.test(f)||Xe.test(f))break;if(pt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
|
|
796
|
+
`+pt.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||dt.test(h)||fo.test(h)||Xe.test(h))break;u+=`
|
|
797
|
+
`+f}b=!f.trim(),p+=ji+`
|
|
798
|
+
`,e=e.substring(ji.length+1),h=pt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Tr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Le(t[0],`
|
|
788
799
|
`),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Cr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
789
800
|
`):[],r={type:"table",raw:Le(t[0],`
|
|
790
801
|
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Cr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Le(t[0],`
|
|
791
802
|
`),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)===`
|
|
792
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Le(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=
|
|
803
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Le(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=nm(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Mr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Mr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let b=h.slice(1,-1);return{type:"em",raw:h,text:b,tokens:this.lexer.inlineTokens(b)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},we=class Is{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Je,this.options.tokenizer=this.options.tokenizer||new vi,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:G,block:Ht.normal,inline:bt.normal};this.options.pedantic?(i.block=Ht.pedantic,i.inline=bt.pedantic):this.options.gfm&&(i.block=Ht.gfm,this.options.breaks?i.inline=bt.breaks:i.inline=bt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Ht,inline:bt}}static lex(t,i){return new Is(i).lex(t)}static lexInline(t,i){return new Is(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
|
|
793
804
|
`),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(G.tabCharGlobal," ").replace(G.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
|
|
794
805
|
`:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
795
806
|
`)?"":`
|
|
@@ -803,9 +814,9 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
803
814
|
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
804
815
|
`)?"":`
|
|
805
816
|
`)+r.raw,a.text+=`
|
|
806
|
-
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),b;this.options.extensions.startInline.forEach(P=>{b=P.call({lexer:this},f),typeof b=="number"&&b>=0&&(h=Math.min(h,b))}),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)}},
|
|
807
|
-
`;return s?'<pre><code class="language-'+
|
|
808
|
-
`:"<pre><code>"+(i?o:
|
|
817
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),b;this.options.extensions.startInline.forEach(P=>{b=P.call({lexer:this},f),typeof b=="number"&&b>=0&&(h=Math.min(h,b))}),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)}},bi=class{options;parser;constructor(e){this.options=e||Je}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
|
|
818
|
+
`;return s?'<pre><code class="language-'+Ie(s)+'">'+(i?o:Ie(o,!0))+`</code></pre>
|
|
819
|
+
`:"<pre><code>"+(i?o:Ie(o,!0))+`</code></pre>
|
|
809
820
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
810
821
|
${this.parser.parse(e)}</blockquote>
|
|
811
822
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -821,19 +832,19 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
821
832
|
`}tablerow({text:e}){return`<tr>
|
|
822
833
|
${e}</tr>
|
|
823
834
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
|
|
824
|
-
`}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>${
|
|
825
|
-
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+
|
|
835
|
+
`}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>${Ie(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=Ir(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ie(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Ir(e);if(o===null)return Ie(i);e=o;let r=`<img src="${e}" alt="${Ie(i)}"`;return t&&(r+=` title="${Ie(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ie(e.text)}},ho=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}},ye=class Cs{options;renderer;textRenderer;constructor(t){this.options=t||Je,this.options.renderer=this.options.renderer||new bi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ho}static parse(t,i){return new Cs(i).parse(t)}static parseInline(t,i){return new Cs(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},yt=class{options;block;constructor(e){this.options=e||Je}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?we.lex:we.lexInline}provideParser(e=this.block){return e?ye.parse:ye.parseInline}},cm=class{defaults=so();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ye;Renderer=bi;TextRenderer=ho;Lexer=we;Tokenizer=vi;Hooks=yt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new bi(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new vi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new yt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];yt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&yt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return we.lex(e,t??this.defaults)}parser(e,t){return ye.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?we.lex:we.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?ye.parse:ye.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?we.lex:we.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?ye.parse:ye.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
|
|
836
|
+
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ie(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ve=new cm;function M(e,t){return Ve.parse(e,t)}M.options=M.setOptions=function(e){return Ve.setOptions(e),M.defaults=Ve.defaults,ra(M.defaults),M};M.getDefaults=so;M.defaults=Je;M.use=function(...e){return Ve.use(...e),M.defaults=Ve.defaults,ra(M.defaults),M};M.walkTokens=function(e,t){return Ve.walkTokens(e,t)};M.parseInline=Ve.parseInline;M.Parser=ye;M.parser=ye.parse;M.Renderer=bi;M.TextRenderer=ho;M.Lexer=we;M.lexer=we.lex;M.Tokenizer=vi;M.Hooks=yt;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;ye.parse;we.lex;const ga=new M.Renderer;ga.html=({text:e})=>hm(e);const dm=300,wt=new Map;function pm(e){const t=wt.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:ga}),s=um(i);if(wt.set(e,s),wt.size>dm){const o=wt.keys().next().value;o!==void 0&&wt.delete(o)}return s}function hm(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function um(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!fm(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function fm(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var gm=Object.defineProperty,mm=Object.getOwnPropertyDescriptor,ma=(e,t,i,s)=>{for(var o=s>1?void 0:s?mm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gm(t,i,o),o};let wi=class extends T{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)},this.onFormattedCopy=e=>{e.clipboardData===null||!wm(vm(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return l`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${Sg(pm(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 o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await ym(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)}};wi.styles=vf;ma([d()],wi.prototype,"text",2);wi=ma([R("formatted-text")],wi);function vm(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&bm(t)?t.getSelection():e.ownerDocument.getSelection()}function bm(e){return"getSelection"in e&&typeof e.getSelection=="function"}function wm(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function ym(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var xm=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,jt=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xm(t,i,o),o};const Rr=180;let Ge=class extends T{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=km(e.args),s=$m(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Pm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
|
|
826
837
|
<section class=${`tool-card ${e.status}`}>
|
|
827
838
|
<div class="tool-header">
|
|
828
839
|
<div class="tool-title">
|
|
829
|
-
<span class="status-icon" aria-hidden="true">${
|
|
840
|
+
<span class="status-icon" aria-hidden="true">${Cm(e.status)}</span>
|
|
830
841
|
<strong>${e.toolName}</strong>
|
|
831
842
|
${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
|
|
832
843
|
</div>
|
|
833
844
|
<div class="tool-meta">
|
|
834
|
-
${
|
|
845
|
+
${Ar(e)===void 0?null:l`<span>${Ar(e)}</span>`}
|
|
835
846
|
${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
|
|
836
|
-
<span class="status-label">${
|
|
847
|
+
<span class="status-label">${Tm(e.status)}</span>
|
|
837
848
|
</div>
|
|
838
849
|
</div>
|
|
839
850
|
|
|
@@ -848,7 +859,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
848
859
|
<pre>${e}</pre>
|
|
849
860
|
</details>
|
|
850
861
|
`}renderDiffBody(e,t){const i=e.split(`
|
|
851
|
-
`),s=!this.showFullDiff&&i.length>
|
|
862
|
+
`),s=!this.showFullDiff&&i.length>Rr,o=s?i.slice(0,Rr):i;return l`
|
|
852
863
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
|
|
853
864
|
<summary>
|
|
854
865
|
<span>${t}</span>
|
|
@@ -858,7 +869,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
858
869
|
<span>${s?`显示 ${String(o.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
|
|
859
870
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
|
|
860
871
|
</div>
|
|
861
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${
|
|
872
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Im(r)}>${r}</span>`)}</code></pre>
|
|
862
873
|
${s?l`
|
|
863
874
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
864
875
|
显示全部 ${String(i.length)} 行 diff
|
|
@@ -905,19 +916,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
905
916
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
906
917
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
907
918
|
.show-more { justify-self: start; }
|
|
908
|
-
`;
|
|
909
|
-
`))
|
|
919
|
+
`;jt([d({attribute:!1})],Ge.prototype,"execution",2);jt([w()],Ge.prototype,"showFullDiff",2);jt([w()],Ge.prototype,"copied",2);jt([w()],Ge.prototype,"diffOpen",2);Ge=jt([R("tool-execution-view")],Ge);function km(e){return Ts(e,"path")??Ts(e,"file_path")}function Ar(e){if(e.toolName!=="edit")return;const t=ti(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof ti(e.args,"oldText")=="string"&&typeof ti(e.args,"newText")=="string")return"1 处编辑"}function $m(e){return Ts(e,"diff")}function Pm(e){let t=0,i=0;for(const s of e.split(`
|
|
920
|
+
`))va(s)?t++:ba(s)&&i++;return{added:t,removed:i}}function Im(e){return va(e)?"added":ba(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function va(e){return e.startsWith("+")&&!e.startsWith("+++")}function ba(e){return e.startsWith("-")&&!e.startsWith("---")}function Cm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Tm(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Mm(e){return typeof e=="object"&&e!==null}function ti(e,t){return Mm(e)?e[t]:void 0}function Ts(e,t){const i=ti(e,t);return typeof i=="string"?i:void 0}var Rm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,z=(e,t,i,s)=>{for(var o=s>1?void 0:s?Am(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rm(t,i,o),o};const Em=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Dm=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ss=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Wm={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 Er(){return ss[Math.floor(Math.random()*ss.length)]??ss[0]}function Dr(e){return ii(e,0,100)}function ii(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=class extends T{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.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new qf,this.scrollController=new gg,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`
|
|
910
921
|
<div class="chat-wrap">
|
|
911
922
|
${this.renderConversationRail()}
|
|
912
923
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
|
|
913
924
|
${this.renderHistoryBoundary()}
|
|
914
|
-
${
|
|
925
|
+
${Bf(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)))}
|
|
915
926
|
${this.renderQueuedMessages()}
|
|
916
927
|
${this.renderSessionActivity()}
|
|
917
928
|
</div>
|
|
918
929
|
${this.renderActivityDock()}
|
|
919
930
|
</div>
|
|
920
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
931
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Gf(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
|
|
921
932
|
<div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
|
|
922
933
|
<span class="dot"></span>
|
|
923
934
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
@@ -931,6 +942,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
931
942
|
${e.map((t,i)=>l`
|
|
932
943
|
<div class="queued-message">
|
|
933
944
|
<span class="queued-kind">${t.kind==="steer"?"引导":"跟进"} ${String(i+1)}</span>
|
|
945
|
+
${t.imageCount!==void 0&&t.imageCount>0?l`<small>含 ${t.imageCount} 张图片</small>`:null}
|
|
934
946
|
<formatted-text .text=${t.text}></formatted-text>
|
|
935
947
|
</div>
|
|
936
948
|
`)}
|
|
@@ -946,7 +958,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
946
958
|
<span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
|
|
947
959
|
${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
|
|
948
960
|
</aside>
|
|
949
|
-
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?
|
|
961
|
+
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Er():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Er(),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)return e;if(e!=="idle"&&t.phase==="idle")return Or(e);const i=Or(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?Dr(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=ii(this.currentConversationIndex??t,0,e-1);return Dr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
|
|
950
962
|
<div class="history-boundary">
|
|
951
963
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
|
|
952
964
|
<span>向上滚动加载更早的消息</span>
|
|
@@ -963,7 +975,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
963
975
|
<details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
|
|
964
976
|
<summary>
|
|
965
977
|
<b class="label">${s?"实时事件":"事件"}</b>
|
|
966
|
-
<span>${
|
|
978
|
+
<span>${Jf(e)}</span>
|
|
967
979
|
</summary>
|
|
968
980
|
<div class="group-body">
|
|
969
981
|
${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
|
|
@@ -976,7 +988,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
976
988
|
</details>
|
|
977
989
|
`}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`
|
|
978
990
|
<div class="msg-header">
|
|
979
|
-
<b class="label">${
|
|
991
|
+
<b class="label">${Wr(e.role)}</b>
|
|
980
992
|
<div class="msg-header-trailing">
|
|
981
993
|
${this.renderMessageActions(e,t)}
|
|
982
994
|
<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=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
|
|
@@ -984,13 +996,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
984
996
|
</div>
|
|
985
997
|
`}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
|
|
986
998
|
<div class="msg-actions" aria-label="消息操作">
|
|
987
|
-
<button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${
|
|
999
|
+
<button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Wr(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
|
|
988
1000
|
<span aria-hidden="true">${i?"✓":"⧉"}</span>
|
|
989
1001
|
</button>
|
|
990
1002
|
</div>
|
|
991
1003
|
`}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(`
|
|
992
1004
|
|
|
993
|
-
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:
|
|
1005
|
+
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Em.format(t),full:Dm.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`
|
|
994
1006
|
<details class="part skill-invocation">
|
|
995
1007
|
<summary><b>[技能]</b> ${e.name}</summary>
|
|
996
1008
|
<small>${e.location}</small>
|
|
@@ -1006,46 +1018,65 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1006
1018
|
<summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
|
|
1007
1019
|
<formatted-text .text=${e.text}></formatted-text>
|
|
1008
1020
|
</details>
|
|
1009
|
-
`: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&&
|
|
1021
|
+
`: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&&ng({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?oa(e):!0}isAtBottom(){const e=this.chat;return e?sa(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 Xf(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Yf(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Qf){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=ii(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ii(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 xr(e,t)??xr(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)}`}};L.styles=mf;z([d({attribute:!1})],L.prototype,"messages",2);z([d()],L.prototype,"sessionId",2);z([d({type:Number})],L.prototype,"messageStart",2);z([d({type:Number})],L.prototype,"messageEnd",2);z([d({type:Number})],L.prototype,"messageTotal",2);z([d({type:Boolean})],L.prototype,"hasMore",2);z([d({type:Boolean})],L.prototype,"loadingMore",2);z([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);z([d({type:Boolean})],L.prototype,"isCompacting",2);z([d({type:Number})],L.prototype,"pendingMessageCount",2);z([d({attribute:!1})],L.prototype,"status",2);z([d({attribute:!1})],L.prototype,"activity",2);z([d({attribute:!1})],L.prototype,"onLoadMore",2);z([F(".chat")],L.prototype,"chat",2);z([w()],L.prototype,"pinnedToBottom",2);z([w()],L.prototype,"expandedMetaKey",2);z([w()],L.prototype,"copiedMessageKey",2);z([w()],L.prototype,"currentConversationIndex",2);z([w()],L.prototype,"loadMoreRequested",2);L=z([R("chat-view")],L);function Wr(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Or(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Wm[e]??e}const Om="请看这张图片。",xt=4,wa=["image/png","image/jpeg","image/webp","image/gif"];function _m(e){return e?.input?.includes("image")===!0}function ya(e){return wa.some(t=>t===e)}async function xa(e){if(!ya(e.type))throw new Error(`Unsupported prompt image MIME type: ${e.type}`);return{type:"image",data:zm(await e.arrayBuffer()),mimeType:e.type}}async function Lm(e,t=xt){const i=[];for(const s of e){if(i.length>=t)break;if(s.kind!=="file"||!ya(s.type))continue;const o=s.getAsFile();o!==null&&i.push(await xa(o))}return i}function jm(e,t){const i=e.trim();return t.length===0?i:{text:i===""?Om:i,images:[...t]}}function Nm(e){return`data:${e.mimeType};base64,${e.data}`}function Fm(e){const t=Math.floor(e.length*3/4);return t>=1024*1024?`${(t/1024/1024).toFixed(1)} MiB`:t>=1024?`${String(Math.max(1,Math.round(t/1024)))} KiB`:`${String(t)} B`}function zm(e){const t=new Uint8Array(e),i=32768;let s="";for(let o=0;o<t.length;o+=i)s+=String.fromCharCode(...t.subarray(o,o+i));return btoa(s)}class Bm extends eo{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Xs.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const uo=Ys(Bm);var Um=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,Li=(e,t,i,s)=>{for(var o=s>1?void 0:s?Hm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Um(t,i,o),o};let nt=class extends T{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
|
|
1010
1022
|
<div class="menu">
|
|
1011
1023
|
${this.items.map((e,t)=>l`
|
|
1012
|
-
<button class=${t===this.selectedIndex?"selected":""} ${
|
|
1024
|
+
<button class=${t===this.selectedIndex?"selected":""} ${uo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
|
|
1013
1025
|
<strong>${e.insertText}</strong>
|
|
1014
1026
|
<span>${e.detail}</span>
|
|
1015
1027
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1016
1028
|
</button>
|
|
1017
1029
|
`)}
|
|
1018
1030
|
</div>
|
|
1019
|
-
`:null}};nt.styles=
|
|
1031
|
+
`:null}};nt.styles=wf;Li([d({attribute:!1})],nt.prototype,"items",2);Li([d({type:Number})],nt.prototype,"selectedIndex",2);Li([d({attribute:!1})],nt.prototype,"onPick",2);nt=Li([R("autocomplete-menu")],nt);var qm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,H=(e,t,i,s)=>{for(var o=s>1?void 0:s?Km(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&qm(t,i,o),o};let N=class extends T{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.images=[],this.imageNotice="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new go,this.readOnlyCompartment=new go}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=qt(i,t);s!==void 0&&di(s,this.draft);const o=qt(this.machineId,this.sessionId);this.draft=o!==void 0?mn(o):"",this.completions=[],this.selectedIndex=0,this.images=[],this.imageNotice=""}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),e.has("status")&&!this.imageInputEnabled()&&this.images.length>0&&(this.images=[]),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=Hs(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.imageInputEnabled();return l`
|
|
1020
1032
|
<footer class=${t?"shell-mode":""}>
|
|
1021
1033
|
<div class="editor-wrap">
|
|
1022
|
-
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
|
|
1034
|
+
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"} @paste=${o=>{this.handlePaste(o)}}></div>
|
|
1023
1035
|
${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 不加入上下文":""}</div>`:null}
|
|
1024
1036
|
${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
|
|
1025
|
-
<autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${
|
|
1037
|
+
<autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${o=>{this.pick(o)}}></autocomplete-menu>
|
|
1026
1038
|
</div>
|
|
1039
|
+
${this.renderImages()}
|
|
1040
|
+
${this.imageNotice===""?null:l`<div class="input-notice" role="status">${this.imageNotice}</div>`}
|
|
1027
1041
|
<div class="actions">
|
|
1028
1042
|
${this.renderCompactStatus()}
|
|
1043
|
+
<label class=${s&&!this.disabled?"image-input-button":"image-input-button disabled"} title=${s?"选择图片":"当前模型不支持图片输入"} aria-disabled=${s&&!this.disabled?"false":"true"}>
|
|
1044
|
+
图片
|
|
1045
|
+
<input type="file" accept=${wa.join(",")} multiple ?disabled=${this.disabled||!s} @change=${o=>{this.handleImageFiles(o)}}>
|
|
1046
|
+
</label>
|
|
1029
1047
|
<button ?disabled=${this.disabled} title=${i?"当前活动结束后排队发送":"发送消息"} @click=${()=>{this.send("followUp")}}>${i?"排队":"发送"}</button>
|
|
1030
1048
|
${this.canSteer&&!this.isCompacting?l`<button ?disabled=${this.disabled} title="在下一次模型调用前引导当前回复" @click=${()=>{this.send("steer")}}>引导</button>`:null}
|
|
1031
1049
|
<button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} @click=${()=>this.onStop?.()}>停止</button>
|
|
1032
1050
|
</div>
|
|
1033
1051
|
</footer>
|
|
1052
|
+
`}renderImages(){return this.images.length===0?null:l`
|
|
1053
|
+
<div class="image-attachments">
|
|
1054
|
+
${this.images.map((e,t)=>l`
|
|
1055
|
+
<figure class="image-attachment">
|
|
1056
|
+
<img src=${Nm(e)} alt="待发送图片 ${String(t+1)}">
|
|
1057
|
+
<figcaption>
|
|
1058
|
+
<span>${e.mimeType}</span>
|
|
1059
|
+
<small>${Fm(e.data)}</small>
|
|
1060
|
+
</figcaption>
|
|
1061
|
+
<button type="button" title="移除图片" aria-label=${`移除图片 ${String(t+1)}`} @click=${()=>{this.removeImage(t)}}>×</button>
|
|
1062
|
+
</figure>
|
|
1063
|
+
`)}
|
|
1064
|
+
</div>
|
|
1034
1065
|
`}focusInput(){this.editor?.focus()}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`
|
|
1035
1066
|
<div class="compact-status" aria-label="会话状态">
|
|
1036
1067
|
<button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
|
|
1037
|
-
<button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${
|
|
1068
|
+
<button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${Zm(e.thinkingLevel)}</button>
|
|
1038
1069
|
</div>
|
|
1039
|
-
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ye({parent:this.editorHost,state:
|
|
1040
|
-
`))+1,o=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:o,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(o.startsWith("/")&&s===0)return{kind:"command",query:o.slice(1),from:s,to:e};if(o.startsWith("!@"))return{kind:"file",query:o.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(o.startsWith("@"))return{kind:"file",query:o.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(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}}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):
|
|
1070
|
+
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ye({parent:this.editorHost,state:Ni.create({doc:this.draft,extensions:[Ta(),ja(),Ma(),Ra.of(" "),Aa(La,{fallback:!0}),Ye.lineWrapping,Ye.contentAttributes.of(e=>Ym(e.state.sliceDoc(0,e.state.selection.main.head))),Ea("给 pi 发送消息... 使用 / 输入命令,使用 @ 引用跟踪文件,使用 @ 空格查看全部文件"),this.editableCompartment.of(Ye.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ni.readOnly.of(this.disabled)),Ye.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Da.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Na(e)||_a(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>mo.shift?.(e)??!1},{key:"Backspace",run:e=>Fa(e)},...Wa,...Oa])]})}))}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:vo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Ye.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ni.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=qt(this.machineId,this.sessionId);t!==void 0&&di(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const i=await U.commands(this.sessionId,this.machineId).catch(Gm);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 U.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Jm);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=Vm(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
|
|
1071
|
+
`))+1,o=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:o,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(o.startsWith("/")&&s===0)return{kind:"command",query:o.slice(1),from:s,to:e};if(o.startsWith("!@"))return{kind:"file",query:o.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(o.startsWith("@"))return{kind:"file",query:o.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(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}}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}imageInputEnabled(){return _m(this.status?.model)}async handlePaste(e){const t=e.clipboardData?.items;if(t===void 0||!Array.from(t).some(o=>o.kind==="file"&&o.type.startsWith("image/")))return;if(!this.imageInputEnabled()){this.imageNotice="当前模型不支持图片输入";return}const i=Math.max(0,xt-this.images.length);if(i===0){this.imageNotice=`最多可附加 ${String(xt)} 张图片`,e.preventDefault();return}const s=await Lm(Array.from(t),i);if(s.length===0){this.imageNotice="仅支持 PNG、JPEG、WebP 或 GIF 图片";return}e.preventDefault(),this.images=[...this.images,...s],this.imageNotice=""}async handleImageFiles(e){const t=e.currentTarget;if(!(t instanceof HTMLInputElement)||t.files===null)return;if(!this.imageInputEnabled()){this.imageNotice="当前模型不支持图片输入",t.value="";return}const i=Math.max(0,xt-this.images.length),s=Array.from(t.files).slice(0,i),o=[];for(const r of s)try{o.push(await xa(r))}catch{this.imageNotice="仅支持 PNG、JPEG、WebP 或 GIF 图片"}t.files.length>i&&(this.imageNotice=`最多可附加 ${String(xt)} 张图片`),o.length>0&&(this.images=[...this.images,...o]),t.value=""}removeImage(e){this.images=this.images.filter((t,i)=>i!==e)}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):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,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:vo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=jm(this.draft,this.images);if(typeof t=="string"&&t===""||this.disabled)return;this.draft="",this.images=[],this.imageNotice="";const i=qt(this.machineId,this.sessionId);i!==void 0&&Us(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};N.styles=xf;H([d({type:Boolean})],N.prototype,"disabled",2);H([d()],N.prototype,"sessionId",2);H([d()],N.prototype,"cwd",2);H([d()],N.prototype,"machineId",2);H([d({type:Boolean})],N.prototype,"canSteer",2);H([d({type:Boolean})],N.prototype,"isCompacting",2);H([d({type:Boolean})],N.prototype,"canStop",2);H([d({attribute:!1})],N.prototype,"status",2);H([d({attribute:!1})],N.prototype,"onSend",2);H([d({attribute:!1})],N.prototype,"onStop",2);H([d({attribute:!1})],N.prototype,"onSelectModel",2);H([d({attribute:!1})],N.prototype,"onSelectThinking",2);H([F(".markdown-editor")],N.prototype,"editorHost",2);H([w()],N.prototype,"draft",2);H([w()],N.prototype,"images",2);H([w()],N.prototype,"imageNotice",2);H([w()],N.prototype,"completions",2);H([w()],N.prototype,"selectedIndex",2);N=H([R("prompt-editor")],N);function qt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return fn(e,t)}function Vm(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Gm(){return[]}function Jm(){return[]}function Zm(e){return e===void 0||e==="off"?"关闭":e==="minimal"?"极简":e==="low"?"低":e==="medium"?"中":e==="high"?"高":e==="xhigh"?"超高":e}const Qm={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Xm={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Ym(e){return Hs(e).kind==="normal"?Qm:Xm}function Kt(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 ev(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var tv=Object.defineProperty,iv=Object.getOwnPropertyDescriptor,Sa=(e,t,i,s)=>{for(var o=s>1?void 0:s?iv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tv(t,i,o),o};let yi=class extends T{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${Kt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Kt(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
|
|
1041
1072
|
<div class="bar">
|
|
1042
|
-
<span>↑${
|
|
1043
|
-
<span>↓${
|
|
1073
|
+
<span>↑${Kt(s.input)}</span>
|
|
1074
|
+
<span>↓${Kt(s.output)}</span>
|
|
1044
1075
|
<span class="context">${i}</span>
|
|
1045
|
-
<span>${
|
|
1076
|
+
<span>${ev(e.cost)}</span>
|
|
1046
1077
|
${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
|
|
1047
1078
|
</div>
|
|
1048
|
-
`}};
|
|
1079
|
+
`}};yi.styles=bf;Sa([d({attribute:!1})],yi.prototype,"status",2);yi=Sa([R("status-bar")],yi);var sv=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,Oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?ov(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sv(t,i,o),o};let Se=class extends T{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
|
|
1049
1080
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1050
1081
|
<section @mousedown=${t=>{t.stopPropagation()}}>
|
|
1051
1082
|
<header>
|
|
@@ -1055,7 +1086,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1055
1086
|
${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
|
|
1056
1087
|
<div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
|
|
1057
1088
|
${e.map((t,i)=>l`
|
|
1058
|
-
<button class=${i===this.selectedIndex?"selected":""} ${
|
|
1089
|
+
<button class=${i===this.selectedIndex?"selected":""} ${uo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
|
|
1059
1090
|
<span>${t.label}</span>
|
|
1060
1091
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1061
1092
|
</button>
|
|
@@ -1064,7 +1095,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1064
1095
|
</div>
|
|
1065
1096
|
</section>
|
|
1066
1097
|
</div>
|
|
1067
|
-
`}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)}}};
|
|
1098
|
+
`}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)}}};Se.styles=ea;Oe([d()],Se.prototype,"title",2);Oe([d({type:Boolean})],Se.prototype,"searchable",2);Oe([d({attribute:!1})],Se.prototype,"options",2);Oe([d({attribute:!1})],Se.prototype,"selectedValue",2);Oe([d({attribute:!1})],Se.prototype,"onPick",2);Oe([d({attribute:!1})],Se.prototype,"onCancel",2);Oe([w()],Se.prototype,"selectedIndex",2);Oe([w()],Se.prototype,"query",2);Se=Oe([R("command-picker")],Se);var rv=Object.defineProperty,nv=Object.getOwnPropertyDescriptor,Ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?nv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&rv(t,i,o),o};let De=class extends T{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
|
|
1068
1099
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1069
1100
|
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1070
1101
|
<header>
|
|
@@ -1077,19 +1108,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1077
1108
|
</header>
|
|
1078
1109
|
<div class="options">
|
|
1079
1110
|
${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
|
|
1080
|
-
<button class=${i===this.selectedIndex?"selected":""} ${
|
|
1111
|
+
<button class=${i===this.selectedIndex?"selected":""} ${uo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
|
|
1081
1112
|
<span class="main">
|
|
1082
1113
|
<strong>${t.title}</strong>
|
|
1083
1114
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1084
1115
|
</span>
|
|
1085
|
-
${t.shortcut!==void 0?l`<kbd>${
|
|
1116
|
+
${t.shortcut!==void 0?l`<kbd>${Yt(t.shortcut)}</kbd>`:null}
|
|
1086
1117
|
${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
|
|
1087
1118
|
</button>
|
|
1088
1119
|
`)}
|
|
1089
1120
|
</div>
|
|
1090
1121
|
</section>
|
|
1091
1122
|
</div>
|
|
1092
|
-
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};De.styles=
|
|
1123
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};De.styles=yf;Ze([d({attribute:!1})],De.prototype,"actions",2);Ze([d({attribute:!1})],De.prototype,"onRun",2);Ze([d({attribute:!1})],De.prototype,"onCancel",2);Ze([F("input")],De.prototype,"input",2);Ze([w()],De.prototype,"queryText",2);Ze([w()],De.prototype,"selectedIndex",2);De=Ze([R("action-palette")],De);var av=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var o=s>1?void 0:s?lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&av(t,i,o),o};let ee=class extends T{render(){const e=this.state;return e===void 0?null:l`
|
|
1093
1124
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
1094
1125
|
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1095
1126
|
<header>
|
|
@@ -1112,11 +1143,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1112
1143
|
<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>
|
|
1113
1144
|
</div>
|
|
1114
1145
|
`;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`
|
|
1115
|
-
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${
|
|
1146
|
+
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${_r(t.authType)}</small></button>
|
|
1116
1147
|
`)}</div>`}}renderProviderButton(e){return l`
|
|
1117
1148
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
1118
|
-
<span>${e.name}${e.status.source!==void 0?l` <em>${
|
|
1119
|
-
<small>${e.id} · ${
|
|
1149
|
+
<span>${e.name}${e.status.source!==void 0?l` <em>${dv(e)}</em>`:null}</span>
|
|
1150
|
+
<small>${e.id} · ${_r(e.authType)}</small>
|
|
1120
1151
|
</button>
|
|
1121
1152
|
`}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
|
|
1122
1153
|
<div class="form">
|
|
@@ -1136,10 +1167,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1136
1167
|
<div class="inline-options">${s.options.map(o=>l`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
|
|
1137
1168
|
`:null}
|
|
1138
1169
|
${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
|
|
1139
|
-
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??
|
|
1170
|
+
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??pv(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
|
|
1140
1171
|
${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
|
|
1141
1172
|
</div>
|
|
1142
|
-
`}focusInputIfNeeded(){const e=
|
|
1173
|
+
`}focusInputIfNeeded(){const e=cv(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?.()}};ee.styles=[ea,A`
|
|
1143
1174
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
1144
1175
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
1145
1176
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -1154,7 +1185,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1154
1185
|
.progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
|
|
1155
1186
|
.inline-options { display: grid; gap: 8px; }
|
|
1156
1187
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
1157
|
-
`];ge([d({attribute:!1})],ee.prototype,"state",2);ge([d({attribute:!1})],ee.prototype,"onChooseMethod",2);ge([d({attribute:!1})],ee.prototype,"onSelectProvider",2);ge([d({attribute:!1})],ee.prototype,"onApiKeyInput",2);ge([d({attribute:!1})],ee.prototype,"onSaveApiKey",2);ge([d({attribute:!1})],ee.prototype,"onLogoutProvider",2);ge([d({attribute:!1})],ee.prototype,"onOAuthInput",2);ge([d({attribute:!1})],ee.prototype,"onOAuthRespond",2);ge([d({attribute:!1})],ee.prototype,"onOAuthCancel",2);ge([d({attribute:!1})],ee.prototype,"onCancel",2);ge([F("input")],ee.prototype,"input",2);ee=ge([R("auth-dialog")],ee);function
|
|
1188
|
+
`];ge([d({attribute:!1})],ee.prototype,"state",2);ge([d({attribute:!1})],ee.prototype,"onChooseMethod",2);ge([d({attribute:!1})],ee.prototype,"onSelectProvider",2);ge([d({attribute:!1})],ee.prototype,"onApiKeyInput",2);ge([d({attribute:!1})],ee.prototype,"onSaveApiKey",2);ge([d({attribute:!1})],ee.prototype,"onLogoutProvider",2);ge([d({attribute:!1})],ee.prototype,"onOAuthInput",2);ge([d({attribute:!1})],ee.prototype,"onOAuthRespond",2);ge([d({attribute:!1})],ee.prototype,"onOAuthCancel",2);ge([d({attribute:!1})],ee.prototype,"onCancel",2);ge([F("input")],ee.prototype,"input",2);ee=ge([R("auth-dialog")],ee);function _r(e){return e==="oauth"?"订阅":"API key"}function cv(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 dv(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 pv(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var hv=Object.defineProperty,uv=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&hv(t,i,o),o};let he=class extends T{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 U.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`
|
|
1158
1189
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1159
1190
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
1160
1191
|
<header>
|
|
@@ -1204,7 +1235,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1204
1235
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1205
1236
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1206
1237
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1207
|
-
`;Me([d({attribute:!1})],he.prototype,"onSubmit",2);Me([d({attribute:!1})],he.prototype,"onCancel",2);Me([d()],he.prototype,"machineId",2);Me([w()],he.prototype,"path",2);Me([w()],he.prototype,"createMissing",2);Me([w()],he.prototype,"suggestions",2);Me([w()],he.prototype,"selected",2);Me([w()],he.prototype,"loading",2);Me([F("input")],he.prototype,"pathInput",2);he=Me([R("project-dialog")],he);var
|
|
1238
|
+
`;Me([d({attribute:!1})],he.prototype,"onSubmit",2);Me([d({attribute:!1})],he.prototype,"onCancel",2);Me([d()],he.prototype,"machineId",2);Me([w()],he.prototype,"path",2);Me([w()],he.prototype,"createMissing",2);Me([w()],he.prototype,"suggestions",2);Me([w()],he.prototype,"selected",2);Me([w()],he.prototype,"loading",2);Me([F("input")],he.prototype,"pathInput",2);he=Me([R("project-dialog")],he);var fv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,Re=(e,t,i,s)=>{for(var o=s>1?void 0:s?gv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&fv(t,i,o),o};let ue=class extends T{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=mv(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"&&os(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===""||os(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?os(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
|
|
1208
1239
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1209
1240
|
<section @click=${s=>{s.stopPropagation()}}>
|
|
1210
1241
|
<form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
|
|
@@ -1259,8 +1290,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1259
1290
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1260
1291
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1261
1292
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1262
|
-
`;Re([d({attribute:!1})],ue.prototype,"onSubmit",2);Re([d({attribute:!1})],ue.prototype,"onCancel",2);Re([d()],ue.prototype,"error",2);Re([w()],ue.prototype,"url",2);Re([w()],ue.prototype,"name",2);Re([w()],ue.prototype,"token",2);Re([w()],ue.prototype,"submitting",2);Re([F("input[name='baseUrl']")],ue.prototype,"urlInput",2);Re([F("input[name='name']")],ue.prototype,"nameInput",2);ue=Re([R("machine-dialog")],ue);function
|
|
1263
|
-
`):""}}function
|
|
1293
|
+
`;Re([d({attribute:!1})],ue.prototype,"onSubmit",2);Re([d({attribute:!1})],ue.prototype,"onCancel",2);Re([d()],ue.prototype,"error",2);Re([w()],ue.prototype,"url",2);Re([w()],ue.prototype,"name",2);Re([w()],ue.prototype,"token",2);Re([w()],ue.prototype,"submitting",2);Re([F("input[name='baseUrl']")],ue.prototype,"urlInput",2);Re([F("input[name='name']")],ue.prototype,"nameInput",2);ue=Re([R("machine-dialog")],ue);function mv(e){const t=e.trim();if(t==="")return"";const i=Lr(t)??Lr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):vv(t)}function os(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 Lr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function vv(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function bv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function wv(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(`
|
|
1294
|
+
`):""}}function yv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:xv(e.allowedHostsText),i}function xv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var Sv=Object.defineProperty,kv=Object.getOwnPropertyDescriptor,Ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?kv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sv(t,i,o),o};let fe=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=bv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=wv(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
|
|
1264
1295
|
<div class="section-heading">
|
|
1265
1296
|
<div>
|
|
1266
1297
|
<h2>通用配置</h2>
|
|
@@ -1281,7 +1312,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1281
1312
|
<span>Host</span>
|
|
1282
1313
|
${this.renderOverrideBadge("host")}
|
|
1283
1314
|
</span>
|
|
1284
|
-
<input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:
|
|
1315
|
+
<input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:jr(t)})}}>
|
|
1285
1316
|
<small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
|
|
1286
1317
|
</label>
|
|
1287
1318
|
|
|
@@ -1290,7 +1321,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1290
1321
|
<span>Port</span>
|
|
1291
1322
|
${this.renderOverrideBadge("port")}
|
|
1292
1323
|
</span>
|
|
1293
|
-
<input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:
|
|
1324
|
+
<input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:jr(t)})}}>
|
|
1294
1325
|
<small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
|
|
1295
1326
|
</label>
|
|
1296
1327
|
|
|
@@ -1299,11 +1330,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1299
1330
|
<span>允许的 hosts</span>
|
|
1300
1331
|
${this.renderOverrideBadge("allowedHosts")}
|
|
1301
1332
|
</span>
|
|
1302
|
-
<select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:
|
|
1333
|
+
<select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Pv(t)==="all"?"all":"list"})}}>
|
|
1303
1334
|
<option value="list">仅允许列出的 hosts</option>
|
|
1304
1335
|
<option value="all">允许所有 host</option>
|
|
1305
1336
|
</select>
|
|
1306
|
-
<textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:
|
|
1337
|
+
<textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Iv(t)})}}></textarea>
|
|
1307
1338
|
<small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
|
|
1308
1339
|
</div>
|
|
1309
1340
|
|
|
@@ -1320,10 +1351,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1320
1351
|
<dl>
|
|
1321
1352
|
<div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
|
|
1322
1353
|
<div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
|
|
1323
|
-
<div><dt>允许的 hosts</dt><dd>${
|
|
1354
|
+
<div><dt>允许的 hosts</dt><dd>${$v(e.allowedHosts)}</dd></div>
|
|
1324
1355
|
</dl>
|
|
1325
1356
|
</section>
|
|
1326
|
-
`}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(
|
|
1357
|
+
`}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(yv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Cv(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};fe.styles=A`
|
|
1327
1358
|
:host { display: block; }
|
|
1328
1359
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1329
1360
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1365,7 +1396,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1365
1396
|
.section-heading .secondary { justify-self: start; }
|
|
1366
1397
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1367
1398
|
}
|
|
1368
|
-
`;Ae([d({attribute:!1})],fe.prototype,"configResponse",2);Ae([d({type:Boolean})],fe.prototype,"loading",2);Ae([d({type:Boolean})],fe.prototype,"saving",2);Ae([d()],fe.prototype,"error",2);Ae([d()],fe.prototype,"savedMessage",2);Ae([d({attribute:!1})],fe.prototype,"onReload",2);Ae([d({attribute:!1})],fe.prototype,"onSave",2);Ae([w()],fe.prototype,"draft",2);Ae([w()],fe.prototype,"localError",2);fe=Ae([R("settings-general-panel")],fe);function
|
|
1399
|
+
`;Ae([d({attribute:!1})],fe.prototype,"configResponse",2);Ae([d({type:Boolean})],fe.prototype,"loading",2);Ae([d({type:Boolean})],fe.prototype,"saving",2);Ae([d()],fe.prototype,"error",2);Ae([d()],fe.prototype,"savedMessage",2);Ae([d({attribute:!1})],fe.prototype,"onReload",2);Ae([d({attribute:!1})],fe.prototype,"onSave",2);Ae([w()],fe.prototype,"draft",2);Ae([w()],fe.prototype,"localError",2);fe=Ae([R("settings-general-panel")],fe);function $v(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function jr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Pv(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Iv(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Cv(e){return e instanceof Error?e.message:String(e)}var Tv=Object.defineProperty,Mv=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?Mv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Tv(t,i,o),o};let ke=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
|
|
1369
1400
|
<div class="section-heading">
|
|
1370
1401
|
<div>
|
|
1371
1402
|
<h2>插件</h2>
|
|
@@ -1392,7 +1423,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1392
1423
|
<span>${e.enabled?"已启用":"已禁用"}</span>
|
|
1393
1424
|
</label>
|
|
1394
1425
|
</article>
|
|
1395
|
-
`}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};
|
|
1426
|
+
`}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};ke.styles=A`
|
|
1396
1427
|
:host { display: block; }
|
|
1397
1428
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1398
1429
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1425,7 +1456,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1425
1456
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1426
1457
|
.toggle { justify-self: start; }
|
|
1427
1458
|
}
|
|
1428
|
-
`;_e([d({attribute:!1})],
|
|
1459
|
+
`;_e([d({attribute:!1})],ke.prototype,"pluginsResponse",2);_e([d({attribute:!1})],ke.prototype,"configResponse",2);_e([d({type:Boolean})],ke.prototype,"loading",2);_e([d({type:Boolean})],ke.prototype,"saving",2);_e([d()],ke.prototype,"error",2);_e([d()],ke.prototype,"savedMessage",2);_e([d({attribute:!1})],ke.prototype,"onReload",2);_e([d({attribute:!1})],ke.prototype,"onTogglePlugin",2);ke=_e([R("settings-plugins-panel")],ke);var Rv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Av(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rv(t,i,o),o};const Nr={capture:!0};let te=class extends T{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Rn(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&&!Tt(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=Ov(this.actions),t=this.shortcutResolutions();return l`
|
|
1429
1460
|
<div class="section-heading">
|
|
1430
1461
|
<div>
|
|
1431
1462
|
<h2>键盘快捷键</h2>
|
|
@@ -1449,19 +1480,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1449
1480
|
</section>
|
|
1450
1481
|
`)}
|
|
1451
1482
|
`}
|
|
1452
|
-
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=
|
|
1453
|
-
<article class=${
|
|
1483
|
+
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=xi(e.id,i),o=Nv(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Vi(r),a=n?.ok===!0?n.shortcut:jv(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=Wv(t);return l`
|
|
1484
|
+
<article class=${Ev(t)}>
|
|
1454
1485
|
<div class="shortcut-main">
|
|
1455
1486
|
<strong>${e.title}</strong>
|
|
1456
1487
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1457
1488
|
<small class="shortcut-id">${e.id}</small>
|
|
1458
|
-
<small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${
|
|
1489
|
+
<small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${Yt(e.shortcut)}</kbd>`:"No default shortcut"}</small>
|
|
1459
1490
|
</div>
|
|
1460
1491
|
<div class="shortcut-editor">
|
|
1461
1492
|
<div class="shortcut-status">
|
|
1462
|
-
${a!==void 0&&a!==""?l`<kbd>${
|
|
1463
|
-
<small class=${u}>${
|
|
1464
|
-
${f===void 0?null:l`<small class=${
|
|
1493
|
+
${a!==void 0&&a!==""?l`<kbd>${Yt(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"已禁用":"未分配"}</span>`}
|
|
1494
|
+
<small class=${u}>${Fv(u)}${p?" · 未保存":""}</small>
|
|
1495
|
+
${f===void 0?null:l`<small class=${Dv(t)}>${f}</small>`}
|
|
1465
1496
|
</div>
|
|
1466
1497
|
<label class="shortcut-input-label">
|
|
1467
1498
|
<span>快捷键</span>
|
|
@@ -1474,7 +1505,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1474
1505
|
autocapitalize="off"
|
|
1475
1506
|
spellcheck="false"
|
|
1476
1507
|
?disabled=${this.saving}
|
|
1477
|
-
@input=${b=>{this.updateDraft(e.id,
|
|
1508
|
+
@input=${b=>{this.updateDraft(e.id,zv(b))}}
|
|
1478
1509
|
>
|
|
1479
1510
|
</label>
|
|
1480
1511
|
${h!==""?l`<small class="recording-hint">${h}</small>`:null}
|
|
@@ -1486,7 +1517,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1486
1517
|
</div>
|
|
1487
1518
|
</div>
|
|
1488
1519
|
</article>
|
|
1489
|
-
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=
|
|
1520
|
+
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=xi(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: ${Yt(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=Vi(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?Lv(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(Vs(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Vi(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Tn)}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,Nr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Nr),this.recordingListenerActive=!1)}};te.styles=A`
|
|
1490
1521
|
:host { display: block; }
|
|
1491
1522
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1492
1523
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1541,7 +1572,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1541
1572
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1542
1573
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
1543
1574
|
}
|
|
1544
|
-
`;me([d({attribute:!1})],te.prototype,"actions",2);me([d({attribute:!1})],te.prototype,"configResponse",2);me([d({type:Boolean})],te.prototype,"loading",2);me([d({type:Boolean})],te.prototype,"saving",2);me([d()],te.prototype,"error",2);me([d()],te.prototype,"savedMessage",2);me([d({attribute:!1})],te.prototype,"onReload",2);me([d({attribute:!1})],te.prototype,"onSave",2);me([w()],te.prototype,"drafts",2);me([w()],te.prototype,"localError",2);me([w()],te.prototype,"recording",2);te=me([R("settings-shortcuts-panel")],te);function
|
|
1575
|
+
`;me([d({attribute:!1})],te.prototype,"actions",2);me([d({attribute:!1})],te.prototype,"configResponse",2);me([d({type:Boolean})],te.prototype,"loading",2);me([d({type:Boolean})],te.prototype,"saving",2);me([d()],te.prototype,"error",2);me([d()],te.prototype,"savedMessage",2);me([d({attribute:!1})],te.prototype,"onReload",2);me([d({attribute:!1})],te.prototype,"onSave",2);me([w()],te.prototype,"drafts",2);me([w()],te.prototype,"localError",2);me([w()],te.prototype,"recording",2);te=me([R("settings-shortcuts-panel")],te);function Ev(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Dv(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Wv(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function Ov(e){const t=new Map;for(const i of[...e].sort(_v)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function _v(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function xi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Lv(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function jv(e,t){const i=xi(e.id,t);if(i!==null)return i??e.shortcut}function Nv(e,t){const i=xi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Fv(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function zv(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let ie=class extends T{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
|
|
1545
1576
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
1546
1577
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1547
1578
|
<header class="settings-header">
|
|
@@ -1600,7 +1631,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1600
1631
|
<strong>${t}</strong>
|
|
1601
1632
|
<small>${i}</small>
|
|
1602
1633
|
</button>
|
|
1603
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([
|
|
1634
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ni.config(),fs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${rs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ni.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${rs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await fs.plugins()}catch(e){this.error=`刷新插件失败:${rs(e)}`}}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?.())}};ie.styles=A`
|
|
1604
1635
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1605
1636
|
.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; }
|
|
1606
1637
|
.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; }
|
|
@@ -1627,7 +1658,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1627
1658
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
1628
1659
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
1629
1660
|
}
|
|
1630
|
-
`;ve([d({attribute:!1})],ie.prototype,"section",2);ve([d({attribute:!1})],ie.prototype,"actions",2);ve([d({attribute:!1})],ie.prototype,"onNavigate",2);ve([d({attribute:!1})],ie.prototype,"onClose",2);ve([d({attribute:!1})],ie.prototype,"onConfigSaved",2);ve([w()],ie.prototype,"configResponse",2);ve([w()],ie.prototype,"pluginsResponse",2);ve([w()],ie.prototype,"loading",2);ve([w()],ie.prototype,"saving",2);ve([w()],ie.prototype,"error",2);ve([w()],ie.prototype,"savedMessage",2);ie=ve([R("settings-dialog")],ie);function
|
|
1661
|
+
`;ve([d({attribute:!1})],ie.prototype,"section",2);ve([d({attribute:!1})],ie.prototype,"actions",2);ve([d({attribute:!1})],ie.prototype,"onNavigate",2);ve([d({attribute:!1})],ie.prototype,"onClose",2);ve([d({attribute:!1})],ie.prototype,"onConfigSaved",2);ve([w()],ie.prototype,"configResponse",2);ve([w()],ie.prototype,"pluginsResponse",2);ve([w()],ie.prototype,"loading",2);ve([w()],ie.prototype,"saving",2);ve([w()],ie.prototype,"error",2);ve([w()],ie.prototype,"savedMessage",2);ie=ve([R("settings-dialog")],ie);function rs(e){return e instanceof Error?e.message:String(e)}var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let ae=class extends T{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"选择工作区",body:"选择工作区来查看文件、Git 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
|
|
1631
1662
|
${this.hideToolTabs?null:l`
|
|
1632
1663
|
<header>
|
|
1633
1664
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -1657,32 +1688,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1657
1688
|
<h2>${e.title}</h2>
|
|
1658
1689
|
${e.body===void 0?null:l`<p>${e.body}</p>`}
|
|
1659
1690
|
</section>
|
|
1660
|
-
`}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}};ae.styles=
|
|
1691
|
+
`}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}};ae.styles=gf;$e([d({attribute:!1})],ae.prototype,"workspace",2);$e([d({attribute:!1})],ae.prototype,"panelContext",2);$e([d({attribute:!1})],ae.prototype,"emptyState",2);$e([d()],ae.prototype,"tool",2);$e([d({attribute:!1})],ae.prototype,"panels",2);$e([d({type:Boolean})],ae.prototype,"hideToolTabs",2);$e([d({attribute:!1})],ae.prototype,"onSelectTool",2);$e([F(".workspace-header-strip")],ae.prototype,"workspaceHeaderStrip",2);$e([w()],ae.prototype,"workspaceHeaderCanScrollLeft",2);$e([w()],ae.prototype,"workspaceHeaderCanScrollRight",2);ae=$e([R("workspace-panel")],ae);var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kv(t,i,o),o};let se=class extends T{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=Gv(this.machines),t=Jv(this.machine),i=Qv(this.project),s=Yv(this.workspace),o=tb(this.session);return l`
|
|
1661
1692
|
<nav class=${this.contextBarClass()} aria-label="当前位置">
|
|
1662
1693
|
<span class="context-bar-label">位置</span>
|
|
1663
1694
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
1664
1695
|
${e?l`
|
|
1665
1696
|
<li class="context-item">
|
|
1666
|
-
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${
|
|
1697
|
+
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Zv(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
|
|
1667
1698
|
<span class="context-kind">机器</span>
|
|
1668
1699
|
<span class="context-value">${t}</span>
|
|
1669
1700
|
</button>
|
|
1670
1701
|
</li>
|
|
1671
1702
|
`:null}
|
|
1672
1703
|
<li class="context-item">
|
|
1673
|
-
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${
|
|
1704
|
+
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Xv(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
|
|
1674
1705
|
<span class="context-kind">项目</span>
|
|
1675
1706
|
<span class="context-value">${i}</span>
|
|
1676
1707
|
</button>
|
|
1677
1708
|
</li>
|
|
1678
1709
|
<li class="context-item">
|
|
1679
|
-
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${
|
|
1710
|
+
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${eb(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
|
|
1680
1711
|
<span class="context-kind">工作区</span>
|
|
1681
1712
|
<span class="context-value">${s}</span>
|
|
1682
1713
|
</button>
|
|
1683
1714
|
</li>
|
|
1684
1715
|
<li class="context-item">
|
|
1685
|
-
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${
|
|
1716
|
+
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${ib(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
|
|
1686
1717
|
<span class="context-kind">会话</span>
|
|
1687
1718
|
<span class="context-value">${o}</span>
|
|
1688
1719
|
</button>
|
|
@@ -1722,7 +1753,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1722
1753
|
.context-kind { display: none; }
|
|
1723
1754
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
1724
1755
|
button { cursor: pointer; }
|
|
1725
|
-
`;be([d({attribute:!1})],se.prototype,"machines",2);be([d({attribute:!1})],se.prototype,"machine",2);be([d({attribute:!1})],se.prototype,"project",2);be([d({attribute:!1})],se.prototype,"workspace",2);be([d({attribute:!1})],se.prototype,"session",2);be([d({attribute:!1})],se.prototype,"refreshControl",2);be([d({attribute:!1})],se.prototype,"onOpenSection",2);be([d({attribute:!1})],se.prototype,"onShowActions",2);be([F(".context-items")],se.prototype,"contextItems",2);be([w()],se.prototype,"canScrollLeft",2);be([w()],se.prototype,"canScrollRight",2);se=be([R("app-context-bar")],se);function
|
|
1756
|
+
`;be([d({attribute:!1})],se.prototype,"machines",2);be([d({attribute:!1})],se.prototype,"machine",2);be([d({attribute:!1})],se.prototype,"project",2);be([d({attribute:!1})],se.prototype,"workspace",2);be([d({attribute:!1})],se.prototype,"session",2);be([d({attribute:!1})],se.prototype,"refreshControl",2);be([d({attribute:!1})],se.prototype,"onOpenSection",2);be([d({attribute:!1})],se.prototype,"onShowActions",2);be([F(".context-items")],se.prototype,"contextItems",2);be([w()],se.prototype,"canScrollLeft",2);be([w()],se.prototype,"canScrollRight",2);se=be([R("app-context-bar")],se);function Gv(e){return e.length>1}function Jv(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function Zv(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function Qv(e){return e?.name??"未选择项目"}function Xv(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function Yv(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function eb(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function tb(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"未选择会话"}function ib(e){return e===void 0?"未选择会话":e.path}var sb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var o=s>1?void 0:s?ob(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sb(t,i,o),o};let We=class extends T{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`
|
|
1726
1757
|
<div class=${this.frameClass()}>
|
|
1727
1758
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
1728
1759
|
${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
|
|
@@ -1734,7 +1765,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1734
1765
|
`})}
|
|
1735
1766
|
</div>
|
|
1736
1767
|
</div>
|
|
1737
|
-
`}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>`:
|
|
1768
|
+
`}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>`:Mh(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};We.styles=A`
|
|
1738
1769
|
:host { flex: 0 0 auto; min-width: 0; }
|
|
1739
1770
|
.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); }
|
|
1740
1771
|
.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; }
|
|
@@ -1760,12 +1791,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1760
1791
|
.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; }
|
|
1761
1792
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
1762
1793
|
}
|
|
1763
|
-
`;Qe([d({attribute:!1})],We.prototype,"tabs",2);Qe([d({attribute:!1})],We.prototype,"selectedView",2);Qe([d({attribute:!1})],We.prototype,"onSelect",2);Qe([F(".mobile-tabs")],We.prototype,"mobileTabs",2);Qe([w()],We.prototype,"canScrollLeft",2);Qe([w()],We.prototype,"canScrollRight",2);We=Qe([R("app-mobile-main-tabs")],We);var
|
|
1794
|
+
`;Qe([d({attribute:!1})],We.prototype,"tabs",2);Qe([d({attribute:!1})],We.prototype,"selectedView",2);Qe([d({attribute:!1})],We.prototype,"onSelect",2);Qe([F(".mobile-tabs")],We.prototype,"mobileTabs",2);Qe([w()],We.prototype,"canScrollLeft",2);Qe([w()],We.prototype,"canScrollRight",2);We=Qe([R("app-mobile-main-tabs")],We);var rb=Object.defineProperty,nb=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?nb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&rb(t,i,o),o};let X=class extends T{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=ns(e,this.statuses),i=e.name;return l`
|
|
1764
1795
|
<div class="machine-switcher">
|
|
1765
1796
|
<button
|
|
1766
1797
|
type="button"
|
|
1767
1798
|
class="machine-switcher-button"
|
|
1768
|
-
title=${
|
|
1799
|
+
title=${zr(e)}
|
|
1769
1800
|
aria-label=${`Machine: ${i}. Switch machine.`}
|
|
1770
1801
|
aria-expanded=${String(this.open)}
|
|
1771
1802
|
@click=${s=>{this.toggleMenu(s.currentTarget)}}
|
|
@@ -1785,12 +1816,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1785
1816
|
</div>
|
|
1786
1817
|
`:null}
|
|
1787
1818
|
</div>
|
|
1788
|
-
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=
|
|
1819
|
+
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=ns(e,this.statuses),s=ta(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
|
|
1789
1820
|
<div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
|
|
1790
1821
|
<button
|
|
1791
1822
|
type="button"
|
|
1792
1823
|
class="machine-option-main"
|
|
1793
|
-
title=${
|
|
1824
|
+
title=${zr(e)}
|
|
1794
1825
|
data-machine-id=${e.id}
|
|
1795
1826
|
@click=${()=>{this.select(e)}}
|
|
1796
1827
|
@keydown=${r=>{this.handleMachineOptionKeydown(r)}}
|
|
@@ -1816,7 +1847,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1816
1847
|
</div>
|
|
1817
1848
|
`:null}
|
|
1818
1849
|
</div>
|
|
1819
|
-
`}renderActivity(e){const t=
|
|
1850
|
+
`}renderActivity(e){const t=ns(e,this.statuses);if(t==="offline"||t==="error")return;const i=Kn(this.activities[e.id]);return Jn(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=Br(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=Br(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=_t(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)}};X.styles=A`
|
|
1820
1851
|
:host { min-width: 0; display: block; }
|
|
1821
1852
|
.machine-switcher { min-width: 0; }
|
|
1822
1853
|
.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; }
|
|
@@ -1848,10 +1879,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1848
1879
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
1849
1880
|
.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); }
|
|
1850
1881
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
1851
|
-
`;ce([d({attribute:!1})],X.prototype,"machines",2);ce([d({attribute:!1})],X.prototype,"selected",2);ce([d({attribute:!1})],X.prototype,"statuses",2);ce([d({attribute:!1})],X.prototype,"activities",2);ce([d({attribute:!1})],X.prototype,"onSelect",2);ce([d({attribute:!1})],X.prototype,"onRemove",2);ce([d({attribute:!1})],X.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],X.prototype,"onCancelKeyboardNavigation",2);ce([w()],X.prototype,"open",2);ce([w()],X.prototype,"menuStyle",2);ce([w()],X.prototype,"openActionsMachineId",2);ce([w()],X.prototype,"actionMenuStyle",2);X=ce([R("machine-switcher")],X);function
|
|
1882
|
+
`;ce([d({attribute:!1})],X.prototype,"machines",2);ce([d({attribute:!1})],X.prototype,"selected",2);ce([d({attribute:!1})],X.prototype,"statuses",2);ce([d({attribute:!1})],X.prototype,"activities",2);ce([d({attribute:!1})],X.prototype,"onSelect",2);ce([d({attribute:!1})],X.prototype,"onRemove",2);ce([d({attribute:!1})],X.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],X.prototype,"onCancelKeyboardNavigation",2);ce([w()],X.prototype,"open",2);ce([w()],X.prototype,"menuStyle",2);ce([w()],X.prototype,"openActionsMachineId",2);ce([w()],X.prototype,"actionMenuStyle",2);X=ce([R("machine-switcher")],X);function ns(e,t){return t[e.id]?.status??e.status??"unknown"}function Fr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function zr(e){return e.baseUrl??e.name}function Br(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Vt(t.bottom)};`,`left: ${Vt(o)};`,`width: ${Vt(s)};`,`max-height: ${Vt(r)};`].join(" ")}function Vt(e){return`${String(Math.round(e))}px`}var ab=Object.defineProperty,lb=Object.getOwnPropertyDescriptor,$=(e,t,i,s)=>{for(var o=s>1?void 0:s?lb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ab(t,i,o),o};let k=class extends T{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1}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`
|
|
1852
1883
|
<header>
|
|
1853
1884
|
<strong>PI WEB</strong>
|
|
1854
|
-
${
|
|
1885
|
+
${Si(this.machines)?l`
|
|
1855
1886
|
<machine-switcher
|
|
1856
1887
|
.machines=${this.machines}
|
|
1857
1888
|
.selected=${this.selectedMachine}
|
|
@@ -1868,7 +1899,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1868
1899
|
<button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
|
|
1869
1900
|
</div>
|
|
1870
1901
|
</header>
|
|
1871
|
-
${this.compact&&
|
|
1902
|
+
${this.compact&&Si(this.machines)?l`
|
|
1872
1903
|
<machine-list
|
|
1873
1904
|
.machines=${this.machines}
|
|
1874
1905
|
.selected=${this.selectedMachine}
|
|
@@ -1933,7 +1964,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1933
1964
|
.onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
|
|
1934
1965
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1935
1966
|
></session-list>
|
|
1936
|
-
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=
|
|
1967
|
+
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=cb(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(db(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};k.styles=A`
|
|
1937
1968
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
1938
1969
|
:host([compact]) { flex: 1 1 auto; }
|
|
1939
1970
|
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); }
|
|
@@ -1956,7 +1987,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1956
1987
|
:host([compact]) workspace-list[collapsed],
|
|
1957
1988
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
1958
1989
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1959
|
-
`;$([d({attribute:!1})],k.prototype,"machines",2);$([d({attribute:!1})],k.prototype,"selectedMachine",2);$([d({attribute:!1})],k.prototype,"machineStatuses",2);$([d({attribute:!1})],k.prototype,"machineActivities",2);$([d({attribute:!1})],k.prototype,"projects",2);$([d({attribute:!1})],k.prototype,"selectedProject",2);$([d({attribute:!1})],k.prototype,"workspaces",2);$([d({attribute:!1})],k.prototype,"selectedWorkspace",2);$([d({attribute:!1})],k.prototype,"sessions",2);$([d({attribute:!1})],k.prototype,"selectedSession",2);$([d({attribute:!1})],k.prototype,"workspaceActivities",2);$([d({attribute:!1})],k.prototype,"sessionActivities",2);$([d({attribute:!1})],k.prototype,"sessionStatuses",2);$([d({attribute:!1})],k.prototype,"workspacesByProjectId",2);$([d({attribute:!1})],k.prototype,"deletingWorkspaceIds",2);$([d({attribute:!1})],k.prototype,"workspaceLabelItems",2);$([d({attribute:!1})],k.prototype,"refreshControl",2);$([d({type:Boolean,reflect:!0})],k.prototype,"collapsible",2);$([d({type:Boolean,reflect:!0})],k.prototype,"compact",2);$([d({type:Boolean})],k.prototype,"machinesCollapsed",2);$([d({type:Boolean})],k.prototype,"projectsCollapsed",2);$([d({type:Boolean})],k.prototype,"workspacesCollapsed",2);$([d({type:Boolean})],k.prototype,"sessionsCollapsed",2);$([d({type:Boolean})],k.prototype,"canStartSession",2);$([d({attribute:!1})],k.prototype,"onShowActions",2);$([d({attribute:!1})],k.prototype,"onToggleMachines",2);$([d({attribute:!1})],k.prototype,"onToggleProjects",2);$([d({attribute:!1})],k.prototype,"onToggleWorkspaces",2);$([d({attribute:!1})],k.prototype,"onToggleSessions",2);$([d({attribute:!1})],k.prototype,"onSelectProject",2);$([d({attribute:!1})],k.prototype,"onCloseProject",2);$([d({attribute:!1})],k.prototype,"onSelectWorkspace",2);$([d({attribute:!1})],k.prototype,"onDeleteWorkspace",2);$([d({attribute:!1})],k.prototype,"onStartSession",2);$([d({attribute:!1})],k.prototype,"onSelectSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSessionWithDescendants",2);$([d({attribute:!1})],k.prototype,"onRestoreSession",2);$([d({attribute:!1})],k.prototype,"onDeleteCachedNewSession",2);$([d({attribute:!1})],k.prototype,"onDetachParentSession",2);$([d({attribute:!1})],k.prototype,"onArchivedCollapsed",2);$([d({attribute:!1})],k.prototype,"onSelectMachine",2);$([d({attribute:!1})],k.prototype,"onRemoveMachine",2);$([d({attribute:!1})],k.prototype,"onFocusNavigationTarget",2);$([d({attribute:!1})],k.prototype,"onCancelKeyboardNavigation",2);$([F("machine-list")],k.prototype,"machineList",2);$([F("machine-switcher")],k.prototype,"machineSwitcher",2);$([F("project-list")],k.prototype,"projectList",2);$([F("workspace-list")],k.prototype,"workspaceList",2);$([F("session-list")],k.prototype,"sessionList",2);k=$([R("app-navigation-panel")],k);function
|
|
1990
|
+
`;$([d({attribute:!1})],k.prototype,"machines",2);$([d({attribute:!1})],k.prototype,"selectedMachine",2);$([d({attribute:!1})],k.prototype,"machineStatuses",2);$([d({attribute:!1})],k.prototype,"machineActivities",2);$([d({attribute:!1})],k.prototype,"projects",2);$([d({attribute:!1})],k.prototype,"selectedProject",2);$([d({attribute:!1})],k.prototype,"workspaces",2);$([d({attribute:!1})],k.prototype,"selectedWorkspace",2);$([d({attribute:!1})],k.prototype,"sessions",2);$([d({attribute:!1})],k.prototype,"selectedSession",2);$([d({attribute:!1})],k.prototype,"workspaceActivities",2);$([d({attribute:!1})],k.prototype,"sessionActivities",2);$([d({attribute:!1})],k.prototype,"sessionStatuses",2);$([d({attribute:!1})],k.prototype,"workspacesByProjectId",2);$([d({attribute:!1})],k.prototype,"deletingWorkspaceIds",2);$([d({attribute:!1})],k.prototype,"workspaceLabelItems",2);$([d({attribute:!1})],k.prototype,"refreshControl",2);$([d({type:Boolean,reflect:!0})],k.prototype,"collapsible",2);$([d({type:Boolean,reflect:!0})],k.prototype,"compact",2);$([d({type:Boolean})],k.prototype,"machinesCollapsed",2);$([d({type:Boolean})],k.prototype,"projectsCollapsed",2);$([d({type:Boolean})],k.prototype,"workspacesCollapsed",2);$([d({type:Boolean})],k.prototype,"sessionsCollapsed",2);$([d({type:Boolean})],k.prototype,"canStartSession",2);$([d({attribute:!1})],k.prototype,"onShowActions",2);$([d({attribute:!1})],k.prototype,"onToggleMachines",2);$([d({attribute:!1})],k.prototype,"onToggleProjects",2);$([d({attribute:!1})],k.prototype,"onToggleWorkspaces",2);$([d({attribute:!1})],k.prototype,"onToggleSessions",2);$([d({attribute:!1})],k.prototype,"onSelectProject",2);$([d({attribute:!1})],k.prototype,"onCloseProject",2);$([d({attribute:!1})],k.prototype,"onSelectWorkspace",2);$([d({attribute:!1})],k.prototype,"onDeleteWorkspace",2);$([d({attribute:!1})],k.prototype,"onStartSession",2);$([d({attribute:!1})],k.prototype,"onSelectSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSessionWithDescendants",2);$([d({attribute:!1})],k.prototype,"onRestoreSession",2);$([d({attribute:!1})],k.prototype,"onDeleteCachedNewSession",2);$([d({attribute:!1})],k.prototype,"onDetachParentSession",2);$([d({attribute:!1})],k.prototype,"onArchivedCollapsed",2);$([d({attribute:!1})],k.prototype,"onSelectMachine",2);$([d({attribute:!1})],k.prototype,"onRemoveMachine",2);$([d({attribute:!1})],k.prototype,"onFocusNavigationTarget",2);$([d({attribute:!1})],k.prototype,"onCancelKeyboardNavigation",2);$([F("machine-list")],k.prototype,"machineList",2);$([F("machine-switcher")],k.prototype,"machineSwitcher",2);$([F("project-list")],k.prototype,"projectList",2);$([F("workspace-list")],k.prototype,"workspaceList",2);$([F("session-list")],k.prototype,"sessionList",2);k=$([R("app-navigation-panel")],k);function Si(e){return e.length>1}function cb(e,t){const i=ka(t);return i[i.indexOf(e)-1]}function db(e,t){const i=ka(t);return i[i.indexOf(e)+1]??"chat"}function ka(e){return gi.filter(t=>t!=="machines"||Si(e))}var pb=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,Q=(e,t,i,s)=>{for(var o=s>1?void 0:s?hb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&pb(t,i,o),o};const ub=new Set(["ArrowLeft","ArrowRight","Home","End"]),fb=420,gb=4;let K=class extends T{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`
|
|
1960
1991
|
${this.renderResizeHandle()}
|
|
1961
1992
|
<button
|
|
1962
1993
|
type="button"
|
|
@@ -1986,7 +2017,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1986
2017
|
@dblclick=${t=>{this.onResizeDoubleClick(t)}}
|
|
1987
2018
|
@keydown=${t=>{this.onResizeKeyDown(t)}}
|
|
1988
2019
|
></div>
|
|
1989
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=
|
|
2020
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=gb)&&(t.moved=!0,this.commitPanelWidth(Nu(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||!ub.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Fu(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<=fb){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 de(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(de(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=Ot(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=A`
|
|
1990
2021
|
: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; }
|
|
1991
2022
|
:host([side="navigation"]) { grid-column: 2; }
|
|
1992
2023
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -2005,7 +2036,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2005
2036
|
@media (max-width: 760px) {
|
|
2006
2037
|
:host([side="navigation"]) { display: none; }
|
|
2007
2038
|
}
|
|
2008
|
-
`;Q([d({reflect:!0})],
|
|
2039
|
+
`;Q([d({reflect:!0})],K.prototype,"side",2);Q([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Q([d({type:Boolean})],K.prototype,"resizable",2);Q([d({type:Number})],K.prototype,"panelWidth",2);Q([d({type:Number})],K.prototype,"minWidth",2);Q([d({type:Number})],K.prototype,"maxWidth",2);Q([d()],K.prototype,"controls",2);Q([d()],K.prototype,"resizeLabel",2);Q([d()],K.prototype,"expandLabel",2);Q([d()],K.prototype,"collapseLabel",2);Q([d({attribute:!1})],K.prototype,"onToggle",2);Q([d({attribute:!1})],K.prototype,"onResizeStart",2);Q([d({attribute:!1})],K.prototype,"onResize",2);Q([d({attribute:!1})],K.prototype,"onResizeEnd",2);Q([d({attribute:!1})],K.prototype,"onReset",2);K=Q([R("app-panel-edge-control")],K);var mb=Object.defineProperty,vb=Object.getOwnPropertyDescriptor,$a=(e,t,i,s)=>{for(var o=s>1?void 0:s?vb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&mb(t,i,o),o};let ki=class extends T{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
|
|
2009
2040
|
<button
|
|
2010
2041
|
class="app-refresh-button"
|
|
2011
2042
|
title=${e}
|
|
@@ -2019,12 +2050,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2019
2050
|
<path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
|
|
2020
2051
|
<path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
|
|
2021
2052
|
</svg>
|
|
2022
|
-
`}};
|
|
2053
|
+
`}};ki.styles=A`
|
|
2023
2054
|
:host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
|
|
2024
2055
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
2025
2056
|
.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; }
|
|
2026
2057
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
2027
|
-
`;ya([d({attribute:!1})],Si.prototype,"onReload",2);Si=ya([R("app-refresh-control")],Si);var rb=Object.defineProperty,nb=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var o=s>1?void 0:s?nb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&rb(t,i,o),o};const ab=900*1e3,Br={capture:!0},ns="auto:on",Ur="auto:off",Vt="theme:",as=Mt("core:workspace.files"),ls=Mt("core:workspace.git"),Gt=Mt("core:workspace.terminal"),lb=320,cb=2,db="(min-width: 1181px)";let le=class extends T{constructor(){super(...arguments),this.state=Mc(),this.sessions=new up(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new ap),this.activity=new Rc(()=>this.state,e=>{this.setState(e)}),this.auth=new Dc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new kp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new xp),this.projects=new qc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Lc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Bc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new _p,this.realtime=new Ko,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Ip,this.terminalSelection=new Wp,this.appShell=new bu(this),this.panelCollapse=new Mu(this),this.panelResize=new Au(this),this.navigationSections=new Cu(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.plugins=pb(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Qp()??Gp,this.activeThemeId=Gs,this.isRefreshingApp=!1,this.settingsSection=cr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Br),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},ab),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute()}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,Br),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.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!fb(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),hb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=lr();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await cn.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>xa(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 ri.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}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(lr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=e.projectId===void 0||e.projectId===""?Kr():i,r=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await n,!this.isCurrentRouteRestore(r))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),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 a=this.state.projects.find(c=>c.id===e.projectId);if(!a){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(a,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(r))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)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Kr():{selectedFilePath:Ui(as,"file"),selectedDiffPath:Ui(ls,"diff"),selectedTerminalId:Ui(Gt,"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){Ji(e,{replace:!0}),re(as,"file",void 0,{replace:!0}),re(ls,"diff",void 0,{replace:!0}),re(Gt,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await cs(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Ji({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(Vo(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Vo(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ji(Go(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){re(as,"file",e.selectedFilePath,{replace:!0}),re(ls,"diff",e.selectedDiffPath,{replace:!0}),re(Gt,"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)??Tp(e.id);if(await this.restoreRouteFor(Go(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=Vr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=Gu(e,{api:{runTerminalCommand:(r,n)=>ot.runTerminalCommand(r,n,t),listCommandRuns:r=>ot.listCommandRuns(r,t),getCommandRun:r=>ot.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"未找到用于运行终端命令的机器"});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){re(Gt,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,Zi(e)}closeSettings(){this.settingsSection=void 0,Zi(void 0)}navigateSettings(e){this.settingsSection=e,Zi(e)}restoreSettingsRoute(){this.settingsSection=cr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Ko;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>ub(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):gb(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await ot.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=qr(e),s=qr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),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`
|
|
2058
|
+
`;$a([d({attribute:!1})],ki.prototype,"onReload",2);ki=$a([R("app-refresh-control")],ki);var bb=Object.defineProperty,wb=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?wb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&bb(t,i,o),o};const yb=900*1e3,Ur={capture:!0},as="auto:on",Hr="auto:off",Gt="theme:",ls=Rt("core:workspace.files"),cs=Rt("core:workspace.git"),Jt=Rt("core:workspace.terminal"),xb=320,Sb=2,kb="(min-width: 1181px)";let le=class extends T{constructor(){super(...arguments),this.state=Oc(),this.sessions=new wp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new up),this.activity=new _c(()=>this.state,e=>{this.setState(e)}),this.auth=new Nc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Mp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Cp),this.projects=new Qc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Jc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Gc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Bp,this.realtime=new Vo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Dp,this.terminalSelection=new Fp,this.appShell=new $u(this),this.panelCollapse=new Ou(this),this.panelResize=new Lu(this),this.navigationSections=new Eu(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.plugins=$b(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=sh()??eh,this.activeThemeId=Js,this.isRefreshingApp=!1,this.settingsSection=dr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},yb),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!Cb(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),Pb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=cr();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await dn.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Pa(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 ni.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}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(cr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=e.projectId===void 0||e.projectId===""?Vr():i,r=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await n,!this.isCurrentRouteRestore(r))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),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 a=this.state.projects.find(c=>c.id===e.projectId);if(!a){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(a,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(r))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)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Vr():{selectedFilePath:Hi(ls,"file"),selectedDiffPath:Hi(cs,"diff"),selectedTerminalId:Hi(Jt,"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){Zi(e,{replace:!0}),re(ls,"file",void 0,{replace:!0}),re(cs,"diff",void 0,{replace:!0}),re(Jt,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ds(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Zi({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(Go(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Go(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Zi(Jo(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){re(ls,"file",e.selectedFilePath,{replace:!0}),re(cs,"diff",e.selectedDiffPath,{replace:!0}),re(Jt,"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)??Wp(e.id);if(await this.restoreRouteFor(Jo(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=Gr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=ef(e,{api:{runTerminalCommand:(r,n)=>ot.runTerminalCommand(r,n,t),listCommandRuns:r=>ot.listCommandRuns(r,t),getCommandRun:r=>ot.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"未找到用于运行终端命令的机器"});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){re(Jt,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,Qi(e)}closeSettings(){this.settingsSection=void 0,Qi(void 0)}navigateSettings(e){this.settingsSection=e,Qi(e)}restoreSettingsRoute(){this.settingsSection=dr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Vo;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Ib(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):Tb(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await ot.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=Kr(e),s=Kr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),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`
|
|
2028
2059
|
<workspace-panel
|
|
2029
2060
|
id="workspace-panel"
|
|
2030
2061
|
.workspace=${e}
|
|
@@ -2070,7 +2101,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2070
2101
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
2071
2102
|
.onReset=${()=>{this.resetResizablePanel("workspace")}}
|
|
2072
2103
|
></app-panel-edge-control>
|
|
2073
|
-
`}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-
|
|
2104
|
+
`}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-Sb-xb);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(kb).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()}renderNavigationPanel(){return l`
|
|
2074
2105
|
<app-navigation-panel
|
|
2075
2106
|
.machines=${this.state.machines}
|
|
2076
2107
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -2086,7 +2117,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2086
2117
|
.workspacesByProjectId=${this.state.workspacesByProjectId}
|
|
2087
2118
|
.workspaces=${this.state.workspaces}
|
|
2088
2119
|
.selectedWorkspace=${this.state.selectedWorkspace}
|
|
2089
|
-
.deletingWorkspaceIds=${
|
|
2120
|
+
.deletingWorkspaceIds=${xh(this.state.workspaceDeletionRuns)}
|
|
2090
2121
|
.sessions=${this.state.sessions}
|
|
2091
2122
|
.sessionStatuses=${this.state.sessionStatuses}
|
|
2092
2123
|
.sessionActivities=${this.state.sessionActivities}
|
|
@@ -2118,14 +2149,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2118
2149
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
2119
2150
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
2120
2151
|
></app-navigation-panel>
|
|
2121
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!
|
|
2152
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Si(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 ds(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await ds(),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=qr(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=>gs.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=qr(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return hu({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},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)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Xu(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",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",()=>rr())}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}`,()=>rr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>pu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:()=>this.machines.refreshMachineHealth(),removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Rp(e)){this.setState({error:"只能删除次级 Git worktree"});return}if(_n(this.state,e))return;const t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?
|
|
2122
2153
|
|
|
2123
2154
|
这会运行 git worktree remove 并删除:
|
|
2124
2155
|
${e.path}
|
|
2125
2156
|
|
|
2126
|
-
Git 分支不会被删除。`))return;const s=g(this.state);try{const o=await
|
|
2157
|
+
Git 分支不会被删除。`))return;const s=g(this.state);try{const o=await gs.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`启动工作区删除失败:${Mb(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=xs(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(wh(t.id));if(g(this.state)!==e)return;const s=yh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))ui(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("刷新工作区删除任务失败",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(ui);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=Gr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=xs(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:Rb(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})}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
|
|
2127
2158
|
|
|
2128
|
-
这只会将它从当前 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 o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?
|
|
2159
|
+
这只会将它从当前 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 o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Hr:as;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${Gt}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开":"关"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${Gt}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===as||e===Hr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===as},this.applyPreferredTheme(!0);return}if(!e.startsWith(Gt))return;const t=e.slice(Gt.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,rh(t),e&&oh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return nh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return On(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=>({value:i,label:`${Db(i)}${i===t?" ✓ 当前":""}`,description:Eb(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),Ab(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){typeof e=="string"&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
|
|
2129
2160
|
<app-context-bar
|
|
2130
2161
|
.machines=${this.state.machines}
|
|
2131
2162
|
.machine=${this.state.selectedMachine}
|
|
@@ -2146,7 +2177,7 @@ Git 分支不会被删除。`))return;const s=g(this.state);try{const o=await fs
|
|
|
2146
2177
|
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
|
|
2147
2178
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
2148
2179
|
${this.renderNavigationPanelEdgeControl()}
|
|
2149
|
-
<main class=${
|
|
2180
|
+
<main class=${Un(e.mainView)}>
|
|
2150
2181
|
${this.renderContextBar()}
|
|
2151
2182
|
${this.renderMobileMainTabs()}
|
|
2152
2183
|
${e.error?l`<div class="error">${e.error}</div>`:null}
|
|
@@ -2169,4 +2200,4 @@ Git 分支不会被删除。`))return;const s=g(this.state);try{const o=await fs
|
|
|
2169
2200
|
${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
|
|
2170
2201
|
${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
|
|
2171
2202
|
</div>
|
|
2172
|
-
`}};le.styles=
|
|
2203
|
+
`}};le.styles=ff;Pe([w()],le.prototype,"state",2);Pe([F("chat-view")],le.prototype,"chatView",2);Pe([F("prompt-editor")],le.prototype,"promptEditor",2);Pe([F("app-navigation-panel")],le.prototype,"navigationPanel",2);Pe([F("#navigation-panel")],le.prototype,"navigationPanelFrame",2);Pe([F("#workspace-panel")],le.prototype,"workspacePanelFrame",2);Pe([w()],le.prototype,"activeThemeId",2);Pe([w()],le.prototype,"isRefreshingApp",2);Pe([w()],le.prototype,"settingsSection",2);Pe([w()],le.prototype,"shortcutConfig",2);le=Pe([R("pi-web-app")],le);function $b(){const e=new cu;return e.register({id:"core",plugin:Vh}),e.register({id:"themes",plugin:Qh}),e}function qr(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 Pb(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Ib(e,t){return Pa(e,t)}function Pa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Cb(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Kr(e){return Ci(e.status,e.activity)}function Tb(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Vr(){return{}}function Gr(e,t){return JSON.stringify([e,t])}function Mb(e){return e instanceof Error?e.message:String(e)}function Rb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ds(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Ab(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function Eb(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)"}}function Db(e){switch(e){case"off":return"关闭";case"minimal":return"极简";case"low":return"低";case"medium":return"中";case"high":return"高";case"xhigh":return"超高"}}export{A as a,l as b,ot as c,qb as d,F as e,Ub as f,T as i,d as n,w as r,Hb as s,R as t};
|