@linkshell/gateway 0.6.6 → 0.6.7

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/qr-scanner.min-zIfv4GCN.js","assets/markdown-SZOrMO_3.js","assets/account-R7yD1rZE.js","assets/terminal-DWFexEE4.js","assets/terminal-DOrYoP_4.css","assets/Prototype-BPv0rB08.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/qr-scanner.min--SdQwB7X.js","assets/markdown-SZOrMO_3.js","assets/account-R7yD1rZE.js","assets/terminal-DWFexEE4.js","assets/terminal-DOrYoP_4.css","assets/Prototype-CXD_ISo-.js"])))=>i.map(i=>d[i]);
2
2
  import{r as E1,g as cA,a as b,R as Zs,j as f,b as cl,M as uA,c as dA,d as fA}from"./markdown-SZOrMO_3.js";import{_ as Ls,a as _1,b as hA,c as mA}from"./account-R7yD1rZE.js";import{D as pA,o as gA}from"./terminal-DWFexEE4.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"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function s(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=s(o);fetch(o.href,l)}})();function C1(n){var t,s,r="";if(typeof n=="string"||typeof n=="number")r+=n;else if(typeof n=="object")if(Array.isArray(n)){var o=n.length;for(t=0;t<o;t++)n[t]&&(s=C1(n[t]))&&(r&&(r+=" "),r+=s)}else for(s in n)n[s]&&(r&&(r+=" "),r+=s);return r}function A1(){for(var n,t,s=0,r="",o=arguments.length;s<o;s++)(n=arguments[s])&&(t=C1(n))&&(r&&(r+=" "),r+=t);return r}const vA=(n,t)=>{const s=new Array(n.length+t.length);for(let r=0;r<n.length;r++)s[r]=n[r];for(let r=0;r<t.length;r++)s[n.length+r]=t[r];return s},yA=(n,t)=>({classGroupId:n,validator:t}),j1=(n=new Map,t=null,s)=>({nextPart:n,validators:t,classGroupId:s}),Eu="-",gb=[],bA="arbitrary..",xA=n=>{const t=SA(n),{conflictingClassGroups:s,conflictingClassGroupModifiers:r}=n;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return wA(u);const d=u.split(Eu),m=d[0]===""&&d.length>1?1:0;return T1(d,m,t)},getConflictingClassGroupIds:(u,d)=>{if(d){const m=r[u],p=s[u];return m?p?vA(p,m):m:p||gb}return s[u]||gb}}},T1=(n,t,s)=>{if(n.length-t===0)return s.classGroupId;const o=n[t],l=s.nextPart.get(o);if(l){const p=T1(n,t+1,l);if(p)return p}const u=s.validators;if(u===null)return;const d=t===0?n.join(Eu):n.slice(t).join(Eu),m=u.length;for(let p=0;p<m;p++){const y=u[p];if(y.validator(d))return y.classGroupId}},wA=n=>n.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=n.slice(1,-1),s=t.indexOf(":"),r=t.slice(0,s);return r?bA+r:void 0})(),SA=n=>{const{theme:t,classGroups:s}=n;return EA(s,t)},EA=(n,t)=>{const s=j1();for(const r in n){const o=n[r];bp(o,s,r,t)}return s},bp=(n,t,s,r)=>{const o=n.length;for(let l=0;l<o;l++){const u=n[l];_A(u,t,s,r)}},_A=(n,t,s,r)=>{if(typeof n=="string"){CA(n,t,s);return}if(typeof n=="function"){AA(n,t,s,r);return}jA(n,t,s,r)},CA=(n,t,s)=>{const r=n===""?t:k1(t,n);r.classGroupId=s},AA=(n,t,s,r)=>{if(TA(n)){bp(n(r),t,s,r);return}t.validators===null&&(t.validators=[]),t.validators.push(yA(s,n))},jA=(n,t,s,r)=>{const o=Object.entries(n),l=o.length;for(let u=0;u<l;u++){const[d,m]=o[u];bp(m,k1(t,d),s,r)}},k1=(n,t)=>{let s=n;const r=t.split(Eu),o=r.length;for(let l=0;l<o;l++){const u=r[l];let d=s.nextPart.get(u);d||(d=j1(),s.nextPart.set(u,d)),s=d}return s},TA=n=>"isThemeGetter"in n&&n.isThemeGetter===!0,kA=n=>{if(n<1)return{get:()=>{},set:()=>{}};let t=0,s=Object.create(null),r=Object.create(null);const o=(l,u)=>{s[l]=u,t++,t>n&&(t=0,r=s,s=Object.create(null))};return{get(l){let u=s[l];if(u!==void 0)return u;if((u=r[l])!==void 0)return o(l,u),u},set(l,u){l in s?s[l]=u:o(l,u)}}},jm="!",vb=":",NA=[],yb=(n,t,s,r,o)=>({modifiers:n,hasImportantModifier:t,baseClassName:s,maybePostfixModifierPosition:r,isExternal:o}),OA=n=>{const{prefix:t,experimentalParseClassName:s}=n;let r=o=>{const l=[];let u=0,d=0,m=0,p;const y=o.length;for(let A=0;A<y;A++){const S=o[A];if(u===0&&d===0){if(S===vb){l.push(o.slice(m,A)),m=A+1;continue}if(S==="/"){p=A;continue}}S==="["?u++:S==="]"?u--:S==="("?d++:S===")"&&d--}const v=l.length===0?o:o.slice(m);let x=v,_=!1;v.endsWith(jm)?(x=v.slice(0,-1),_=!0):v.startsWith(jm)&&(x=v.slice(1),_=!0);const E=p&&p>m?p-m:void 0;return yb(l,_,x,E)};if(t){const o=t+vb,l=r;r=u=>u.startsWith(o)?l(u.slice(o.length)):yb(NA,!1,u,void 0,!0)}if(s){const o=r;r=l=>s({className:l,parseClassName:o})}return r},RA=n=>{const t=new Map;return n.orderSensitiveModifiers.forEach((s,r)=>{t.set(s,1e6+r)}),s=>{const r=[];let o=[];for(let l=0;l<s.length;l++){const u=s[l],d=u[0]==="[",m=t.has(u);d||m?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(u)):o.push(u)}return o.length>0&&(o.sort(),r.push(...o)),r}},DA=n=>({cache:kA(n.cacheSize),parseClassName:OA(n),sortModifiers:RA(n),postfixLookupClassGroupIds:MA(n),...xA(n)}),MA=n=>{const t=Object.create(null),s=n.postfixLookupClassGroups;if(s)for(let r=0;r<s.length;r++)t[s[r]]=!0;return t},zA=/\s+/,LA=(n,t)=>{const{parseClassName:s,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:l,postfixLookupClassGroupIds:u}=t,d=[],m=n.trim().split(zA);let p="";for(let y=m.length-1;y>=0;y-=1){const v=m[y],{isExternal:x,modifiers:_,hasImportantModifier:E,baseClassName:A,maybePostfixModifierPosition:S}=s(v);if(x){p=v+(p.length>0?" "+p:p);continue}let j=!!S,T;if(j){const M=A.substring(0,S);T=r(M);const z=T&&u[T]?r(A):void 0;z&&z!==T&&(T=z,j=!1)}else T=r(A);if(!T){if(!j){p=v+(p.length>0?" "+p:p);continue}if(T=r(A),!T){p=v+(p.length>0?" "+p:p);continue}j=!1}const k=_.length===0?"":_.length===1?_[0]:l(_).join(":"),C=E?k+jm:k,R=C+T;if(d.indexOf(R)>-1)continue;d.push(R);const O=o(T,j);for(let M=0;M<O.length;++M){const z=O[M];d.push(C+z)}p=v+(p.length>0?" "+p:p)}return p},UA=(...n)=>{let t=0,s,r,o="";for(;t<n.length;)(s=n[t++])&&(r=N1(s))&&(o&&(o+=" "),o+=r);return o},N1=n=>{if(typeof n=="string")return n;let t,s="";for(let r=0;r<n.length;r++)n[r]&&(t=N1(n[r]))&&(s&&(s+=" "),s+=t);return s},BA=(n,...t)=>{let s,r,o,l;const u=m=>{const p=t.reduce((y,v)=>v(y),n());return s=DA(p),r=s.cache.get,o=s.cache.set,l=d,d(m)},d=m=>{const p=r(m);if(p)return p;const y=LA(m,s);return o(m,y),y};return l=u,(...m)=>l(UA(...m))},IA=[],zt=n=>{const t=s=>s[n]||IA;return t.isThemeGetter=!0,t.themeKey=n,t},O1=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,R1=/^\((?:(\w[\w-]*):)?(.+)\)$/i,HA=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,VA=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qA=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,$A=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,PA=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,FA=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,js=n=>HA.test(n),Ve=n=>!!n&&!Number.isNaN(Number(n)),ia=n=>!!n&&Number.isInteger(Number(n)),$h=n=>n.endsWith("%")&&Ve(n.slice(0,-1)),Ba=n=>VA.test(n),D1=()=>!0,GA=n=>qA.test(n)&&!$A.test(n),xp=()=>!1,ZA=n=>PA.test(n),YA=n=>FA.test(n),KA=n=>!ve(n)&&!ye(n),XA=n=>n.startsWith("@container")&&(n[10]==="/"&&n[11]!==void 0||n[11]==="s"&&n[16]!==void 0&&n.startsWith("-size/",10)||n[11]==="n"&&n[18]!==void 0&&n.startsWith("-normal/",10)),QA=n=>Ys(n,L1,xp),ve=n=>O1.test(n),br=n=>Ys(n,U1,GA),bb=n=>Ys(n,rj,Ve),WA=n=>Ys(n,I1,D1),JA=n=>Ys(n,B1,xp),xb=n=>Ys(n,M1,xp),ej=n=>Ys(n,z1,YA),Xc=n=>Ys(n,H1,ZA),ye=n=>R1.test(n),sl=n=>Vr(n,U1),tj=n=>Vr(n,B1),wb=n=>Vr(n,M1),nj=n=>Vr(n,L1),aj=n=>Vr(n,z1),Qc=n=>Vr(n,H1,!0),sj=n=>Vr(n,I1,!0),Ys=(n,t,s)=>{const r=O1.exec(n);return r?r[1]?t(r[1]):s(r[2]):!1},Vr=(n,t,s=!1)=>{const r=R1.exec(n);return r?r[1]?t(r[1]):s:!1},M1=n=>n==="position"||n==="percentage",z1=n=>n==="image"||n==="url",L1=n=>n==="length"||n==="size"||n==="bg-size",U1=n=>n==="length",rj=n=>n==="number",B1=n=>n==="family-name",I1=n=>n==="number"||n==="weight",H1=n=>n==="shadow",ij=()=>{const n=zt("color"),t=zt("font"),s=zt("text"),r=zt("font-weight"),o=zt("tracking"),l=zt("leading"),u=zt("breakpoint"),d=zt("container"),m=zt("spacing"),p=zt("radius"),y=zt("shadow"),v=zt("inset-shadow"),x=zt("text-shadow"),_=zt("drop-shadow"),E=zt("blur"),A=zt("perspective"),S=zt("aspect"),j=zt("ease"),T=zt("animate"),k=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...C(),ye,ve],O=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto","contain","none"],z=()=>[ye,ve,m],L=()=>[js,"full","auto",...z()],q=()=>[ia,"none","subgrid",ye,ve],V=()=>["auto",{span:["full",ia,ye,ve]},ia,ye,ve],G=()=>[ia,"auto",ye,ve],Z=()=>["auto","min","max","fr",ye,ve],ee=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],re=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...z()],$=()=>[js,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...z()],W=()=>[d,js,"screen","full","dvw","lvw","svw","min","max","fit",...z()],J=()=>[js,"screen","full","lh","dvh","lvh","svh","min","max","fit",...z()],Q=()=>[n,ye,ve],pe=()=>[...C(),wb,xb,{position:[ye,ve]}],F=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",nj,QA,{size:[ye,ve]}],de=()=>[$h,sl,br],ce=()=>["","none","full",p,ye,ve],ie=()=>["",Ve,sl,br],we=()=>["solid","dashed","dotted","double"],me=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],he=()=>[Ve,$h,wb,xb],De=()=>["","none",E,ye,ve],Oe=()=>["none",Ve,ye,ve],Me=()=>["none",Ve,ye,ve],He=()=>[Ve,ye,ve],ze=()=>[js,"full",...z()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ba],breakpoint:[Ba],color:[D1],container:[Ba],"drop-shadow":[Ba],ease:["in","out","in-out"],font:[KA],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ba],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ba],shadow:[Ba],spacing:["px",Ve],text:[Ba],"text-shadow":[Ba],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",js,ve,ye,S]}],container:["container"],"container-type":[{"@container":["","normal","size",ye,ve]}],"container-named":[XA],columns:[{columns:[Ve,"auto",ve,ye,d]}],"break-after":[{"break-after":k()}],"break-before":[{"break-before":k()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:R()}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:L()}],"inset-x":[{"inset-x":L()}],"inset-y":[{"inset-y":L()}],start:[{"inset-s":L(),start:L()}],end:[{"inset-e":L(),end:L()}],"inset-bs":[{"inset-bs":L()}],"inset-be":[{"inset-be":L()}],top:[{top:L()}],right:[{right:L()}],bottom:[{bottom:L()}],left:[{left:L()}],visibility:["visible","invisible","collapse"],z:[{z:[ia,"auto",ye,ve]}],basis:[{basis:[js,"full","auto",d,...z()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ve,js,"auto","initial","none",ve]}],grow:[{grow:["",Ve,ye,ve]}],shrink:[{shrink:["",Ve,ye,ve]}],order:[{order:[ia,"first","last","none",ye,ve]}],"grid-cols":[{"grid-cols":q()}],"col-start-end":[{col:V()}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":q()}],"row-start-end":[{row:V()}],"row-start":[{"row-start":G()}],"row-end":[{"row-end":G()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":Z()}],"auto-rows":[{"auto-rows":Z()}],gap:[{gap:z()}],"gap-x":[{"gap-x":z()}],"gap-y":[{"gap-y":z()}],"justify-content":[{justify:[...ee(),"normal"]}],"justify-items":[{"justify-items":[...re(),"normal"]}],"justify-self":[{"justify-self":["auto",...re()]}],"align-content":[{content:["normal",...ee()]}],"align-items":[{items:[...re(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...re(),{baseline:["","last"]}]}],"place-content":[{"place-content":ee()}],"place-items":[{"place-items":[...re(),"baseline"]}],"place-self":[{"place-self":["auto",...re()]}],p:[{p:z()}],px:[{px:z()}],py:[{py:z()}],ps:[{ps:z()}],pe:[{pe:z()}],pbs:[{pbs:z()}],pbe:[{pbe:z()}],pt:[{pt:z()}],pr:[{pr:z()}],pb:[{pb:z()}],pl:[{pl:z()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mbs:[{mbs:U()}],mbe:[{mbe:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":z()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":z()}],"space-y-reverse":["space-y-reverse"],size:[{size:$()}],"inline-size":[{inline:["auto",...W()]}],"min-inline-size":[{"min-inline":["auto",...W()]}],"max-inline-size":[{"max-inline":["none",...W()]}],"block-size":[{block:["auto",...J()]}],"min-block-size":[{"min-block":["auto",...J()]}],"max-block-size":[{"max-block":["none",...J()]}],w:[{w:[d,"screen",...$()]}],"min-w":[{"min-w":[d,"screen","none",...$()]}],"max-w":[{"max-w":[d,"screen","none","prose",{screen:[u]},...$()]}],h:[{h:["screen","lh",...$()]}],"min-h":[{"min-h":["screen","lh","none",...$()]}],"max-h":[{"max-h":["screen","lh","none",...$()]}],"font-size":[{text:["base",s,sl,br]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,sj,WA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",$h,ve]}],"font-family":[{font:[tj,JA,t]}],"font-features":[{"font-features":[ve]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,ye,ve]}],"line-clamp":[{"line-clamp":[Ve,"none",ye,bb]}],leading:[{leading:["none",l,...z()]}],"list-image":[{"list-image":["none",ye,ve]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",ye,ve]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:Q()}],"text-color":[{text:Q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...we(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ve,"from-font","auto",ye,br]}],"text-decoration-color":[{decoration:Q()}],"underline-offset":[{"underline-offset":[Ve,"auto",ye,ve]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:z()}],"tab-size":[{tab:[ia,ye,ve]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ye,ve]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",ye,ve]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:pe()}],"bg-repeat":[{bg:F()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ia,ye,ve],radial:["",ye,ve],conic:["",ia,ye,ve]},aj,ej]}],"bg-color":[{bg:Q()}],"gradient-from-pos":[{from:de()}],"gradient-via-pos":[{via:de()}],"gradient-to-pos":[{to:de()}],"gradient-from":[{from:Q()}],"gradient-via":[{via:Q()}],"gradient-to":[{to:Q()}],rounded:[{rounded:ce()}],"rounded-s":[{"rounded-s":ce()}],"rounded-e":[{"rounded-e":ce()}],"rounded-t":[{"rounded-t":ce()}],"rounded-r":[{"rounded-r":ce()}],"rounded-b":[{"rounded-b":ce()}],"rounded-l":[{"rounded-l":ce()}],"rounded-ss":[{"rounded-ss":ce()}],"rounded-se":[{"rounded-se":ce()}],"rounded-ee":[{"rounded-ee":ce()}],"rounded-es":[{"rounded-es":ce()}],"rounded-tl":[{"rounded-tl":ce()}],"rounded-tr":[{"rounded-tr":ce()}],"rounded-br":[{"rounded-br":ce()}],"rounded-bl":[{"rounded-bl":ce()}],"border-w":[{border:ie()}],"border-w-x":[{"border-x":ie()}],"border-w-y":[{"border-y":ie()}],"border-w-s":[{"border-s":ie()}],"border-w-e":[{"border-e":ie()}],"border-w-bs":[{"border-bs":ie()}],"border-w-be":[{"border-be":ie()}],"border-w-t":[{"border-t":ie()}],"border-w-r":[{"border-r":ie()}],"border-w-b":[{"border-b":ie()}],"border-w-l":[{"border-l":ie()}],"divide-x":[{"divide-x":ie()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ie()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...we(),"hidden","none"]}],"divide-style":[{divide:[...we(),"hidden","none"]}],"border-color":[{border:Q()}],"border-color-x":[{"border-x":Q()}],"border-color-y":[{"border-y":Q()}],"border-color-s":[{"border-s":Q()}],"border-color-e":[{"border-e":Q()}],"border-color-bs":[{"border-bs":Q()}],"border-color-be":[{"border-be":Q()}],"border-color-t":[{"border-t":Q()}],"border-color-r":[{"border-r":Q()}],"border-color-b":[{"border-b":Q()}],"border-color-l":[{"border-l":Q()}],"divide-color":[{divide:Q()}],"outline-style":[{outline:[...we(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ve,ye,ve]}],"outline-w":[{outline:["",Ve,sl,br]}],"outline-color":[{outline:Q()}],shadow:[{shadow:["","inner","none",y,Qc,Xc]}],"shadow-color":[{shadow:Q()}],"inset-shadow":[{"inset-shadow":["none",v,Qc,Xc]}],"inset-shadow-color":[{"inset-shadow":Q()}],"ring-w":[{ring:ie()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:Q()}],"ring-offset-w":[{"ring-offset":[Ve,br]}],"ring-offset-color":[{"ring-offset":Q()}],"inset-ring-w":[{"inset-ring":ie()}],"inset-ring-color":[{"inset-ring":Q()}],"text-shadow":[{"text-shadow":["none",x,Qc,Xc]}],"text-shadow-color":[{"text-shadow":Q()}],opacity:[{opacity:[Ve,ye,ve]}],"mix-blend":[{"mix-blend":[...me(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":me()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ve]}],"mask-image-linear-from-pos":[{"mask-linear-from":he()}],"mask-image-linear-to-pos":[{"mask-linear-to":he()}],"mask-image-linear-from-color":[{"mask-linear-from":Q()}],"mask-image-linear-to-color":[{"mask-linear-to":Q()}],"mask-image-t-from-pos":[{"mask-t-from":he()}],"mask-image-t-to-pos":[{"mask-t-to":he()}],"mask-image-t-from-color":[{"mask-t-from":Q()}],"mask-image-t-to-color":[{"mask-t-to":Q()}],"mask-image-r-from-pos":[{"mask-r-from":he()}],"mask-image-r-to-pos":[{"mask-r-to":he()}],"mask-image-r-from-color":[{"mask-r-from":Q()}],"mask-image-r-to-color":[{"mask-r-to":Q()}],"mask-image-b-from-pos":[{"mask-b-from":he()}],"mask-image-b-to-pos":[{"mask-b-to":he()}],"mask-image-b-from-color":[{"mask-b-from":Q()}],"mask-image-b-to-color":[{"mask-b-to":Q()}],"mask-image-l-from-pos":[{"mask-l-from":he()}],"mask-image-l-to-pos":[{"mask-l-to":he()}],"mask-image-l-from-color":[{"mask-l-from":Q()}],"mask-image-l-to-color":[{"mask-l-to":Q()}],"mask-image-x-from-pos":[{"mask-x-from":he()}],"mask-image-x-to-pos":[{"mask-x-to":he()}],"mask-image-x-from-color":[{"mask-x-from":Q()}],"mask-image-x-to-color":[{"mask-x-to":Q()}],"mask-image-y-from-pos":[{"mask-y-from":he()}],"mask-image-y-to-pos":[{"mask-y-to":he()}],"mask-image-y-from-color":[{"mask-y-from":Q()}],"mask-image-y-to-color":[{"mask-y-to":Q()}],"mask-image-radial":[{"mask-radial":[ye,ve]}],"mask-image-radial-from-pos":[{"mask-radial-from":he()}],"mask-image-radial-to-pos":[{"mask-radial-to":he()}],"mask-image-radial-from-color":[{"mask-radial-from":Q()}],"mask-image-radial-to-color":[{"mask-radial-to":Q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[Ve]}],"mask-image-conic-from-pos":[{"mask-conic-from":he()}],"mask-image-conic-to-pos":[{"mask-conic-to":he()}],"mask-image-conic-from-color":[{"mask-conic-from":Q()}],"mask-image-conic-to-color":[{"mask-conic-to":Q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:pe()}],"mask-repeat":[{mask:F()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",ye,ve]}],filter:[{filter:["","none",ye,ve]}],blur:[{blur:De()}],brightness:[{brightness:[Ve,ye,ve]}],contrast:[{contrast:[Ve,ye,ve]}],"drop-shadow":[{"drop-shadow":["","none",_,Qc,Xc]}],"drop-shadow-color":[{"drop-shadow":Q()}],grayscale:[{grayscale:["",Ve,ye,ve]}],"hue-rotate":[{"hue-rotate":[Ve,ye,ve]}],invert:[{invert:["",Ve,ye,ve]}],saturate:[{saturate:[Ve,ye,ve]}],sepia:[{sepia:["",Ve,ye,ve]}],"backdrop-filter":[{"backdrop-filter":["","none",ye,ve]}],"backdrop-blur":[{"backdrop-blur":De()}],"backdrop-brightness":[{"backdrop-brightness":[Ve,ye,ve]}],"backdrop-contrast":[{"backdrop-contrast":[Ve,ye,ve]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ve,ye,ve]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ve,ye,ve]}],"backdrop-invert":[{"backdrop-invert":["",Ve,ye,ve]}],"backdrop-opacity":[{"backdrop-opacity":[Ve,ye,ve]}],"backdrop-saturate":[{"backdrop-saturate":[Ve,ye,ve]}],"backdrop-sepia":[{"backdrop-sepia":["",Ve,ye,ve]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":z()}],"border-spacing-x":[{"border-spacing-x":z()}],"border-spacing-y":[{"border-spacing-y":z()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",ye,ve]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ve,"initial",ye,ve]}],ease:[{ease:["linear","initial",j,ye,ve]}],delay:[{delay:[Ve,ye,ve]}],animate:[{animate:["none",T,ye,ve]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[A,ye,ve]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:Oe()}],"rotate-x":[{"rotate-x":Oe()}],"rotate-y":[{"rotate-y":Oe()}],"rotate-z":[{"rotate-z":Oe()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:He()}],"skew-x":[{"skew-x":He()}],"skew-y":[{"skew-y":He()}],transform:[{transform:[ye,ve,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ze()}],"translate-x":[{"translate-x":ze()}],"translate-y":[{"translate-y":ze()}],"translate-z":[{"translate-z":ze()}],"translate-none":["translate-none"],zoom:[{zoom:[ia,ye,ve]}],accent:[{accent:Q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:Q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",ye,ve]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":Q()}],"scrollbar-track-color":[{"scrollbar-track":Q()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":z()}],"scroll-mx":[{"scroll-mx":z()}],"scroll-my":[{"scroll-my":z()}],"scroll-ms":[{"scroll-ms":z()}],"scroll-me":[{"scroll-me":z()}],"scroll-mbs":[{"scroll-mbs":z()}],"scroll-mbe":[{"scroll-mbe":z()}],"scroll-mt":[{"scroll-mt":z()}],"scroll-mr":[{"scroll-mr":z()}],"scroll-mb":[{"scroll-mb":z()}],"scroll-ml":[{"scroll-ml":z()}],"scroll-p":[{"scroll-p":z()}],"scroll-px":[{"scroll-px":z()}],"scroll-py":[{"scroll-py":z()}],"scroll-ps":[{"scroll-ps":z()}],"scroll-pe":[{"scroll-pe":z()}],"scroll-pbs":[{"scroll-pbs":z()}],"scroll-pbe":[{"scroll-pbe":z()}],"scroll-pt":[{"scroll-pt":z()}],"scroll-pr":[{"scroll-pr":z()}],"scroll-pb":[{"scroll-pb":z()}],"scroll-pl":[{"scroll-pl":z()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ye,ve]}],fill:[{fill:["none",...Q()]}],"stroke-w":[{stroke:[Ve,sl,br,bb]}],stroke:[{stroke:["none",...Q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["start","end","right","left"],"inset-y":["inset-bs","inset-be","top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["ps","pe","pr","pl"],py:["pbs","pbe","pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["ms","me","mr","ml"],my:["mbs","mbe","mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-s","border-w-e","border-w-r","border-w-l"],"border-w-y":["border-w-bs","border-w-be","border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-s","border-color-e","border-color-r","border-color-l"],"border-color-y":["border-color-bs","border-color-be","border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-ms","scroll-me","scroll-mr","scroll-ml"],"scroll-my":["scroll-mbs","scroll-mbe","scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-ps","scroll-pe","scroll-pr","scroll-pl"],"scroll-py":["scroll-pbs","scroll-pbe","scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},oj=BA(ij);function qe(...n){return oj(A1(n))}var Ph={exports:{}},en={};/**
3
3
  * @license React
4
4
  * react-dom.production.js
@@ -150,13 +150,13 @@ Error generating stack: `+c.message+`
150
150
  ${JSON.stringify(t)}
151
151
  </send_user_message_question_reply>
152
152
  `}function JS(n){const t=/^<send_user_message_question_reply>\n([\s\S]+)\n<\/send_user_message_question_reply>$/.exec(n.replace(/\r\n/g,`
153
- `).trim());if(!t)return;let s;try{s=JSON.parse(t[1])}catch{return}if(!Array.isArray(s)||s.length===0)return;const r=[];for(const o of s){if(!o||typeof o!="object")return;const{questionItemId:l,question:u,answer:d}=o;if(typeof u!="string"||typeof d!="string")return;r.push({...typeof l=="string"?{id:l}:{},question:u.trim(),answer:d.trim()})}return r}function gN(n){return(JS(n)??[]).flatMap(t=>t.id?[[t.id,t.answer]]:[])}function Yi(n){return{sessionId:n,lastSeq:0,startSeq:0,items:[],index:{},permissions:[],config:[],commands:[],state:"idle",turnActive:!1}}function Xt(n,t){const s=n.index[t.id];if(s===void 0)return{...n,items:[...n.items,t],index:{...n.index,[t.id]:n.items.length}};const r=n.items.slice();return r[s]=t,{...n,items:r}}function Un(n,t,s){const r=n.index[t],o=r===void 0?void 0:n.items[r];return o&&o.kind===s?o:void 0}function ux(n,t){return t.type==="text"?n+t.text:n}function bu(n,t){let s;return n.items.forEach((r,o)=>{(r.kind==="agent"||r.kind==="thought")&&r.streaming&&(s??=n.items.slice(),s[o]=r.kind==="thought"?{...r,streaming:!1,endedTs:r.endedTs??t}:{...r,streaming:!1})}),s?{...n,items:s}:n}function Ou(n,t){const s=bu(n,t);let r;return s.items.forEach((o,l)=>{if(o.kind!=="tool"||!o.sub)return;const u=Ou(o.sub,t);u!==o.sub&&(r??=s.items.slice(),r[l]={...o,sub:u})}),r?{...s,items:r}:s}function vN(n){switch(n.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":case"tool_call":case"tool_call_update":case"ls_message_done":case"ls_turn":return n.parentToolCallId;default:return}}function yN(n,t){return n.flatMap(s=>{const r=t.find(u=>u.id===s.id);if(!r)return[];const o=r.values.filter(Boolean).map(u=>s.options?.find(d=>d.value===u)?.label??u),l=[...s.secret&&o.length>0?["••••••"]:o,...r.other?[r.other]:[]];return l.length>0?[{question:s.header??s.text,answer:l.join(",")}]:[]})}function e2(n,t,s,r,o){if(!Un(n,t,"tool")){for(const m of n.items)if(!(m.kind!=="tool"||!m.sub||!Wp(m.sub,t)))return Xt(n,{...m,sub:e2(m.sub,t,s,r,o)})}const l=Un(n,t,"tool")??{kind:"tool",id:t,title:"Sub-agent",toolKind:"other",status:"in_progress",detail:{type:"subagent",action:"spawn"},content:[],output:"",ts:r},u={...s,parentToolCallId:void 0},d=Jp(l.sub??Yi(n.sessionId),u,r,o);return d===l.sub?n:Xt(n,{...l,sub:d})}function Wp(n,t){const s=Un(n,t,"tool");if(s)return s;for(const r of n.items){if(r.kind!=="tool"||!r.sub)continue;const o=Wp(r.sub,t);if(o)return o}}function Jp(n,t,s,r){const o=vN(t);if(o)return e2(n,o,t,s,r);switch(t.sessionUpdate){case"user_message_chunk":{const l=t.messageId??`user-${r}`,u=Un(n,l,"user"),d=u&&!u.pending?[...u.blocks,t.content]:[t.content];return Xt(n,{kind:"user",id:l,blocks:t2(d),ts:u?.ts??s})}case"agent_message_chunk":{const l=Un(n,t.messageId,"agent"),u=t.content.type==="text"?l?.attachments:[...l?.attachments??[],t.content];return Xt(n,{kind:"agent",id:t.messageId,text:ux(l?.text??"",t.content),attachments:u,streaming:!0,ts:l?.ts??s})}case"agent_thought_chunk":{const l=`thought:${t.messageId}`,u=Un(n,l,"thought");return Xt(n,{kind:"thought",id:l,text:ux(u?.text??"",t.content),streaming:!0,ts:u?.ts??s})}case"ls_message_done":{const l=t.role==="thought"?`thought:${t.messageId}`:t.messageId,u=Un(n,l,"agent");if(u)return Xt(n,{...u,streaming:!1,...t.questions?.length?{questions:t.questions}:{}});const d=Un(n,l,"thought");return d?Xt(n,{...d,streaming:!1,endedTs:d.endedTs??s}):n}case"tool_call":{const l=Un(n,t.toolCallId,"tool"),u=t.status==="completed"||t.status==="failed";return Xt(bu(n,s),{kind:"tool",id:t.toolCallId,title:t.title,toolKind:t.kind,status:t.status,rawInput:t.rawInput??l?.rawInput,rawOutput:l?.rawOutput,locations:t.locations??l?.locations,detail:t.detail??l?.detail,sub:l?.sub,content:t.content??l?.content??[],output:l?.output??"",ts:l?.ts??s,endedTs:u?s:l?.endedTs})}case"tool_call_update":{const u=Un(n,t.toolCallId,"tool")??{kind:"tool",id:t.toolCallId,title:t.title??"Tool",toolKind:"other",status:"in_progress",content:[],output:"",ts:s},d=t.status??u.status,m=d==="completed"||d==="failed";return Xt(n,{...u,title:t.title??u.title,detail:t.detail??u.detail,status:d,content:t.content?a2(u.content,t.content):u.content,output:t.appendOutput?u.output+t.appendOutput:u.output,rawOutput:t.rawOutput??u.rawOutput,endedTs:m?u.endedTs??s:u.endedTs,sub:m&&u.sub?Ou(u.sub,s):u.sub})}case"plan":{const l=n.planId??`plan-${r}`;return{...Xt(n,{kind:"plan",id:l,entries:t.entries,ts:Un(n,l,"plan")?.ts??s}),planId:l}}case"available_commands_update":return{...n,commands:t.availableCommands};case"ls_goal":return{...n,goal:t.goal};case"current_mode_update":return{...n,modeId:t.currentModeId,config:n.config.map(l=>l.category==="mode"?{...l,current:t.currentModeId}:l)};case"ls_config":return{...n,config:t.options,modeId:t.options.find(l=>l.category==="mode")?.current??n.modeId};case"session_info_update":return{...n,title:t.title??n.title};case"usage_update":return{...n,usage:{usedTokens:t.usedTokens,contextWindow:t.contextWindow}};case"ls_turn":if(t.state==="started")return{...n,turnActive:!0,state:"running",planId:void 0};{const u={...Ou(n,s),turnActive:!1,state:t.stopReason==="error"?"error":"idle",permissions:[]};return t.stopReason==="cancelled"?Xt(u,{kind:"turn-end",id:`turn-end-${r}`,stopReason:"cancelled",ts:s}):u}case"ls_status":return{...n,state:t.state};case"ls_permission":return n.permissions.some(l=>l.requestId===t.requestId)?n:{...bu(n,s),state:"waiting",permissions:[...n.permissions,{requestId:t.requestId,toolCallId:t.toolCallId,title:t.title,detail:t.detail,options:t.options,questions:t.questions,ts:s}]};case"ls_permission_resolved":{const l=n.permissions.find(p=>p.requestId===t.requestId);if(!l)return n;const u=l.options.find(p=>p.optionId===t.optionId),d=n.permissions.filter(p=>p.requestId!==t.requestId),m={...n,permissions:d,state:d.length>0?"waiting":n.turnActive?"running":n.state==="waiting"?"idle":n.state};return Xt(m,{kind:"permission-result",id:`perm-${t.requestId}`,title:l.title,detail:l.detail,optionName:u?.name,allowed:u?u.kind.startsWith("allow"):void 0,asked:l.questions?!0:void 0,answers:l.questions&&t.answers?yN(l.questions,t.answers):void 0,ts:s})}case"ls_driver":{if(n.driver===t.driver)return n;const l={...n,driver:t.driver};return n.driver===void 0?l:Xt(l,{kind:"driver",id:`driver-${r}`,driver:t.driver,ts:s})}case"ls_error":return Xt(bu(n,s),{kind:"error",id:`error-${r}`,code:t.code,message:t.message,hint:t.hint,ts:s});case"ls_notice":return Xt(n,{kind:"notice",id:`notice-${r}`,level:t.level,title:t.title,detail:t.detail,ts:s});default:return n}}function t2(n){const t=[];for(const s of n){const r=t[t.length-1];s.type==="text"&&r?.type==="text"?t[t.length-1]={type:"text",text:r.text+s.text}:t.push(s)}return t}function bN(n,t){if(t.seq<=n.lastSeq)return n;const s=Jp(n,t.update,t.ts,String(t.seq));return s===n?{...n,lastSeq:t.seq}:{...s,lastSeq:t.seq}}function lm(n,t){return t.reduce(bN,n)}function xN(n,t){if(n.lastSeq===0)return{...n,startSeq:t};if(n.lastSeq===t)return n;const s=n.items.filter(o=>o.kind==="user"&&(o.pending||o.failed)),r={};return s.forEach((o,l)=>{r[o.id]=l}),{...Yi(n.sessionId),startSeq:t,items:s,index:r}}const wN=new Set(["Tool","Sub-agent"]);function SN(n,t){if(n.kind==="agent"&&t.kind==="agent"){const s=[...n.attachments??[],...t.attachments??[]];return{...t,text:n.text+t.text,attachments:s.length?s:void 0,ts:n.ts}}return n.kind==="thought"&&t.kind==="thought"?{...t,text:n.text+t.text,ts:n.ts}:n.kind==="user"&&t.kind==="user"?{...t,blocks:t2([...n.blocks,...t.blocks]),ts:n.ts}:n.kind==="tool"&&t.kind==="tool"?{...t,title:wN.has(t.title)?n.title:t.title,toolKind:n.toolKind,rawInput:t.rawInput??n.rawInput,rawOutput:t.rawOutput??n.rawOutput,locations:t.locations??n.locations,detail:t.detail??n.detail,content:t.content.length?a2(n.content,t.content):n.content,output:n.output+t.output,sub:n.sub&&t.sub?n2(n.sub,t.sub):t.sub??n.sub,ts:n.ts,endedTs:t.endedTs??n.endedTs}:t}function n2(n,t){const s=[],r=new Set;for(const l of n.items){const u=t.index[l.id];u===void 0?s.push(l):(s.push(SN(l,t.items[u])),r.add(l.id))}for(const l of t.items)r.has(l.id)||s.push(l);const o={};return s.forEach((l,u)=>{o[l.id]=u}),{...t,items:s,index:o}}function EN(n,t,s){let r=Yi(n.sessionId);for(const o of t)r=Jp(r,o.update,o.ts,String(o.seq));return r=Ou(r,t[t.length-1]?.ts??0),{...n2(r,n),startSeq:s}}function iu(n,t,s,r=Date.now(),o=!1){return Xt(n,{kind:"user",id:`local-${t}`,blocks:s,ts:r,pending:!0,...o?{accepted:!0}:{}})}function dx(n,t){const s=Un(n,`local-${t}`,"user");return s&&s.pending?Xt(n,{...s,pending:!1,failed:!0}):n}function fx(n,t){const s=n.index[t];if(s===void 0)return n;const r=n.items.filter((l,u)=>u!==s),o={};return r.forEach((l,u)=>{o[l.id]=u}),{...n,items:r,index:o}}function a2(n,t){if(t.some(r=>r.type==="diff"))return t;const s=n.filter(r=>r.type==="diff");return s.length?[...s,...t]:t}var et;(function(n){n.assertEqual=o=>{};function t(o){}n.assertIs=t;function s(o){throw new Error}n.assertNever=s,n.arrayToEnum=o=>{const l={};for(const u of o)l[u]=u;return l},n.getValidEnumValues=o=>{const l=n.objectKeys(o).filter(d=>typeof o[o[d]]!="number"),u={};for(const d of l)u[d]=o[d];return n.objectValues(u)},n.objectValues=o=>n.objectKeys(o).map(function(l){return o[l]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const l=[];for(const u in o)Object.prototype.hasOwnProperty.call(o,u)&&l.push(u);return l},n.find=(o,l)=>{for(const u of o)if(l(u))return u},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,l=" | "){return o.map(u=>typeof u=="string"?`'${u}'`:u).join(l)}n.joinValues=r,n.jsonStringifyReplacer=(o,l)=>typeof l=="bigint"?l.toString():l})(et||(et={}));var hx;(function(n){n.mergeShapes=(t,s)=>({...t,...s})})(hx||(hx={}));const be=et.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zs=n=>{switch(typeof n){case"undefined":return be.undefined;case"string":return be.string;case"number":return Number.isNaN(n)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(n)?be.array:n===null?be.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?be.promise:typeof Map<"u"&&n instanceof Map?be.map:typeof Set<"u"&&n instanceof Set?be.set:typeof Date<"u"&&n instanceof Date?be.date:be.object;default:return be.unknown}},fe=et.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Qa extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(l){return l.message},r={_errors:[]},o=l=>{for(const u of l.issues)if(u.code==="invalid_union")u.unionErrors.map(o);else if(u.code==="invalid_return_type")o(u.returnTypeError);else if(u.code==="invalid_arguments")o(u.argumentsError);else if(u.path.length===0)r._errors.push(s(u));else{let d=r,m=0;for(;m<u.path.length;){const p=u.path[m];m===u.path.length-1?(d[p]=d[p]||{_errors:[]},d[p]._errors.push(s(u))):d[p]=d[p]||{_errors:[]},d=d[p],m++}}};return o(this),r}static assert(t){if(!(t instanceof Qa))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,et.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=s=>s.message){const s={},r=[];for(const o of this.issues)if(o.path.length>0){const l=o.path[0];s[l]=s[l]||[],s[l].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}Qa.create=n=>new Qa(n);const Km=(n,t)=>{let s;switch(n.code){case fe.invalid_type:n.received===be.undefined?s="Required":s=`Expected ${n.expected}, received ${n.received}`;break;case fe.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(n.expected,et.jsonStringifyReplacer)}`;break;case fe.unrecognized_keys:s=`Unrecognized key(s) in object: ${et.joinValues(n.keys,", ")}`;break;case fe.invalid_union:s="Invalid input";break;case fe.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${et.joinValues(n.options)}`;break;case fe.invalid_enum_value:s=`Invalid enum value. Expected ${et.joinValues(n.options)}, received '${n.received}'`;break;case fe.invalid_arguments:s="Invalid function arguments";break;case fe.invalid_return_type:s="Invalid function return type";break;case fe.invalid_date:s="Invalid date";break;case fe.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(s=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?s=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?s=`Invalid input: must end with "${n.validation.endsWith}"`:et.assertNever(n.validation):n.validation!=="regex"?s=`Invalid ${n.validation}`:s="Invalid";break;case fe.too_small:n.type==="array"?s=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?s=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?s=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?s=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?s=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:s="Invalid input";break;case fe.too_big:n.type==="array"?s=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?s=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?s=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?s=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?s=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:s="Invalid input";break;case fe.custom:s="Invalid input";break;case fe.invalid_intersection_types:s="Intersection results could not be merged";break;case fe.not_multiple_of:s=`Number must be a multiple of ${n.multipleOf}`;break;case fe.not_finite:s="Number must be finite";break;default:s=t.defaultError,et.assertNever(n)}return{message:s}};let _N=Km;function CN(){return _N}const AN=n=>{const{data:t,path:s,errorMaps:r,issueData:o}=n,l=[...s,...o.path||[]],u={...o,path:l};if(o.message!==void 0)return{...o,path:l,message:o.message};let d="";const m=r.filter(p=>!!p).slice().reverse();for(const p of m)d=p(u,{data:t,defaultError:d}).message;return{...o,path:l,message:d}};function ge(n,t){const s=CN(),r=AN({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,s,s===Km?void 0:Km].filter(o=>!!o)});n.common.issues.push(r)}class sn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const r=[];for(const o of s){if(o.status==="aborted")return ke;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,s){const r=[];for(const o of s){const l=await o.key,u=await o.value;r.push({key:l,value:u})}return sn.mergeObjectSync(t,r)}static mergeObjectSync(t,s){const r={};for(const o of s){const{key:l,value:u}=o;if(l.status==="aborted"||u.status==="aborted")return ke;l.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),l.value!=="__proto__"&&(typeof u.value<"u"||o.alwaysSet)&&(r[l.value]=u.value)}return{status:t.value,value:r}}}const ke=Object.freeze({status:"aborted"}),ul=n=>({status:"dirty",value:n}),Vn=n=>({status:"valid",value:n}),mx=n=>n.status==="aborted",px=n=>n.status==="dirty",Wi=n=>n.status==="valid",Ru=n=>typeof Promise<"u"&&n instanceof Promise;var _e;(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(_e||(_e={}));class ya{constructor(t,s,r,o){this._cachedPath=[],this.parent=t,this.data=s,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const gx=(n,t)=>{if(Wi(t))return{success:!0,data:t.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new Qa(n.common.issues);return this._error=s,this._error}}};function Ie(n){if(!n)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:o}=n;if(t&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(u,d)=>{const{message:m}=n;return u.code==="invalid_enum_value"?{message:m??d.defaultError}:typeof d.data>"u"?{message:m??r??d.defaultError}:u.code!=="invalid_type"?{message:d.defaultError}:{message:m??s??d.defaultError}},description:o}}class Ye{get description(){return this._def.description}_getType(t){return zs(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:zs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sn,ctx:{common:t.parent.common,data:t.data,parsedType:zs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(Ru(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const r=this.safeParse(t,s);if(r.success)return r.data;throw r.error}safeParse(t,s){const r={common:{issues:[],async:s?.async??!1,contextualErrorMap:s?.errorMap},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)},o=this._parseSync({data:t,path:r.path,parent:r});return gx(r,o)}"~validate"(t){const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:s});return Wi(r)?{value:r.value}:{issues:s.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(r=>Wi(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(t,s){const r=await this.safeParseAsync(t,s);if(r.success)return r.data;throw r.error}async safeParseAsync(t,s){const r={common:{issues:[],contextualErrorMap:s?.errorMap,async:!0},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)},o=this._parse({data:t,path:r.path,parent:r}),l=await(Ru(o)?o:Promise.resolve(o));return gx(r,l)}refine(t,s){const r=o=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(o):s;return this._refinement((o,l)=>{const u=t(o),d=()=>l.addIssue({code:fe.custom,...r(o)});return typeof Promise<"u"&&u instanceof Promise?u.then(m=>m?!0:(d(),!1)):u?!0:(d(),!1)})}refinement(t,s){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof s=="function"?s(r,o):s),!1))}_refinement(t){return new Dr({schema:this,typeName:Ne.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Za.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ma.create(this)}promise(){return Bu.create(this,this._def)}or(t){return Mu.create([this,t],this._def)}and(t){return zu.create(this,t,this._def)}transform(t){return new Dr({...Ie(this._def),schema:this,typeName:Ne.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Iu({...Ie(this._def),innerType:this,defaultValue:s,typeName:Ne.ZodDefault})}brand(){return new o2({typeName:Ne.ZodBranded,type:this,...Ie(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new Hu({...Ie(this._def),innerType:this,catchValue:s,typeName:Ne.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return tg.create(this,t)}readonly(){return Vu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const jN=/^c[^\s-]{8,}$/i,TN=/^[0-9a-z]+$/,kN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,NN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ON=/^[a-z0-9_-]{21}$/i,RN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,DN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cm;const LN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,UN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,BN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,IN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,HN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,VN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,s2="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",qN=new RegExp(`^${s2}$`);function r2(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);const s=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function $N(n){return new RegExp(`^${r2(n)}$`)}function PN(n){let t=`${s2}T${r2(n)}`;const s=[];return s.push(n.local?"Z?":"Z"),n.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function FN(n,t){return!!((t==="v4"||!t)&&LN.test(n)||(t==="v6"||!t)&&BN.test(n))}function GN(n,t){if(!RN.test(n))return!1;try{const[s]=n.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function ZN(n,t){return!!((t==="v4"||!t)&&UN.test(n)||(t==="v6"||!t)&&IN.test(n))}class $a extends Ye{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.string,received:l.parsedType}),ke}const r=new sn;let o;for(const l of this._def.checks)if(l.kind==="min")t.data.length<l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),r.dirty());else if(l.kind==="max")t.data.length>l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),r.dirty());else if(l.kind==="length"){const u=t.data.length>l.value,d=t.data.length<l.value;(u||d)&&(o=this._getOrReturnCtx(t,o),u?ge(o,{code:fe.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):d&&ge(o,{code:fe.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),r.dirty())}else if(l.kind==="email")MN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"email",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="emoji")cm||(cm=new RegExp(zN,"u")),cm.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"emoji",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="uuid")NN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"uuid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="nanoid")ON.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"nanoid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="cuid")jN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cuid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="cuid2")TN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cuid2",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="ulid")kN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"ulid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ge(o,{validation:"url",code:fe.invalid_string,message:l.message}),r.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"regex",code:fe.invalid_string,message:l.message}),r.dirty())):l.kind==="trim"?t.data=t.data.trim():l.kind==="includes"?t.data.includes(l.value,l.position)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),r.dirty()):l.kind==="toLowerCase"?t.data=t.data.toLowerCase():l.kind==="toUpperCase"?t.data=t.data.toUpperCase():l.kind==="startsWith"?t.data.startsWith(l.value)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{startsWith:l.value},message:l.message}),r.dirty()):l.kind==="endsWith"?t.data.endsWith(l.value)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{endsWith:l.value},message:l.message}),r.dirty()):l.kind==="datetime"?PN(l).test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"datetime",message:l.message}),r.dirty()):l.kind==="date"?qN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"date",message:l.message}),r.dirty()):l.kind==="time"?$N(l).test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"time",message:l.message}),r.dirty()):l.kind==="duration"?DN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"duration",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="ip"?FN(t.data,l.version)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"ip",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="jwt"?GN(t.data,l.alg)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"jwt",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="cidr"?ZN(t.data,l.version)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cidr",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="base64"?HN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"base64",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="base64url"?VN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"base64url",code:fe.invalid_string,message:l.message}),r.dirty()):et.assertNever(l);return{status:r.value,value:t.data}}_regex(t,s,r){return this.refinement(o=>t.test(o),{validation:s,code:fe.invalid_string,..._e.errToObj(r)})}_addCheck(t){return new $a({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._e.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._e.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._e.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._e.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._e.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._e.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._e.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._e.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._e.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",..._e.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",..._e.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._e.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",..._e.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,..._e.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,..._e.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",..._e.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,..._e.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s?.position,..._e.errToObj(s?.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,..._e.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,..._e.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,..._e.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,..._e.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,..._e.errToObj(s)})}nonempty(t){return this.min(1,_e.errToObj(t))}trim(){return new $a({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $a({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $a({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}$a.create=n=>new $a({checks:[],typeName:Ne.ZodString,coerce:n?.coerce??!1,...Ie(n)});function YN(n,t){const s=(n.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=s>r?s:r,l=Number.parseInt(n.toFixed(o).replace(".","")),u=Number.parseInt(t.toFixed(o).replace(".",""));return l%u/10**o}class Ji extends Ye{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.number,received:l.parsedType}),ke}let r;const o=new sn;for(const l of this._def.checks)l.kind==="int"?et.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.invalid_type,expected:"integer",received:"float",message:l.message}),o.dirty()):l.kind==="min"?(l.inclusive?t.data<l.value:t.data<=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),o.dirty()):l.kind==="max"?(l.inclusive?t.data>l.value:t.data>=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),o.dirty()):l.kind==="multipleOf"?YN(t.data,l.value)!==0&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_multiple_of,multipleOf:l.value,message:l.message}),o.dirty()):l.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_finite,message:l.message}),o.dirty()):et.assertNever(l);return{status:o.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,_e.toString(s))}gt(t,s){return this.setLimit("min",t,!1,_e.toString(s))}lte(t,s){return this.setLimit("max",t,!0,_e.toString(s))}lt(t,s){return this.setLimit("max",t,!1,_e.toString(s))}setLimit(t,s,r,o){return new Ji({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:_e.toString(o)}]})}_addCheck(t){return new Ji({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_e.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:_e.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&et.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(s)&&Number.isFinite(t)}}Ji.create=n=>new Ji({checks:[],typeName:Ne.ZodNumber,coerce:n?.coerce||!1,...Ie(n)});class bl extends Ye{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==be.bigint)return this._getInvalidInput(t);let r;const o=new sn;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?t.data<l.value:t.data<=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),o.dirty()):l.kind==="max"?(l.inclusive?t.data>l.value:t.data>=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),o.dirty()):l.kind==="multipleOf"?t.data%l.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_multiple_of,multipleOf:l.value,message:l.message}),o.dirty()):et.assertNever(l);return{status:o.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return ge(s,{code:fe.invalid_type,expected:be.bigint,received:s.parsedType}),ke}gte(t,s){return this.setLimit("min",t,!0,_e.toString(s))}gt(t,s){return this.setLimit("min",t,!1,_e.toString(s))}lte(t,s){return this.setLimit("max",t,!0,_e.toString(s))}lt(t,s){return this.setLimit("max",t,!1,_e.toString(s))}setLimit(t,s,r,o){return new bl({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:_e.toString(o)}]})}_addCheck(t){return new bl({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}bl.create=n=>new bl({checks:[],typeName:Ne.ZodBigInt,coerce:n?.coerce??!1,...Ie(n)});class Xm extends Ye{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.boolean,received:r.parsedType}),ke}return Vn(t.data)}}Xm.create=n=>new Xm({typeName:Ne.ZodBoolean,coerce:n?.coerce||!1,...Ie(n)});class Du extends Ye{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.date,received:l.parsedType}),ke}if(Number.isNaN(t.data.getTime())){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_date}),ke}const r=new sn;let o;for(const l of this._def.checks)l.kind==="min"?t.data.getTime()<l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),r.dirty()):l.kind==="max"?t.data.getTime()>l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),r.dirty()):et.assertNever(l);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Du({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:_e.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:_e.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t!=null?new Date(t):null}}Du.create=n=>new Du({checks:[],coerce:n?.coerce||!1,typeName:Ne.ZodDate,...Ie(n)});class vx extends Ye{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.symbol,received:r.parsedType}),ke}return Vn(t.data)}}vx.create=n=>new vx({typeName:Ne.ZodSymbol,...Ie(n)});class Qm extends Ye{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.undefined,received:r.parsedType}),ke}return Vn(t.data)}}Qm.create=n=>new Qm({typeName:Ne.ZodUndefined,...Ie(n)});class Wm extends Ye{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.null,received:r.parsedType}),ke}return Vn(t.data)}}Wm.create=n=>new Wm({typeName:Ne.ZodNull,...Ie(n)});class yx extends Ye{constructor(){super(...arguments),this._any=!0}_parse(t){return Vn(t.data)}}yx.create=n=>new yx({typeName:Ne.ZodAny,...Ie(n)});class Jm extends Ye{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Vn(t.data)}}Jm.create=n=>new Jm({typeName:Ne.ZodUnknown,...Ie(n)});class $s extends Ye{_parse(t){const s=this._getOrReturnCtx(t);return ge(s,{code:fe.invalid_type,expected:be.never,received:s.parsedType}),ke}}$s.create=n=>new $s({typeName:Ne.ZodNever,...Ie(n)});class bx extends Ye{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.void,received:r.parsedType}),ke}return Vn(t.data)}}bx.create=n=>new bx({typeName:Ne.ZodVoid,...Ie(n)});class ma extends Ye{_parse(t){const{ctx:s,status:r}=this._processInputParams(t),o=this._def;if(s.parsedType!==be.array)return ge(s,{code:fe.invalid_type,expected:be.array,received:s.parsedType}),ke;if(o.exactLength!==null){const u=s.data.length>o.exactLength.value,d=s.data.length<o.exactLength.value;(u||d)&&(ge(s,{code:u?fe.too_big:fe.too_small,minimum:d?o.exactLength.value:void 0,maximum:u?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&s.data.length<o.minLength.value&&(ge(s,{code:fe.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&s.data.length>o.maxLength.value&&(ge(s,{code:fe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((u,d)=>o.type._parseAsync(new ya(s,u,s.path,d)))).then(u=>sn.mergeArray(r,u));const l=[...s.data].map((u,d)=>o.type._parseSync(new ya(s,u,s.path,d)));return sn.mergeArray(r,l)}get element(){return this._def.type}min(t,s){return new ma({...this._def,minLength:{value:t,message:_e.toString(s)}})}max(t,s){return new ma({...this._def,maxLength:{value:t,message:_e.toString(s)}})}length(t,s){return new ma({...this._def,exactLength:{value:t,message:_e.toString(s)}})}nonempty(t){return this.min(1,t)}}ma.create=(n,t)=>new ma({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Ne.ZodArray,...Ie(t)});function $i(n){if(n instanceof Ot){const t={};for(const s in n.shape){const r=n.shape[s];t[s]=Za.create($i(r))}return new Ot({...n._def,shape:()=>t})}else return n instanceof ma?new ma({...n._def,type:$i(n.element)}):n instanceof Za?Za.create($i(n.unwrap())):n instanceof Mr?Mr.create($i(n.unwrap())):n instanceof Or?Or.create(n.items.map(t=>$i(t))):n}class Ot extends Ye{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=et.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==be.object){const p=this._getOrReturnCtx(t);return ge(p,{code:fe.invalid_type,expected:be.object,received:p.parsedType}),ke}const{status:r,ctx:o}=this._processInputParams(t),{shape:l,keys:u}=this._getCached(),d=[];if(!(this._def.catchall instanceof $s&&this._def.unknownKeys==="strip"))for(const p in o.data)u.includes(p)||d.push(p);const m=[];for(const p of u){const y=l[p],v=o.data[p];m.push({key:{status:"valid",value:p},value:y._parse(new ya(o,v,o.path,p)),alwaysSet:p in o.data})}if(this._def.catchall instanceof $s){const p=this._def.unknownKeys;if(p==="passthrough")for(const y of d)m.push({key:{status:"valid",value:y},value:{status:"valid",value:o.data[y]}});else if(p==="strict")d.length>0&&(ge(o,{code:fe.unrecognized_keys,keys:d}),r.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const p=this._def.catchall;for(const y of d){const v=o.data[y];m.push({key:{status:"valid",value:y},value:p._parse(new ya(o,v,o.path,y)),alwaysSet:y in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const p=[];for(const y of m){const v=await y.key,x=await y.value;p.push({key:v,value:x,alwaysSet:y.alwaysSet})}return p}).then(p=>sn.mergeObjectSync(r,p)):sn.mergeObjectSync(r,m)}get shape(){return this._def.shape()}strict(t){return _e.errToObj,new Ot({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,r)=>{const o=this._def.errorMap?.(s,r).message??r.defaultError;return s.code==="unrecognized_keys"?{message:_e.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ot({...this._def,unknownKeys:"strip"})}passthrough(){return new Ot({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ot({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ot({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ne.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new Ot({...this._def,catchall:t})}pick(t){const s={};for(const r of et.objectKeys(t))t[r]&&this.shape[r]&&(s[r]=this.shape[r]);return new Ot({...this._def,shape:()=>s})}omit(t){const s={};for(const r of et.objectKeys(this.shape))t[r]||(s[r]=this.shape[r]);return new Ot({...this._def,shape:()=>s})}deepPartial(){return $i(this)}partial(t){const s={};for(const r of et.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?s[r]=o:s[r]=o.optional()}return new Ot({...this._def,shape:()=>s})}required(t){const s={};for(const r of et.objectKeys(this.shape))if(t&&!t[r])s[r]=this.shape[r];else{let l=this.shape[r];for(;l instanceof Za;)l=l._def.innerType;s[r]=l}return new Ot({...this._def,shape:()=>s})}keyof(){return i2(et.objectKeys(this.shape))}}Ot.create=(n,t)=>new Ot({shape:()=>n,unknownKeys:"strip",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});Ot.strictCreate=(n,t)=>new Ot({shape:()=>n,unknownKeys:"strict",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});Ot.lazycreate=(n,t)=>new Ot({shape:n,unknownKeys:"strip",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});class Mu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r=this._def.options;function o(l){for(const d of l)if(d.result.status==="valid")return d.result;for(const d of l)if(d.result.status==="dirty")return s.common.issues.push(...d.ctx.common.issues),d.result;const u=l.map(d=>new Qa(d.ctx.common.issues));return ge(s,{code:fe.invalid_union,unionErrors:u}),ke}if(s.common.async)return Promise.all(r.map(async l=>{const u={...s,common:{...s.common,issues:[]},parent:null};return{result:await l._parseAsync({data:s.data,path:s.path,parent:u}),ctx:u}})).then(o);{let l;const u=[];for(const m of r){const p={...s,common:{...s.common,issues:[]},parent:null},y=m._parseSync({data:s.data,path:s.path,parent:p});if(y.status==="valid")return y;y.status==="dirty"&&!l&&(l={result:y,ctx:p}),p.common.issues.length&&u.push(p.common.issues)}if(l)return s.common.issues.push(...l.ctx.common.issues),l.result;const d=u.map(m=>new Qa(m));return ge(s,{code:fe.invalid_union,unionErrors:d}),ke}}get options(){return this._def.options}}Mu.create=(n,t)=>new Mu({options:n,typeName:Ne.ZodUnion,...Ie(t)});const Va=n=>n instanceof tp?Va(n.schema):n instanceof Dr?Va(n.innerType()):n instanceof Uu?[n.value]:n instanceof Rr?n.options:n instanceof np?et.objectValues(n.enum):n instanceof Iu?Va(n._def.innerType):n instanceof Qm?[void 0]:n instanceof Wm?[null]:n instanceof Za?[void 0,...Va(n.unwrap())]:n instanceof Mr?[null,...Va(n.unwrap())]:n instanceof o2||n instanceof Vu?Va(n.unwrap()):n instanceof Hu?Va(n._def.innerType):[];class eg extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==be.object)return ge(s,{code:fe.invalid_type,expected:be.object,received:s.parsedType}),ke;const r=this.discriminator,o=s.data[r],l=this.optionsMap.get(o);return l?s.common.async?l._parseAsync({data:s.data,path:s.path,parent:s}):l._parseSync({data:s.data,path:s.path,parent:s}):(ge(s,{code:fe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ke)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,r){const o=new Map;for(const l of s){const u=Va(l.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const d of u){if(o.has(d))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(d)}`);o.set(d,l)}}return new eg({typeName:Ne.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:o,...Ie(r)})}}function ep(n,t){const s=zs(n),r=zs(t);if(n===t)return{valid:!0,data:n};if(s===be.object&&r===be.object){const o=et.objectKeys(t),l=et.objectKeys(n).filter(d=>o.indexOf(d)!==-1),u={...n,...t};for(const d of l){const m=ep(n[d],t[d]);if(!m.valid)return{valid:!1};u[d]=m.data}return{valid:!0,data:u}}else if(s===be.array&&r===be.array){if(n.length!==t.length)return{valid:!1};const o=[];for(let l=0;l<n.length;l++){const u=n[l],d=t[l],m=ep(u,d);if(!m.valid)return{valid:!1};o.push(m.data)}return{valid:!0,data:o}}else return s===be.date&&r===be.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}class zu extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t),o=(l,u)=>{if(mx(l)||mx(u))return ke;const d=ep(l.value,u.value);return d.valid?((px(l)||px(u))&&s.dirty(),{status:s.value,value:d.data}):(ge(r,{code:fe.invalid_intersection_types}),ke)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([l,u])=>o(l,u)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}zu.create=(n,t,s)=>new zu({left:n,right:t,typeName:Ne.ZodIntersection,...Ie(s)});class Or extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return ge(r,{code:fe.invalid_type,expected:be.array,received:r.parsedType}),ke;if(r.data.length<this._def.items.length)return ge(r,{code:fe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ke;!this._def.rest&&r.data.length>this._def.items.length&&(ge(r,{code:fe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const l=[...r.data].map((u,d)=>{const m=this._def.items[d]||this._def.rest;return m?m._parse(new ya(r,u,r.path,d)):null}).filter(u=>!!u);return r.common.async?Promise.all(l).then(u=>sn.mergeArray(s,u)):sn.mergeArray(s,l)}get items(){return this._def.items}rest(t){return new Or({...this._def,rest:t})}}Or.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Or({items:n,typeName:Ne.ZodTuple,rest:null,...Ie(t)})};class Lu extends Ye{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return ge(r,{code:fe.invalid_type,expected:be.object,received:r.parsedType}),ke;const o=[],l=this._def.keyType,u=this._def.valueType;for(const d in r.data)o.push({key:l._parse(new ya(r,d,r.path,d)),value:u._parse(new ya(r,r.data[d],r.path,d)),alwaysSet:d in r.data});return r.common.async?sn.mergeObjectAsync(s,o):sn.mergeObjectSync(s,o)}get element(){return this._def.valueType}static create(t,s,r){return s instanceof Ye?new Lu({keyType:t,valueType:s,typeName:Ne.ZodRecord,...Ie(r)}):new Lu({keyType:$a.create(),valueType:t,typeName:Ne.ZodRecord,...Ie(s)})}}class xx extends Ye{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return ge(r,{code:fe.invalid_type,expected:be.map,received:r.parsedType}),ke;const o=this._def.keyType,l=this._def.valueType,u=[...r.data.entries()].map(([d,m],p)=>({key:o._parse(new ya(r,d,r.path,[p,"key"])),value:l._parse(new ya(r,m,r.path,[p,"value"]))}));if(r.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const m of u){const p=await m.key,y=await m.value;if(p.status==="aborted"||y.status==="aborted")return ke;(p.status==="dirty"||y.status==="dirty")&&s.dirty(),d.set(p.value,y.value)}return{status:s.value,value:d}})}else{const d=new Map;for(const m of u){const p=m.key,y=m.value;if(p.status==="aborted"||y.status==="aborted")return ke;(p.status==="dirty"||y.status==="dirty")&&s.dirty(),d.set(p.value,y.value)}return{status:s.value,value:d}}}}xx.create=(n,t,s)=>new xx({valueType:t,keyType:n,typeName:Ne.ZodMap,...Ie(s)});class xl extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return ge(r,{code:fe.invalid_type,expected:be.set,received:r.parsedType}),ke;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(ge(r,{code:fe.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),s.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(ge(r,{code:fe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),s.dirty());const l=this._def.valueType;function u(m){const p=new Set;for(const y of m){if(y.status==="aborted")return ke;y.status==="dirty"&&s.dirty(),p.add(y.value)}return{status:s.value,value:p}}const d=[...r.data.values()].map((m,p)=>l._parse(new ya(r,m,r.path,p)));return r.common.async?Promise.all(d).then(m=>u(m)):u(d)}min(t,s){return new xl({...this._def,minSize:{value:t,message:_e.toString(s)}})}max(t,s){return new xl({...this._def,maxSize:{value:t,message:_e.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}xl.create=(n,t)=>new xl({valueType:n,minSize:null,maxSize:null,typeName:Ne.ZodSet,...Ie(t)});class tp extends Ye{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}tp.create=(n,t)=>new tp({getter:n,typeName:Ne.ZodLazy,...Ie(t)});class Uu extends Ye{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return ge(s,{received:s.data,code:fe.invalid_literal,expected:this._def.value}),ke}return{status:"valid",value:t.data}}get value(){return this._def.value}}Uu.create=(n,t)=>new Uu({value:n,typeName:Ne.ZodLiteral,...Ie(t)});function i2(n,t){return new Rr({values:n,typeName:Ne.ZodEnum,...Ie(t)})}class Rr extends Ye{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),r=this._def.values;return ge(s,{expected:et.joinValues(r),received:s.parsedType,code:fe.invalid_type}),ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),r=this._def.values;return ge(s,{received:s.data,code:fe.invalid_enum_value,options:r}),ke}return Vn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return Rr.create(t,{...this._def,...s})}exclude(t,s=this._def){return Rr.create(this.options.filter(r=>!t.includes(r)),{...this._def,...s})}}Rr.create=i2;class np extends Ye{_parse(t){const s=et.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=et.objectValues(s);return ge(r,{expected:et.joinValues(o),received:r.parsedType,code:fe.invalid_type}),ke}if(this._cache||(this._cache=new Set(et.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=et.objectValues(s);return ge(r,{received:r.data,code:fe.invalid_enum_value,options:o}),ke}return Vn(t.data)}get enum(){return this._def.values}}np.create=(n,t)=>new np({values:n,typeName:Ne.ZodNativeEnum,...Ie(t)});class Bu extends Ye{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==be.promise&&s.common.async===!1)return ge(s,{code:fe.invalid_type,expected:be.promise,received:s.parsedType}),ke;const r=s.parsedType===be.promise?s.data:Promise.resolve(s.data);return Vn(r.then(o=>this._def.type.parseAsync(o,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Bu.create=(n,t)=>new Bu({type:n,typeName:Ne.ZodPromise,...Ie(t)});class Dr extends Ye{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:r}=this._processInputParams(t),o=this._def.effect||null,l={addIssue:u=>{ge(r,u),u.fatal?s.abort():s.dirty()},get path(){return r.path}};if(l.addIssue=l.addIssue.bind(l),o.type==="preprocess"){const u=o.transform(r.data,l);if(r.common.async)return Promise.resolve(u).then(async d=>{if(s.value==="aborted")return ke;const m=await this._def.schema._parseAsync({data:d,path:r.path,parent:r});return m.status==="aborted"?ke:m.status==="dirty"||s.value==="dirty"?ul(m.value):m});{if(s.value==="aborted")return ke;const d=this._def.schema._parseSync({data:u,path:r.path,parent:r});return d.status==="aborted"?ke:d.status==="dirty"||s.value==="dirty"?ul(d.value):d}}if(o.type==="refinement"){const u=d=>{const m=o.refinement(d,l);if(r.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return d.status==="aborted"?ke:(d.status==="dirty"&&s.dirty(),u(d.value),{status:s.value,value:d.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>d.status==="aborted"?ke:(d.status==="dirty"&&s.dirty(),u(d.value).then(()=>({status:s.value,value:d.value}))))}if(o.type==="transform")if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Wi(u))return ke;const d=o.transform(u.value,l);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:d}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>Wi(u)?Promise.resolve(o.transform(u.value,l)).then(d=>({status:s.value,value:d})):ke);et.assertNever(o)}}Dr.create=(n,t,s)=>new Dr({schema:n,typeName:Ne.ZodEffects,effect:t,...Ie(s)});Dr.createWithPreprocess=(n,t,s)=>new Dr({schema:t,effect:{type:"preprocess",transform:n},typeName:Ne.ZodEffects,...Ie(s)});class Za extends Ye{_parse(t){return this._getType(t)===be.undefined?Vn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Za.create=(n,t)=>new Za({innerType:n,typeName:Ne.ZodOptional,...Ie(t)});class Mr extends Ye{_parse(t){return this._getType(t)===be.null?Vn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mr.create=(n,t)=>new Mr({innerType:n,typeName:Ne.ZodNullable,...Ie(t)});class Iu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t);let r=s.data;return s.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Iu.create=(n,t)=>new Iu({innerType:n,typeName:Ne.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ie(t)});class Hu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r={...s,common:{...s.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ru(o)?o.then(l=>({status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Qa(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Hu.create=(n,t)=>new Hu({innerType:n,typeName:Ne.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ie(t)});class wx extends Ye{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.nan,received:r.parsedType}),ke}return{status:"valid",value:t.data}}}wx.create=n=>new wx({typeName:Ne.ZodNaN,...Ie(n)});class o2 extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class tg extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const l=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?ke:l.status==="dirty"?(s.dirty(),ul(l.value)):this._def.out._parseAsync({data:l.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ke:o.status==="dirty"?(s.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,s){return new tg({in:t,out:s,typeName:Ne.ZodPipeline})}}class Vu extends Ye{_parse(t){const s=this._def.innerType._parse(t),r=o=>(Wi(o)&&(o.value=Object.freeze(o.value)),o);return Ru(s)?s.then(o=>r(o)):r(s)}unwrap(){return this._def.innerType}}Vu.create=(n,t)=>new Vu({innerType:n,typeName:Ne.ZodReadonly,...Ie(t)});var Ne;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Ne||(Ne={}));const D=$a.create,ue=Ji.create,Te=Xm.create,Ps=Jm.create;$s.create;const Le=ma.create,I=Ot.create,KN=Mu.create,Ws=eg.create;zu.create;Or.create;const um=Lu.create,Ee=Uu.create,Qe=Rr.create;Bu.create;Za.create;Mr.create;const XN=Qe(["running","paused","completed","failed","stopped"]),ng=Qe(["pending","running","paused","completed","failed","stopped","unknown"]),QN=I({id:D(),toolCallId:D().optional(),title:D(),state:ng,phaseId:D().optional(),model:D().optional(),tokens:ue().nonnegative().optional(),toolCalls:ue().int().nonnegative().optional(),durationMs:ue().nonnegative().optional(),startedAt:ue().optional(),endedAt:ue().optional(),result:D().optional()}),WN=I({id:D(),title:D(),order:ue()}),l2=I({runId:D().optional(),name:D().optional(),state:XN.optional(),started:ue().int().nonnegative().optional(),completed:ue().int().nonnegative().optional(),tokens:ue().nonnegative().optional(),durationMs:ue().nonnegative().optional(),startedAt:ue().optional(),endedAt:ue().optional(),phases:Le(WN).optional(),agents:Le(QN).optional()}),JN=Qe(["multi_client","handoff","remote","terminal"]),e5=I({interrupt:Te(),steer:Te(),permissions:Te(),images:Te(),fork:Te(),models:Te(),modes:Te()}),t5=I({state:Qe(["ok","missing","unknown"]),method:D().optional(),hint:D().optional()}),n5=I({id:D().min(1),label:D().min(1),tier:JN,installed:Te(),version:D().optional(),problem:D().optional(),auth:t5.optional(),capabilities:e5}),qu=Qe(["desktop","remote","none"]),c2=Qe(["idle","running","waiting","error","offline"]),u2=Qe(["read","edit","delete","move","search","execute","think","fetch","other"]),d2=I({optionId:D().min(1),name:D().min(1),kind:Qe(["allow_once","allow_always","reject_once","reject_always"])}),a5=I({kind:Qe(["thinking","responding","tool"]),title:D().optional(),toolKind:u2.optional()}),f2=I({id:D(),header:D().optional(),text:D(),kind:Qe(["choice","choices","text"]),options:Le(I({value:D(),label:D(),description:D().optional()})).optional(),other:Te().optional(),secret:Te().optional(),required:Te().optional()}),h2=I({id:D(),values:Le(D().max(2e4)).max(50),other:D().max(2e4).optional()}),s5=I({requestId:D(),toolCallId:D().optional(),title:D(),detail:D().optional(),options:Le(d2).min(1),questions:Le(f2).optional()}),r5=I({clientMessageId:D(),text:D(),images:ue().int().nonnegative()}),i5=I({toolCallId:D(),parentToolCallId:D().optional(),task:D(),agentType:D().optional(),running:Te(),failed:Te().optional(),startedAt:ue(),endedAt:ue().optional(),state:ng.optional(),workflow:l2.optional(),lastSeq:ue().int().nonnegative().optional()}),o5=Qe(["running","completed","failed","stopped","unknown"]),m2=I({id:D(),kind:Qe(["shell","monitor"]),toolCallId:D().optional(),title:D(),command:D().optional(),state:o5,startedAt:ue(),endedAt:ue().optional(),summary:D().optional(),exitCode:ue().int().optional(),output:Te().optional(),canStop:Te().optional(),lastSeq:ue().int().nonnegative().optional()}),Sr=I({id:D().min(1),agent:D().min(1),nativeId:D().min(1),title:D().optional(),preview:D().optional(),cwd:D(),state:c2,driver:qu.optional(),pendingPermissions:ue().int().nonnegative(),model:D().optional(),createdAt:ue(),updatedAt:ue(),lastSeq:ue().int().nonnegative(),archived:Te(),activity:a5.optional(),permission:s5.optional(),queue:Le(r5).optional(),worktree:I({branch:D(),source:D()}).optional(),subagents:I({total:ue().int(),running:ue().int()}).optional(),tasks:I({total:ue().int(),running:ue().int()}).optional()}),l5=I({root:D(),branch:D().optional(),head:D().optional(),dirty:Te()}),c5=I({path:D(),branch:D(),source:D(),createdAt:ue(),sessions:Le(D()),dirty:Te(),ahead:ue().int().nonnegative()}),u5=I({cwd:D(),name:D(),lastActiveAt:ue(),sessionCount:ue().int().nonnegative(),branch:D().optional()});I({machineId:D().min(1),hostname:D(),platform:D(),hostVersion:D(),home:D().optional(),agents:Le(n5),direct:I({iceServers:Le(D())}).optional()});const d5=I({port:ue().int().min(1).max(65535),process:D(),pid:ue().int().optional(),cwd:D().optional(),title:D().optional(),http:Te()}),xu=I({id:D(),title:D(),cwd:D(),cols:ue().int(),rows:ue().int(),createdAt:ue(),activeAt:ue(),command:D().optional(),exitCode:ue().int().nullable().optional(),interrupted:Te().optional()});I({url:D().optional(),status:Qe(["off","connecting","online","offline"]),error:I({code:D(),message:D()}).optional(),machine:I({id:D(),name:D()}).optional(),account:I({userId:D(),email:D().optional()}).optional(),devices:Le(I({id:D(),name:D(),pairedAt:ue(),online:Te()}))});const p2=I({objective:D(),status:Qe(["active","paused","blocked","usageLimited","budgetLimited","complete"]),tokenBudget:ue().nonnegative().nullable().optional(),tokensUsed:ue().nonnegative().optional(),timeUsedSeconds:ue().nonnegative().optional(),iterations:ue().int().nonnegative().optional(),lastReason:D().nullable().optional()}),f5=Ws("action",[I({action:Ee("get")}),I({action:Ee("set"),objective:D().trim().min(1).max(4e3),tokenBudget:ue().int().positive().max(Number.MAX_SAFE_INTEGER).optional()}),I({action:Ee("pause")}),I({action:Ee("resume")}),I({action:Ee("clear")})]),Ki=Ws("type",[I({type:Ee("text"),text:D()}),I({type:Ee("image"),mimeType:D(),data:D().optional(),uri:D().optional()}),I({type:Ee("resource_link"),uri:D(),name:D(),kind:Qe(["file","skill","agent"]).optional()})]),Sx=Qe(["pending","in_progress","completed","failed"]),Ex=Ws("type",[I({type:Ee("content"),content:Ki}),I({type:Ee("diff"),path:D(),oldText:D().nullable().optional(),newText:D()}),I({type:Ee("patch"),path:D(),change:Qe(["add","delete","update"]),movePath:D().optional(),diff:D()}),I({type:Ee("terminal"),terminalId:D()})]),h5=I({path:D(),line:ue().int().optional()}),_x=Ws("type",[I({type:Ee("mcp"),server:D(),tool:D()}),I({type:Ee("subagent"),action:Qe(["spawn","message","wait","stop","resume","list"]).default("spawn"),task:D().optional(),agentType:D().optional(),model:D().optional(),state:ng.optional(),workflow:l2.optional()}),I({type:Ee("skill"),name:D(),description:D().optional()}),I({type:Ee("web_search"),query:D().optional()}),I({type:Ee("image_generation"),prompt:D().optional()}),I({type:Ee("compaction")}),I({type:Ee("review"),phase:Qe(["started","finished"])}),I({type:Ee("question"),text:D(),more:ue().int().optional()})]),m5=I({content:D(),priority:Qe(["high","medium","low"]).default("medium"),status:Qe(["pending","in_progress","completed"])}),p5=Qe(["end_turn","cancelled","error","max_tokens","refusal"]),g5=I({id:D(),name:D(),category:Qe(["model","mode","effort","other"]).default("other"),current:D(),values:Le(I({value:D(),name:D(),description:D().optional()}))}),v5=Ws("sessionUpdate",[I({sessionUpdate:Ee("user_message_chunk"),messageId:D().optional(),content:Ki}),I({sessionUpdate:Ee("agent_message_chunk"),parentToolCallId:D().optional(),messageId:D(),content:Ki}),I({sessionUpdate:Ee("agent_thought_chunk"),parentToolCallId:D().optional(),messageId:D(),content:Ki}),I({sessionUpdate:Ee("tool_call"),toolCallId:D(),parentToolCallId:D().optional(),title:D(),kind:u2,status:Sx,rawInput:Ps().optional(),content:Le(Ex).optional(),locations:Le(h5).optional(),detail:_x.optional()}),I({sessionUpdate:Ee("tool_call_update"),toolCallId:D(),parentToolCallId:D().optional(),status:Sx.optional(),title:D().optional(),detail:_x.optional(),content:Le(Ex).optional(),appendOutput:D().optional(),rawOutput:Ps().optional()}),I({sessionUpdate:Ee("plan"),entries:Le(m5)}),I({sessionUpdate:Ee("ls_goal"),goal:p2.nullable()}),I({sessionUpdate:Ee("available_commands_update"),availableCommands:Le(I({name:D(),description:D(),hint:D().optional()}))}),I({sessionUpdate:Ee("current_mode_update"),currentModeId:D()}),I({sessionUpdate:Ee("session_info_update"),title:D().optional(),model:D().optional()}),I({sessionUpdate:Ee("usage_update"),usedTokens:ue().optional(),contextWindow:ue().optional()}),I({sessionUpdate:Ee("ls_message_done"),parentToolCallId:D().optional(),messageId:D(),role:Qe(["agent","thought","user"]),questions:Le(I({id:D(),title:D(),options:Le(D())})).optional()}),I({sessionUpdate:Ee("ls_config"),options:Le(g5)}),I({sessionUpdate:Ee("ls_notice"),level:Qe(["info","warning"]),title:D(),detail:D().optional()}),I({sessionUpdate:Ee("ls_turn"),parentToolCallId:D().optional(),state:Qe(["started","ended"]),turnId:D().optional(),stopReason:p5.optional()}),I({sessionUpdate:Ee("ls_permission"),requestId:D(),toolCallId:D().optional(),title:D(),detail:D().optional(),options:Le(d2).min(1),questions:Le(f2).optional()}),I({sessionUpdate:Ee("ls_permission_resolved"),requestId:D(),optionId:D().optional(),answers:Le(h2).optional()}),I({sessionUpdate:Ee("ls_driver"),driver:qu,deviceId:D().optional()}),I({sessionUpdate:Ee("ls_status"),state:c2}),I({sessionUpdate:Ee("ls_task"),task:m2}),I({sessionUpdate:Ee("ls_error"),code:D(),message:D(),hint:D().optional()})]),Cx=I({sessionId:D(),seq:ue().int().positive(),ts:ue(),update:v5}),y5=KN([D(),ue()]),b5=I({code:ue().int(),message:D(),data:Ps().optional()});I({jsonrpc:Ee("2.0"),id:y5.optional(),method:D().optional(),params:Ps().optional(),result:Ps().optional(),error:b5.optional()});Qe(["invalid_params","not_found","agent_unavailable","not_supported","not_ready","busy","offline","internal"]);const x5=-32601,dl=-32e3;I({}).passthrough();const Ax=I({name:D(),path:D(),project:Te().optional(),file:Te().optional(),size:ue().int().optional()});I({limit:ue().int().positive().max(200).optional()}),I({projects:Le(u5)}),I({limit:ue().int().positive().max(200).optional(),before:ue().optional(),includeArchived:Te().optional()}),I({sessions:Le(Sr),nextBefore:ue().optional()}),I({agent:D().min(1),cwd:D().min(1),prompt:Le(Ki).optional(),clientMessageId:D().optional(),model:D().optional(),worktree:Te().optional()}),I({session:Sr}),I({sessionId:D().min(1),itemId:D().min(1).optional(),worktree:Te().optional()}),I({session:Sr}),I({sessionId:D().min(1),fromSeq:ue().int().nonnegative(),lazyImages:Te().optional()}),I({session:Sr,startSeq:ue().int().nonnegative().optional()}),I({sessionId:D().min(1),beforeSeq:ue().int().positive(),lazyImages:Te().optional()}),I({events:Le(Cx),startSeq:ue().int().nonnegative()}),I({sessionId:D().min(1)}),I({subagents:Le(i5)}),I({sessionId:D().min(1),toolCallId:D().min(1),lazyImages:Te().optional()}),I({events:Le(Cx)}),I({sessionId:D().min(1)}),I({tasks:Le(m2)}),I({sessionId:D().min(1),taskId:D().min(1),before:ue().int().nonnegative().optional(),limit:ue().int().positive().max(256*1024).optional()}),I({text:D(),start:ue().int().nonnegative(),size:ue().int().nonnegative()}),I({sessionId:D().min(1),taskId:D().min(1)}),I({sessionId:D().min(1),direct:Te().optional()}),I({port:ue().int().positive(),token:D()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),uri:D().min(1)}),I({mimeType:D(),data:D()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),clientMessageId:D().min(1),content:Le(Ki).min(1),whenBusy:Qe(["queue"]).optional()}),I({delivery:Qe(["started","steered","queued","duplicate"])}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),requestId:D().min(1),optionId:D().min(1)}),I({sessionId:D().min(1),requestId:D().min(1),answers:Le(h2).max(50)}),I({sessionId:D(),change:f5}),I({goal:p2.nullable()}),I({sessionId:D().min(1),optionId:D().min(1),value:D().min(1)}),I({sessionId:D().min(1),clientMessageId:D().min(1).optional()}),I({sessionId:D().min(1),clientMessageIds:Le(D().min(1))}),I({sessionId:D().min(1),clientMessageId:D().min(1)}),I({removed:Te()}),I({sessionId:D().min(1),archived:Te()}),I({session:Sr}),I({sessionId:D().min(1),title:D().max(200)}),I({session:Sr}),I({sessionId:D().min(1),worktree:Qe(["keep","remove"]).optional()}),I({sessionId:D().min(1)}),I({driver:qu.optional()}),I({sessionId:D().min(1)}),I({driver:qu.optional()}),I({agent:D().min(1),sessionId:D().optional(),args:Le(D()).default([]),cwd:D().optional(),env:um(D()).optional()}),I({command:D(),args:Le(D()),env:um(D()).optional(),sessionId:D().optional()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1)}),I({command:D(),args:Le(D()),env:um(D()).optional()}),I({link:D(),code:D(),expiresAt:ue(),gateway:D()}),I({deviceId:D().min(1)}),I({path:D().min(1)}),I({git:l5.optional()}),I({worktrees:Le(c5)}),I({path:D().min(1),force:Te().optional()}),I({path:D().optional(),hidden:Te().default(!1),files:Te().default(!1)}),I({path:D(),parent:D().optional(),home:D(),entries:Le(Ax),truncated:Te().optional()}),I({path:D().min(1),offset:ue().int().nonnegative().default(0),maxBytes:ue().int().min(1).max(2e6).default(512e3)}),I({path:D(),size:ue().int(),modifiedAt:ue(),kind:Qe(["text","image","binary"]),text:D().optional(),data:D().optional(),mimeType:D().optional(),truncated:Te(),nextOffset:ue().int().optional()}),I({dir:D().min(1),name:D().min(1).max(255),data:D().max(4e7)}),I({path:D(),size:ue().int()}),I({parent:D().min(1),name:D().min(1).max(255)}),I({path:D()}),I({query:D().min(1).max(200),limit:ue().int().min(1).max(200).default(60)}),I({entries:Le(Ax),truncated:Te()}),I({terminals:Le(xu)}),I({cwd:D().optional(),command:D().max(4e3).optional(),cols:ue().int().min(10).max(1e3).default(80),rows:ue().int().min(4).max(500).default(24)}),I({terminal:xu}),I({terminalId:D().min(1),fromSeq:ue().int().min(0).optional(),replayFormat:Ee("frames-v1").optional(),fromFrame:ue().int().min(0).optional()}),I({terminal:xu,replay:D(),reset:Te(),seq:ue().int(),recording:I({afterFrame:ue().int(),throughFrame:ue().int()}).optional()}),I({terminalId:D().min(1),afterFrame:ue().int().min(0),throughFrame:ue().int().min(0)}),I({frames:Le(I({frame:ue().int(),cols:ue().int(),rows:ue().int(),data:D()})),nextFrame:ue().int(),done:Te()}),I({terminalId:D().min(1)}),I({terminalId:D().min(1),data:D().max(1e6)}),I({terminalId:D().min(1),cols:ue().int().min(10).max(1e3),rows:ue().int().min(4).max(500)}),I({terminalId:D().min(1)}),I({ports:Le(d5)}),I({port:ue().int().min(1).max(65535),direct:Te().optional()}),I({streamId:D(),channel:ue().int().nonnegative().optional()}),I({sdp:D().min(1).max(2e5)}),I({sdp:D()}),I({port:ue().int(),token:D(),displays:Le(I({index:ue().int(),name:D()}))}),I({ask:Te().optional()}),I({supported:Te(),ffmpeg:Te(),recording:Te().nullable(),control:Te().nullable(),app:D().optional(),problem:D().optional()}),I({streamId:D().min(1),data:D().max(2e6)}),I({streamId:D().min(1)});I({sessionId:D(),startSeq:ue().int().nonnegative()}),I({session:Sr}),I({sessionId:D()}),I({sessionId:D()}),I({sessionId:D()}),I({sessionId:D(),line:D()}),I({device:I({id:D(),name:D()})}),I({terminalId:D(),seq:ue().int(),data:D(),frame:ue().int().optional(),cols:ue().int().optional(),rows:ue().int().optional()}),I({terminal:xu,closed:Te().optional()}),I({streamId:D(),data:D()}),I({streamId:D(),error:D().optional()});class ca extends Error{constructor(t,s,r){super(s),this.code=t,this.data=r,this.name="RpcError"}static app(t,s,r){return new ca(dl,s,{code:t,...r})}get appCode(){const t=this.data;return typeof t?.code=="string"?t.code:void 0}toObject(){return this.data===void 0?{code:this.code,message:this.message}:{code:this.code,message:this.message,data:this.data}}}const w5=Symbol("rpc.abandon");class S5{constructor(t){this.options=t}nextId=1;pending=new Map;closed=!1;request(t,s,r){if(this.closed)return Promise.reject(new ca(dl,`connection closed (${t})`));const o=this.nextId++;return new Promise((l,u)=>{const d={resolve:l,reject:u,method:t},m=r??this.options.requestTimeoutMs??3e4;m>0&&(d.timer=setTimeout(()=>{this.pending.delete(o),u(new ca(dl,`${t} timed out after ${m}ms`,{code:"timeout"}))},m)),this.pending.set(o,d),this.write({jsonrpc:"2.0",id:o,method:t,params:s??{}})})}notify(t,s){this.closed||this.write({jsonrpc:"2.0",method:t,params:s??{}})}receive(t){for(const s of t.split(`
153
+ `).trim());if(!t)return;let s;try{s=JSON.parse(t[1])}catch{return}if(!Array.isArray(s)||s.length===0)return;const r=[];for(const o of s){if(!o||typeof o!="object")return;const{questionItemId:l,question:u,answer:d}=o;if(typeof u!="string"||typeof d!="string")return;r.push({...typeof l=="string"?{id:l}:{},question:u.trim(),answer:d.trim()})}return r}function gN(n){return(JS(n)??[]).flatMap(t=>t.id?[[t.id,t.answer]]:[])}function Yi(n){return{sessionId:n,lastSeq:0,startSeq:0,items:[],index:{},permissions:[],config:[],commands:[],state:"idle",turnActive:!1}}function Xt(n,t){const s=n.index[t.id];if(s===void 0)return{...n,items:[...n.items,t],index:{...n.index,[t.id]:n.items.length}};const r=n.items.slice();return r[s]=t,{...n,items:r}}function Un(n,t,s){const r=n.index[t],o=r===void 0?void 0:n.items[r];return o&&o.kind===s?o:void 0}function ux(n,t){return t.type==="text"?n+t.text:n}function bu(n,t){let s;return n.items.forEach((r,o)=>{(r.kind==="agent"||r.kind==="thought")&&r.streaming&&(s??=n.items.slice(),s[o]=r.kind==="thought"?{...r,streaming:!1,endedTs:r.endedTs??t}:{...r,streaming:!1})}),s?{...n,items:s}:n}function Ou(n,t){const s=bu(n,t);let r;return s.items.forEach((o,l)=>{if(o.kind!=="tool"||!o.sub)return;const u=Ou(o.sub,t);u!==o.sub&&(r??=s.items.slice(),r[l]={...o,sub:u})}),r?{...s,items:r}:s}function vN(n){switch(n.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":case"tool_call":case"tool_call_update":case"ls_message_done":case"ls_turn":return n.parentToolCallId;default:return}}function yN(n,t){return n.flatMap(s=>{const r=t.find(u=>u.id===s.id);if(!r)return[];const o=r.values.filter(Boolean).map(u=>s.options?.find(d=>d.value===u)?.label??u),l=[...s.secret&&o.length>0?["••••••"]:o,...r.other?[r.other]:[]];return l.length>0?[{question:s.header??s.text,answer:l.join(",")}]:[]})}function e2(n,t,s,r,o){if(!Un(n,t,"tool")){for(const m of n.items)if(!(m.kind!=="tool"||!m.sub||!Wp(m.sub,t)))return Xt(n,{...m,sub:e2(m.sub,t,s,r,o)})}const l=Un(n,t,"tool")??{kind:"tool",id:t,title:"Sub-agent",toolKind:"other",status:"in_progress",detail:{type:"subagent",action:"spawn"},content:[],output:"",ts:r},u={...s,parentToolCallId:void 0},d=Jp(l.sub??Yi(n.sessionId),u,r,o);return d===l.sub?n:Xt(n,{...l,sub:d})}function Wp(n,t){const s=Un(n,t,"tool");if(s)return s;for(const r of n.items){if(r.kind!=="tool"||!r.sub)continue;const o=Wp(r.sub,t);if(o)return o}}function Jp(n,t,s,r){const o=vN(t);if(o)return e2(n,o,t,s,r);switch(t.sessionUpdate){case"user_message_chunk":{const l=t.messageId??`user-${r}`,u=Un(n,l,"user"),d=u&&!u.pending?[...u.blocks,t.content]:[t.content];return Xt(n,{kind:"user",id:l,blocks:t2(d),ts:u?.ts??s})}case"agent_message_chunk":{const l=Un(n,t.messageId,"agent"),u=t.content.type==="text"?l?.attachments:[...l?.attachments??[],t.content];return Xt(n,{kind:"agent",id:t.messageId,text:ux(l?.text??"",t.content),attachments:u,streaming:!0,ts:l?.ts??s})}case"agent_thought_chunk":{const l=`thought:${t.messageId}`,u=Un(n,l,"thought");return Xt(n,{kind:"thought",id:l,text:ux(u?.text??"",t.content),streaming:!0,ts:u?.ts??s})}case"ls_message_done":{const l=t.role==="thought"?`thought:${t.messageId}`:t.messageId,u=Un(n,l,"agent");if(u)return Xt(n,{...u,streaming:!1,...t.questions?.length?{questions:t.questions}:{}});const d=Un(n,l,"thought");return d?Xt(n,{...d,streaming:!1,endedTs:d.endedTs??s}):n}case"tool_call":{const l=Un(n,t.toolCallId,"tool"),u=t.status==="completed"||t.status==="failed";return Xt(bu(n,s),{kind:"tool",id:t.toolCallId,title:t.title,toolKind:t.kind,status:t.status,rawInput:t.rawInput??l?.rawInput,rawOutput:l?.rawOutput,locations:t.locations??l?.locations,detail:t.detail??l?.detail,sub:l?.sub,content:t.content??l?.content??[],output:l?.output??"",ts:l?.ts??s,endedTs:u?s:l?.endedTs})}case"tool_call_update":{const u=Un(n,t.toolCallId,"tool")??{kind:"tool",id:t.toolCallId,title:t.title??"Tool",toolKind:"other",status:"in_progress",content:[],output:"",ts:s},d=t.status??u.status,m=d==="completed"||d==="failed";return Xt(n,{...u,title:t.title??u.title,detail:t.detail??u.detail,status:d,content:t.content?a2(u.content,t.content):u.content,output:t.appendOutput?u.output+t.appendOutput:u.output,rawOutput:t.rawOutput??u.rawOutput,endedTs:m?u.endedTs??s:u.endedTs,sub:m&&u.sub?Ou(u.sub,s):u.sub})}case"plan":{const l=n.planId??`plan-${r}`;return{...Xt(n,{kind:"plan",id:l,entries:t.entries,ts:Un(n,l,"plan")?.ts??s}),planId:l}}case"available_commands_update":return{...n,commands:t.availableCommands};case"ls_goal":return{...n,goal:t.goal};case"current_mode_update":return{...n,modeId:t.currentModeId,config:n.config.map(l=>l.category==="mode"?{...l,current:t.currentModeId}:l)};case"ls_config":return{...n,config:t.options,modeId:t.options.find(l=>l.category==="mode")?.current??n.modeId};case"session_info_update":return{...n,title:t.title??n.title};case"usage_update":return{...n,usage:{usedTokens:t.usedTokens,contextWindow:t.contextWindow}};case"ls_turn":if(t.state==="started")return{...n,turnActive:!0,state:"running",planId:void 0};{const u={...Ou(n,s),turnActive:!1,state:t.stopReason==="error"?"error":"idle",permissions:[]};return t.stopReason==="cancelled"?Xt(u,{kind:"turn-end",id:`turn-end-${r}`,stopReason:"cancelled",ts:s}):u}case"ls_status":return{...n,state:t.state};case"ls_permission":return n.permissions.some(l=>l.requestId===t.requestId)?n:{...bu(n,s),state:"waiting",permissions:[...n.permissions,{requestId:t.requestId,toolCallId:t.toolCallId,title:t.title,detail:t.detail,options:t.options,questions:t.questions,ts:s}]};case"ls_permission_resolved":{const l=n.permissions.find(p=>p.requestId===t.requestId);if(!l)return n;const u=l.options.find(p=>p.optionId===t.optionId),d=n.permissions.filter(p=>p.requestId!==t.requestId),m={...n,permissions:d,state:d.length>0?"waiting":n.turnActive?"running":n.state==="waiting"?"idle":n.state};return Xt(m,{kind:"permission-result",id:`perm-${t.requestId}`,title:l.title,detail:l.detail,optionName:u?.name,allowed:u?u.kind.startsWith("allow"):void 0,asked:l.questions?!0:void 0,answers:l.questions&&t.answers?yN(l.questions,t.answers):void 0,ts:s})}case"ls_driver":{if(n.driver===t.driver)return n;const l={...n,driver:t.driver};return n.driver===void 0?l:Xt(l,{kind:"driver",id:`driver-${r}`,driver:t.driver,ts:s})}case"ls_error":return Xt(bu(n,s),{kind:"error",id:`error-${r}`,code:t.code,message:t.message,hint:t.hint,ts:s});case"ls_notice":return Xt(n,{kind:"notice",id:`notice-${r}`,level:t.level,title:t.title,detail:t.detail,ts:s});default:return n}}function t2(n){const t=[];for(const s of n){const r=t[t.length-1];s.type==="text"&&r?.type==="text"?t[t.length-1]={type:"text",text:r.text+s.text}:t.push(s)}return t}function bN(n,t){if(t.seq<=n.lastSeq)return n;const s=Jp(n,t.update,t.ts,String(t.seq));return s===n?{...n,lastSeq:t.seq}:{...s,lastSeq:t.seq}}function lm(n,t){return t.reduce(bN,n)}function xN(n,t){if(n.lastSeq===0)return{...n,startSeq:t};if(n.lastSeq===t)return n;const s=n.items.filter(o=>o.kind==="user"&&(o.pending||o.failed)),r={};return s.forEach((o,l)=>{r[o.id]=l}),{...Yi(n.sessionId),startSeq:t,items:s,index:r}}const wN=new Set(["Tool","Sub-agent"]);function SN(n,t){if(n.kind==="agent"&&t.kind==="agent"){const s=[...n.attachments??[],...t.attachments??[]];return{...t,text:n.text+t.text,attachments:s.length?s:void 0,ts:n.ts}}return n.kind==="thought"&&t.kind==="thought"?{...t,text:n.text+t.text,ts:n.ts}:n.kind==="user"&&t.kind==="user"?{...t,blocks:t2([...n.blocks,...t.blocks]),ts:n.ts}:n.kind==="tool"&&t.kind==="tool"?{...t,title:wN.has(t.title)?n.title:t.title,toolKind:n.toolKind,rawInput:t.rawInput??n.rawInput,rawOutput:t.rawOutput??n.rawOutput,locations:t.locations??n.locations,detail:t.detail??n.detail,content:t.content.length?a2(n.content,t.content):n.content,output:n.output+t.output,sub:n.sub&&t.sub?n2(n.sub,t.sub):t.sub??n.sub,ts:n.ts,endedTs:t.endedTs??n.endedTs}:t}function n2(n,t){const s=[],r=new Set;for(const l of n.items){const u=t.index[l.id];u===void 0?s.push(l):(s.push(SN(l,t.items[u])),r.add(l.id))}for(const l of t.items)r.has(l.id)||s.push(l);const o={};return s.forEach((l,u)=>{o[l.id]=u}),{...t,items:s,index:o}}function EN(n,t,s){let r=Yi(n.sessionId);for(const o of t)r=Jp(r,o.update,o.ts,String(o.seq));return r=Ou(r,t[t.length-1]?.ts??0),{...n2(r,n),startSeq:s}}function iu(n,t,s,r=Date.now(),o=!1){return Xt(n,{kind:"user",id:`local-${t}`,blocks:s,ts:r,pending:!0,...o?{accepted:!0}:{}})}function dx(n,t){const s=Un(n,`local-${t}`,"user");return s&&s.pending?Xt(n,{...s,pending:!1,failed:!0}):n}function fx(n,t){const s=n.index[t];if(s===void 0)return n;const r=n.items.filter((l,u)=>u!==s),o={};return r.forEach((l,u)=>{o[l.id]=u}),{...n,items:r,index:o}}function a2(n,t){if(t.some(r=>r.type==="diff"))return t;const s=n.filter(r=>r.type==="diff");return s.length?[...s,...t]:t}var et;(function(n){n.assertEqual=o=>{};function t(o){}n.assertIs=t;function s(o){throw new Error}n.assertNever=s,n.arrayToEnum=o=>{const l={};for(const u of o)l[u]=u;return l},n.getValidEnumValues=o=>{const l=n.objectKeys(o).filter(d=>typeof o[o[d]]!="number"),u={};for(const d of l)u[d]=o[d];return n.objectValues(u)},n.objectValues=o=>n.objectKeys(o).map(function(l){return o[l]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const l=[];for(const u in o)Object.prototype.hasOwnProperty.call(o,u)&&l.push(u);return l},n.find=(o,l)=>{for(const u of o)if(l(u))return u},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,l=" | "){return o.map(u=>typeof u=="string"?`'${u}'`:u).join(l)}n.joinValues=r,n.jsonStringifyReplacer=(o,l)=>typeof l=="bigint"?l.toString():l})(et||(et={}));var hx;(function(n){n.mergeShapes=(t,s)=>({...t,...s})})(hx||(hx={}));const be=et.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zs=n=>{switch(typeof n){case"undefined":return be.undefined;case"string":return be.string;case"number":return Number.isNaN(n)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(n)?be.array:n===null?be.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?be.promise:typeof Map<"u"&&n instanceof Map?be.map:typeof Set<"u"&&n instanceof Set?be.set:typeof Date<"u"&&n instanceof Date?be.date:be.object;default:return be.unknown}},fe=et.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Qa extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(l){return l.message},r={_errors:[]},o=l=>{for(const u of l.issues)if(u.code==="invalid_union")u.unionErrors.map(o);else if(u.code==="invalid_return_type")o(u.returnTypeError);else if(u.code==="invalid_arguments")o(u.argumentsError);else if(u.path.length===0)r._errors.push(s(u));else{let d=r,m=0;for(;m<u.path.length;){const p=u.path[m];m===u.path.length-1?(d[p]=d[p]||{_errors:[]},d[p]._errors.push(s(u))):d[p]=d[p]||{_errors:[]},d=d[p],m++}}};return o(this),r}static assert(t){if(!(t instanceof Qa))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,et.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=s=>s.message){const s={},r=[];for(const o of this.issues)if(o.path.length>0){const l=o.path[0];s[l]=s[l]||[],s[l].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}Qa.create=n=>new Qa(n);const Km=(n,t)=>{let s;switch(n.code){case fe.invalid_type:n.received===be.undefined?s="Required":s=`Expected ${n.expected}, received ${n.received}`;break;case fe.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(n.expected,et.jsonStringifyReplacer)}`;break;case fe.unrecognized_keys:s=`Unrecognized key(s) in object: ${et.joinValues(n.keys,", ")}`;break;case fe.invalid_union:s="Invalid input";break;case fe.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${et.joinValues(n.options)}`;break;case fe.invalid_enum_value:s=`Invalid enum value. Expected ${et.joinValues(n.options)}, received '${n.received}'`;break;case fe.invalid_arguments:s="Invalid function arguments";break;case fe.invalid_return_type:s="Invalid function return type";break;case fe.invalid_date:s="Invalid date";break;case fe.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(s=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?s=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?s=`Invalid input: must end with "${n.validation.endsWith}"`:et.assertNever(n.validation):n.validation!=="regex"?s=`Invalid ${n.validation}`:s="Invalid";break;case fe.too_small:n.type==="array"?s=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?s=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?s=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?s=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?s=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:s="Invalid input";break;case fe.too_big:n.type==="array"?s=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?s=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?s=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?s=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?s=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:s="Invalid input";break;case fe.custom:s="Invalid input";break;case fe.invalid_intersection_types:s="Intersection results could not be merged";break;case fe.not_multiple_of:s=`Number must be a multiple of ${n.multipleOf}`;break;case fe.not_finite:s="Number must be finite";break;default:s=t.defaultError,et.assertNever(n)}return{message:s}};let _N=Km;function CN(){return _N}const AN=n=>{const{data:t,path:s,errorMaps:r,issueData:o}=n,l=[...s,...o.path||[]],u={...o,path:l};if(o.message!==void 0)return{...o,path:l,message:o.message};let d="";const m=r.filter(p=>!!p).slice().reverse();for(const p of m)d=p(u,{data:t,defaultError:d}).message;return{...o,path:l,message:d}};function ge(n,t){const s=CN(),r=AN({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,s,s===Km?void 0:Km].filter(o=>!!o)});n.common.issues.push(r)}class sn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const r=[];for(const o of s){if(o.status==="aborted")return ke;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,s){const r=[];for(const o of s){const l=await o.key,u=await o.value;r.push({key:l,value:u})}return sn.mergeObjectSync(t,r)}static mergeObjectSync(t,s){const r={};for(const o of s){const{key:l,value:u}=o;if(l.status==="aborted"||u.status==="aborted")return ke;l.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),l.value!=="__proto__"&&(typeof u.value<"u"||o.alwaysSet)&&(r[l.value]=u.value)}return{status:t.value,value:r}}}const ke=Object.freeze({status:"aborted"}),ul=n=>({status:"dirty",value:n}),Vn=n=>({status:"valid",value:n}),mx=n=>n.status==="aborted",px=n=>n.status==="dirty",Wi=n=>n.status==="valid",Ru=n=>typeof Promise<"u"&&n instanceof Promise;var _e;(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(_e||(_e={}));class ya{constructor(t,s,r,o){this._cachedPath=[],this.parent=t,this.data=s,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const gx=(n,t)=>{if(Wi(t))return{success:!0,data:t.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new Qa(n.common.issues);return this._error=s,this._error}}};function Ie(n){if(!n)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:o}=n;if(t&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(u,d)=>{const{message:m}=n;return u.code==="invalid_enum_value"?{message:m??d.defaultError}:typeof d.data>"u"?{message:m??r??d.defaultError}:u.code!=="invalid_type"?{message:d.defaultError}:{message:m??s??d.defaultError}},description:o}}class Ye{get description(){return this._def.description}_getType(t){return zs(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:zs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sn,ctx:{common:t.parent.common,data:t.data,parsedType:zs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(Ru(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const r=this.safeParse(t,s);if(r.success)return r.data;throw r.error}safeParse(t,s){const r={common:{issues:[],async:s?.async??!1,contextualErrorMap:s?.errorMap},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)},o=this._parseSync({data:t,path:r.path,parent:r});return gx(r,o)}"~validate"(t){const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:s});return Wi(r)?{value:r.value}:{issues:s.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(r=>Wi(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(t,s){const r=await this.safeParseAsync(t,s);if(r.success)return r.data;throw r.error}async safeParseAsync(t,s){const r={common:{issues:[],contextualErrorMap:s?.errorMap,async:!0},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:zs(t)},o=this._parse({data:t,path:r.path,parent:r}),l=await(Ru(o)?o:Promise.resolve(o));return gx(r,l)}refine(t,s){const r=o=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(o):s;return this._refinement((o,l)=>{const u=t(o),d=()=>l.addIssue({code:fe.custom,...r(o)});return typeof Promise<"u"&&u instanceof Promise?u.then(m=>m?!0:(d(),!1)):u?!0:(d(),!1)})}refinement(t,s){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof s=="function"?s(r,o):s),!1))}_refinement(t){return new Dr({schema:this,typeName:Ne.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Za.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ma.create(this)}promise(){return Bu.create(this,this._def)}or(t){return Mu.create([this,t],this._def)}and(t){return zu.create(this,t,this._def)}transform(t){return new Dr({...Ie(this._def),schema:this,typeName:Ne.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Iu({...Ie(this._def),innerType:this,defaultValue:s,typeName:Ne.ZodDefault})}brand(){return new o2({typeName:Ne.ZodBranded,type:this,...Ie(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new Hu({...Ie(this._def),innerType:this,catchValue:s,typeName:Ne.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return tg.create(this,t)}readonly(){return Vu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const jN=/^c[^\s-]{8,}$/i,TN=/^[0-9a-z]+$/,kN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,NN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ON=/^[a-z0-9_-]{21}$/i,RN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,DN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cm;const LN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,UN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,BN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,IN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,HN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,VN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,s2="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",qN=new RegExp(`^${s2}$`);function r2(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);const s=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function $N(n){return new RegExp(`^${r2(n)}$`)}function PN(n){let t=`${s2}T${r2(n)}`;const s=[];return s.push(n.local?"Z?":"Z"),n.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function FN(n,t){return!!((t==="v4"||!t)&&LN.test(n)||(t==="v6"||!t)&&BN.test(n))}function GN(n,t){if(!RN.test(n))return!1;try{const[s]=n.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function ZN(n,t){return!!((t==="v4"||!t)&&UN.test(n)||(t==="v6"||!t)&&IN.test(n))}class $a extends Ye{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.string,received:l.parsedType}),ke}const r=new sn;let o;for(const l of this._def.checks)if(l.kind==="min")t.data.length<l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),r.dirty());else if(l.kind==="max")t.data.length>l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),r.dirty());else if(l.kind==="length"){const u=t.data.length>l.value,d=t.data.length<l.value;(u||d)&&(o=this._getOrReturnCtx(t,o),u?ge(o,{code:fe.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):d&&ge(o,{code:fe.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),r.dirty())}else if(l.kind==="email")MN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"email",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="emoji")cm||(cm=new RegExp(zN,"u")),cm.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"emoji",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="uuid")NN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"uuid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="nanoid")ON.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"nanoid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="cuid")jN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cuid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="cuid2")TN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cuid2",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="ulid")kN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"ulid",code:fe.invalid_string,message:l.message}),r.dirty());else if(l.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ge(o,{validation:"url",code:fe.invalid_string,message:l.message}),r.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"regex",code:fe.invalid_string,message:l.message}),r.dirty())):l.kind==="trim"?t.data=t.data.trim():l.kind==="includes"?t.data.includes(l.value,l.position)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),r.dirty()):l.kind==="toLowerCase"?t.data=t.data.toLowerCase():l.kind==="toUpperCase"?t.data=t.data.toUpperCase():l.kind==="startsWith"?t.data.startsWith(l.value)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{startsWith:l.value},message:l.message}),r.dirty()):l.kind==="endsWith"?t.data.endsWith(l.value)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:{endsWith:l.value},message:l.message}),r.dirty()):l.kind==="datetime"?PN(l).test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"datetime",message:l.message}),r.dirty()):l.kind==="date"?qN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"date",message:l.message}),r.dirty()):l.kind==="time"?$N(l).test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.invalid_string,validation:"time",message:l.message}),r.dirty()):l.kind==="duration"?DN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"duration",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="ip"?FN(t.data,l.version)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"ip",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="jwt"?GN(t.data,l.alg)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"jwt",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="cidr"?ZN(t.data,l.version)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"cidr",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="base64"?HN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"base64",code:fe.invalid_string,message:l.message}),r.dirty()):l.kind==="base64url"?VN.test(t.data)||(o=this._getOrReturnCtx(t,o),ge(o,{validation:"base64url",code:fe.invalid_string,message:l.message}),r.dirty()):et.assertNever(l);return{status:r.value,value:t.data}}_regex(t,s,r){return this.refinement(o=>t.test(o),{validation:s,code:fe.invalid_string,..._e.errToObj(r)})}_addCheck(t){return new $a({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._e.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._e.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._e.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._e.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._e.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._e.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._e.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._e.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._e.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",..._e.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",..._e.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._e.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",..._e.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,..._e.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,..._e.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",..._e.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,..._e.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s?.position,..._e.errToObj(s?.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,..._e.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,..._e.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,..._e.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,..._e.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,..._e.errToObj(s)})}nonempty(t){return this.min(1,_e.errToObj(t))}trim(){return new $a({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $a({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $a({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}$a.create=n=>new $a({checks:[],typeName:Ne.ZodString,coerce:n?.coerce??!1,...Ie(n)});function YN(n,t){const s=(n.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=s>r?s:r,l=Number.parseInt(n.toFixed(o).replace(".","")),u=Number.parseInt(t.toFixed(o).replace(".",""));return l%u/10**o}class Ji extends Ye{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.number,received:l.parsedType}),ke}let r;const o=new sn;for(const l of this._def.checks)l.kind==="int"?et.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.invalid_type,expected:"integer",received:"float",message:l.message}),o.dirty()):l.kind==="min"?(l.inclusive?t.data<l.value:t.data<=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),o.dirty()):l.kind==="max"?(l.inclusive?t.data>l.value:t.data>=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),o.dirty()):l.kind==="multipleOf"?YN(t.data,l.value)!==0&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_multiple_of,multipleOf:l.value,message:l.message}),o.dirty()):l.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_finite,message:l.message}),o.dirty()):et.assertNever(l);return{status:o.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,_e.toString(s))}gt(t,s){return this.setLimit("min",t,!1,_e.toString(s))}lte(t,s){return this.setLimit("max",t,!0,_e.toString(s))}lt(t,s){return this.setLimit("max",t,!1,_e.toString(s))}setLimit(t,s,r,o){return new Ji({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:_e.toString(o)}]})}_addCheck(t){return new Ji({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_e.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:_e.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&et.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(s)&&Number.isFinite(t)}}Ji.create=n=>new Ji({checks:[],typeName:Ne.ZodNumber,coerce:n?.coerce||!1,...Ie(n)});class bl extends Ye{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==be.bigint)return this._getInvalidInput(t);let r;const o=new sn;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?t.data<l.value:t.data<=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),o.dirty()):l.kind==="max"?(l.inclusive?t.data>l.value:t.data>=l.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),o.dirty()):l.kind==="multipleOf"?t.data%l.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:fe.not_multiple_of,multipleOf:l.value,message:l.message}),o.dirty()):et.assertNever(l);return{status:o.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return ge(s,{code:fe.invalid_type,expected:be.bigint,received:s.parsedType}),ke}gte(t,s){return this.setLimit("min",t,!0,_e.toString(s))}gt(t,s){return this.setLimit("min",t,!1,_e.toString(s))}lte(t,s){return this.setLimit("max",t,!0,_e.toString(s))}lt(t,s){return this.setLimit("max",t,!1,_e.toString(s))}setLimit(t,s,r,o){return new bl({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:r,message:_e.toString(o)}]})}_addCheck(t){return new bl({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t}}bl.create=n=>new bl({checks:[],typeName:Ne.ZodBigInt,coerce:n?.coerce??!1,...Ie(n)});class Xm extends Ye{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.boolean,received:r.parsedType}),ke}return Vn(t.data)}}Xm.create=n=>new Xm({typeName:Ne.ZodBoolean,coerce:n?.coerce||!1,...Ie(n)});class Du extends Ye{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_type,expected:be.date,received:l.parsedType}),ke}if(Number.isNaN(t.data.getTime())){const l=this._getOrReturnCtx(t);return ge(l,{code:fe.invalid_date}),ke}const r=new sn;let o;for(const l of this._def.checks)l.kind==="min"?t.data.getTime()<l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),r.dirty()):l.kind==="max"?t.data.getTime()>l.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:fe.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),r.dirty()):et.assertNever(l);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Du({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:_e.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:_e.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.value<t)&&(t=s.value);return t!=null?new Date(t):null}}Du.create=n=>new Du({checks:[],coerce:n?.coerce||!1,typeName:Ne.ZodDate,...Ie(n)});class vx extends Ye{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.symbol,received:r.parsedType}),ke}return Vn(t.data)}}vx.create=n=>new vx({typeName:Ne.ZodSymbol,...Ie(n)});class Qm extends Ye{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.undefined,received:r.parsedType}),ke}return Vn(t.data)}}Qm.create=n=>new Qm({typeName:Ne.ZodUndefined,...Ie(n)});class Wm extends Ye{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.null,received:r.parsedType}),ke}return Vn(t.data)}}Wm.create=n=>new Wm({typeName:Ne.ZodNull,...Ie(n)});class yx extends Ye{constructor(){super(...arguments),this._any=!0}_parse(t){return Vn(t.data)}}yx.create=n=>new yx({typeName:Ne.ZodAny,...Ie(n)});class Jm extends Ye{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Vn(t.data)}}Jm.create=n=>new Jm({typeName:Ne.ZodUnknown,...Ie(n)});class $s extends Ye{_parse(t){const s=this._getOrReturnCtx(t);return ge(s,{code:fe.invalid_type,expected:be.never,received:s.parsedType}),ke}}$s.create=n=>new $s({typeName:Ne.ZodNever,...Ie(n)});class bx extends Ye{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.void,received:r.parsedType}),ke}return Vn(t.data)}}bx.create=n=>new bx({typeName:Ne.ZodVoid,...Ie(n)});class ma extends Ye{_parse(t){const{ctx:s,status:r}=this._processInputParams(t),o=this._def;if(s.parsedType!==be.array)return ge(s,{code:fe.invalid_type,expected:be.array,received:s.parsedType}),ke;if(o.exactLength!==null){const u=s.data.length>o.exactLength.value,d=s.data.length<o.exactLength.value;(u||d)&&(ge(s,{code:u?fe.too_big:fe.too_small,minimum:d?o.exactLength.value:void 0,maximum:u?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&s.data.length<o.minLength.value&&(ge(s,{code:fe.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&s.data.length>o.maxLength.value&&(ge(s,{code:fe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((u,d)=>o.type._parseAsync(new ya(s,u,s.path,d)))).then(u=>sn.mergeArray(r,u));const l=[...s.data].map((u,d)=>o.type._parseSync(new ya(s,u,s.path,d)));return sn.mergeArray(r,l)}get element(){return this._def.type}min(t,s){return new ma({...this._def,minLength:{value:t,message:_e.toString(s)}})}max(t,s){return new ma({...this._def,maxLength:{value:t,message:_e.toString(s)}})}length(t,s){return new ma({...this._def,exactLength:{value:t,message:_e.toString(s)}})}nonempty(t){return this.min(1,t)}}ma.create=(n,t)=>new ma({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Ne.ZodArray,...Ie(t)});function $i(n){if(n instanceof Ot){const t={};for(const s in n.shape){const r=n.shape[s];t[s]=Za.create($i(r))}return new Ot({...n._def,shape:()=>t})}else return n instanceof ma?new ma({...n._def,type:$i(n.element)}):n instanceof Za?Za.create($i(n.unwrap())):n instanceof Mr?Mr.create($i(n.unwrap())):n instanceof Or?Or.create(n.items.map(t=>$i(t))):n}class Ot extends Ye{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=et.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==be.object){const p=this._getOrReturnCtx(t);return ge(p,{code:fe.invalid_type,expected:be.object,received:p.parsedType}),ke}const{status:r,ctx:o}=this._processInputParams(t),{shape:l,keys:u}=this._getCached(),d=[];if(!(this._def.catchall instanceof $s&&this._def.unknownKeys==="strip"))for(const p in o.data)u.includes(p)||d.push(p);const m=[];for(const p of u){const y=l[p],v=o.data[p];m.push({key:{status:"valid",value:p},value:y._parse(new ya(o,v,o.path,p)),alwaysSet:p in o.data})}if(this._def.catchall instanceof $s){const p=this._def.unknownKeys;if(p==="passthrough")for(const y of d)m.push({key:{status:"valid",value:y},value:{status:"valid",value:o.data[y]}});else if(p==="strict")d.length>0&&(ge(o,{code:fe.unrecognized_keys,keys:d}),r.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const p=this._def.catchall;for(const y of d){const v=o.data[y];m.push({key:{status:"valid",value:y},value:p._parse(new ya(o,v,o.path,y)),alwaysSet:y in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const p=[];for(const y of m){const v=await y.key,x=await y.value;p.push({key:v,value:x,alwaysSet:y.alwaysSet})}return p}).then(p=>sn.mergeObjectSync(r,p)):sn.mergeObjectSync(r,m)}get shape(){return this._def.shape()}strict(t){return _e.errToObj,new Ot({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,r)=>{const o=this._def.errorMap?.(s,r).message??r.defaultError;return s.code==="unrecognized_keys"?{message:_e.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ot({...this._def,unknownKeys:"strip"})}passthrough(){return new Ot({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ot({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ot({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ne.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new Ot({...this._def,catchall:t})}pick(t){const s={};for(const r of et.objectKeys(t))t[r]&&this.shape[r]&&(s[r]=this.shape[r]);return new Ot({...this._def,shape:()=>s})}omit(t){const s={};for(const r of et.objectKeys(this.shape))t[r]||(s[r]=this.shape[r]);return new Ot({...this._def,shape:()=>s})}deepPartial(){return $i(this)}partial(t){const s={};for(const r of et.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?s[r]=o:s[r]=o.optional()}return new Ot({...this._def,shape:()=>s})}required(t){const s={};for(const r of et.objectKeys(this.shape))if(t&&!t[r])s[r]=this.shape[r];else{let l=this.shape[r];for(;l instanceof Za;)l=l._def.innerType;s[r]=l}return new Ot({...this._def,shape:()=>s})}keyof(){return i2(et.objectKeys(this.shape))}}Ot.create=(n,t)=>new Ot({shape:()=>n,unknownKeys:"strip",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});Ot.strictCreate=(n,t)=>new Ot({shape:()=>n,unknownKeys:"strict",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});Ot.lazycreate=(n,t)=>new Ot({shape:n,unknownKeys:"strip",catchall:$s.create(),typeName:Ne.ZodObject,...Ie(t)});class Mu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r=this._def.options;function o(l){for(const d of l)if(d.result.status==="valid")return d.result;for(const d of l)if(d.result.status==="dirty")return s.common.issues.push(...d.ctx.common.issues),d.result;const u=l.map(d=>new Qa(d.ctx.common.issues));return ge(s,{code:fe.invalid_union,unionErrors:u}),ke}if(s.common.async)return Promise.all(r.map(async l=>{const u={...s,common:{...s.common,issues:[]},parent:null};return{result:await l._parseAsync({data:s.data,path:s.path,parent:u}),ctx:u}})).then(o);{let l;const u=[];for(const m of r){const p={...s,common:{...s.common,issues:[]},parent:null},y=m._parseSync({data:s.data,path:s.path,parent:p});if(y.status==="valid")return y;y.status==="dirty"&&!l&&(l={result:y,ctx:p}),p.common.issues.length&&u.push(p.common.issues)}if(l)return s.common.issues.push(...l.ctx.common.issues),l.result;const d=u.map(m=>new Qa(m));return ge(s,{code:fe.invalid_union,unionErrors:d}),ke}}get options(){return this._def.options}}Mu.create=(n,t)=>new Mu({options:n,typeName:Ne.ZodUnion,...Ie(t)});const Va=n=>n instanceof tp?Va(n.schema):n instanceof Dr?Va(n.innerType()):n instanceof Uu?[n.value]:n instanceof Rr?n.options:n instanceof np?et.objectValues(n.enum):n instanceof Iu?Va(n._def.innerType):n instanceof Qm?[void 0]:n instanceof Wm?[null]:n instanceof Za?[void 0,...Va(n.unwrap())]:n instanceof Mr?[null,...Va(n.unwrap())]:n instanceof o2||n instanceof Vu?Va(n.unwrap()):n instanceof Hu?Va(n._def.innerType):[];class eg extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==be.object)return ge(s,{code:fe.invalid_type,expected:be.object,received:s.parsedType}),ke;const r=this.discriminator,o=s.data[r],l=this.optionsMap.get(o);return l?s.common.async?l._parseAsync({data:s.data,path:s.path,parent:s}):l._parseSync({data:s.data,path:s.path,parent:s}):(ge(s,{code:fe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ke)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,r){const o=new Map;for(const l of s){const u=Va(l.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const d of u){if(o.has(d))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(d)}`);o.set(d,l)}}return new eg({typeName:Ne.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:o,...Ie(r)})}}function ep(n,t){const s=zs(n),r=zs(t);if(n===t)return{valid:!0,data:n};if(s===be.object&&r===be.object){const o=et.objectKeys(t),l=et.objectKeys(n).filter(d=>o.indexOf(d)!==-1),u={...n,...t};for(const d of l){const m=ep(n[d],t[d]);if(!m.valid)return{valid:!1};u[d]=m.data}return{valid:!0,data:u}}else if(s===be.array&&r===be.array){if(n.length!==t.length)return{valid:!1};const o=[];for(let l=0;l<n.length;l++){const u=n[l],d=t[l],m=ep(u,d);if(!m.valid)return{valid:!1};o.push(m.data)}return{valid:!0,data:o}}else return s===be.date&&r===be.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}class zu extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t),o=(l,u)=>{if(mx(l)||mx(u))return ke;const d=ep(l.value,u.value);return d.valid?((px(l)||px(u))&&s.dirty(),{status:s.value,value:d.data}):(ge(r,{code:fe.invalid_intersection_types}),ke)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([l,u])=>o(l,u)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}zu.create=(n,t,s)=>new zu({left:n,right:t,typeName:Ne.ZodIntersection,...Ie(s)});class Or extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return ge(r,{code:fe.invalid_type,expected:be.array,received:r.parsedType}),ke;if(r.data.length<this._def.items.length)return ge(r,{code:fe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ke;!this._def.rest&&r.data.length>this._def.items.length&&(ge(r,{code:fe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const l=[...r.data].map((u,d)=>{const m=this._def.items[d]||this._def.rest;return m?m._parse(new ya(r,u,r.path,d)):null}).filter(u=>!!u);return r.common.async?Promise.all(l).then(u=>sn.mergeArray(s,u)):sn.mergeArray(s,l)}get items(){return this._def.items}rest(t){return new Or({...this._def,rest:t})}}Or.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Or({items:n,typeName:Ne.ZodTuple,rest:null,...Ie(t)})};class Lu extends Ye{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return ge(r,{code:fe.invalid_type,expected:be.object,received:r.parsedType}),ke;const o=[],l=this._def.keyType,u=this._def.valueType;for(const d in r.data)o.push({key:l._parse(new ya(r,d,r.path,d)),value:u._parse(new ya(r,r.data[d],r.path,d)),alwaysSet:d in r.data});return r.common.async?sn.mergeObjectAsync(s,o):sn.mergeObjectSync(s,o)}get element(){return this._def.valueType}static create(t,s,r){return s instanceof Ye?new Lu({keyType:t,valueType:s,typeName:Ne.ZodRecord,...Ie(r)}):new Lu({keyType:$a.create(),valueType:t,typeName:Ne.ZodRecord,...Ie(s)})}}class xx extends Ye{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return ge(r,{code:fe.invalid_type,expected:be.map,received:r.parsedType}),ke;const o=this._def.keyType,l=this._def.valueType,u=[...r.data.entries()].map(([d,m],p)=>({key:o._parse(new ya(r,d,r.path,[p,"key"])),value:l._parse(new ya(r,m,r.path,[p,"value"]))}));if(r.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const m of u){const p=await m.key,y=await m.value;if(p.status==="aborted"||y.status==="aborted")return ke;(p.status==="dirty"||y.status==="dirty")&&s.dirty(),d.set(p.value,y.value)}return{status:s.value,value:d}})}else{const d=new Map;for(const m of u){const p=m.key,y=m.value;if(p.status==="aborted"||y.status==="aborted")return ke;(p.status==="dirty"||y.status==="dirty")&&s.dirty(),d.set(p.value,y.value)}return{status:s.value,value:d}}}}xx.create=(n,t,s)=>new xx({valueType:t,keyType:n,typeName:Ne.ZodMap,...Ie(s)});class xl extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return ge(r,{code:fe.invalid_type,expected:be.set,received:r.parsedType}),ke;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(ge(r,{code:fe.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),s.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(ge(r,{code:fe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),s.dirty());const l=this._def.valueType;function u(m){const p=new Set;for(const y of m){if(y.status==="aborted")return ke;y.status==="dirty"&&s.dirty(),p.add(y.value)}return{status:s.value,value:p}}const d=[...r.data.values()].map((m,p)=>l._parse(new ya(r,m,r.path,p)));return r.common.async?Promise.all(d).then(m=>u(m)):u(d)}min(t,s){return new xl({...this._def,minSize:{value:t,message:_e.toString(s)}})}max(t,s){return new xl({...this._def,maxSize:{value:t,message:_e.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}xl.create=(n,t)=>new xl({valueType:n,minSize:null,maxSize:null,typeName:Ne.ZodSet,...Ie(t)});class tp extends Ye{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}tp.create=(n,t)=>new tp({getter:n,typeName:Ne.ZodLazy,...Ie(t)});class Uu extends Ye{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return ge(s,{received:s.data,code:fe.invalid_literal,expected:this._def.value}),ke}return{status:"valid",value:t.data}}get value(){return this._def.value}}Uu.create=(n,t)=>new Uu({value:n,typeName:Ne.ZodLiteral,...Ie(t)});function i2(n,t){return new Rr({values:n,typeName:Ne.ZodEnum,...Ie(t)})}class Rr extends Ye{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),r=this._def.values;return ge(s,{expected:et.joinValues(r),received:s.parsedType,code:fe.invalid_type}),ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),r=this._def.values;return ge(s,{received:s.data,code:fe.invalid_enum_value,options:r}),ke}return Vn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return Rr.create(t,{...this._def,...s})}exclude(t,s=this._def){return Rr.create(this.options.filter(r=>!t.includes(r)),{...this._def,...s})}}Rr.create=i2;class np extends Ye{_parse(t){const s=et.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=et.objectValues(s);return ge(r,{expected:et.joinValues(o),received:r.parsedType,code:fe.invalid_type}),ke}if(this._cache||(this._cache=new Set(et.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=et.objectValues(s);return ge(r,{received:r.data,code:fe.invalid_enum_value,options:o}),ke}return Vn(t.data)}get enum(){return this._def.values}}np.create=(n,t)=>new np({values:n,typeName:Ne.ZodNativeEnum,...Ie(t)});class Bu extends Ye{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==be.promise&&s.common.async===!1)return ge(s,{code:fe.invalid_type,expected:be.promise,received:s.parsedType}),ke;const r=s.parsedType===be.promise?s.data:Promise.resolve(s.data);return Vn(r.then(o=>this._def.type.parseAsync(o,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Bu.create=(n,t)=>new Bu({type:n,typeName:Ne.ZodPromise,...Ie(t)});class Dr extends Ye{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:r}=this._processInputParams(t),o=this._def.effect||null,l={addIssue:u=>{ge(r,u),u.fatal?s.abort():s.dirty()},get path(){return r.path}};if(l.addIssue=l.addIssue.bind(l),o.type==="preprocess"){const u=o.transform(r.data,l);if(r.common.async)return Promise.resolve(u).then(async d=>{if(s.value==="aborted")return ke;const m=await this._def.schema._parseAsync({data:d,path:r.path,parent:r});return m.status==="aborted"?ke:m.status==="dirty"||s.value==="dirty"?ul(m.value):m});{if(s.value==="aborted")return ke;const d=this._def.schema._parseSync({data:u,path:r.path,parent:r});return d.status==="aborted"?ke:d.status==="dirty"||s.value==="dirty"?ul(d.value):d}}if(o.type==="refinement"){const u=d=>{const m=o.refinement(d,l);if(r.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return d.status==="aborted"?ke:(d.status==="dirty"&&s.dirty(),u(d.value),{status:s.value,value:d.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>d.status==="aborted"?ke:(d.status==="dirty"&&s.dirty(),u(d.value).then(()=>({status:s.value,value:d.value}))))}if(o.type==="transform")if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Wi(u))return ke;const d=o.transform(u.value,l);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:d}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>Wi(u)?Promise.resolve(o.transform(u.value,l)).then(d=>({status:s.value,value:d})):ke);et.assertNever(o)}}Dr.create=(n,t,s)=>new Dr({schema:n,typeName:Ne.ZodEffects,effect:t,...Ie(s)});Dr.createWithPreprocess=(n,t,s)=>new Dr({schema:t,effect:{type:"preprocess",transform:n},typeName:Ne.ZodEffects,...Ie(s)});class Za extends Ye{_parse(t){return this._getType(t)===be.undefined?Vn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Za.create=(n,t)=>new Za({innerType:n,typeName:Ne.ZodOptional,...Ie(t)});class Mr extends Ye{_parse(t){return this._getType(t)===be.null?Vn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mr.create=(n,t)=>new Mr({innerType:n,typeName:Ne.ZodNullable,...Ie(t)});class Iu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t);let r=s.data;return s.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Iu.create=(n,t)=>new Iu({innerType:n,typeName:Ne.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ie(t)});class Hu extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r={...s,common:{...s.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ru(o)?o.then(l=>({status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Qa(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Hu.create=(n,t)=>new Hu({innerType:n,typeName:Ne.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ie(t)});class wx extends Ye{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return ge(r,{code:fe.invalid_type,expected:be.nan,received:r.parsedType}),ke}return{status:"valid",value:t.data}}}wx.create=n=>new wx({typeName:Ne.ZodNaN,...Ie(n)});class o2 extends Ye{_parse(t){const{ctx:s}=this._processInputParams(t),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class tg extends Ye{_parse(t){const{status:s,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const l=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?ke:l.status==="dirty"?(s.dirty(),ul(l.value)):this._def.out._parseAsync({data:l.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ke:o.status==="dirty"?(s.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,s){return new tg({in:t,out:s,typeName:Ne.ZodPipeline})}}class Vu extends Ye{_parse(t){const s=this._def.innerType._parse(t),r=o=>(Wi(o)&&(o.value=Object.freeze(o.value)),o);return Ru(s)?s.then(o=>r(o)):r(s)}unwrap(){return this._def.innerType}}Vu.create=(n,t)=>new Vu({innerType:n,typeName:Ne.ZodReadonly,...Ie(t)});var Ne;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Ne||(Ne={}));const D=$a.create,ue=Ji.create,Te=Xm.create,Ps=Jm.create;$s.create;const Le=ma.create,I=Ot.create,KN=Mu.create,Ws=eg.create;zu.create;Or.create;const um=Lu.create,Ee=Uu.create,Qe=Rr.create;Bu.create;Za.create;Mr.create;const XN=Qe(["running","paused","completed","failed","stopped"]),ng=Qe(["pending","running","paused","completed","failed","stopped","unknown"]),QN=I({id:D(),toolCallId:D().optional(),title:D(),state:ng,phaseId:D().optional(),model:D().optional(),tokens:ue().nonnegative().optional(),toolCalls:ue().int().nonnegative().optional(),durationMs:ue().nonnegative().optional(),startedAt:ue().optional(),endedAt:ue().optional(),result:D().optional()}),WN=I({id:D(),title:D(),order:ue()}),l2=I({runId:D().optional(),name:D().optional(),state:XN.optional(),started:ue().int().nonnegative().optional(),completed:ue().int().nonnegative().optional(),tokens:ue().nonnegative().optional(),durationMs:ue().nonnegative().optional(),startedAt:ue().optional(),endedAt:ue().optional(),phases:Le(WN).optional(),agents:Le(QN).optional()}),JN=Qe(["multi_client","handoff","remote","terminal"]),e5=I({interrupt:Te(),steer:Te(),permissions:Te(),images:Te(),fork:Te(),models:Te(),modes:Te()}),t5=I({state:Qe(["ok","missing","unknown"]),method:D().optional(),hint:D().optional()}),n5=I({id:D().min(1),label:D().min(1),tier:JN,installed:Te(),version:D().optional(),problem:D().optional(),auth:t5.optional(),capabilities:e5}),qu=Qe(["desktop","remote","none"]),c2=Qe(["idle","running","waiting","error","offline"]),u2=Qe(["read","edit","delete","move","search","execute","think","fetch","other"]),d2=I({optionId:D().min(1),name:D().min(1),kind:Qe(["allow_once","allow_always","reject_once","reject_always"])}),a5=I({kind:Qe(["thinking","responding","tool"]),title:D().optional(),toolKind:u2.optional()}),f2=I({id:D(),header:D().optional(),text:D(),kind:Qe(["choice","choices","text"]),options:Le(I({value:D(),label:D(),description:D().optional()})).optional(),other:Te().optional(),secret:Te().optional(),required:Te().optional()}),h2=I({id:D(),values:Le(D().max(2e4)).max(50),other:D().max(2e4).optional()}),s5=I({requestId:D(),toolCallId:D().optional(),title:D(),detail:D().optional(),options:Le(d2).min(1),questions:Le(f2).optional()}),r5=I({clientMessageId:D(),text:D(),images:ue().int().nonnegative()}),i5=I({toolCallId:D(),parentToolCallId:D().optional(),task:D(),agentType:D().optional(),running:Te(),failed:Te().optional(),startedAt:ue(),endedAt:ue().optional(),state:ng.optional(),workflow:l2.optional(),lastSeq:ue().int().nonnegative().optional()}),o5=Qe(["running","completed","failed","stopped","unknown"]),m2=I({id:D(),kind:Qe(["shell","monitor"]),toolCallId:D().optional(),title:D(),command:D().optional(),state:o5,startedAt:ue(),endedAt:ue().optional(),summary:D().optional(),exitCode:ue().int().optional(),output:Te().optional(),canStop:Te().optional(),lastSeq:ue().int().nonnegative().optional()}),Sr=I({id:D().min(1),agent:D().min(1),nativeId:D().min(1),title:D().optional(),preview:D().optional(),cwd:D(),state:c2,driver:qu.optional(),pendingPermissions:ue().int().nonnegative(),model:D().optional(),createdAt:ue(),updatedAt:ue(),lastSeq:ue().int().nonnegative(),archived:Te(),activity:a5.optional(),permission:s5.optional(),queue:Le(r5).optional(),worktree:I({branch:D(),source:D()}).optional(),subagents:I({total:ue().int(),running:ue().int()}).optional(),tasks:I({total:ue().int(),running:ue().int()}).optional()}),l5=I({root:D(),branch:D().optional(),head:D().optional(),dirty:Te()}),c5=I({path:D(),branch:D(),source:D(),createdAt:ue(),sessions:Le(D()),dirty:Te(),ahead:ue().int().nonnegative()}),u5=I({cwd:D(),name:D(),lastActiveAt:ue(),sessionCount:ue().int().nonnegative(),branch:D().optional()});I({machineId:D().min(1),hostname:D(),platform:D(),hostVersion:D(),home:D().optional(),agents:Le(n5),direct:I({iceServers:Le(D())}).optional()});const d5=I({port:ue().int().min(1).max(65535),process:D(),pid:ue().int().optional(),cwd:D().optional(),title:D().optional(),http:Te()}),xu=I({id:D(),title:D(),cwd:D(),cols:ue().int(),rows:ue().int(),createdAt:ue(),activeAt:ue(),command:D().optional(),exitCode:ue().int().nullable().optional(),interrupted:Te().optional()});I({url:D().optional(),status:Qe(["off","connecting","online","offline"]),error:I({code:D(),message:D()}).optional(),machine:I({id:D(),name:D()}).optional(),account:I({userId:D(),email:D().optional()}).optional(),devices:Le(I({id:D(),name:D(),pairedAt:ue(),online:Te()}))});const p2=I({objective:D(),status:Qe(["active","paused","blocked","usageLimited","budgetLimited","complete"]),tokenBudget:ue().nonnegative().nullable().optional(),tokensUsed:ue().nonnegative().optional(),timeUsedSeconds:ue().nonnegative().optional(),iterations:ue().int().nonnegative().optional(),lastReason:D().nullable().optional()}),f5=Ws("action",[I({action:Ee("get")}),I({action:Ee("set"),objective:D().trim().min(1).max(4e3),tokenBudget:ue().int().positive().max(Number.MAX_SAFE_INTEGER).optional()}),I({action:Ee("pause")}),I({action:Ee("resume")}),I({action:Ee("clear")})]),Ki=Ws("type",[I({type:Ee("text"),text:D()}),I({type:Ee("image"),mimeType:D(),data:D().optional(),uri:D().optional()}),I({type:Ee("resource_link"),uri:D(),name:D(),kind:Qe(["file","skill","agent"]).optional()})]),Sx=Qe(["pending","in_progress","completed","failed"]),Ex=Ws("type",[I({type:Ee("content"),content:Ki}),I({type:Ee("diff"),path:D(),oldText:D().nullable().optional(),newText:D()}),I({type:Ee("patch"),path:D(),change:Qe(["add","delete","update"]),movePath:D().optional(),diff:D()}),I({type:Ee("terminal"),terminalId:D()})]),h5=I({path:D(),line:ue().int().optional()}),_x=Ws("type",[I({type:Ee("mcp"),server:D(),tool:D()}),I({type:Ee("subagent"),action:Qe(["spawn","message","wait","stop","resume","list"]).default("spawn"),task:D().optional(),agentType:D().optional(),model:D().optional(),state:ng.optional(),workflow:l2.optional()}),I({type:Ee("skill"),name:D(),description:D().optional()}),I({type:Ee("web_search"),query:D().optional()}),I({type:Ee("image_generation"),prompt:D().optional()}),I({type:Ee("compaction")}),I({type:Ee("review"),phase:Qe(["started","finished"])}),I({type:Ee("question"),text:D(),more:ue().int().optional()})]),m5=I({content:D(),priority:Qe(["high","medium","low"]).default("medium"),status:Qe(["pending","in_progress","completed"])}),p5=Qe(["end_turn","cancelled","error","max_tokens","refusal"]),g5=I({id:D(),name:D(),category:Qe(["model","mode","effort","other"]).default("other"),current:D(),values:Le(I({value:D(),name:D(),description:D().optional()}))}),v5=Ws("sessionUpdate",[I({sessionUpdate:Ee("user_message_chunk"),messageId:D().optional(),content:Ki}),I({sessionUpdate:Ee("agent_message_chunk"),parentToolCallId:D().optional(),messageId:D(),content:Ki}),I({sessionUpdate:Ee("agent_thought_chunk"),parentToolCallId:D().optional(),messageId:D(),content:Ki}),I({sessionUpdate:Ee("tool_call"),toolCallId:D(),parentToolCallId:D().optional(),title:D(),kind:u2,status:Sx,rawInput:Ps().optional(),content:Le(Ex).optional(),locations:Le(h5).optional(),detail:_x.optional()}),I({sessionUpdate:Ee("tool_call_update"),toolCallId:D(),parentToolCallId:D().optional(),status:Sx.optional(),title:D().optional(),detail:_x.optional(),content:Le(Ex).optional(),appendOutput:D().optional(),rawOutput:Ps().optional()}),I({sessionUpdate:Ee("plan"),entries:Le(m5)}),I({sessionUpdate:Ee("ls_goal"),goal:p2.nullable()}),I({sessionUpdate:Ee("available_commands_update"),availableCommands:Le(I({name:D(),description:D(),hint:D().optional()}))}),I({sessionUpdate:Ee("current_mode_update"),currentModeId:D()}),I({sessionUpdate:Ee("session_info_update"),title:D().optional(),model:D().optional()}),I({sessionUpdate:Ee("usage_update"),usedTokens:ue().optional(),contextWindow:ue().optional()}),I({sessionUpdate:Ee("ls_message_done"),parentToolCallId:D().optional(),messageId:D(),role:Qe(["agent","thought","user"]),questions:Le(I({id:D(),title:D(),options:Le(D())})).optional()}),I({sessionUpdate:Ee("ls_config"),options:Le(g5)}),I({sessionUpdate:Ee("ls_notice"),level:Qe(["info","warning"]),title:D(),detail:D().optional()}),I({sessionUpdate:Ee("ls_turn"),parentToolCallId:D().optional(),state:Qe(["started","ended"]),turnId:D().optional(),stopReason:p5.optional()}),I({sessionUpdate:Ee("ls_permission"),requestId:D(),toolCallId:D().optional(),title:D(),detail:D().optional(),options:Le(d2).min(1),questions:Le(f2).optional()}),I({sessionUpdate:Ee("ls_permission_resolved"),requestId:D(),optionId:D().optional(),answers:Le(h2).optional()}),I({sessionUpdate:Ee("ls_driver"),driver:qu,deviceId:D().optional()}),I({sessionUpdate:Ee("ls_status"),state:c2}),I({sessionUpdate:Ee("ls_task"),task:m2}),I({sessionUpdate:Ee("ls_error"),code:D(),message:D(),hint:D().optional()})]),Cx=I({sessionId:D(),seq:ue().int().positive(),ts:ue(),update:v5}),y5=KN([D(),ue()]),b5=I({code:ue().int(),message:D(),data:Ps().optional()});I({jsonrpc:Ee("2.0"),id:y5.optional(),method:D().optional(),params:Ps().optional(),result:Ps().optional(),error:b5.optional()});Qe(["invalid_params","not_found","agent_unavailable","not_supported","not_ready","busy","offline","internal"]);const x5=-32601,dl=-32e3;I({}).passthrough();const Ax=I({name:D(),path:D(),project:Te().optional(),file:Te().optional(),size:ue().int().optional()});I({limit:ue().int().positive().max(200).optional()}),I({projects:Le(u5)}),I({limit:ue().int().positive().max(200).optional(),before:ue().optional(),includeArchived:Te().optional()}),I({sessions:Le(Sr),nextBefore:ue().optional()}),I({agent:D().min(1),cwd:D().min(1),prompt:Le(Ki).optional(),clientMessageId:D().optional(),model:D().optional(),worktree:Te().optional()}),I({session:Sr}),I({sessionId:D().min(1),itemId:D().min(1).optional(),worktree:Te().optional()}),I({session:Sr}),I({sessionId:D().min(1),fromSeq:ue().int().nonnegative(),lazyImages:Te().optional()}),I({session:Sr,startSeq:ue().int().nonnegative().optional()}),I({sessionId:D().min(1),beforeSeq:ue().int().positive(),lazyImages:Te().optional()}),I({events:Le(Cx),startSeq:ue().int().nonnegative()}),I({sessionId:D().min(1)}),I({subagents:Le(i5)}),I({sessionId:D().min(1),toolCallId:D().min(1),lazyImages:Te().optional()}),I({events:Le(Cx)}),I({sessionId:D().min(1)}),I({tasks:Le(m2)}),I({sessionId:D().min(1),taskId:D().min(1),before:ue().int().nonnegative().optional(),limit:ue().int().positive().max(256*1024).optional()}),I({text:D(),start:ue().int().nonnegative(),size:ue().int().nonnegative()}),I({sessionId:D().min(1),taskId:D().min(1)}),I({sessionId:D().min(1),direct:Te().optional()}),I({port:ue().int().positive(),token:D()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),uri:D().min(1)}),I({mimeType:D(),data:D()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),clientMessageId:D().min(1),content:Le(Ki).min(1),whenBusy:Qe(["queue"]).optional()}),I({delivery:Qe(["started","steered","queued","duplicate"])}),I({sessionId:D().min(1)}),I({sessionId:D().min(1),requestId:D().min(1),optionId:D().min(1)}),I({sessionId:D().min(1),requestId:D().min(1),answers:Le(h2).max(50)}),I({sessionId:D(),change:f5}),I({goal:p2.nullable()}),I({sessionId:D().min(1),optionId:D().min(1),value:D().min(1)}),I({sessionId:D().min(1),clientMessageId:D().min(1).optional()}),I({sessionId:D().min(1),clientMessageIds:Le(D().min(1))}),I({sessionId:D().min(1),clientMessageId:D().min(1)}),I({removed:Te()}),I({sessionId:D().min(1),archived:Te()}),I({session:Sr}),I({sessionId:D().min(1),title:D().max(200)}),I({session:Sr}),I({sessionId:D().min(1),worktree:Qe(["keep","remove"]).optional()}),I({sessionId:D().min(1)}),I({driver:qu.optional()}),I({sessionId:D().min(1)}),I({driver:qu.optional()}),I({agent:D().min(1),sessionId:D().optional(),args:Le(D()).default([]),cwd:D().optional(),env:um(D()).optional()}),I({command:D(),args:Le(D()),env:um(D()).optional(),sessionId:D().optional()}),I({sessionId:D().min(1)}),I({sessionId:D().min(1)}),I({command:D(),args:Le(D()),env:um(D()).optional()}),I({link:D(),code:D(),expiresAt:ue(),gateway:D()}),I({deviceId:D().min(1)}),I({path:D().min(1)}),I({git:l5.optional()}),I({worktrees:Le(c5)}),I({path:D().min(1),force:Te().optional()}),I({path:D().optional(),hidden:Te().default(!1),files:Te().default(!1)}),I({path:D(),parent:D().optional(),home:D(),entries:Le(Ax),truncated:Te().optional()}),I({path:D().min(1),offset:ue().int().nonnegative().default(0),maxBytes:ue().int().min(1).max(2e6).default(512e3)}),I({path:D(),size:ue().int(),modifiedAt:ue(),kind:Qe(["text","image","binary"]),text:D().optional(),data:D().optional(),mimeType:D().optional(),truncated:Te(),nextOffset:ue().int().optional()}),I({dir:D().min(1),name:D().min(1).max(255),data:D().max(4e7)}),I({path:D(),size:ue().int()}),I({parent:D().min(1),name:D().min(1).max(255)}),I({path:D()}),I({query:D().min(1).max(200),limit:ue().int().min(1).max(200).default(60)}),I({entries:Le(Ax),truncated:Te()}),I({terminals:Le(xu)}),I({cwd:D().optional(),command:D().max(4e3).optional(),cols:ue().int().min(10).max(1e3).default(80),rows:ue().int().min(4).max(500).default(24)}),I({terminal:xu}),I({terminalId:D().min(1),fromSeq:ue().int().min(0).optional(),replayFormat:Ee("frames-v1").optional(),fromFrame:ue().int().min(0).optional(),snapshot:Te().optional()}),I({terminal:xu,replay:D(),reset:Te(),seq:ue().int(),recording:I({afterFrame:ue().int(),throughFrame:ue().int()}).optional(),state:I({snapshotId:D(),length:ue().int().min(0),frame:ue().int().min(0),cols:ue().int().min(1),rows:ue().int().min(1)}).optional()}),I({terminalId:D().min(1),snapshotId:D().min(1),offset:ue().int().min(0)}),I({data:D(),nextOffset:ue().int().min(0),done:Te()}),I({terminalId:D().min(1),afterFrame:ue().int().min(0),throughFrame:ue().int().min(0)}),I({frames:Le(I({frame:ue().int(),cols:ue().int(),rows:ue().int(),data:D()})),nextFrame:ue().int(),done:Te()}),I({terminalId:D().min(1)}),I({terminalId:D().min(1),data:D().max(1e6)}),I({terminalId:D().min(1),cols:ue().int().min(10).max(1e3),rows:ue().int().min(4).max(500)}),I({terminalId:D().min(1)}),I({ports:Le(d5)}),I({port:ue().int().min(1).max(65535),direct:Te().optional()}),I({streamId:D(),channel:ue().int().nonnegative().optional()}),I({sdp:D().min(1).max(2e5)}),I({sdp:D()}),I({port:ue().int(),token:D(),displays:Le(I({index:ue().int(),name:D()}))}),I({ask:Te().optional()}),I({supported:Te(),ffmpeg:Te(),recording:Te().nullable(),control:Te().nullable(),app:D().optional(),problem:D().optional()}),I({streamId:D().min(1),data:D().max(2e6)}),I({streamId:D().min(1)});I({sessionId:D(),startSeq:ue().int().nonnegative()}),I({session:Sr}),I({sessionId:D()}),I({sessionId:D()}),I({sessionId:D()}),I({sessionId:D(),line:D()}),I({device:I({id:D(),name:D()})}),I({terminalId:D(),seq:ue().int(),data:D(),frame:ue().int().optional(),cols:ue().int().optional(),rows:ue().int().optional()}),I({terminal:xu,closed:Te().optional()}),I({streamId:D(),data:D()}),I({streamId:D(),error:D().optional()});class ca extends Error{constructor(t,s,r){super(s),this.code=t,this.data=r,this.name="RpcError"}static app(t,s,r){return new ca(dl,s,{code:t,...r})}get appCode(){const t=this.data;return typeof t?.code=="string"?t.code:void 0}toObject(){return this.data===void 0?{code:this.code,message:this.message}:{code:this.code,message:this.message,data:this.data}}}const w5=Symbol("rpc.abandon");class S5{constructor(t){this.options=t}nextId=1;pending=new Map;closed=!1;request(t,s,r){if(this.closed)return Promise.reject(new ca(dl,`connection closed (${t})`));const o=this.nextId++;return new Promise((l,u)=>{const d={resolve:l,reject:u,method:t},m=r??this.options.requestTimeoutMs??3e4;m>0&&(d.timer=setTimeout(()=>{this.pending.delete(o),u(new ca(dl,`${t} timed out after ${m}ms`,{code:"timeout"}))},m)),this.pending.set(o,d),this.write({jsonrpc:"2.0",id:o,method:t,params:s??{}})})}notify(t,s){this.closed||this.write({jsonrpc:"2.0",method:t,params:s??{}})}receive(t){for(const s of t.split(`
154
154
  `)){if(!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.dispatch(r)}}close(t="connection closed"){if(!this.closed){this.closed=!0;for(const[s,r]of this.pending)r.timer&&clearTimeout(r.timer),r.reject(new ca(dl,`${t} (${r.method})`,{code:"closed"})),this.pending.delete(s)}}get isClosed(){return this.closed}dispatch(t){const s=t.id,r=typeof t.method=="string"?t.method:void 0;if(r===void 0){if(s===void 0)return;const l=this.pending.get(s);if(!l)return;this.pending.delete(s),l.timer&&clearTimeout(l.timer);const u=t.error;u?l.reject(new ca(u.code,u.message,u.data)):l.resolve(t.result);return}if(s===void 0){this.options.onNotification?.(r,t.params);return}const o=this.options.onRequest;if(!o){this.write({jsonrpc:"2.0",id:s,error:{code:x5,message:`no handler for ${r}`}});return}Promise.resolve().then(()=>o(r,t.params,s)).then(l=>{l!==w5&&this.write({jsonrpc:"2.0",id:s,result:l??{}})},l=>{const u=l instanceof ca?l:new ca(dl,l instanceof Error?l.message:String(l),{code:"internal"});this.write({jsonrpc:"2.0",id:s,error:u.toObject()})})}write(t){if(!this.closed)try{this.options.send(JSON.stringify(t))}catch{this.close("send failed")}}}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function ap(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}const $u=n=>n?`"${n}" `:"";function sp(n,t=""){if(typeof n!="boolean")throw new TypeError($u(t)+"expected boolean, got type="+typeof n);return n}function Xi(n,t=""){if(typeof n!="number")throw new TypeError($u(t)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError($u(t)+"expected integer >= 0, got "+n);return n}function qt(n,t,s=""){if(ap(n)&&(t===void 0||n.length===t))return n;t!==void 0&&Xi(t,"length");const r=ap(n),o=t!==void 0?` of length ${t}`:"",l=r?`length=${n.length}`:`type=${typeof n}`,u=$u(s)+"expected Uint8Array"+o+", got "+l;throw r?new RangeError(u):new TypeError(u)}const jx=(n,t)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof n}`)};function Tx(n,t=!0){if(n.destroyed)throw new Error("hash was destroyed");if(t&&n.finished)throw new Error("digest() was already called")}function E5(n,t){qt(n,void 0,"output");const s=t.outputLen;if(!(n.length>=s))throw new RangeError('"output" expected length >= '+s)}function Pa(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function pa(...n){for(let t=0;t<n.length;t++)n[t].fill(0)}function _5(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}const fa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function C5(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function A5(n){for(let t=0;t<n.length;t++)n[t]=C5(n[t]);return n}const Yn=fa?n=>n:A5;function j5(n,t){return!n.byteLength||!t.byteLength?!1:n.buffer===t.buffer&&n.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<n.byteOffset+n.byteLength}function T5(n,t){if(j5(n,t)&&n.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function k5(n,t){return jx(n,"defaults"),jx(t,"opts"),Object.assign(n,t)}function N5(n,t){if(n=qt(n),t=qt(t),n.length!==t.length)return!1;let s=0;for(let r=0;r<n.length;r++)s|=n[r]^t[r];return s===0}function O5(n,t,s){const r=t,o=(()=>[]),l=(d,m)=>r(m,...o(d)).update(d).digest(),u=r(new Uint8Array(n),...o(new Uint8Array(0)));return l.outputLen=u.outputLen,l.blockLen=u.blockLen,l.create=(d,...m)=>r(d,...m),l}const R5=(n,t)=>{function s(r,...o){if(qt(r,void 0,"key"),n.nonceLength!==void 0){const v=o[0];qt(v,n.varSizeNonce?void 0:n.nonceLength,"nonce")}const l=n.tagLength,u=n.nonceLength!==void 0?1:0;if(!n.withAAD){for(let v=u;v<o.length;v++)if(ap(o[v]))throw new Error("AAD not supported")}n.withAAD&&o[u]!==void 0&&qt(o[u],void 0,"AAD");const d=t(r,...o),m=(v,x)=>{if(x!==void 0){if(v!==2)throw new Error("cipher output not supported");qt(x,void 0,"output")}};let p=!1;return{encrypt(v,x){if(p)throw new Error("cannot encrypt() twice with same key + nonce");return p=!0,qt(v,void 0,"data"),m(d.encrypt.length,x),d.encrypt(v,x)},decrypt(v,x){if(qt(v,void 0,"data"),l&&v.length<l)throw new Error('"ciphertext" expected length >= tagLength='+l);return m(d.decrypt.length,x),d.decrypt(v,x)}}}return Object.assign(s,n),s};function rp(n,t,s=!0){if(t===void 0)return new Uint8Array(n);if(qt(t,n,"output"),s&&!Pu(t))throw new Error("invalid output, must be aligned");return t}function D5(n,t,s){Xi(n),Xi(t),sp(s);const r=new Uint8Array(16),o=_5(r);return o.setBigUint64(0,BigInt(t),s),o.setBigUint64(8,BigInt(n),s),r}function Pu(n){return n.byteOffset%4===0}function Fu(n){return Uint8Array.from(qt(n))}const g2=n=>Uint8Array.from(n.split(""),t=>t.charCodeAt(0)),M5=Yn(Pa(g2("expand 16-byte k"))),z5=Yn(Pa(g2("expand 32-byte k")));function at(n,t){return n<<t|n>>>32-t}const il=64,L5=16,ip=2**32-1,kx=Uint32Array.of();function U5(n,t,s,r,o,l,u,d){const m=o.length,p=new Uint8Array(il),y=Pa(p),v=fa&&Pu(o)&&Pu(l),x=v?Pa(o):kx,_=v?Pa(l):kx;if(!fa){for(let E=0;E<m;u++){if(n(t,s,r,y,u,d),Yn(y),u>=ip)throw new Error("arx: counter overflow");const A=Math.min(il,m-E);for(let S=0,j;S<A;S++)j=E+S,l[j]=o[j]^p[S];E+=A}return}for(let E=0;E<m;u++){if(n(t,s,r,y,u,d),u>=ip)throw new Error("arx: counter overflow");const A=Math.min(il,m-E);if(v&&A===il){const S=E/4;if(E%4!==0)throw new Error("arx: invalid block position");for(let j=0,T;j<L5;j++)T=S+j,_[T]=x[T]^y[j];E+=il;continue}for(let S=0,j;S<A;S++)j=E+S,l[j]=o[j]^p[S];E+=A}}function B5(n,t){const{allowShortKeys:s,extendNonceFn:r,counterLength:o,counterRight:l,rounds:u}=k5({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof n!="function")throw new Error("core must be a function");return Xi(o),Xi(u),sp(l),sp(s),(d,m,p,y,v=0)=>{qt(d,void 0,"key"),qt(m,void 0,"nonce"),qt(p,void 0,"data");const x=p.length,_=y!==void 0;if(y=rp(x,y,!1),_&&T5(p,y),Xi(v),v<0||v>=ip)throw new Error("arx: counter overflow");const E=[];let A=d.length,S,j;if(A===32)E.push(S=Fu(d)),j=z5;else if(A===16&&s)S=new Uint8Array(32),S.set(d),S.set(d,16),j=M5,E.push(S);else throw qt(d,32,"arx key"),new Error("invalid key size");(!fa||!Pu(m))&&E.push(m=Fu(m));let T=Pa(S);if(r){if(m.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const R=m.subarray(0,16);if(fa)r(j,T,Pa(R),T);else{const O=Yn(Uint32Array.from(j));r(O,T,Pa(R),T),pa(O),Yn(T)}m=m.subarray(16)}else fa||Yn(T);const k=16-o;if(k!==m.length)throw new Error(`arx: nonce must be ${k} or 16 bytes`);if(k!==12){const R=new Uint8Array(12);R.set(m,l?0:12-m.length),m=R,E.push(m)}const C=Yn(Pa(m));try{return U5(n,j,T,C,p,y,v,u),y}finally{pa(...E)}}}function Kt(n,t){return n[t++]&255|(n[t++]&255)<<8}class I5{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(t){t=Fu(qt(t,32,"key"));const s=Kt(t,0),r=Kt(t,2),o=Kt(t,4),l=Kt(t,6),u=Kt(t,8),d=Kt(t,10),m=Kt(t,12),p=Kt(t,14);this.r[0]=s&8191,this.r[1]=(s>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|l<<9)&8191,this.r[4]=(l>>>4|u<<12)&255,this.r[5]=u>>>1&8190,this.r[6]=(u>>>14|d<<2)&8191,this.r[7]=(d>>>11|m<<5)&8065,this.r[8]=(m>>>8|p<<8)&8191,this.r[9]=p>>>5&127;for(let y=0;y<8;y++)this.pad[y]=Kt(t,16+2*y)}process(t,s,r=!1){const o=r?0:2048,{h:l,r:u}=this,d=u[0],m=u[1],p=u[2],y=u[3],v=u[4],x=u[5],_=u[6],E=u[7],A=u[8],S=u[9],j=Kt(t,s+0),T=Kt(t,s+2),k=Kt(t,s+4),C=Kt(t,s+6),R=Kt(t,s+8),O=Kt(t,s+10),M=Kt(t,s+12),z=Kt(t,s+14);let L=l[0]+(j&8191),q=l[1]+((j>>>13|T<<3)&8191),V=l[2]+((T>>>10|k<<6)&8191),G=l[3]+((k>>>7|C<<9)&8191),Z=l[4]+((C>>>4|R<<12)&8191),ee=l[5]+(R>>>1&8191),re=l[6]+((R>>>14|O<<2)&8191),U=l[7]+((O>>>11|M<<5)&8191),$=l[8]+((M>>>8|z<<8)&8191),W=l[9]+(z>>>5|o),J=0,Q=J+L*d+q*(5*S)+V*(5*A)+G*(5*E)+Z*(5*_);J=Q>>>13,Q&=8191,Q+=ee*(5*x)+re*(5*v)+U*(5*y)+$*(5*p)+W*(5*m),J+=Q>>>13,Q&=8191;let pe=J+L*m+q*d+V*(5*S)+G*(5*A)+Z*(5*E);J=pe>>>13,pe&=8191,pe+=ee*(5*_)+re*(5*x)+U*(5*v)+$*(5*y)+W*(5*p),J+=pe>>>13,pe&=8191;let F=J+L*p+q*m+V*d+G*(5*S)+Z*(5*A);J=F>>>13,F&=8191,F+=ee*(5*E)+re*(5*_)+U*(5*x)+$*(5*v)+W*(5*y),J+=F>>>13,F&=8191;let te=J+L*y+q*p+V*m+G*d+Z*(5*S);J=te>>>13,te&=8191,te+=ee*(5*A)+re*(5*E)+U*(5*_)+$*(5*x)+W*(5*v),J+=te>>>13,te&=8191;let de=J+L*v+q*y+V*p+G*m+Z*d;J=de>>>13,de&=8191,de+=ee*(5*S)+re*(5*A)+U*(5*E)+$*(5*_)+W*(5*x),J+=de>>>13,de&=8191;let ce=J+L*x+q*v+V*y+G*p+Z*m;J=ce>>>13,ce&=8191,ce+=ee*d+re*(5*S)+U*(5*A)+$*(5*E)+W*(5*_),J+=ce>>>13,ce&=8191;let ie=J+L*_+q*x+V*v+G*y+Z*p;J=ie>>>13,ie&=8191,ie+=ee*m+re*d+U*(5*S)+$*(5*A)+W*(5*E),J+=ie>>>13,ie&=8191;let we=J+L*E+q*_+V*x+G*v+Z*y;J=we>>>13,we&=8191,we+=ee*p+re*m+U*d+$*(5*S)+W*(5*A),J+=we>>>13,we&=8191;let me=J+L*A+q*E+V*_+G*x+Z*v;J=me>>>13,me&=8191,me+=ee*y+re*p+U*m+$*d+W*(5*S),J+=me>>>13,me&=8191;let he=J+L*S+q*A+V*E+G*_+Z*x;J=he>>>13,he&=8191,he+=ee*v+re*y+U*p+$*m+W*d,J+=he>>>13,he&=8191,J=(J<<2)+J|0,J=J+Q|0,Q=J&8191,J=J>>>13,pe+=J,l[0]=Q,l[1]=pe,l[2]=F,l[3]=te,l[4]=de,l[5]=ce,l[6]=ie,l[7]=we,l[8]=me,l[9]=he}finalize(){const{h:t,pad:s}=this,r=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let d=2;d<10;d++)t[d]+=o,o=t[d]>>>13,t[d]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let d=1;d<10;d++)r[d]=t[d]+o,o=r[d]>>>13,r[d]&=8191;r[9]-=8192;let l=(o^1)-1;for(let d=0;d<10;d++)r[d]&=l;l=~l;for(let d=0;d<10;d++)t[d]=t[d]&l|r[d];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let u=t[0]+s[0];t[0]=u&65535;for(let d=1;d<8;d++)u=(t[d]+s[d]|0)+(u>>>16)|0,t[d]=u&65535;pa(r)}update(t){Tx(this),qt(t),t=Fu(t);const{buffer:s,blockLen:r}=this,o=t.length;for(let l=0;l<o;){const u=Math.min(r-this.pos,o-l);if(u===r){for(;r<=o-l;l+=r)this.process(t,l);continue}s.set(t.subarray(l,l+u),this.pos),this.pos+=u,l+=u,this.pos===r&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,pa(this.h,this.r,this.buffer,this.pad)}digestInto(t){Tx(this),E5(t,this),this.finished=!0;const{buffer:s,h:r}=this;let{pos:o}=this;if(o){for(s[o++]=1;o<16;o++)s[o]=0;this.process(s,0,!0)}this.finalize();let l=0;for(let u=0;u<8;u++)t[l++]=r[u]>>>0,t[l++]=r[u]>>>8}digest(){const{buffer:t,outputLen:s}=this;this.digestInto(t);const r=t.slice(0,s);return this.destroy(),r}}const H5=O5(32,n=>new I5(n));function v2(n,t,s,r,o,l=20){let u=n[0],d=n[1],m=n[2],p=n[3],y=t[0],v=t[1],x=t[2],_=t[3],E=t[4],A=t[5],S=t[6],j=t[7],T=o,k=s[0],C=s[1],R=s[2],O=u,M=d,z=m,L=p,q=y,V=v,G=x,Z=_,ee=E,re=A,U=S,$=j,W=T,J=k,Q=C,pe=R;for(let te=0;te<l;te+=2)O=O+q|0,W=at(W^O,16),ee=ee+W|0,q=at(q^ee,12),O=O+q|0,W=at(W^O,8),ee=ee+W|0,q=at(q^ee,7),M=M+V|0,J=at(J^M,16),re=re+J|0,V=at(V^re,12),M=M+V|0,J=at(J^M,8),re=re+J|0,V=at(V^re,7),z=z+G|0,Q=at(Q^z,16),U=U+Q|0,G=at(G^U,12),z=z+G|0,Q=at(Q^z,8),U=U+Q|0,G=at(G^U,7),L=L+Z|0,pe=at(pe^L,16),$=$+pe|0,Z=at(Z^$,12),L=L+Z|0,pe=at(pe^L,8),$=$+pe|0,Z=at(Z^$,7),O=O+V|0,pe=at(pe^O,16),U=U+pe|0,V=at(V^U,12),O=O+V|0,pe=at(pe^O,8),U=U+pe|0,V=at(V^U,7),M=M+G|0,W=at(W^M,16),$=$+W|0,G=at(G^$,12),M=M+G|0,W=at(W^M,8),$=$+W|0,G=at(G^$,7),z=z+Z|0,J=at(J^z,16),ee=ee+J|0,Z=at(Z^ee,12),z=z+Z|0,J=at(J^z,8),ee=ee+J|0,Z=at(Z^ee,7),L=L+q|0,Q=at(Q^L,16),re=re+Q|0,q=at(q^re,12),L=L+q|0,Q=at(Q^L,8),re=re+Q|0,q=at(q^re,7);let F=0;r[F++]=u+O|0,r[F++]=d+M|0,r[F++]=m+z|0,r[F++]=p+L|0,r[F++]=y+q|0,r[F++]=v+V|0,r[F++]=x+G|0,r[F++]=_+Z|0,r[F++]=E+ee|0,r[F++]=A+re|0,r[F++]=S+U|0,r[F++]=j+$|0,r[F++]=T+W|0,r[F++]=k+J|0,r[F++]=C+Q|0,r[F++]=R+pe|0}function V5(n,t,s,r){const o=fa?n:Yn(n.slice(0,4)),l=fa?t:Yn(t.slice(0,8)),u=fa?s:Yn(s.slice(0,4)),d=new Uint32Array(16);v2(o,l,u.subarray(1),d,u[0]);let m=0;r[m++]=d[0]-o[0]|0,r[m++]=d[1]-o[1]|0,r[m++]=d[2]-o[2]|0,r[m++]=d[3]-o[3]|0,r[m++]=d[12]-u[0]|0,r[m++]=d[13]-u[1]|0,r[m++]=d[14]-u[2]|0,r[m++]=d[15]-u[3]|0,Yn(r),fa||pa(o,l,u),pa(d)}const q5=B5(v2,{counterRight:!1,counterLength:8,extendNonceFn:V5,allowShortKeys:!1}),$5=new Uint8Array(16),Nx=(n,t)=>{n.update(t);const s=t.length%16;s&&n.update($5.subarray(s))},P5=new Uint8Array(32);function Ox(n,t,s,r,o){o!==void 0&&qt(o,void 0,"AAD");const l=n(t,s,P5),u=D5(r.length,o?o.length:0,!0),d=H5.create(l);o&&Nx(d,o),Nx(d,r),d.update(u);const m=d.digest();return pa(l,u),m}const F5=n=>(t,s,r)=>({encrypt(l,u){const d=l.length;u=rp(d+16,u,!1),u.set(l);const m=u.subarray(0,-16);n(t,s,m,m,1);const p=Ox(n,t,s,m,r);return u.set(p,d),pa(p),u},decrypt(l,u){u=rp(l.length-16,u,!1);const d=l.subarray(0,-16),m=l.subarray(-16),p=Ox(n,t,s,d,r);if(!N5(m,p))throw pa(p),new Error("invalid tag");return u.set(l.subarray(0,-16)),n(t,s,u,u,1),pa(p),u}}),Rx=R5({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},F5(q5)),Bi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function wd(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Gu(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Js(n,...t){if(!wd(n))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(n.length))throw new Error("Uint8Array expected of length "+t+", got length="+n.length)}function ag(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Gu(n.outputLen),Gu(n.blockLen)}function Zu(n,t=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(t&&n.finished)throw new Error("Hash#digest() has already been called")}function G5(n,t){Js(n);const s=t.outputLen;if(n.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function zr(...n){for(let t=0;t<n.length;t++)n[t].fill(0)}function dm(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function oa(n,t){return n<<32-t|n>>>t}const y2=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Z5=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function sg(n){if(Js(n),y2)return n.toHex();let t="";for(let s=0;s<n.length;s++)t+=Z5[n[s]];return t}const Ia={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dx(n){if(n>=Ia._0&&n<=Ia._9)return n-Ia._0;if(n>=Ia.A&&n<=Ia.F)return n-(Ia.A-10);if(n>=Ia.a&&n<=Ia.f)return n-(Ia.a-10)}function b2(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(y2)return Uint8Array.fromHex(n);const t=n.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(s);for(let o=0,l=0;o<s;o++,l+=2){const u=Dx(n.charCodeAt(l)),d=Dx(n.charCodeAt(l+1));if(u===void 0||d===void 0){const m=n[l]+n[l+1];throw new Error('hex string expected, got non-hex character "'+m+'" at index '+l)}r[o]=u*16+d}return r}function Y5(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function wl(n){return typeof n=="string"&&(n=Y5(n)),Js(n),n}function Mx(...n){let t=0;for(let r=0;r<n.length;r++){const o=n[r];Js(o),t+=o.length}const s=new Uint8Array(t);for(let r=0,o=0;r<n.length;r++){const l=n[r];s.set(l,o),o+=l.length}return s}class x2{}function w2(n){const t=r=>n().update(wl(r)).digest(),s=n();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>n(),t}function S2(n=32){if(Bi&&typeof Bi.getRandomValues=="function")return Bi.getRandomValues(new Uint8Array(n));if(Bi&&typeof Bi.randomBytes=="function")return Uint8Array.from(Bi.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function K5(n,t,s,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(t,s,r);const o=BigInt(32),l=BigInt(4294967295),u=Number(s>>o&l),d=Number(s&l),m=r?4:0,p=r?0:4;n.setUint32(t+m,u,r),n.setUint32(t+p,d,r)}function X5(n,t,s){return n&t^~n&s}function Q5(n,t,s){return n&t^n&s^t&s}class E2 extends x2{constructor(t,s,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=s,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=dm(this.buffer)}update(t){Zu(this),t=wl(t),Js(t);const{view:s,buffer:r,blockLen:o}=this,l=t.length;for(let u=0;u<l;){const d=Math.min(o-this.pos,l-u);if(d===o){const m=dm(t);for(;o<=l-u;u+=o)this.process(m,u);continue}r.set(t.subarray(u,u+d),this.pos),this.pos+=d,u+=d,this.pos===o&&(this.process(s,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Zu(this),G5(t,this),this.finished=!0;const{buffer:s,view:r,blockLen:o,isLE:l}=this;let{pos:u}=this;s[u++]=128,zr(this.buffer.subarray(u)),this.padOffset>o-u&&(this.process(r,0),u=0);for(let v=u;v<o;v++)s[v]=0;K5(r,o-8,BigInt(this.length*8),l),this.process(r,0);const d=dm(t),m=this.outputLen;if(m%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const p=m/4,y=this.get();if(p>y.length)throw new Error("_sha2: outputLen bigger than state");for(let v=0;v<p;v++)d.setUint32(4*v,y[v],l)}digest(){const{buffer:t,outputLen:s}=this;this.digestInto(t);const r=t.slice(0,s);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:s,buffer:r,length:o,finished:l,destroyed:u,pos:d}=this;return t.destroyed=u,t.finished=l,t.length=o,t.pos=d,o%s&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Ts=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),tn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ou=BigInt(2**32-1),zx=BigInt(32);function W5(n,t=!1){return t?{h:Number(n&ou),l:Number(n>>zx&ou)}:{h:Number(n>>zx&ou)|0,l:Number(n&ou)|0}}function J5(n,t=!1){const s=n.length;let r=new Uint32Array(s),o=new Uint32Array(s);for(let l=0;l<s;l++){const{h:u,l:d}=W5(n[l],t);[r[l],o[l]]=[u,d]}return[r,o]}const Lx=(n,t,s)=>n>>>s,Ux=(n,t,s)=>n<<32-s|t>>>s,Ii=(n,t,s)=>n>>>s|t<<32-s,Hi=(n,t,s)=>n<<32-s|t>>>s,lu=(n,t,s)=>n<<64-s|t>>>s-32,cu=(n,t,s)=>n>>>s-32|t<<64-s;function Ha(n,t,s,r){const o=(t>>>0)+(r>>>0);return{h:n+s+(o/2**32|0)|0,l:o|0}}const eO=(n,t,s)=>(n>>>0)+(t>>>0)+(s>>>0),tO=(n,t,s,r)=>t+s+r+(n/2**32|0)|0,nO=(n,t,s,r)=>(n>>>0)+(t>>>0)+(s>>>0)+(r>>>0),aO=(n,t,s,r,o)=>t+s+r+o+(n/2**32|0)|0,sO=(n,t,s,r,o)=>(n>>>0)+(t>>>0)+(s>>>0)+(r>>>0)+(o>>>0),rO=(n,t,s,r,o,l)=>t+s+r+o+l+(n/2**32|0)|0,iO=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ks=new Uint32Array(64);class oO extends E2{constructor(t=32){super(64,t,8,!1),this.A=Ts[0]|0,this.B=Ts[1]|0,this.C=Ts[2]|0,this.D=Ts[3]|0,this.E=Ts[4]|0,this.F=Ts[5]|0,this.G=Ts[6]|0,this.H=Ts[7]|0}get(){const{A:t,B:s,C:r,D:o,E:l,F:u,G:d,H:m}=this;return[t,s,r,o,l,u,d,m]}set(t,s,r,o,l,u,d,m){this.A=t|0,this.B=s|0,this.C=r|0,this.D=o|0,this.E=l|0,this.F=u|0,this.G=d|0,this.H=m|0}process(t,s){for(let v=0;v<16;v++,s+=4)ks[v]=t.getUint32(s,!1);for(let v=16;v<64;v++){const x=ks[v-15],_=ks[v-2],E=oa(x,7)^oa(x,18)^x>>>3,A=oa(_,17)^oa(_,19)^_>>>10;ks[v]=A+ks[v-7]+E+ks[v-16]|0}let{A:r,B:o,C:l,D:u,E:d,F:m,G:p,H:y}=this;for(let v=0;v<64;v++){const x=oa(d,6)^oa(d,11)^oa(d,25),_=y+x+X5(d,m,p)+iO[v]+ks[v]|0,A=(oa(r,2)^oa(r,13)^oa(r,22))+Q5(r,o,l)|0;y=p,p=m,m=d,d=u+_|0,u=l,l=o,o=r,r=_+A|0}r=r+this.A|0,o=o+this.B|0,l=l+this.C|0,u=u+this.D|0,d=d+this.E|0,m=m+this.F|0,p=p+this.G|0,y=y+this.H|0,this.set(r,o,l,u,d,m,p,y)}roundClean(){zr(ks)}destroy(){this.set(0,0,0,0,0,0,0,0),zr(this.buffer)}}const _2=J5(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),lO=_2[0],cO=_2[1],Ns=new Uint32Array(80),Os=new Uint32Array(80);class uO extends E2{constructor(t=64){super(128,t,16,!1),this.Ah=tn[0]|0,this.Al=tn[1]|0,this.Bh=tn[2]|0,this.Bl=tn[3]|0,this.Ch=tn[4]|0,this.Cl=tn[5]|0,this.Dh=tn[6]|0,this.Dl=tn[7]|0,this.Eh=tn[8]|0,this.El=tn[9]|0,this.Fh=tn[10]|0,this.Fl=tn[11]|0,this.Gh=tn[12]|0,this.Gl=tn[13]|0,this.Hh=tn[14]|0,this.Hl=tn[15]|0}get(){const{Ah:t,Al:s,Bh:r,Bl:o,Ch:l,Cl:u,Dh:d,Dl:m,Eh:p,El:y,Fh:v,Fl:x,Gh:_,Gl:E,Hh:A,Hl:S}=this;return[t,s,r,o,l,u,d,m,p,y,v,x,_,E,A,S]}set(t,s,r,o,l,u,d,m,p,y,v,x,_,E,A,S){this.Ah=t|0,this.Al=s|0,this.Bh=r|0,this.Bl=o|0,this.Ch=l|0,this.Cl=u|0,this.Dh=d|0,this.Dl=m|0,this.Eh=p|0,this.El=y|0,this.Fh=v|0,this.Fl=x|0,this.Gh=_|0,this.Gl=E|0,this.Hh=A|0,this.Hl=S|0}process(t,s){for(let k=0;k<16;k++,s+=4)Ns[k]=t.getUint32(s),Os[k]=t.getUint32(s+=4);for(let k=16;k<80;k++){const C=Ns[k-15]|0,R=Os[k-15]|0,O=Ii(C,R,1)^Ii(C,R,8)^Lx(C,R,7),M=Hi(C,R,1)^Hi(C,R,8)^Ux(C,R,7),z=Ns[k-2]|0,L=Os[k-2]|0,q=Ii(z,L,19)^lu(z,L,61)^Lx(z,L,6),V=Hi(z,L,19)^cu(z,L,61)^Ux(z,L,6),G=nO(M,V,Os[k-7],Os[k-16]),Z=aO(G,O,q,Ns[k-7],Ns[k-16]);Ns[k]=Z|0,Os[k]=G|0}let{Ah:r,Al:o,Bh:l,Bl:u,Ch:d,Cl:m,Dh:p,Dl:y,Eh:v,El:x,Fh:_,Fl:E,Gh:A,Gl:S,Hh:j,Hl:T}=this;for(let k=0;k<80;k++){const C=Ii(v,x,14)^Ii(v,x,18)^lu(v,x,41),R=Hi(v,x,14)^Hi(v,x,18)^cu(v,x,41),O=v&_^~v&A,M=x&E^~x&S,z=sO(T,R,M,cO[k],Os[k]),L=rO(z,j,C,O,lO[k],Ns[k]),q=z|0,V=Ii(r,o,28)^lu(r,o,34)^lu(r,o,39),G=Hi(r,o,28)^cu(r,o,34)^cu(r,o,39),Z=r&l^r&d^l&d,ee=o&u^o&m^u&m;j=A|0,T=S|0,A=_|0,S=E|0,_=v|0,E=x|0,{h:v,l:x}=Ha(p|0,y|0,L|0,q|0),p=d|0,y=m|0,d=l|0,m=u|0,l=r|0,u=o|0;const re=eO(q,G,ee);r=tO(re,L,V,Z),o=re|0}({h:r,l:o}=Ha(this.Ah|0,this.Al|0,r|0,o|0)),{h:l,l:u}=Ha(this.Bh|0,this.Bl|0,l|0,u|0),{h:d,l:m}=Ha(this.Ch|0,this.Cl|0,d|0,m|0),{h:p,l:y}=Ha(this.Dh|0,this.Dl|0,p|0,y|0),{h:v,l:x}=Ha(this.Eh|0,this.El|0,v|0,x|0),{h:_,l:E}=Ha(this.Fh|0,this.Fl|0,_|0,E|0),{h:A,l:S}=Ha(this.Gh|0,this.Gl|0,A|0,S|0),{h:j,l:T}=Ha(this.Hh|0,this.Hl|0,j|0,T|0),this.set(r,o,l,u,d,m,p,y,v,x,_,E,A,S,j,T)}roundClean(){zr(Ns,Os)}destroy(){zr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Sl=w2(()=>new oO),dO=w2(()=>new uO);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rg=BigInt(0),op=BigInt(1);function lp(n,t=""){if(typeof n!="boolean"){const s=t&&`"${t}"`;throw new Error(s+"expected boolean, got type="+typeof n)}return n}function wu(n,t,s=""){const r=wd(n),o=n?.length,l=t!==void 0;if(!r||l&&o!==t){const u=s&&`"${s}" `,d=l?` of length ${t}`:"",m=r?`length=${o}`:`type=${typeof n}`;throw new Error(u+"expected Uint8Array"+d+", got "+m)}return n}function C2(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?rg:BigInt("0x"+n)}function fO(n){return C2(sg(n))}function eo(n){return Js(n),C2(sg(Uint8Array.from(n).reverse()))}function A2(n,t){return b2(n.toString(16).padStart(t*2,"0"))}function j2(n,t){return A2(n,t).reverse()}function la(n,t,s){let r;if(typeof t=="string")try{r=b2(t)}catch(l){throw new Error(n+" must be hex string or Uint8Array, cause: "+l)}else if(wd(t))r=Uint8Array.from(t);else throw new Error(n+" must be hex string or Uint8Array");const o=r.length;if(typeof s=="number"&&o!==s)throw new Error(n+" of length "+s+" expected, got "+o);return r}function Bx(n){return Uint8Array.from(n)}const fm=n=>typeof n=="bigint"&&rg<=n;function hO(n,t,s){return fm(n)&&fm(t)&&fm(s)&&t<=n&&n<s}function Yu(n,t,s,r){if(!hO(t,s,r))throw new Error("expected valid "+n+": "+s+" <= n < "+r+", got "+t)}function mO(n){let t;for(t=0;n>rg;n>>=op,t+=1);return t}const ig=n=>(op<<BigInt(n))-op;function Sd(n,t,s={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(o,l,u){const d=n[o];if(u&&d===void 0)return;const m=typeof d;if(m!==l||d===null)throw new Error(`param "${o}" is invalid: expected ${l}, got ${m}`)}Object.entries(t).forEach(([o,l])=>r(o,l,!1)),Object.entries(s).forEach(([o,l])=>r(o,l,!0))}function Ix(n){const t=new WeakMap;return(s,...r)=>{const o=t.get(s);if(o!==void 0)return o;const l=n(s,...r);return t.set(s,l),l}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hn=BigInt(0),an=BigInt(1),Ar=BigInt(2),T2=BigInt(3),k2=BigInt(4),N2=BigInt(5),pO=BigInt(7),O2=BigInt(8),gO=BigInt(9),R2=BigInt(16);function Et(n,t){const s=n%t;return s>=hn?s:t+s}function Gn(n,t,s){let r=n;for(;t-- >hn;)r*=r,r%=s;return r}function Hx(n,t){if(n===hn)throw new Error("invert: expected non-zero number");if(t<=hn)throw new Error("invert: expected positive modulus, got "+t);let s=Et(n,t),r=t,o=hn,l=an;for(;s!==hn;){const d=r/s,m=r%s,p=o-l*d;r=s,s=m,o=l,l=p}if(r!==an)throw new Error("invert: does not exist");return Et(o,t)}function og(n,t,s){if(!n.eql(n.sqr(t),s))throw new Error("Cannot find square root")}function D2(n,t){const s=(n.ORDER+an)/k2,r=n.pow(t,s);return og(n,r,t),r}function vO(n,t){const s=(n.ORDER-N2)/O2,r=n.mul(t,Ar),o=n.pow(r,s),l=n.mul(t,o),u=n.mul(n.mul(l,Ar),o),d=n.mul(l,n.sub(u,n.ONE));return og(n,d,t),d}function yO(n){const t=Ol(n),s=M2(n),r=s(t,t.neg(t.ONE)),o=s(t,r),l=s(t,t.neg(r)),u=(n+pO)/R2;return(d,m)=>{let p=d.pow(m,u),y=d.mul(p,r);const v=d.mul(p,o),x=d.mul(p,l),_=d.eql(d.sqr(y),m),E=d.eql(d.sqr(v),m);p=d.cmov(p,y,_),y=d.cmov(x,v,E);const A=d.eql(d.sqr(y),m),S=d.cmov(p,y,A);return og(d,S,m),S}}function M2(n){if(n<T2)throw new Error("sqrt is not defined for small field");let t=n-an,s=0;for(;t%Ar===hn;)t/=Ar,s++;let r=Ar;const o=Ol(n);for(;Vx(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return D2;let l=o.pow(r,t);const u=(t+an)/Ar;return function(m,p){if(m.is0(p))return p;if(Vx(m,p)!==1)throw new Error("Cannot find square root");let y=s,v=m.mul(m.ONE,l),x=m.pow(p,t),_=m.pow(p,u);for(;!m.eql(x,m.ONE);){if(m.is0(x))return m.ZERO;let E=1,A=m.sqr(x);for(;!m.eql(A,m.ONE);)if(E++,A=m.sqr(A),E===y)throw new Error("Cannot find square root");const S=an<<BigInt(y-E-1),j=m.pow(v,S);y=E,v=m.sqr(j),x=m.mul(x,v),_=m.mul(_,j)}return _}}function bO(n){return n%k2===T2?D2:n%O2===N2?vO:n%R2===gO?yO(n):M2(n)}const xO=(n,t)=>(Et(n,t)&an)===an,wO=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function SO(n){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=wO.reduce((r,o)=>(r[o]="function",r),t);return Sd(n,s),n}function EO(n,t,s){if(s<hn)throw new Error("invalid exponent, negatives unsupported");if(s===hn)return n.ONE;if(s===an)return t;let r=n.ONE,o=t;for(;s>hn;)s&an&&(r=n.mul(r,o)),o=n.sqr(o),s>>=an;return r}function z2(n,t,s=!1){const r=new Array(t.length).fill(s?n.ZERO:void 0),o=t.reduce((u,d,m)=>n.is0(d)?u:(r[m]=u,n.mul(u,d)),n.ONE),l=n.inv(o);return t.reduceRight((u,d,m)=>n.is0(d)?u:(r[m]=n.mul(u,r[m]),n.mul(u,d)),l),r}function Vx(n,t){const s=(n.ORDER-an)/Ar,r=n.pow(t,s),o=n.eql(r,n.ONE),l=n.eql(r,n.ZERO),u=n.eql(r,n.neg(n.ONE));if(!o&&!l&&!u)throw new Error("invalid Legendre symbol result");return o?1:l?0:-1}function _O(n,t){t!==void 0&&Gu(t);const s=t!==void 0?t:n.toString(2).length,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}function Ol(n,t,s=!1,r={}){if(n<=hn)throw new Error("invalid field: expected ORDER > 0, got "+n);let o,l,u=!1,d;if(typeof t=="object"&&t!=null){if(r.sqrt||s)throw new Error("cannot specify opts in two arguments");const x=t;x.BITS&&(o=x.BITS),x.sqrt&&(l=x.sqrt),typeof x.isLE=="boolean"&&(s=x.isLE),typeof x.modFromBytes=="boolean"&&(u=x.modFromBytes),d=x.allowedLengths}else typeof t=="number"&&(o=t),r.sqrt&&(l=r.sqrt);const{nBitLength:m,nByteLength:p}=_O(n,o);if(p>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let y;const v=Object.freeze({ORDER:n,isLE:s,BITS:m,BYTES:p,MASK:ig(m),ZERO:hn,ONE:an,allowedLengths:d,create:x=>Et(x,n),isValid:x=>{if(typeof x!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof x);return hn<=x&&x<n},is0:x=>x===hn,isValidNot0:x=>!v.is0(x)&&v.isValid(x),isOdd:x=>(x&an)===an,neg:x=>Et(-x,n),eql:(x,_)=>x===_,sqr:x=>Et(x*x,n),add:(x,_)=>Et(x+_,n),sub:(x,_)=>Et(x-_,n),mul:(x,_)=>Et(x*_,n),pow:(x,_)=>EO(v,x,_),div:(x,_)=>Et(x*Hx(_,n),n),sqrN:x=>x*x,addN:(x,_)=>x+_,subN:(x,_)=>x-_,mulN:(x,_)=>x*_,inv:x=>Hx(x,n),sqrt:l||(x=>(y||(y=bO(n)),y(v,x))),toBytes:x=>s?j2(x,p):A2(x,p),fromBytes:(x,_=!0)=>{if(d){if(!d.includes(x.length)||x.length>p)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+x.length);const A=new Uint8Array(p);A.set(x,s?0:A.length-x.length),x=A}if(x.length!==p)throw new Error("Field.fromBytes: expected "+p+" bytes, got "+x.length);let E=s?eo(x):fO(x);if(u&&(E=Et(E,n)),!_&&!v.isValid(E))throw new Error("invalid field element: outside of range 0..ORDER");return E},invertBatch:x=>z2(v,x),cmov:(x,_,E)=>E?_:x});return Object.freeze(v)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ku=BigInt(0),cp=BigInt(1);function qx(n,t){const s=t.negate();return n?s:t}function uu(n,t){const s=z2(n.Fp,t.map(r=>r.Z));return t.map((r,o)=>n.fromAffine(r.toAffine(s[o])))}function L2(n,t){if(!Number.isSafeInteger(n)||n<=0||n>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+n)}function hm(n,t){L2(n,t);const s=Math.ceil(t/n)+1,r=2**(n-1),o=2**n,l=ig(n),u=BigInt(n);return{windows:s,windowSize:r,mask:l,maxNumber:o,shiftBy:u}}function $x(n,t,s){const{windowSize:r,mask:o,maxNumber:l,shiftBy:u}=s;let d=Number(n&o),m=n>>u;d>r&&(d-=l,m+=cp);const p=t*r,y=p+Math.abs(d)-1,v=d===0,x=d<0,_=t%2!==0;return{nextN:m,offset:y,isZero:v,isNeg:x,isNegF:_,offsetF:p}}function CO(n,t){if(!Array.isArray(n))throw new Error("array expected");n.forEach((s,r)=>{if(!(s instanceof t))throw new Error("invalid point at index "+r)})}function AO(n,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((s,r)=>{if(!t.isValid(s))throw new Error("invalid scalar at index "+r)})}const mm=new WeakMap,U2=new WeakMap;function pm(n){return U2.get(n)||1}function Px(n){if(n!==Ku)throw new Error("invalid wNAF")}class jO{constructor(t,s){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=s}_unsafeLadder(t,s,r=this.ZERO){let o=t;for(;s>Ku;)s&cp&&(r=r.add(o)),o=o.double(),s>>=cp;return r}precomputeWindow(t,s){const{windows:r,windowSize:o}=hm(s,this.bits),l=[];let u=t,d=u;for(let m=0;m<r;m++){d=u,l.push(d);for(let p=1;p<o;p++)d=d.add(u),l.push(d);u=d.double()}return l}wNAF(t,s,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,l=this.BASE;const u=hm(t,this.bits);for(let d=0;d<u.windows;d++){const{nextN:m,offset:p,isZero:y,isNeg:v,isNegF:x,offsetF:_}=$x(r,d,u);r=m,y?l=l.add(qx(x,s[_])):o=o.add(qx(v,s[p]))}return Px(r),{p:o,f:l}}wNAFUnsafe(t,s,r,o=this.ZERO){const l=hm(t,this.bits);for(let u=0;u<l.windows&&r!==Ku;u++){const{nextN:d,offset:m,isZero:p,isNeg:y}=$x(r,u,l);if(r=d,!p){const v=s[m];o=o.add(y?v.negate():v)}}return Px(r),o}getPrecomputes(t,s,r){let o=mm.get(s);return o||(o=this.precomputeWindow(s,t),t!==1&&(typeof r=="function"&&(o=r(o)),mm.set(s,o))),o}cached(t,s,r){const o=pm(t);return this.wNAF(o,this.getPrecomputes(o,t,r),s)}unsafe(t,s,r,o){const l=pm(t);return l===1?this._unsafeLadder(t,s,o):this.wNAFUnsafe(l,this.getPrecomputes(l,t,r),s,o)}createCache(t,s){L2(s,this.bits),U2.set(t,s),mm.delete(t)}hasCache(t){return pm(t)!==1}}function TO(n,t,s,r){CO(s,n),AO(r,t);const o=s.length,l=r.length;if(o!==l)throw new Error("arrays of points and scalars must have equal length");const u=n.ZERO,d=mO(BigInt(o));let m=1;d>12?m=d-3:d>4?m=d-2:d>0&&(m=2);const p=ig(m),y=new Array(Number(p)+1).fill(u),v=Math.floor((t.BITS-1)/m)*m;let x=u;for(let _=v;_>=0;_-=m){y.fill(u);for(let A=0;A<l;A++){const S=r[A],j=Number(S>>BigInt(_)&p);y[j]=y[j].add(s[A])}let E=u;for(let A=y.length-1,S=u;A>0;A--)S=S.add(y[A]),E=E.add(S);if(x=x.add(E),_!==0)for(let A=0;A<m;A++)x=x.double()}return x}function Fx(n,t,s){if(t){if(t.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return SO(t),t}else return Ol(n,{isLE:s})}function kO(n,t,s={},r){if(r===void 0&&(r=n==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${n} CURVE object`);for(const m of["p","n","h"]){const p=t[m];if(!(typeof p=="bigint"&&p>Ku))throw new Error(`CURVE.${m} must be positive bigint`)}const o=Fx(t.p,s.Fp,r),l=Fx(t.n,s.Fn,r),d=["Gx","Gy","a","d"];for(const m of d)if(!o.isValid(t[m]))throw new Error(`CURVE.${m} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:l}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Rs=BigInt(0),It=BigInt(1),gm=BigInt(2),NO=BigInt(8);function OO(n,t,s,r){const o=n.sqr(s),l=n.sqr(r),u=n.add(n.mul(t.a,o),l),d=n.add(n.ONE,n.mul(t.d,n.mul(o,l)));return n.eql(u,d)}function RO(n,t={}){const s=kO("edwards",n,t,t.FpFnLE),{Fp:r,Fn:o}=s;let l=s.CURVE;const{h:u}=l;Sd(t,{},{uvRatio:"function"});const d=gm<<BigInt(o.BYTES*8)-It,m=S=>r.create(S),p=t.uvRatio||((S,j)=>{try{return{isValid:!0,value:r.sqrt(r.div(S,j))}}catch{return{isValid:!1,value:Rs}}});if(!OO(r,l,l.Gx,l.Gy))throw new Error("bad curve params: generator point");function y(S,j,T=!1){const k=T?It:Rs;return Yu("coordinate "+S,j,k,d),j}function v(S){if(!(S instanceof E))throw new Error("ExtendedPoint expected")}const x=Ix((S,j)=>{const{X:T,Y:k,Z:C}=S,R=S.is0();j==null&&(j=R?NO:r.inv(C));const O=m(T*j),M=m(k*j),z=r.mul(C,j);if(R)return{x:Rs,y:It};if(z!==It)throw new Error("invZ was invalid");return{x:O,y:M}}),_=Ix(S=>{const{a:j,d:T}=l;if(S.is0())throw new Error("bad point: ZERO");const{X:k,Y:C,Z:R,T:O}=S,M=m(k*k),z=m(C*C),L=m(R*R),q=m(L*L),V=m(M*j),G=m(L*m(V+z)),Z=m(q+m(T*m(M*z)));if(G!==Z)throw new Error("bad point: equation left != right (1)");const ee=m(k*C),re=m(R*O);if(ee!==re)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(j,T,k,C){this.X=y("x",j),this.Y=y("y",T),this.Z=y("z",k,!0),this.T=y("t",C),Object.freeze(this)}static CURVE(){return l}static fromAffine(j){if(j instanceof E)throw new Error("extended point not allowed");const{x:T,y:k}=j||{};return y("x",T),y("y",k),new E(T,k,It,m(T*k))}static fromBytes(j,T=!1){const k=r.BYTES,{a:C,d:R}=l;j=Bx(wu(j,k,"point")),lp(T,"zip215");const O=Bx(j),M=j[k-1];O[k-1]=M&-129;const z=eo(O),L=T?d:r.ORDER;Yu("point.y",z,Rs,L);const q=m(z*z),V=m(q-It),G=m(R*q-C);let{isValid:Z,value:ee}=p(V,G);if(!Z)throw new Error("bad point: invalid y coordinate");const re=(ee&It)===It,U=(M&128)!==0;if(!T&&ee===Rs&&U)throw new Error("bad point: x=0 and x_0=1");return U!==re&&(ee=m(-ee)),E.fromAffine({x:ee,y:z})}static fromHex(j,T=!1){return E.fromBytes(la("point",j),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,T=!0){return A.createCache(this,j),T||this.multiply(gm),this}assertValidity(){_(this)}equals(j){v(j);const{X:T,Y:k,Z:C}=this,{X:R,Y:O,Z:M}=j,z=m(T*M),L=m(R*C),q=m(k*M),V=m(O*C);return z===L&&q===V}is0(){return this.equals(E.ZERO)}negate(){return new E(m(-this.X),this.Y,this.Z,m(-this.T))}double(){const{a:j}=l,{X:T,Y:k,Z:C}=this,R=m(T*T),O=m(k*k),M=m(gm*m(C*C)),z=m(j*R),L=T+k,q=m(m(L*L)-R-O),V=z+O,G=V-M,Z=z-O,ee=m(q*G),re=m(V*Z),U=m(q*Z),$=m(G*V);return new E(ee,re,$,U)}add(j){v(j);const{a:T,d:k}=l,{X:C,Y:R,Z:O,T:M}=this,{X:z,Y:L,Z:q,T:V}=j,G=m(C*z),Z=m(R*L),ee=m(M*k*V),re=m(O*q),U=m((C+R)*(z+L)-G-Z),$=re-ee,W=re+ee,J=m(Z-T*G),Q=m(U*$),pe=m(W*J),F=m(U*J),te=m($*W);return new E(Q,pe,te,F)}subtract(j){return this.add(j.negate())}multiply(j){if(!o.isValidNot0(j))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:T,f:k}=A.cached(this,j,C=>uu(E,C));return uu(E,[T,k])[0]}multiplyUnsafe(j,T=E.ZERO){if(!o.isValid(j))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return j===Rs?E.ZERO:this.is0()||j===It?this:A.unsafe(this,j,k=>uu(E,k),T)}isSmallOrder(){return this.multiplyUnsafe(u).is0()}isTorsionFree(){return A.unsafe(this,l.n).is0()}toAffine(j){return x(this,j)}clearCofactor(){return u===It?this:this.multiplyUnsafe(u)}toBytes(){const{x:j,y:T}=this.toAffine(),k=r.toBytes(T);return k[k.length-1]|=j&It?128:0,k}toHex(){return sg(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(j){return uu(E,j)}static msm(j,T){return TO(E,o,j,T)}_setWindowSize(j){this.precompute(j)}toRawBytes(){return this.toBytes()}}E.BASE=new E(l.Gx,l.Gy,It,m(l.Gx*l.Gy)),E.ZERO=new E(Rs,It,It,Rs),E.Fp=r,E.Fn=o;const A=new jO(E,o.BITS);return E.BASE.precompute(8),E}function DO(n,t,s={}){if(typeof t!="function")throw new Error('"hash" function param is required');Sd(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=s,{BASE:o,Fp:l,Fn:u}=n,d=s.randomBytes||S2,m=s.adjustScalarBytes||(L=>L),p=s.domain||((L,q,V)=>{if(lp(V,"phflag"),q.length||V)throw new Error("Contexts/pre-hash are not supported");return L});function y(L){return u.create(eo(L))}function v(L){const q=k.secretKey;L=la("private key",L,q);const V=la("hashed private key",t(L),2*q),G=m(V.slice(0,q)),Z=V.slice(q,2*q),ee=y(G);return{head:G,prefix:Z,scalar:ee}}function x(L){const{head:q,prefix:V,scalar:G}=v(L),Z=o.multiply(G),ee=Z.toBytes();return{head:q,prefix:V,scalar:G,point:Z,pointBytes:ee}}function _(L){return x(L).pointBytes}function E(L=Uint8Array.of(),...q){const V=Mx(...q);return y(t(p(V,la("context",L),!!r)))}function A(L,q,V={}){L=la("message",L),r&&(L=r(L));const{prefix:G,scalar:Z,pointBytes:ee}=x(q),re=E(V.context,G,L),U=o.multiply(re).toBytes(),$=E(V.context,U,ee,L),W=u.create(re+$*Z);if(!u.isValid(W))throw new Error("sign failed: invalid s");const J=Mx(U,u.toBytes(W));return wu(J,k.signature,"result")}const S={zip215:!0};function j(L,q,V,G=S){const{context:Z,zip215:ee}=G,re=k.signature;L=la("signature",L,re),q=la("message",q),V=la("publicKey",V,k.publicKey),ee!==void 0&&lp(ee,"zip215"),r&&(q=r(q));const U=re/2,$=L.subarray(0,U),W=eo(L.subarray(U,re));let J,Q,pe;try{J=n.fromBytes(V,ee),Q=n.fromBytes($,ee),pe=o.multiplyUnsafe(W)}catch{return!1}if(!ee&&J.isSmallOrder())return!1;const F=E(Z,Q.toBytes(),J.toBytes(),q);return Q.add(J.multiplyUnsafe(F)).subtract(pe).clearCofactor().is0()}const T=l.BYTES,k={secretKey:T,publicKey:T,signature:2*T,seed:T};function C(L=d(k.seed)){return wu(L,k.seed,"seed")}function R(L){const q=z.randomSecretKey(L);return{secretKey:q,publicKey:_(q)}}function O(L){return wd(L)&&L.length===u.BYTES}function M(L,q){try{return!!n.fromBytes(L,q)}catch{return!1}}const z={getExtendedPublicKey:x,randomSecretKey:C,isValidSecretKey:O,isValidPublicKey:M,toMontgomery(L){const{y:q}=n.fromBytes(L),V=k.publicKey,G=V===32;if(!G&&V!==57)throw new Error("only defined for 25519 and 448");const Z=G?l.div(It+q,It-q):l.div(q-It,q+It);return l.toBytes(Z)},toMontgomerySecret(L){const q=k.secretKey;wu(L,q);const V=t(L.subarray(0,q));return m(V).subarray(0,q)},randomPrivateKey:C,precompute(L=8,q=n.BASE){return q.precompute(L,!1)}};return Object.freeze({keygen:R,getPublicKey:_,sign:A,verify:j,utils:z,Point:n,lengths:k})}function MO(n){const t={a:n.a,d:n.d,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},s=n.Fp,r=Ol(t.n,n.nBitLength,!0),o={Fp:s,Fn:r,uvRatio:n.uvRatio},l={randomBytes:n.randomBytes,adjustScalarBytes:n.adjustScalarBytes,domain:n.domain,prehash:n.prehash,mapToCurve:n.mapToCurve};return{CURVE:t,curveOpts:o,hash:n.hash,eddsaOpts:l}}function zO(n,t){const s=t.Point;return Object.assign({},t,{ExtendedPoint:s,CURVE:n,nBitLength:s.Fn.BITS,nByteLength:s.Fn.BYTES})}function LO(n){const{CURVE:t,curveOpts:s,hash:r,eddsaOpts:o}=MO(n),l=RO(t,s),u=DO(l,r,o);return zO(n,u)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ol=BigInt(0),Vi=BigInt(1),du=BigInt(2);function UO(n){return Sd(n,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n})}function BO(n){const t=UO(n),{P:s,type:r,adjustScalarBytes:o,powPminus2:l,randomBytes:u}=t,d=r==="x25519";if(!d&&r!=="x448")throw new Error("invalid type");const m=u||S2,p=d?255:448,y=d?32:56,v=BigInt(d?9:5),x=BigInt(d?121665:39081),_=d?du**BigInt(254):du**BigInt(447),E=d?BigInt(8)*du**BigInt(251)-Vi:BigInt(4)*du**BigInt(445)-Vi,A=_+E+Vi,S=Z=>Et(Z,s),j=T(v);function T(Z){return j2(S(Z),y)}function k(Z){const ee=la("u coordinate",Z,y);return d&&(ee[31]&=127),S(eo(ee))}function C(Z){return eo(o(la("scalar",Z,y)))}function R(Z,ee){const re=z(k(ee),C(Z));if(re===ol)throw new Error("invalid private or public key received");return T(re)}function O(Z){return R(Z,j)}function M(Z,ee,re){const U=S(Z*(ee-re));return ee=S(ee-U),re=S(re+U),{x_2:ee,x_3:re}}function z(Z,ee){Yu("u",Z,ol,s),Yu("scalar",ee,_,A);const re=ee,U=Z;let $=Vi,W=ol,J=Z,Q=Vi,pe=ol;for(let te=BigInt(p-1);te>=ol;te--){const de=re>>te&Vi;pe^=de,{x_2:$,x_3:J}=M(pe,$,J),{x_2:W,x_3:Q}=M(pe,W,Q),pe=de;const ce=$+W,ie=S(ce*ce),we=$-W,me=S(we*we),he=ie-me,De=J+Q,Oe=J-Q,Me=S(Oe*ce),He=S(De*we),ze=Me+He,ht=Me-He;J=S(ze*ze),Q=S(U*S(ht*ht)),$=S(ie*me),W=S(he*(ie+S(x*he)))}({x_2:$,x_3:J}=M(pe,$,J)),{x_2:W,x_3:Q}=M(pe,W,Q);const F=l(W);return S($*F)}const L={secretKey:y,publicKey:y,seed:y},q=(Z=m(y))=>(Js(Z,L.seed),Z);function V(Z){const ee=q(Z);return{secretKey:ee,publicKey:O(ee)}}return{keygen:V,getSharedSecret:(Z,ee)=>R(Z,ee),getPublicKey:Z=>O(Z),scalarMult:R,scalarMultBase:O,utils:{randomSecretKey:q,randomPrivateKey:q},GuBytes:j.slice(),lengths:L}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const IO=BigInt(1),Gx=BigInt(2),HO=BigInt(3),VO=BigInt(5),qO=BigInt(8),lg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),B2={p:lg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qO,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function I2(n){const t=BigInt(10),s=BigInt(20),r=BigInt(40),o=BigInt(80),l=lg,d=n*n%l*n%l,m=Gn(d,Gx,l)*d%l,p=Gn(m,IO,l)*n%l,y=Gn(p,VO,l)*p%l,v=Gn(y,t,l)*y%l,x=Gn(v,s,l)*v%l,_=Gn(x,r,l)*x%l,E=Gn(_,o,l)*_%l,A=Gn(E,o,l)*_%l,S=Gn(A,t,l)*y%l;return{pow_p_5_8:Gn(S,Gx,l)*n%l,b2:d}}function H2(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}const Zx=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $O(n,t){const s=lg,r=Et(t*t*t,s),o=Et(r*r*t,s),l=I2(n*o).pow_p_5_8;let u=Et(n*r*l,s);const d=Et(t*u*u,s),m=u,p=Et(u*Zx,s),y=d===n,v=d===Et(-n,s),x=d===Et(-n*Zx,s);return y&&(u=m),(v||x)&&(u=p),xO(u,s)&&(u=Et(-u,s)),{isValid:y||v,value:u}}const V2=Ol(B2.p,{isLE:!0}),PO={...B2,Fp:V2,hash:dO,adjustScalarBytes:H2,uvRatio:$O},cg=LO(PO),_r=(()=>{const n=V2.ORDER;return BO({P:n,type:"x25519",powPminus2:t=>{const{pow_p_5_8:s,b2:r}=I2(t);return Et(Gn(s,HO,n)*r,n)},adjustScalarBytes:H2})})();class q2 extends x2{constructor(t,s){super(),this.finished=!1,this.destroyed=!1,ag(t);const r=wl(s);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,l=new Uint8Array(o);l.set(r.length>o?t.create().update(r).digest():r);for(let u=0;u<l.length;u++)l[u]^=54;this.iHash.update(l),this.oHash=t.create();for(let u=0;u<l.length;u++)l[u]^=106;this.oHash.update(l),zr(l)}update(t){return Zu(this),this.iHash.update(t),this}digestInto(t){Zu(this),Js(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:r,finished:o,destroyed:l,blockLen:u,outputLen:d}=this;return t=t,t.finished=o,t.destroyed=l,t.blockLen=u,t.outputLen=d,t.oHash=s._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ed=(n,t,s)=>new q2(n,t).update(s).digest();Ed.create=(n,t)=>new q2(n,t);function FO(n,t,s){return ag(n),s===void 0&&(s=new Uint8Array(n.outputLen)),Ed(n,wl(s),wl(t))}const vm=Uint8Array.from([0]),Yx=Uint8Array.of();function GO(n,t,s,r=32){ag(n),Gu(r);const o=n.outputLen;if(r>255*o)throw new Error("Length should be <= 255*HashLen");const l=Math.ceil(r/o);s===void 0&&(s=Yx);const u=new Uint8Array(l*o),d=Ed.create(n,t),m=d._cloneInto(),p=new Uint8Array(d.outputLen);for(let y=0;y<l;y++)vm[0]=y+1,m.update(y===0?Yx:p).update(s).update(vm).digestInto(p),u.set(p,o*y),d._cloneInto(m);return d.destroy(),m.destroy(),zr(p,vm),u.slice(0,r)}const ZO=(n,t,s,r,o)=>GO(n,FO(n,t,s),r,o);function YO(n){const t=[];for(let s=0;s<n.length;s++){let r=n.charCodeAt(s);if(r>=55296&&r<=56319&&s+1<n.length){const o=n.charCodeAt(s+1);o>=56320&&o<=57343&&(r=65536+(r-55296<<10)+(o-56320),s++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|r&63):r<65536?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return Uint8Array.from(t)}function KO(n){let t="",s=[];const r=()=>{t+=String.fromCharCode(...s),s=[]};for(let o=0;o<n.length;){const l=n[o];let u;l<128?(u=l,o+=1):l>=240?(u=(l&7)<<18|(n[o+1]&63)<<12|(n[o+2]&63)<<6|n[o+3]&63,o+=4):l>=224?(u=(l&15)<<12|(n[o+1]&63)<<6|n[o+2]&63,o+=3):(u=(l&31)<<6|n[o+1]&63,o+=2),u>65535?(u-=65536,s.push(55296+(u>>10),56320+(u&1023))):s.push(u),s.length>8e3&&r()}return r(),t}const Lr={encode:YO},fl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",XO=new Map([...fl].map((n,t)=>[n,t]));function Kn(n){let t="";for(let s=0;s<n.length;s+=3){const r=n[s]<<16|(n[s+1]??0)<<8|(n[s+2]??0);t+=fl[r>>18&63]+fl[r>>12&63],s+1<n.length&&(t+=fl[r>>6&63]),s+2<n.length&&(t+=fl[r&63])}return t}function ha(n){const t=n.replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),s=new Uint8Array(Math.floor(t.length*3/4));let r=0,o=0,l=0;for(const u of t){const d=XO.get(u);if(d===void 0)throw new Error("invalid base64");o=o<<6|d,r+=6,r>=8&&(r-=8,s[l++]=o>>r&255)}return s.subarray(0,l)}function Kx(...n){const t=new Uint8Array(n.reduce((r,o)=>r+o.length,0));let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}function Xu(n){const t=new Uint8Array(n);return globalThis.crypto.getRandomValues(t),t}function $2(n){return Kn(Sl(ha(n)).subarray(0,16))}function QO(){const n=Xu(32),t=Xu(32),s=Kn(cg.getPublicKey(n));return{id:$2(s),signKey:s,boxKey:Kn(_r.getPublicKey(t)),signSecret:Kn(n),boxSecret:Kn(t)}}function Qu(n){return{id:n.id,signKey:n.signKey,boxKey:n.boxKey}}function P2(n,t){return Kn(cg.sign(Lr.encode(t),ha(n.signSecret)))}function WO(n,t,s){try{return cg.verify(ha(s),Lr.encode(t),ha(n))}catch{return!1}}function JO(n){return`linkshell-gateway-v2:${n}`}function F2(n,t){return Kn(Ed(Sl,ha(n),Lr.encode(`${t.id}.${t.boxKey}`)))}function eR(n){return Kn(Sl(Lr.encode(`linkshell-pair-code:${n}`)))}function tR(){const n=Xu(32);return{secret:n,public:Kn(_r.getPublicKey(n))}}function nR(n){const t=ha(n.local.boxSecret),s=ha(n.remoteBoxKey),r=ha(n.remoteEphemeral),o=_r.getSharedSecret(n.localEphemeral,r),l=_r.getSharedSecret(t,s),u=_r.getSharedSecret(n.localEphemeral,s),d=_r.getSharedSecret(t,r),m=u,p=d,y=_r.getPublicKey(n.localEphemeral),[v,x]=[y,r],[_,E]=[ha(n.local.boxKey),s],A=Kx(Lr.encode("linkshell/v2/channel"),v,x,_,E),S=ZO(Sl,Kx(o,m,p,l),Sl(A),Lr.encode("linkshell/v2/keys"),64),j=S.subarray(0,32),T=S.subarray(32,64);return n.initiator?{send:j,receive:T}:{send:T,receive:j}}function Xx(n){const t=new Uint8Array(24),s=new DataView(t.buffer);return s.setUint32(16,Math.floor(n/2**32)),s.setUint32(20,n>>>0),t}class aR{constructor(t){this.keys=t}sent=0;received=0;seal(t){const s=++this.sent,r=Rx(this.keys.send,Xx(s)).encrypt(Lr.encode(t));return`${s}.${Kn(r)}`}open(t){const s=t.indexOf("."),r=Number(t.slice(0,s));if(!Number.isSafeInteger(r)||r<=this.received)throw new Error("replayed or out-of-order frame");const o=Rx(this.keys.receive,Xx(r)).decrypt(ha(t.slice(s+1)));return this.received=r,KO(o)}}const sR="/v2/connect",_d=I({id:D(),signKey:D(),boxKey:D()}),rR=Qe(["machine","device"]);_d.extend({name:D(),platform:D().optional(),online:Te(),via:Qe(["paired","account"])});_d.extend({name:D(),online:Te(),pairedAt:ue().optional()});Ws("t",[I({t:Ee("auth"),role:rR,identity:_d,signature:D(),name:D().max(120),platform:D().max(40).optional(),token:D().optional()}),I({t:Ee("req"),id:ue().int(),method:D(),params:Ps().optional()}),I({t:Ee("to"),to:D(),d:D().max(40*1024*1024)}),I({t:Ee("ping")})]);const iR=Ws("t",[I({t:Ee("challenge"),nonce:D()}),I({t:Ee("ready"),userId:D().optional(),email:D().optional()}),I({t:Ee("res"),id:ue().int(),result:Ps().optional(),error:I({code:D(),message:D()}).optional()}),I({t:Ee("event"),name:D(),data:Ps()}),I({t:Ee("from"),from:_d,via:Qe(["paired","account"]),d:D()}),I({t:Ee("undeliverable"),to:D(),reason:D()}),I({t:Ee("pong")}),I({t:Ee("error"),code:D(),message:D()})]),Qx="linkshell://pair?";function G2(n){const t=n.trim();if(!t.startsWith(Qx))return;const s=new URLSearchParams(t.slice(Qx.length)),r=s.get("g"),o=s.get("k"),l=s.get("s"),u=s.get("c");if(!(!r||!o||!l||!u||!/^(wss?|https?):\/\//.test(r)))return{gateway:r,signKey:o,secret:l,code:u}}const oR=Ws("k",[I({k:Ee("hello"),ch:D(),eph:D(),sig:D()}),I({k:Ee("welcome"),ch:D(),eph:D(),sig:D()}),I({k:Ee("data"),ch:D(),box:D()}),I({k:Ee("close"),ch:D(),reason:D().optional()}),I({k:Ee("refuse"),ch:D(),code:D(),message:D()})]);function Wx(n,t,s,r,o){return`linkshell-tunnel-v2:${n}:${t}:${s}:${r}:${o}`}function lR(n,t,s){const r=tR();return{hello:{k:"hello",ch:s,eph:r.public,sig:P2(n,Wx("hello",s,n.id,t.id,r.public))},accept(l){if(!WO(t.signKey,Wx("welcome",s,t.id,n.id,l.eph),l.sig))throw new Error("the computer's key doesn't match: refusing to connect");return new aR(nR({initiator:!0,local:n,localEphemeral:r.secret,remoteBoxKey:t.boxKey,remoteEphemeral:l.eph}))}}}class fu extends Error{constructor(t,s){super(s),this.code=t}}const cR=1;class uR{constructor(t){this.options=t}socket;statusValue="offline";attempt=0;timer;nextId=1;pending=new Map;statusListeners=new Set;frameListeners=new Set;undeliverableListeners=new Set;eventListeners=new Map;waiters=new Set;account;lastError;get status(){return this.statusValue}get identity(){return Qu(this.options.identity)}onStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}onFrame(t){return this.frameListeners.add(t),()=>this.frameListeners.delete(t)}onUndeliverable(t){return this.undeliverableListeners.add(t),()=>this.undeliverableListeners.delete(t)}on(t,s){let r=this.eventListeners.get(t);r||this.eventListeners.set(t,r=new Set);const o=s;return r.add(o),()=>r.delete(o)}start(){this.statusValue==="connecting"||this.statusValue==="online"||this.open()}stop(){this.setStatus("stopped"),clearTimeout(this.timer),this.socket?.close(1e3,"stopped"),this.socket=void 0,this.failPending("stopped");for(const t of this.waiters)t()}reconnectNow(){this.statusValue==="stopped"||this.statusValue==="online"||this.statusValue==="connecting"||(clearTimeout(this.timer),this.attempt=0,this.open())}reauthenticate(){if(this.statusValue==="stopped")return;clearTimeout(this.timer),this.attempt=0;const t=this.socket;this.socket=void 0,t?.close(1e3,"signing in again"),this.failPending("connection closed"),this.open()}waitOnline(t){return this.statusValue==="online"?Promise.resolve(!0):this.statusValue==="stopped"?Promise.resolve(!1):new Promise(s=>{const r=()=>{clearTimeout(o),this.waiters.delete(r),s(this.statusValue==="online")},o=setTimeout(r,t);this.waiters.add(r)})}async request(t,s,r){const o=r??this.options.requestTimeoutMs??2e4;if(!await this.waitOnline(o))throw new fu("offline","not connected to the gateway");const l=this.nextId++;return new Promise((u,d)=>{const m=setTimeout(()=>{this.pending.delete(l),d(new fu("timeout",`${t} timed out`))},o);this.pending.set(l,{resolve:u,reject:d,timer:m}),this.sendFrame({t:"req",id:l,method:t,params:s})})}send(t,s){return this.statusValue!=="online"?!1:this.sendFrame({t:"to",to:t,d:JSON.stringify(s)})}sendFrame(t){return!this.socket||this.socket.readyState!==cR?!1:(this.socket.send(JSON.stringify(t)),!0)}setStatus(t,s){if(s&&(this.lastError=s),t==="online"&&(this.lastError=void 0),!(this.statusValue===t&&!s)){this.statusValue=t;for(const r of this.statusListeners)r(t,s);if(t==="online"||t==="stopped")for(const r of this.waiters)r()}}failPending(t){for(const[s,r]of this.pending)clearTimeout(r.timer),r.reject(new fu("offline",t)),this.pending.delete(s)}open(){this.setStatus("connecting");let t;try{t=this.options.createSocket(this.options.url)}catch(r){this.scheduleReconnect({code:"connect_failed",message:r instanceof Error?r.message:String(r)});return}this.socket=t;let s;t.onmessage=r=>{let o;try{const l=iR.safeParse(JSON.parse(String(r.data)));if(!l.success)return;o=l.data}catch{return}switch(o.t){case"challenge":this.authenticate(o.nonce);return;case"ready":this.attempt=0,this.account=o.userId?{userId:o.userId,email:o.email}:void 0,this.setStatus("online");return;case"res":{const l=this.pending.get(o.id);if(!l)return;clearTimeout(l.timer),this.pending.delete(o.id),o.error?l.reject(new fu(o.error.code,o.error.message)):l.resolve(o.result);return}case"event":for(const l of this.eventListeners.get(o.name)??[])l(o.data);return;case"from":{let l;try{const u=oR.safeParse(JSON.parse(o.d));if(!u.success)return;l=u.data}catch{return}for(const u of this.frameListeners)u(o.from,o.via,l);return}case"undeliverable":for(const l of this.undeliverableListeners)l(o.to,o.reason);return;case"error":s={code:o.code,message:o.message};return;case"pong":return}},t.onerror=()=>{},t.onclose=r=>{if(this.socket===t&&(this.socket=void 0,this.failPending("connection closed"),this.statusValue!=="stopped")){if(r.code===4e3){this.setStatus("offline",{code:"replaced",message:"connected elsewhere with this identity"});return}this.scheduleReconnect(s??{code:"disconnected",message:r.reason||"connection lost"})}}}async authenticate(t){let s;try{s=await this.options.token?.()??void 0}catch{s=void 0}this.sendFrame({t:"auth",role:this.options.role,identity:Qu(this.options.identity),signature:P2(this.options.identity,JO(t)),name:this.options.name.slice(0,120),platform:this.options.platform,token:s})}scheduleReconnect(t){this.setStatus("offline",t);const s=this.options.minBackoffMs??500,r=this.options.maxBackoffMs??3e4,o=Math.min(r,s*2**this.attempt)*(.75+Math.random()*.5);this.attempt+=1,this.timer=setTimeout(()=>this.open(),o)}}const dR="linkshell-bulk",Jx=16*1024,Z2=1,Y2=2;function e1(n){const t=n.type==="data"?n.data:new TextEncoder().encode(n.error??""),s=new Uint8Array(5+t.length);return s[0]=n.type==="data"?Z2:Y2,new DataView(s.buffer).setUint32(1,n.stream),s.set(t,5),s}function fR(n){if(n.length<5)return;const t=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(1),s=n.subarray(5);if(n[0]===Z2)return{type:"data",stream:t,data:s};if(n[0]===Y2)return{type:"close",stream:t,error:s.length?new TextDecoder().decode(s):void 0}}const t1=48*1024,hR=I({id:D().regex(/^[a-f0-9]{64}$/),target:D().max(1024),capturedAt:ue().finite().nonnegative(),width:ue().int().positive().max(2048),height:ue().int().positive().max(2048),mimeType:Ee("image/webp")});class mR{held=new Uint8Array(0);push(t){if(this.held.length+t.length>t1+4104)throw new Error("preview buffer too large");const s=new Uint8Array(this.held.length+t.length);s.set(this.held),s.set(t,this.held.length),this.held=s;const r=[];for(;this.held.length>=8;){const o=new DataView(this.held.buffer,this.held.byteOffset),l=o.getUint32(0),u=o.getUint32(4);if(l>4096||u>t1||!l||!u)throw new Error("invalid preview frame");const d=8+l+u;if(this.held.length<d)break;const m=hR.parse(JSON.parse(new TextDecoder().decode(this.held.subarray(8,8+l))));r.push({...m,bytes:this.held.slice(8+l,d)}),this.held=this.held.slice(d)}return r}}const pR=1;function gR(n){const t=globalThis.WebSocket;if(!t)throw new Error("No WebSocket implementation available");return new t(n)}class vR{constructor(t){this.options=t}socket;peer;statusValue="idle";attempt=0;reconnectTimer;heartbeatTimer;subscriptions=new Map;waiters=new Set;statusListeners=new Set;eventListeners=new Set;summaryListeners=new Set;onlineListeners=new Set;restoredListeners=new Set;notificationListeners=new Map;lastError;get status(){return this.statusValue}onStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}onEvent(t){return this.eventListeners.add(t),()=>this.eventListeners.delete(t)}onSummary(t){return this.summaryListeners.add(t),()=>this.summaryListeners.delete(t)}on(t,s){let r=this.notificationListeners.get(t);r||this.notificationListeners.set(t,r=new Set);const o=s;return r.add(o),()=>r.delete(o)}onOnline(t){return this.onlineListeners.add(t),()=>this.onlineListeners.delete(t)}start(){this.statusValue==="connecting"||this.statusValue==="online"||this.open()}stop(){this.setStatus("stopped"),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.peer?.close("stopped"),this.socket?.close(),this.socket=void 0;for(const t of this.waiters)t()}reconnectNow(){this.statusValue!=="stopped"&&this.statusValue!=="online"&&(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.attempt=0,this.open())}async call(t,s,r){const o=r??this.options.requestTimeoutMs??3e4,l=Date.now()+o;if(await this.waitOnline(o),!this.peer||this.statusValue!=="online")throw ca.app("offline","Not connected to the computer",{code:"offline"});return this.peer.request(t,s,Math.max(1e3,l-Date.now()))}onRestored(t){return this.restoredListeners.add(t),()=>this.restoredListeners.delete(t)}subscribe(t,s){return this.subscriptions.set(t,{cursor:s}),this.statusValue!=="online"?Promise.resolve(void 0):this.sendSubscribe(t).then(r=>r?.session)}unsubscribe(t){this.subscriptions.delete(t)&&this.statusValue==="online"&&this.peer?.request("sessions.unsubscribe",{sessionId:t}).catch(()=>{})}setStatus(t,s){if(s!==void 0&&(this.lastError=s),this.statusValue!==t){this.statusValue=t;for(const r of this.statusListeners)r(t,s)}}waitOnline(t){return this.statusValue==="online"||this.statusValue==="stopped"?Promise.resolve():new Promise(s=>{const r=()=>{clearTimeout(o),this.waiters.delete(r),s()},o=setTimeout(r,t);this.waiters.add(r)})}open(){this.setStatus(this.attempt===0?"connecting":"reconnecting");let t;try{t=(this.options.createSocket??gR)(this.options.url)}catch(o){this.scheduleReconnect(o instanceof Error?o.message:String(o));return}this.socket=t;const s=new S5({send:o=>{t.readyState===pR&&t.send(o)},onNotification:(o,l)=>this.onNotification(o,l),requestTimeoutMs:this.options.requestTimeoutMs??3e4});this.peer=s,t.onmessage=o=>{const l=o.data;s.receive(typeof l=="string"?l:String(l))};let r;t.onopen=()=>void this.onOpen(t),t.onerror=o=>{const l=o?.message;typeof l=="string"&&l&&(r=l)},t.onclose=()=>{this.socket===t&&(s.close("connection closed"),this.socket=void 0,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.statusValue!=="stopped"&&this.scheduleReconnect(r??"连接已断开"))}}async onOpen(t){if(this.socket!==t)return;this.attempt=0,this.setStatus("online",""),await Promise.all([...this.subscriptions.keys()].map(r=>this.sendSubscribe(r).then(o=>{if(o?.session)for(const l of this.restoredListeners)l(o.session)})));for(const r of[...this.waiters])r();for(const r of this.onlineListeners)r();const s=this.options.heartbeatMs??25e3;s>0&&(this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.socket!==t||this.statusValue!=="online"||this.peer?.request("machine.info",{},1e4).catch(()=>{this.socket===t&&t.close()})},s))}sendSubscribe(t){const s=this.subscriptions.get(t);return!s||!this.peer?Promise.resolve(void 0):this.peer.request("sessions.subscribe",{sessionId:t,fromSeq:s.cursor(),lazyImages:this.options.lazyImages}).catch(()=>{})}scheduleReconnect(t){if(this.statusValue==="stopped")return;this.setStatus("reconnecting",t);const s=this.options.minBackoffMs??500,r=this.options.maxBackoffMs??15e3,o=Math.min(r,s*2**this.attempt)*(.8+Math.random()*.4);this.attempt+=1,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.open()},o)}onNotification(t,s){if(t==="session.event")for(const r of this.eventListeners)r(s);else if(t==="session.summary"){const r=s.session;if(r)for(const o of this.summaryListeners)o(r)}for(const r of this.notificationListeners.get(t)??[])r(s)}}function K2(n,t){return t.reduce((s,r)=>{const o=s[r.id];return o&&(o.lastSeq??0)>=(r.lastSeq??0)?s:{...s,[r.id]:r}},n)}function yR(n,t){return t.update.sessionUpdate==="ls_task"?K2(n,[{...t.update.task,lastSeq:t.seq}]):n}function up(n,t){const s=n[t.toolCallId];return s&&s.lastSeq>=t.lastSeq?n:{...n,[t.toolCallId]:{...t,startedAt:t.workflow.startedAt??s?.startedAt??t.startedAt,workflow:{...s?.workflow,...t.workflow}}}}function bR(n,t){const s=t.update;if(s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return n;const r=n[s.toolCallId],o=s.detail?.type==="subagent"?s.detail:void 0;return o?.workflow?up(n,{toolCallId:s.toolCallId,task:o.task??r?.task??s.title??"工作流",startedAt:r?.startedAt??t.ts,lastSeq:t.seq,workflow:o.workflow}):r&&!r.workflow.state&&s.status==="failed"?up(n,{...r,lastSeq:t.seq,workflow:{...r.workflow,state:"failed",endedAt:t.ts}}):n}function xR(n,t){return t.reduce((s,r)=>r.workflow?up(s,{toolCallId:r.toolCallId,task:r.task,startedAt:r.startedAt,lastSeq:r.lastSeq??0,workflow:r.workflow}):s,n)}function wR(n,t){const s=n??[];if(!t?.length)return s;const r=new Set(s.map(o=>o.clientMessageId));return[...s,...t.filter(o=>!r.has(o.clientMessageId))]}function dp(n,t){return`${n}
155
155
  ${t}`}function n1(n,t,s){const r=s.update;if(r.toolCallId===t)return{...s,update:{...s.update,parentToolCallId:void 0}};if(r.parentToolCallId&&(r.parentToolCallId===t||Wp(n,r.parentToolCallId)))return s}function SR(){const n=globalThis.crypto;return n?.randomUUID?n.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function ER(n){return n instanceof ca||n instanceof Error?n.message:String(n)}function _R(n,t={}){const s=t.newId??SR;let r=[],o;const l=()=>{if(o&&clearTimeout(o),o=void 0,r.length===0)return;const S=r;r=[],A.setState(j=>{let T=j.views,k=j.subagentViews,C=j.workflows,R=j.tasks;const O=new Map;for(const M of S){const z=R[M.sessionId]??{},L=yR(z,M);L!==z&&(R={...R,[M.sessionId]:L});const q=C[M.sessionId]??{},V=bR(q,M);V!==q&&(C={...C,[M.sessionId]:V});const G=O.get(M.sessionId)??[];G.push(M),O.set(M.sessionId,G);const Z=`${M.sessionId}
156
156
  `;for(const[ee,re]of d)ee.startsWith(Z)&&re.push(M);for(const[ee,re]of Object.entries(k)){if(!ee.startsWith(Z))continue;const U=n1(re,ee.slice(Z.length),M);if(!U)continue;const $=lm(re,[U]);$!==re&&(k={...k,[ee]:$})}}for(const[M,z]of O){const L=T[M];if(!L)continue;const q=lm(L,z);q!==L&&(T={...T,[M]:q})}return T===j.views&&k===j.subagentViews&&C===j.workflows&&R===j.tasks?j:{views:T,subagentViews:k,workflows:C,tasks:R}})},u=S=>{const j=S.id;A.getState().open[j]&&(l(),A.setState(T=>({sessions:{...T.sessions,[j]:S},ready:{...T.ready,[j]:!0}})),A.getState().loadTasks(j).catch(()=>{}))},d=new Map,m=new Map,p=(S,j)=>{m.set(S,j),m.size>50&&m.delete(m.keys().next().value)},y=new Map,v=new Map;let x=0;const _=S=>{y.delete(S),x-=v.get(S)??0,v.delete(S)};function E(S){A.setState(j=>{const T=k=>{if(!(S in k))return k;const C={...k};return delete C[S],C};return{sessions:T(j.sessions),views:T(j.views),open:T(j.open),ready:T(j.ready),loadingEarlier:T(j.loadingEarlier),queueing:T(j.queueing),subagents:T(j.subagents),workflows:T(j.workflows),tasks:T(j.tasks),subagentViews:Object.fromEntries(Object.entries(j.subagentViews).filter(([k])=>!k.startsWith(`${S}
157
- `)))}})}const A=WS()((S,j)=>{const T=(C,R)=>S(O=>{const M=O.views[C]??Yi(C),z=R(M);return z===M?O:{views:{...O.views,[C]:z}}}),k=async(C,R=!1)=>{const O=j().outbox[C];if(!O)return"failed";try{const M=await n.call("sessions.prompt",{sessionId:O.sessionId,clientMessageId:C,content:O.content,whenBusy:R?void 0:"queue"});return M.delivery==="queued"&&p(C,O.content),S(z=>{const L={...z.outbox};return delete L[C],{outbox:L}}),M.delivery}catch{return T(O.sessionId,M=>dx(M,C)),"failed"}};return{status:n.status,sessions:{},sessionsLoaded:!1,projects:[],views:{},open:{},ready:{},loadingEarlier:{},subagents:{},workflows:{},tasks:{},subagentViews:{},outbox:{},queueing:{},connect(){n.start()},disconnect(){n.stop()},async refresh(){try{const[C,R,O]=await Promise.all([n.call("machine.info",{}),n.call("sessions.list",{limit:200}),n.call("projects.list",{limit:100})]);S(M=>{const z={...M.sessions};if(R.sessions.length<200){const L=new Set(R.sessions.map(q=>q.id));for(const[q,V]of Object.entries(z))!V.archived&&!L.has(q)&&delete z[q]}for(const L of R.sessions)z[L.id]=L;return{machine:C,sessions:z,projects:O.projects,sessionsLoaded:!0,sessionsError:void 0}})}catch(C){S({sessionsError:ER(C)})}},openSession(C){j().open[C]||(S(R=>({open:{...R.open,[C]:!0},views:R.views[C]?R.views:{...R.views,[C]:Yi(C)}})),n.subscribe(C,()=>j().views[C]?.lastSeq??0).then(R=>{R&&u(R)}))},closeSession(C){j().open[C]&&(n.unsubscribe(C),S(R=>{const O={...R.open};delete O[C];const M={...R.ready};return delete M[C],{open:O,ready:M}}))},async send(C,R,O){const M=s(),z=j().sessions[C],L=!O?.now&&(z?.state==="running"||z?.state==="waiting"||(z?.queue?.length??0)>0);if(S(V=>({outbox:{...V.outbox,[M]:{sessionId:C,content:R}}})),L){const V={clientMessageId:M,text:R.map(G=>G.type==="text"?G.text:"").join("").trim(),images:R.filter(G=>G.type==="image").length,pending:!0};S(G=>({queueing:{...G.queueing,[C]:[...G.queueing[C]??[],V]}}))}else T(C,V=>iu(V,M,R));const q=await k(M,O?.now);return L?(S(V=>{const G=(V.queueing[C]??[]).filter(ee=>ee.clientMessageId!==M),Z={...V.queueing};return G.length>0?Z[C]=G:delete Z[C],{queueing:Z}}),(q==="started"||q==="steered"||q==="failed")&&(T(C,V=>V.index[`local-${M}`]===void 0?iu(V,M,R):V),q==="failed"&&T(C,V=>dx(V,M))),q):(q==="queued"&&T(C,V=>fx(V,`local-${M}`)),q)},async retry(C){const R=j().outbox[C];R&&(T(R.sessionId,O=>iu(O,C,R.content)),await k(C))},discard(C){const R=j().outbox[C];R&&(T(R.sessionId,O=>fx(O,`local-${C}`)),S(O=>{const M={...O.outbox};return delete M[C],{outbox:M}}))},async respond(C,R,O){await n.call("sessions.permission",{sessionId:C,requestId:R,optionId:O})},async answer(C,R,O){await n.call("sessions.answer",{sessionId:C,requestId:R,answers:O})},async cancel(C){await n.call("sessions.cancel",{sessionId:C})},async takeover(C){await n.call("sessions.takeover",{sessionId:C},6e4)},async release(C){await n.call("sessions.release",{sessionId:C})},async setConfig(C,R,O){await n.call("sessions.setConfig",{sessionId:C,optionId:R,value:O})},async unqueue(C,R){const{removed:O}=await n.call("sessions.unqueue",{sessionId:C,clientMessageId:R});return O&&m.delete(R),O},async takeQueued(C,R){const O=j().sessions[C]?.queue?.find(L=>L.clientMessageId===R),{removed:M}=await n.call("sessions.unqueue",{sessionId:C,clientMessageId:R});if(!M)return;const z=m.get(R)??(O?.text?[{type:"text",text:O.text}]:[]);return m.delete(R),z},async sendQueuedNow(C,R){const O=j().sessions[C]?.queue??[],M=R?O.find(L=>L.clientMessageId===R):O[0],z=M&&(m.get(M.clientMessageId)??(M.text?[{type:"text",text:M.text}]:[]));if(await n.call("sessions.sendQueued",{sessionId:C,clientMessageId:R},3e4),M&&z?.length){const L=M.clientMessageId;j().sessions[C]?.queue?.some(V=>V.clientMessageId===L)||T(C,V=>V.index[`local-${L}`]===void 0?iu(V,L,z,Date.now(),!0):V)}},async reorderQueue(C,R){await n.call("sessions.reorderQueue",{sessionId:C,clientMessageIds:R})},async archive(C,R){const{session:O}=await n.call("sessions.archive",{sessionId:C,archived:R});S(M=>({sessions:{...M.sessions,[O.id]:O}}))},async rename(C,R){const{session:O}=await n.call("sessions.rename",{sessionId:C,title:R});S(M=>({sessions:{...M.sessions,[O.id]:O}}))},async deleteSession(C,R){await n.call("sessions.delete",{sessionId:C,worktree:R},6e4),E(C)},async forkSession(C,R){const{session:O}=await n.call("sessions.fork",{sessionId:C,itemId:R?.itemId,worktree:R?.worktree},9e4);return S(M=>({sessions:{...M.sessions,[O.id]:O}})),j().openSession(O.id),O},async gitInfo(C){return(await n.call("git.info",{path:C})).git},async listWorktrees(){return(await n.call("worktrees.list",{})).worktrees},async removeWorktree(C,R){await n.call("worktrees.remove",{path:C,force:R},6e4)},async loadArchived(){const C=await n.call("sessions.list",{limit:200,includeArchived:!0});S(R=>{const O={...R.sessions};for(const M of C.sessions)O[M.id]=M;return{sessions:O}})},async loadEarlier(C){const R=j().views[C]?.startSeq??0;if(R===0||j().loadingEarlier[C])return!1;S(O=>({loadingEarlier:{...O.loadingEarlier,[C]:!0}}));try{const O=await n.call("sessions.history",{sessionId:C,beforeSeq:R+1,lazyImages:t.lazyImages});return l(),j().views[C]?.startSeq!==R?!1:(T(C,M=>EN(M,O.events,O.startSeq)),!0)}catch{return!1}finally{S(O=>{const M={...O.loadingEarlier};return delete M[C],{loadingEarlier:M}})}},async loadTasks(C){const{tasks:R}=await n.call("sessions.tasks",{sessionId:C});return l(),S(O=>({tasks:{...O.tasks,[C]:K2(O.tasks[C]??{},R)}})),R},loadTaskOutput:(C,R,O)=>n.call("sessions.taskOutput",{sessionId:C,taskId:R,before:O}),async stopTask(C,R){await n.call("sessions.stopTask",{sessionId:C,taskId:R}),await j().loadTasks(C)},async loadSubagents(C){const{subagents:R}=await n.call("sessions.subagents",{sessionId:C});return l(),S(O=>({subagents:{...O.subagents,[C]:R},workflows:{...O.workflows,[C]:xR(O.workflows[C]??{},R)}})),R},async openSubagent(C,R){const O=dp(C,R);if(d.has(O))return!1;const M=[];d.set(O,M);try{const{events:z}=await n.call("sessions.subagent",{sessionId:C,toolCallId:R,lazyImages:t.lazyImages},3e4);l();let L=Yi(C);for(const q of[...z,...M]){const V=n1(L,R,q);V&&(L=lm(L,[V]))}return S(q=>({subagentViews:{...q.subagentViews,[O]:L}})),!0}catch{return!1}finally{d.delete(O)}},closeSubagent(C,R){const O=dp(C,R);O in j().subagentViews&&S(M=>{const z={...M.subagentViews};return delete z[O],{subagentViews:z}})},loadImage(C,R){const O=`${C} ${R}`,M=y.get(O);if(M)return y.delete(O),y.set(O,M),M;const z=n.call("sessions.image",{sessionId:C,uri:R}).then(L=>{const q=`data:${L.mimeType};base64,${L.data}`;v.set(O,q.length),x+=q.length;const V=t.imageCacheChars??24*1024*1024;for(const G of y.keys()){if(x<=V||G===O)break;_(G)}return q},L=>{throw _(O),L});return y.set(O,z),z},async createSession(C){const{session:R}=await n.call("sessions.create",{agent:C.agent,cwd:C.cwd,worktree:C.worktree},6e4);return S(O=>({sessions:{...O.sessions,[R.id]:R}})),j().openSession(R.id),C.prompt&&C.prompt.length>0&&await j().send(R.id,C.prompt),R}}});return n.onStatus((S,j)=>A.setState({status:S,statusDetail:j||void 0})),n.on("session.removed",({sessionId:S})=>E(S)),n.on("session.window",({sessionId:S,startSeq:j})=>{l(),A.setState(T=>{const k=T.views[S];if(!k)return T;const C=xN(k,j);return C===k?T:{views:{...T.views,[S]:C}}})}),n.onSummary(S=>A.setState(j=>({sessions:{...j.sessions,[S.id]:S}}))),n.onEvent(S=>{r.push(S),o??=setTimeout(l,16)}),n.onRestored(S=>u(S)),n.onOnline(()=>{A.getState().refresh()}),A}const a1=0,ym=1,hu=3,s1=15e3;class CR{constructor(t,s,r){this.relay=t,this.machine=r;const o=lR(s,r,this.ch);this.cleanup.push(t.onFrame((l,u,d)=>{if(!(l.id!==r.id||d.ch!==this.ch))switch(d.k){case"welcome":try{this.channel=o.accept(d)}catch(m){this.fail(m instanceof Error?m.message:String(m));return}clearTimeout(this.timer),this.readyState=ym,this.onopen?.({});return;case"data":{if(!this.channel)return;let m;try{m=this.channel.open(d.box)}catch{this.fail("the connection was tampered with");return}this.onmessage?.({data:m});return}case"refuse":this.fail(d.code==="not_paired"?"这台电脑不再信任这台设备,请重新配对":d.message,d.code);return;case"close":this.finish(1e3,d.reason??"closed");return;default:return}}),t.onUndeliverable((l,u)=>{l===r.id&&this.fail(u==="offline"?"电脑不在线":u==="not_allowed"?"没有权限连接这台电脑":u,u)}),t.onStatus(l=>{(l==="offline"||l==="stopped")&&this.fail("与网关的连接断开了")})),t.waitOnline(s1).then(l=>{if(this.readyState===a1){if(!l){this.fail(t.lastError?.message??"连不上网关");return}t.send(r.id,o.hello),this.timer=setTimeout(()=>this.fail("电脑没有响应"),s1)}})}readyState=a1;onopen=null;onclose=null;onerror=null;onmessage=null;ch=Kn(Xu(12));channel;cleanup=[];timer;send(t){this.readyState!==ym||!this.channel||this.relay.send(this.machine.id,{k:"data",ch:this.ch,box:this.channel.seal(t)})}close(){this.readyState!==hu&&(this.readyState===ym&&this.relay.send(this.machine.id,{k:"close",ch:this.ch}),this.finish(1e3,"closed"))}fail(t,s){this.readyState!==hu&&(this.onerror?.({message:t,code:s}),this.finish(4e3,t))}finish(t,s){if(this.readyState!==hu){this.readyState=hu,clearTimeout(this.timer);for(const r of this.cleanup.splice(0))r();this.onclose?.({code:t,reason:s})}}}async function AR(n,t,s){const{machine:r}=await n.request("pair.claim",{machineId:$2(s.signKey),proof:F2(s.secret,Qu(t))},4e4);if(r.signKey!==s.signKey)throw new Error("网关返回的电脑和二维码不一致,已拒绝");return r}async function jR(n,t,s){const r=s.replace(/\D/g,""),{machine:o}=await n.request("pair.claim",{code:r,proof:F2(eR(r),Qu(t))},4e4);return o}const r1={encode(n){let t="";for(let s=0;s<n.length;s+=32768)t+=String.fromCharCode(...n.subarray(s,s+32768));return btoa(t)},decode(n){const t=atob(n),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}};class TR{constructor(t,s){this.link=t,this.options=s,t.on("proxy.data",({streamId:r,data:o})=>this.relayed.get(r)?.data(r1.decode(o))),t.on("proxy.closed",({streamId:r,error:o})=>{const l=this.relayed.get(r);this.relayed.delete(r),l?.closed(o)}),t.onStatus(r=>{if(r==="online")return;this.dropRelayed("连接已断开");const o=this.connection;this.dropDirect(),o?.close()}),t.onOnline(()=>this.connect()),t.status==="online"&&this.connect()}pathValue="relay";connection;attempt=0;retryTimer;stopped=!1;pathListeners=new Set;relayed=new Map;directed=new Map;early=new Map;get path(){return this.pathValue}onPath(t){return this.pathListeners.add(t),()=>this.pathListeners.delete(t)}connect(){if(this.stopped||!this.options.connector||this.connection||this.link.status!=="online")return;const t=this.options.iceServers();if(!t)return;this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;const s=this.options.connector(t);this.connection=s,this.setPath("connecting");let r=!1;const o=setTimeout(()=>!r&&this.lose(s),this.options.connectTimeoutMs??12e3);s.onMessage(l=>{const u=fR(l);u&&this.receive(u)}),s.onState(l=>{this.connection===s&&(l==="open"?(r=!0,clearTimeout(o),this.attempt=0,this.setPath("direct")):(clearTimeout(o),this.lose(s)))}),s.offer().then(l=>this.link.call("direct.offer",{sdp:l},2e4)).then(l=>s.accept(l.sdp)).catch(()=>{clearTimeout(o),this.lose(s)})}async open(t,s){const r=this.pathValue==="direct"?this.connection:void 0,o=await this.link.call("proxy.open",{port:t,direct:r?!0:void 0}),{streamId:l}=o;if(o.channel!==void 0&&r&&this.connection===r){const d=o.channel;this.directed.set(d,s);for(const p of this.early.get(d)??[])this.receive(p);this.early.delete(d);let m=!1;return{direct:!0,write:p=>{if(!(m||this.connection!==r))for(let y=0;y<p.length;y+=Jx)r.send(e1({type:"data",stream:d,data:p.subarray(y,y+Jx)}))},close:()=>{m||(m=!0,this.directed.delete(d)&&this.connection===r&&r.send(e1({type:"close",stream:d})))}}}if(o.channel!==void 0)throw new Error("直连中断了");this.relayed.set(l,s);let u=!1;return{direct:!1,write:d=>{u||this.link.call("proxy.write",{streamId:l,data:r1.encode(d)}).catch(()=>{this.relayed.delete(l)&&s.closed("发送失败")})},close:()=>{u||(u=!0,this.relayed.delete(l)&&this.link.call("proxy.close",{streamId:l}).catch(()=>{}))}}}start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.dropRelayed();const t=this.connection;this.dropDirect(),t?.close()}receive(t){const s=this.directed.get(t.stream);if(!s){const r=this.early.get(t.stream)??[];r.length<64&&this.early.size<32&&this.early.set(t.stream,[...r,t]);return}t.type==="data"?s.data(t.data):(this.directed.delete(t.stream),s.closed(t.error))}setPath(t){if(this.pathValue!==t){this.pathValue=t;for(const s of this.pathListeners)s(t)}}lose(t){if(this.connection!==t||(this.dropDirect(),t.close(),this.stopped||this.link.status!=="online"))return;const s=this.options.retryMs??[5e3,2e4,6e4],r=s[Math.min(this.attempt,s.length-1)];this.attempt+=1,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.connect()},r)}dropDirect(){this.connection=void 0;const t=[...this.directed.values()];this.directed.clear(),this.early.clear(),this.setPath("relay");for(const s of t)s.closed("直连中断了")}dropRelayed(t){const s=[...this.relayed.values()];this.relayed.clear();for(const r of s)r.closed(t)}}class kR{constructor(t,s,r,o,l){this.link=t,this.streams=s,this.sessionId=r,this.onFrame=o,this.last=l,this.remove=[t.onStatus(u=>{u==="online"?this.open():this.drop()}),s.onPath(u=>{u==="direct"&&!this.stream?.direct&&this.open()})],t.status==="online"&&this.open()}stream;generation=0;stopped=!1;retry;remove;last;drop(){this.generation++,this.retry&&clearTimeout(this.retry),this.retry=void 0;const t=this.stream;this.stream=void 0,t?.close()}open(){if(this.stopped||this.link.status!=="online")return;this.drop();const t=this.generation,s=new mR,r=()=>{this.stopped||t!==this.generation||(this.drop(),this.retry=setTimeout(()=>this.open(),3e3))};this.link.call("sessions.preview",{sessionId:this.sessionId,direct:this.streams.path==="direct"}).then(async o=>{if(this.stopped||t!==this.generation)return;const l=await this.streams.open(o.port,{data:u=>{if(!(this.stopped||t!==this.generation))try{for(const d of s.push(u))this.last=d.id,this.onFrame(d),this.stream?.write(new TextEncoder().encode(`ack
157
+ `)))}})}const A=WS()((S,j)=>{const T=(C,R)=>S(O=>{const M=O.views[C]??Yi(C),z=R(M);return z===M?O:{views:{...O.views,[C]:z}}}),k=async(C,R=!1)=>{const O=j().outbox[C];if(!O)return"failed";try{const M=await n.call("sessions.prompt",{sessionId:O.sessionId,clientMessageId:C,content:O.content,whenBusy:R?void 0:"queue"});return M.delivery==="queued"&&p(C,O.content),S(z=>{const L={...z.outbox};return delete L[C],{outbox:L}}),M.delivery}catch{return T(O.sessionId,M=>dx(M,C)),"failed"}};return{status:n.status,sessions:{},sessionsLoaded:!1,projects:[],views:{},open:{},ready:{},loadingEarlier:{},subagents:{},workflows:{},tasks:{},subagentViews:{},outbox:{},queueing:{},connect(){n.start()},disconnect(){n.stop()},async refresh(){try{const[C,R,O]=await Promise.all([n.call("machine.info",{}),n.call("sessions.list",{limit:200}),n.call("projects.list",{limit:100})]);S(M=>{const z={...M.sessions};if(R.sessions.length<200){const L=new Set(R.sessions.map(q=>q.id));for(const[q,V]of Object.entries(z))!V.archived&&!L.has(q)&&delete z[q]}for(const L of R.sessions)z[L.id]=L;return{machine:C,sessions:z,projects:O.projects,sessionsLoaded:!0,sessionsError:void 0}})}catch(C){S({sessionsError:ER(C)})}},openSession(C){j().open[C]||(S(R=>({open:{...R.open,[C]:!0},views:R.views[C]?R.views:{...R.views,[C]:Yi(C)}})),n.subscribe(C,()=>j().views[C]?.lastSeq??0).then(R=>{R&&u(R)}))},closeSession(C){j().open[C]&&(n.unsubscribe(C),S(R=>{const O={...R.open};delete O[C];const M={...R.ready};return delete M[C],{open:O,ready:M}}))},async send(C,R,O){const M=s(),z=j().sessions[C],L=!O?.now&&(z?.state==="running"||z?.state==="waiting"||(z?.queue?.length??0)>0);if(S(V=>({outbox:{...V.outbox,[M]:{sessionId:C,content:R}}})),L){const V={clientMessageId:M,text:R.map(G=>G.type==="text"?G.text:"").join("").trim(),images:R.filter(G=>G.type==="image").length,pending:!0};S(G=>({queueing:{...G.queueing,[C]:[...G.queueing[C]??[],V]}}))}else T(C,V=>iu(V,M,R));const q=await k(M,O?.now);return L?(S(V=>{const G=(V.queueing[C]??[]).filter(ee=>ee.clientMessageId!==M),Z={...V.queueing};return G.length>0?Z[C]=G:delete Z[C],{queueing:Z}}),(q==="started"||q==="steered"||q==="failed")&&(T(C,V=>V.index[`local-${M}`]===void 0?iu(V,M,R):V),q==="failed"&&T(C,V=>dx(V,M))),q):(q==="queued"&&T(C,V=>fx(V,`local-${M}`)),q)},async retry(C){const R=j().outbox[C];R&&(T(R.sessionId,O=>iu(O,C,R.content)),await k(C))},discard(C){const R=j().outbox[C];R&&(T(R.sessionId,O=>fx(O,`local-${C}`)),S(O=>{const M={...O.outbox};return delete M[C],{outbox:M}}))},async respond(C,R,O){await n.call("sessions.permission",{sessionId:C,requestId:R,optionId:O})},async answer(C,R,O){await n.call("sessions.answer",{sessionId:C,requestId:R,answers:O})},async cancel(C){await n.call("sessions.cancel",{sessionId:C})},async takeover(C){await n.call("sessions.takeover",{sessionId:C},6e4)},async release(C){await n.call("sessions.release",{sessionId:C})},async setConfig(C,R,O){await n.call("sessions.setConfig",{sessionId:C,optionId:R,value:O})},async unqueue(C,R){const{removed:O}=await n.call("sessions.unqueue",{sessionId:C,clientMessageId:R});return O&&m.delete(R),O},async takeQueued(C,R){const O=j().sessions[C]?.queue?.find(L=>L.clientMessageId===R),{removed:M}=await n.call("sessions.unqueue",{sessionId:C,clientMessageId:R});if(!M)return;const z=m.get(R)??(O?.text?[{type:"text",text:O.text}]:[]);return m.delete(R),z},async sendQueuedNow(C,R){const O=j().sessions[C]?.queue??[],M=R?O.find(L=>L.clientMessageId===R):O[0],z=M&&(m.get(M.clientMessageId)??(M.text?[{type:"text",text:M.text}]:[]));if(await n.call("sessions.sendQueued",{sessionId:C,clientMessageId:R},3e4),M&&z?.length){const L=M.clientMessageId;j().sessions[C]?.queue?.some(V=>V.clientMessageId===L)||T(C,V=>V.index[`local-${L}`]===void 0?iu(V,L,z,Date.now(),!0):V)}},async reorderQueue(C,R){await n.call("sessions.reorderQueue",{sessionId:C,clientMessageIds:R})},async archive(C,R){const{session:O}=await n.call("sessions.archive",{sessionId:C,archived:R});S(M=>({sessions:{...M.sessions,[O.id]:O}}))},async rename(C,R){const{session:O}=await n.call("sessions.rename",{sessionId:C,title:R});S(M=>({sessions:{...M.sessions,[O.id]:O}}))},async deleteSession(C,R){await n.call("sessions.delete",{sessionId:C,worktree:R},6e4),E(C)},async forkSession(C,R){const{session:O}=await n.call("sessions.fork",{sessionId:C,itemId:R?.itemId,worktree:R?.worktree},9e4);return S(M=>({sessions:{...M.sessions,[O.id]:O}})),j().openSession(O.id),O},async gitInfo(C){return(await n.call("git.info",{path:C})).git},async listWorktrees(){return(await n.call("worktrees.list",{})).worktrees},async removeWorktree(C,R){await n.call("worktrees.remove",{path:C,force:R},6e4)},async loadArchived(){const C=await n.call("sessions.list",{limit:200,includeArchived:!0});S(R=>{const O={...R.sessions};for(const M of C.sessions)O[M.id]=M;return{sessions:O}})},async loadEarlier(C){const R=j().views[C]?.startSeq??0;if(R===0||j().loadingEarlier[C])return!1;S(O=>({loadingEarlier:{...O.loadingEarlier,[C]:!0}}));try{const O=await n.call("sessions.history",{sessionId:C,beforeSeq:R+1,lazyImages:t.lazyImages});return l(),j().views[C]?.startSeq!==R?!1:(T(C,M=>EN(M,O.events,O.startSeq)),!0)}catch{return!1}finally{S(O=>{const M={...O.loadingEarlier};return delete M[C],{loadingEarlier:M}})}},async loadTasks(C){const{tasks:R}=await n.call("sessions.tasks",{sessionId:C});return l(),S(O=>({tasks:{...O.tasks,[C]:K2(O.tasks[C]??{},R)}})),R},loadTaskOutput:(C,R,O)=>n.call("sessions.taskOutput",{sessionId:C,taskId:R,before:O}),async stopTask(C,R){await n.call("sessions.stopTask",{sessionId:C,taskId:R}),await j().loadTasks(C)},async loadSubagents(C){const{subagents:R}=await n.call("sessions.subagents",{sessionId:C});return l(),S(O=>({subagents:{...O.subagents,[C]:R},workflows:{...O.workflows,[C]:xR(O.workflows[C]??{},R)}})),R},async openSubagent(C,R){const O=dp(C,R);if(d.has(O))return!1;const M=[];d.set(O,M);try{const{events:z}=await n.call("sessions.subagent",{sessionId:C,toolCallId:R,lazyImages:t.lazyImages},3e4);l();let L=Yi(C);for(const q of[...z,...M]){const V=n1(L,R,q);V&&(L=lm(L,[V]))}return S(q=>({subagentViews:{...q.subagentViews,[O]:L}})),!0}catch{return!1}finally{d.delete(O)}},closeSubagent(C,R){const O=dp(C,R);O in j().subagentViews&&S(M=>{const z={...M.subagentViews};return delete z[O],{subagentViews:z}})},loadImage(C,R){const O=`${C} ${R}`,M=y.get(O);if(M)return y.delete(O),y.set(O,M),M;const z=n.call("sessions.image",{sessionId:C,uri:R}).then(L=>{const q=`data:${L.mimeType};base64,${L.data}`;v.set(O,q.length),x+=q.length;const V=t.imageCacheChars??24*1024*1024;for(const G of y.keys()){if(x<=V||G===O)break;_(G)}return q},L=>{throw _(O),L});return y.set(O,z),z},async createSession(C){const{session:R}=await n.call("sessions.create",{agent:C.agent,cwd:C.cwd,worktree:C.worktree},6e4);return S(O=>({sessions:{...O.sessions,[R.id]:R}})),j().openSession(R.id),C.prompt&&C.prompt.length>0&&await j().send(R.id,C.prompt),R}}});return n.onStatus((S,j)=>A.setState({status:S,statusDetail:j||void 0})),n.on("session.removed",({sessionId:S})=>E(S)),n.on("session.window",({sessionId:S,startSeq:j})=>{l(),A.setState(T=>{const k=T.views[S];if(!k)return T;const C=xN(k,j);return C===k?T:{views:{...T.views,[S]:C}}})}),n.onSummary(S=>A.setState(j=>({sessions:{...j.sessions,[S.id]:S}}))),n.onEvent(S=>{r.push(S),o??=setTimeout(l,16)}),n.onRestored(S=>u(S)),n.onOnline(()=>{A.getState().refresh()}),A}const a1=0,ym=1,hu=3,s1=15e3;class CR{constructor(t,s,r){this.relay=t,this.machine=r;const o=lR(s,r,this.ch);this.cleanup.push(t.onFrame((l,u,d)=>{if(!(l.id!==r.id||d.ch!==this.ch))switch(d.k){case"welcome":try{this.channel=o.accept(d)}catch(m){this.fail(m instanceof Error?m.message:String(m));return}clearTimeout(this.timer),this.readyState=ym,this.onopen?.({});return;case"data":{if(!this.channel)return;let m;try{m=this.channel.open(d.box)}catch{this.fail("the connection was tampered with");return}this.onmessage?.({data:m});return}case"refuse":this.fail(d.code==="not_paired"?"这台电脑不再信任这台设备,请重新配对":d.message,d.code);return;case"close":this.finish(1e3,d.reason??"closed");return;default:return}}),t.onUndeliverable((l,u)=>{l===r.id&&this.fail(u==="offline"?"电脑不在线":u==="not_allowed"?"没有权限连接这台电脑":u,u)}),t.onStatus(l=>{(l==="offline"||l==="stopped")&&this.fail("与网关的连接断开了")})),t.waitOnline(s1).then(l=>{if(this.readyState===a1){if(!l){this.fail(t.lastError?.message??"连不上网关");return}t.send(r.id,o.hello),this.timer=setTimeout(()=>this.fail("电脑没有响应"),s1)}})}readyState=a1;onopen=null;onclose=null;onerror=null;onmessage=null;ch=Kn(Xu(12));channel;cleanup=[];timer;send(t){this.readyState!==ym||!this.channel||this.relay.send(this.machine.id,{k:"data",ch:this.ch,box:this.channel.seal(t)})}close(){this.readyState!==hu&&(this.readyState===ym&&this.relay.send(this.machine.id,{k:"close",ch:this.ch}),this.finish(1e3,"closed"))}fail(t,s){this.readyState!==hu&&(this.onerror?.({message:t,code:s}),this.finish(4e3,t))}finish(t,s){if(this.readyState!==hu){this.readyState=hu,clearTimeout(this.timer);for(const r of this.cleanup.splice(0))r();this.onclose?.({code:t,reason:s})}}}async function AR(n,t,s){const{machine:r}=await n.request("pair.claim",{machineId:$2(s.signKey),proof:F2(s.secret,Qu(t))},4e4);if(r.signKey!==s.signKey)throw new Error("网关返回的电脑和二维码不一致,已拒绝");return r}async function jR(n,t,s){const r=s.replace(/\D/g,""),{machine:o}=await n.request("pair.claim",{code:r,proof:F2(eR(r),Qu(t))},4e4);return o}const r1={encode(n){let t="";for(let s=0;s<n.length;s+=32768)t+=String.fromCharCode(...n.subarray(s,s+32768));return btoa(t)},decode(n){const t=atob(n),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}};class TR{constructor(t,s){this.link=t,this.options=s,t.on("proxy.data",({streamId:r,data:o})=>this.relayed.get(r)?.data(r1.decode(o))),t.on("proxy.closed",({streamId:r,error:o})=>{const l=this.relayed.get(r);this.relayed.delete(r),l?.closed(o)}),t.onStatus(r=>{if(r==="online")return;this.dropRelayed("连接已断开");const o=this.connection;this.dropDirect(),o?.close()}),t.onOnline(()=>this.connect()),t.status==="online"&&this.connect()}pathValue="relay";connection;attempt=0;retryTimer;stopped=!1;pathListeners=new Set;relayed=new Map;directed=new Map;early=new Map;get path(){return this.pathValue}onPath(t){return this.pathListeners.add(t),()=>this.pathListeners.delete(t)}connect(){if(this.stopped||!this.options.connector||this.connection||this.link.status!=="online")return;const t=this.options.iceServers();if(!t)return;this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;const s=this.options.connector(t);this.connection=s,this.setPath("connecting");let r=!1;const o=setTimeout(()=>!r&&this.lose(s),this.options.connectTimeoutMs??12e3);s.onMessage(l=>{const u=fR(l);u&&this.receive(u)}),s.onState(l=>{this.connection===s&&(l==="open"?(r=!0,clearTimeout(o),this.attempt=0,this.setPath("direct")):(clearTimeout(o),this.lose(s)))}),s.offer().then(l=>this.link.call("direct.offer",{sdp:l},2e4)).then(l=>s.accept(l.sdp)).catch(()=>{clearTimeout(o),this.lose(s)})}async open(t,s,r={}){const o=r.direct!==!1&&this.pathValue==="direct"?this.connection:void 0,l=await this.link.call("proxy.open",{port:t,direct:o?!0:void 0}),{streamId:u}=l;if(l.channel!==void 0&&o&&this.connection===o){const m=l.channel;this.directed.set(m,s);for(const y of this.early.get(m)??[])this.receive(y);this.early.delete(m);let p=!1;return{direct:!0,write:y=>{if(!(p||this.connection!==o))for(let v=0;v<y.length;v+=Jx)o.send(e1({type:"data",stream:m,data:y.subarray(v,v+Jx)}))},close:()=>{p||(p=!0,this.directed.delete(m)&&this.connection===o&&o.send(e1({type:"close",stream:m})))}}}if(l.channel!==void 0)throw new Error("直连中断了");this.relayed.set(u,s);let d=!1;return{direct:!1,write:m=>{d||this.link.call("proxy.write",{streamId:u,data:r1.encode(m)}).catch(()=>{this.relayed.delete(u)&&s.closed("发送失败")})},close:()=>{d||(d=!0,this.relayed.delete(u)&&this.link.call("proxy.close",{streamId:u}).catch(()=>{}))}}}start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0,this.dropRelayed();const t=this.connection;this.dropDirect(),t?.close()}receive(t){const s=this.directed.get(t.stream);if(!s){const r=this.early.get(t.stream)??[];r.length<64&&this.early.size<32&&this.early.set(t.stream,[...r,t]);return}t.type==="data"?s.data(t.data):(this.directed.delete(t.stream),s.closed(t.error))}setPath(t){if(this.pathValue!==t){this.pathValue=t;for(const s of this.pathListeners)s(t)}}lose(t){if(this.connection!==t||(this.dropDirect(),t.close(),this.stopped||this.link.status!=="online"))return;const s=this.options.retryMs??[5e3,2e4,6e4],r=s[Math.min(this.attempt,s.length-1)];this.attempt+=1,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.connect()},r)}dropDirect(){this.connection=void 0;const t=[...this.directed.values()];this.directed.clear(),this.early.clear(),this.setPath("relay");for(const s of t)s.closed("直连中断了")}dropRelayed(t){const s=[...this.relayed.values()];this.relayed.clear();for(const r of s)r.closed(t)}}class kR{constructor(t,s,r,o,l){this.link=t,this.streams=s,this.sessionId=r,this.onFrame=o,this.last=l,this.remove=[t.onStatus(u=>{u==="online"?this.open():this.drop()}),s.onPath(u=>{u==="direct"&&!this.stream?.direct&&this.open()})],t.status==="online"&&this.open()}stream;generation=0;stopped=!1;retry;remove;last;drop(){this.generation++,this.retry&&clearTimeout(this.retry),this.retry=void 0;const t=this.stream;this.stream=void 0,t?.close()}open(){if(this.stopped||this.link.status!=="online")return;this.drop();const t=this.generation,s=new mR,r=()=>{this.stopped||t!==this.generation||(this.drop(),this.retry=setTimeout(()=>this.open(),3e3))};this.link.call("sessions.preview",{sessionId:this.sessionId,direct:this.streams.path==="direct"}).then(async o=>{if(this.stopped||t!==this.generation)return;const l=await this.streams.open(o.port,{data:u=>{if(!(this.stopped||t!==this.generation))try{for(const d of s.push(u))this.last=d.id,this.onFrame(d),this.stream?.write(new TextEncoder().encode(`ack
158
158
  `))}catch{r()}},closed:r});if(this.stopped||t!==this.generation){l.close();return}this.stream=l,l.write(new TextEncoder().encode(JSON.stringify({token:o.token,after:this.last,direct:l.direct})+`
159
- `))}).catch(o=>{o?.code!==-32601&&r()})}close(){this.stopped=!0,this.drop();for(const t of this.remove)t()}}const NR="https://mkbeusztkzffnzjdwmqk.supabase.co",OR="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1rYmV1c3p0a3pmZm56amR3bXFrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjU5Nzc0NzgsImV4cCI6MjA4MTU1MzQ3OH0.2wlT6q6687Z5rpEYsdp01IQpNNl_XWv0IAfBgwPyDP0";let RR;function hl(){return RR??=mA(window.__LINKSHELL_CONFIG__?.account?.url??NR,window.__LINKSHELL_CONFIG__?.account?.anonKey??OR,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"linkshell.web.account.v2"}})}async function DR(){const n=hl().auth,{data:t,error:s}=await n.getSession();if(s)throw s;if(!t.session)return;if((t.session.expires_at??0)*1e3>Date.now()+12e4)return t.session.access_token;const r=await n.refreshSession();if(r.error)throw r.error;if(!r.data.session)throw new Error("登录已失效,请重新登录");return r.data.session.access_token}function Fs(n,t){try{return JSON.parse(localStorage.getItem(`linkshell.web.${n}`)??"null")??t}catch{return t}}function ua(n,t){localStorage.setItem(`linkshell.web.${n}`,JSON.stringify(t))}let MR;function zR(){return MR??=new Promise((n,t)=>{const s=indexedDB.open("linkshell.web.identity",1);s.onupgradeneeded=()=>s.result.createObjectStore("keys"),s.onerror=()=>t(new Error("无法保存浏览器设备身份,请允许此网站使用本地存储")),s.onsuccess=()=>{const r=s.result,o=r.transaction("keys","readwrite"),l=o.objectStore("keys"),u=l.get("device");let d;u.onsuccess=()=>{d=u.result??QO(),u.result||l.put(d,"device")},o.oncomplete=()=>{r.close(),n(d)},o.onerror=()=>{r.close(),t(new Error("设备身份保存失败"))}}})}const LR=n=>{const t=new RTCPeerConnection({iceServers:n.map(r=>({urls:r}))}),s=t.createDataChannel(dR,{ordered:!0});return s.binaryType="arraybuffer",{async offer(){if(await t.setLocalDescription(await t.createOffer()),t.iceGatheringState!=="complete"&&await new Promise(r=>{const o=()=>{clearTimeout(u),t.removeEventListener("icegatheringstatechange",l),r()},l=()=>{t.iceGatheringState==="complete"&&o()},u=setTimeout(o,2e3);t.addEventListener("icegatheringstatechange",l)}),!t.localDescription?.sdp)throw new Error("无法建立直连通道");return t.localDescription.sdp},accept:r=>t.setRemoteDescription({type:"answer",sdp:r}),send(r){s.send(r)},onState(r){s.addEventListener("open",()=>r("open")),s.addEventListener("close",()=>r("closed")),t.addEventListener("connectionstatechange",()=>{["failed","closed"].includes(t.connectionState)&&r("closed")})},onMessage(r){s.addEventListener("message",o=>{o.data instanceof ArrayBuffer&&r(new Uint8Array(o.data))})},close(){t.close()}}},UR=Fs("source",qs),X2=qs==="self-hosted"?"self-hosted":UR,BR=X2==="official"?Er:Fs("gateway",sN);class IR{state=WS(()=>({source:X2,gateway:BR,computers:[],relayStatus:{},locked:!1,ready:!1}));identity;relays=new Map;paired=Fs("paired",[]);selected=Fs("selected","");releaseLock;starting;authUser;authSubscribed=!1;generation=0;channel=typeof BroadcastChannel<"u"?new BroadcastChannel("linkshell.web.owner"):void 0;constructor(){this.channel?.addEventListener("message",t=>{t.data==="yield"&&(this.stop(),this.state.setState({locked:!0}))}),window.addEventListener("pagehide",()=>this.stop()),window.addEventListener("pageshow",()=>{this.start()}),window.addEventListener("online",()=>this.reconnect()),document.addEventListener("visibilitychange",()=>{document.hidden||this.reconnect()})}report(t){this.state.setState({error:t instanceof Error?t.message:String(t)})}async start(){return this.releaseLock||this.starting?this.starting:(this.starting=this.acquire(!1).finally(()=>{this.starting=void 0}),this.starting)}async claim(){this.channel?.postMessage("yield"),await this.acquire(!0)}async acquire(t){if(!navigator.locks){this.report(new Error("此浏览器不支持设备连接锁,请使用最新版 Chrome、Edge、Safari 或 Firefox"));return}await new Promise((s,r)=>{navigator.locks.request("linkshell.web.connection",{ifAvailable:!t},async o=>{if(!o){this.state.setState({locked:!0,ready:!0}),s();return}await new Promise(l=>{this.releaseLock=l,this.state.setState({locked:!1}),this.boot().then(s,r)})}).catch(r)}).catch(s=>this.report(s))}async boot(){const t=++this.generation;if(this.identity=await zR(),t===this.generation){this.state.setState({computers:this.paired.map(s=>({...s,machine:{...s.machine,online:!1}})),ready:!0});for(const s of this.paired)this.relay(s.gateway);this.state.getState().source==="official"?await this.connectAccount():this.state.getState().gateway&&this.relay(om(this.state.getState().gateway))}}async connectAccount(){if(qs==="self-hosted")throw new Error("私有部署使用设备配对");const t=hl().auth,{data:s,error:r}=await t.getSession();if(r)throw r;this.authUser=s.session?.user.id,this.state.setState({account:s.session?.user.email,source:"official",gateway:Er}),this.authSubscribed||(this.authSubscribed=!0,t.onAuthStateChange((o,l)=>{const u=this.authUser!==l?.user.id;this.authUser=l?.user.id,this.state.setState({account:l?.user.email}),u&&this.releaseLock&&setTimeout(()=>{this.relays.get(Er)?.reauthenticate(),l&&this.relay(Er)},0)})),ua("source","official"),s.session&&this.relay(Er).reauthenticate()}relay(t){if(!this.identity||!this.releaseLock)throw new Error("请先在本标签页启用连接");const s=om(t),r=this.relays.get(s);if(r)return r;const o=s===Er&&qs!=="self-hosted",l=new uR({url:s+sR,identity:this.identity,role:"device",name:"LinkShell Web",platform:"web",token:o?async()=>{try{return await DR()}catch(u){throw this.report(u),u}}:void 0,createSocket:u=>{const d=new WebSocket(u),m=d.send.bind(d);return d.send=p=>{if(typeof p=="string"&&o&&this.authUser){const y=JSON.parse(p);if(y.t==="auth"&&!y.token){d.close(4001,"账号续期失败,正在重试");return}}m(p)},d}});return this.relays.set(s,l),l.onStatus((u,d)=>{this.state.setState(m=>({relayStatus:{...m.relayStatus,[s]:u},...d?{error:d.message}:{}})),u==="online"&&this.refresh(s).catch(m=>this.report(m))}),l.on("machines.changed",()=>{this.refresh(s).catch(u=>this.report(u))}),l.on("presence",({id:u,online:d})=>this.state.setState(m=>({computers:m.computers.map(p=>p.gateway===s&&p.machine.id===u?{...p,machine:{...p.machine,online:d}}:p)}))),l.start(),l}async refresh(t){const s=this.relays.get(t);if(!s)return;const{machines:r}=await s.request("machines.list",{}),o=r.map(u=>({gateway:t,machine:u,key:`${t}#${u.id}`}));this.state.setState(u=>({computers:[...u.computers.filter(d=>d.gateway!==t),...o]}));const l=this.state.getState();if(!l.connection){const u=l.computers.find(d=>d.key===this.selected)??l.computers.find(d=>d.machine.online);u&&this.select(u)}}select(t){if(!this.identity)throw new Error("设备身份尚未就绪");this.disconnect();const s=this.identity,r=this.relay(t.gateway),o=new vR({url:t.key,createSocket:()=>new CR(r,s,t.machine),lazyImages:!0}),l=_R(o,{lazyImages:!0}),u=new TR(o,{connector:LR,iceServers:()=>l.getState().machine?.direct?.iceServers});l.subscribe((d,m)=>{d.machine!==m.machine&&u.connect()}),this.state.setState({connection:{computer:t,link:o,store:l,streams:u},error:void 0}),this.selected=t.key,ua("selected",t.key),l.getState().connect(),u.start()}async pair(t,s){const r=s.trim().startsWith("linkshell:")?G2(s.trim()):void 0;if(s.trim().startsWith("linkshell:")&&!r)throw new Error("配对链接格式不正确");if(!r&&!/^\d{6}$/.test(s.trim()))throw new Error("请输入 6 位配对码");const o=om((r?.gateway??t).replace(/^http/,"ws")),l=this.relay(o),u=r?await AR(l,this.identity,r):await jR(l,this.identity,s.trim()),d={key:`${o}#${u.id}`,gateway:o,machine:u};this.paired=[...this.paired.filter(m=>m.key!==d.key),d],ua("paired",this.paired),ua("source","self-hosted"),ua("gateway",o),this.state.setState({source:"self-hosted",gateway:o}),await this.refresh(o),this.select(d)}async forget(t){await this.relay(t.gateway).request("machines.forget",{machineId:t.machine.id}),this.paired=this.paired.filter(s=>s.key!==t.key),ua("paired",this.paired),this.state.getState().connection?.computer.key===t.key&&this.disconnect(),this.state.setState(s=>({computers:s.computers.filter(r=>r.key!==t.key)}))}reconnect(){if(this.releaseLock){for(const t of this.relays.values())t.reconnectNow();this.state.getState().connection?.link.reconnectNow()}}disconnect(){const t=this.state.getState().connection;t?.streams.stop(),t?.store.getState().disconnect(),this.state.setState({connection:void 0})}stop(){this.generation++,this.disconnect();for(const t of this.relays.values())t.stop();this.relays.clear(),this.releaseLock?.(),this.releaseLock=void 0}}const Qt=new IR,HR={codex:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.503 0H4.496A4.496 4.496 0 000 4.496v15.007A4.496 4.496 0 004.496 24h15.007A4.496 4.496 0 0024 19.503V4.496A4.496 4.496 0 0019.503 0z" fill="#fff"></path><path d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" fill="url(#lobe-icons-codex-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-codex-_R_0_" x1="12" x2="12" y1="3" y2="21"><stop stop-color="#B1A7FF"></stop><stop offset=".5" stop-color="#7A9DFF"></stop><stop offset="1" stop-color="#3941FF"></stop></linearGradient></defs></svg>',full:!0},gemini:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 4.391A4.391 4.391 0 014.391 0h15.217A4.391 4.391 0 0124 4.391v15.217A4.391 4.391 0 0119.608 24H4.391A4.391 4.391 0 010 19.608V4.391z" fill="url(#lobe-icons-gemini-cli-_R_0_)"></path><path clip-rule="evenodd" d="M19.74 1.444a2.816 2.816 0 012.816 2.816v15.48a2.816 2.816 0 01-2.816 2.816H4.26a2.816 2.816 0 01-2.816-2.816V4.26A2.816 2.816 0 014.26 1.444h15.48zM7.236 8.564l7.752 3.728-7.752 3.727v2.802l9.557-4.596v-3.866L7.236 5.763v2.801z" fill="#1E1E2E" fill-rule="evenodd"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-cli-_R_0_" x1="24" x2="0" y1="6.587" y2="16.494"><stop stop-color="#EE4D5D"></stop><stop offset=".328" stop-color="#B381DD"></stop><stop offset=".476" stop-color="#207CFE"></stop></linearGradient></defs></svg>',full:!0},claude:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path clip-rule="evenodd" d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z" fill="#D97757" fill-rule="evenodd"></path></svg>',full:!1,bg:{light:"#F4F1EA",dark:"#2A2926"}},copilot:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.245 5.364c1.322 1.36 1.877 3.216 2.11 5.817.622 0 1.2.135 1.592.654l.73.964c.21.278.323.61.323.955v2.62c0 .339-.173.669-.453.868C20.239 19.602 16.157 21.5 12 21.5c-4.6 0-9.205-2.583-11.547-4.258-.28-.2-.452-.53-.453-.868v-2.62c0-.345.113-.679.321-.956l.73-.963c.392-.517.974-.654 1.593-.654l.029-.297c.25-2.446.81-4.213 2.082-5.52 2.461-2.54 5.71-2.851 7.146-2.864h.198c1.436.013 4.685.323 7.146 2.864zm-7.244 4.328c-.284 0-.613.016-.962.05-.123.447-.305.85-.57 1.108-1.05 1.023-2.316 1.18-2.994 1.18-.638 0-1.306-.13-1.851-.464-.516.165-1.012.403-1.044.996a65.882 65.882 0 00-.063 2.884l-.002.48c-.002.563-.005 1.126-.013 1.69.002.326.204.63.51.765 2.482 1.102 4.83 1.657 6.99 1.657 2.156 0 4.504-.555 6.985-1.657a.854.854 0 00.51-.766c.03-1.682.006-3.372-.076-5.053-.031-.596-.528-.83-1.046-.996-.546.333-1.212.464-1.85.464-.677 0-1.942-.157-2.993-1.18-.266-.258-.447-.661-.57-1.108-.32-.032-.64-.049-.96-.05zm-2.525 4.013c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zm5 0c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zM7.635 5.087c-1.05.102-1.935.438-2.385.906-.975 1.037-.765 3.668-.21 4.224.405.394 1.17.657 1.995.657h.09c.649-.013 1.785-.176 2.73-1.11.435-.41.705-1.433.675-2.47-.03-.834-.27-1.52-.63-1.813-.39-.336-1.275-.482-2.265-.394zm6.465.394c-.36.292-.6.98-.63 1.813-.03 1.037.24 2.06.675 2.47.968.957 2.136 1.104 2.776 1.11h.044c.825 0 1.59-.263 1.995-.657.555-.556.765-3.187-.21-4.224-.45-.468-1.335-.804-2.385-.906-.99-.088-1.875.058-2.265.394zM12 7.615c-.24 0-.525.015-.84.044.03.16.045.336.06.526l-.001.159a2.94 2.94 0 01-.014.25c.225-.022.425-.027.612-.028h.366c.187 0 .387.006.612.028-.015-.146-.015-.277-.015-.409.015-.19.03-.365.06-.526a9.29 9.29 0 00-.84-.044z"></path></svg>',full:!1,bg:{light:"#0D1117",dark:"#F0F3F6"},fg:{light:"#FFFFFF",dark:"#0D1117"}},grok:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>',full:!1,bg:{light:"#000000",dark:"#FFFFFF"},fg:{light:"#FFFFFF",dark:"#000000"}},opencode:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M16 6H8v12h8V6zm4 16H4V2h16v20z"></path></svg>',full:!1,bg:{light:"#131010",dark:"#F1ECEC"},fg:{light:"#F1ECEC",dark:"#131010"}},cursor:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.106 5.68L12.5.135a.998.998 0 00-.998 0L1.893 5.68a.84.84 0 00-.419.726v11.186c0 .3.16.577.42.727l9.607 5.547a.999.999 0 00.998 0l9.608-5.547a.84.84 0 00.42-.727V6.407a.84.84 0 00-.42-.726zm-.603 1.176L12.228 22.92c-.063.108-.228.064-.228-.061V12.34a.59.59 0 00-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264 0 .428.286.296.514z"></path></svg>',full:!1,bg:{light:"#14120B",dark:"#EDECEC"},fg:{light:"#EDECEC",dark:"#14120B"}}},Q2=b.createContext(null);function Lt(){const n=b.useContext(Q2);if(!n)throw new Error("尚未连接电脑");return n}function yt(n){return xd(Lt().store,n)}function Jn(){return Lt().store.getState()}const W2=n=>n instanceof Error?n.message:String(n),Wu=n=>n.replace(/\/$/,"").split("/").pop()??n,Cr=n=>n.title||Wu(n.cwd)||"未命名会话",VR=n=>({idle:"已完成",waiting:"需要你",running:"进行中",error:"出错",offline:"离线",completed:"已完成",failed:"失败",stopped:"已停止",pending:"等待中",active:"进行中",paused:"已暂停",complete:"已完成",blocked:"待处理",usageLimited:"用量受限",budgetLimited:"预算已用完",unknown:"未知"})[n]??n;function Cd({agent:n}){const t=HR[n.toLowerCase()];return f.jsx("span",{className:`agent-mark ${n.toLowerCase()} ${t?.full?"full-mark":""}`,children:t?f.jsx("img",{src:`data:image/svg+xml,${encodeURIComponent(t.svg.replaceAll("currentColor",t.fg?.light??"#333"))}`,alt:n}):n.slice(0,1).toUpperCase()})}function Ur({state:n}){return f.jsxs("span",{className:`badge ${n==="idle"||n==="completed"?"done":n}`,children:[f.jsx("span",{className:"status-dot"}),VR(n)]})}function Dt({error:n}){return n?f.jsx("p",{role:"alert",className:"form-error",children:n}):null}function El({title:n,children:t,close:s,wide:r=!1,returnFocus:o}){return f.jsx(FS,{open:!0,onOpenChange:l=>{l||s()},children:f.jsxs(GS,{onCloseAutoFocus:o?l=>{l.preventDefault(),o()}:void 0,className:qe("max-h-[85dvh] overflow-y-auto p-6 sm:max-w-xl",r&&"sm:max-w-5xl"),children:[f.jsxs(ZS,{children:[f.jsx(YS,{children:n}),f.jsxs(KS,{className:"sr-only",children:[n,"设置与操作"]})]}),t]})})}function Wt(){const[n,t]=b.useState(),[s,r]=b.useState(!1),o=b.useRef(!1);async function l(u){if(!o.current){o.current=!0,r(!0),t(void 0);try{return await u()}catch(d){t(W2(d))}finally{o.current=!1,r(!1)}}}return{error:n,busy:s,run:l,clear:()=>t(void 0)}}function ea(n,t,s=0){const[r,o]=b.useState({loading:!0}),[l,u]=b.useState(0),d=b.useRef(n);return d.current=n,b.useEffect(()=>{let m=!0,p=!1;const y=async()=>{if(!p){p=!0;try{const x=await d.current();m&&o({value:x,loading:!1})}catch(x){m&&o(_=>({..._,error:W2(x),loading:!1}))}finally{p=!1}}};o({loading:!0}),y();const v=s?setInterval(()=>void y(),s):void 0;return()=>{m=!1,clearInterval(v)}},[...t,l,s]),{...r,reload:()=>u(m=>m+1)}}function ba({loading:n,error:t}){return f.jsxs(f.Fragment,{children:[n&&f.jsx("p",{className:"muted loading-copy",role:"status",children:"正在加载…"}),f.jsx(Dt,{error:t})]})}function qR({found:n}){const t=b.useRef(null),[s,r]=b.useState(!1),[o,l]=b.useState(),u=b.useRef(n);u.current=n;function d(p){if(!G2(p)){l("这不是有效的 LinkShell 配对二维码");return}u.current(p),r(!1),l(void 0)}const m=b.useRef(d);return m.current=d,b.useEffect(()=>{if(!s||!t.current)return;let p=!1,y;return Ym(()=>import("./qr-scanner.min-zIfv4GCN.js"),__vite__mapDeps([0,1,2,3,4])).then(async({default:v})=>{p||!t.current||(y=new v(t.current,x=>m.current(x.data),{preferredCamera:"environment",returnDetailedScanResult:!0,highlightScanRegion:!0}),await y.start())}).catch(v=>{p||(l(v instanceof Error?v.message:"无法打开摄像头,请使用图片或配对码"),r(!1))}),()=>{p=!0,y?.destroy()}},[s]),f.jsxs("div",{className:"qr-scan",children:[f.jsxs("div",{className:"permission-buttons",children:[f.jsx("button",{className:"button secondary",type:"button",onClick:()=>r(!s),children:s?"关闭摄像头":"扫描二维码"}),f.jsxs("label",{className:"button secondary",children:["从图片识别",f.jsx("input",{type:"file",accept:"image/*",hidden:!0,onChange:p=>{const y=p.target.files?.[0];p.target.value="",y&&Ym(()=>import("./qr-scanner.min-zIfv4GCN.js"),__vite__mapDeps([0,1,2,3,4])).then(v=>v.default.scanImage(y,{returnDetailedScanResult:!0})).then(v=>d(v.data),()=>l("没有识别到二维码,请换一张图片或输入配对码"))}})]})]}),s&&f.jsx("video",{ref:t,className:"qr-video",muted:!0,playsInline:!0}),f.jsx(Dt,{error:o})]})}function $R({close:n}){const t=xd(Qt.state),[s,r]=b.useState(t.source),[o,l]=b.useState(""),[u,d]=b.useState(""),[m,p]=b.useState(s==="self-hosted"?t.gateway:""),[y,v]=b.useState(""),x=Wt();return f.jsxs(El,{title:"连接你的电脑",close:n,children:[f.jsx("p",{className:"muted modal-subtitle",children:"电脑保持运行,网页即可继续你的会话。"}),qs==="official"&&f.jsxs("div",{className:"source-options",children:[f.jsxs("button",{className:`source-option ${s==="official"?"selected":""}`,"aria-pressed":s==="official",onClick:()=>r("official"),children:[f.jsx(_t,{name:"globe"}),f.jsx("strong",{children:"官方账号"}),f.jsx("span",{children:"同一 iTool 账号发现电脑"})]}),f.jsxs("button",{className:`source-option ${s==="self-hosted"?"selected":""}`,"aria-pressed":s==="self-hosted",onClick:()=>r("self-hosted"),children:[f.jsx(_t,{name:"server"}),f.jsx("strong",{children:"配对电脑"}),f.jsx("span",{children:"官方或自托管网关的配对码"})]})]}),s==="official"?f.jsxs("form",{className:"new-form",onSubmit:_=>{_.preventDefault(),x.run(async()=>{const E=await hl().auth.signInWithPassword({email:o.trim(),password:u});if(E.error)throw E.error;await Qt.connectAccount(),n()})},children:[t.account?f.jsx("div",{className:"private-note",children:f.jsxs("div",{children:[f.jsx("strong",{children:t.account}),f.jsx("p",{children:"电脑端运行 linkshell login,使用同一账号。电脑接入官方网关需要 Pro 订阅。"}),f.jsx("button",{type:"button",className:"text-button",onClick:()=>void x.run(async()=>{await Qt.connectAccount(),n()}),children:"刷新账号电脑"})]})}):f.jsxs(f.Fragment,{children:[f.jsx("label",{htmlFor:"email",children:"邮箱"}),f.jsx("input",{id:"email",type:"email",autoComplete:"username",value:o,onChange:_=>l(_.target.value),required:!0}),f.jsx("label",{htmlFor:"password",children:"密码"}),f.jsx("input",{id:"password",type:"password",autoComplete:"current-password",value:u,onChange:_=>d(_.target.value),required:!0}),f.jsx("button",{className:"button primary full",disabled:x.busy,children:"登录"}),f.jsx("div",{className:"form-columns",children:["github","google"].map(_=>f.jsx("button",{type:"button",className:"button secondary",disabled:x.busy,onClick:()=>void x.run(async()=>{const E=await hl().auth.signInWithOAuth({provider:_,options:{redirectTo:location.origin+location.pathname}});if(E.error)throw E.error}),children:_==="github"?"GitHub 登录":"Google 登录"},_))}),f.jsxs("p",{className:"field-hint",children:["登录状态自动续期。",f.jsx("a",{href:"https://itool.tech/zh/register",target:"_blank",rel:"noreferrer",children:"注册 iTool 账号 ↗"})]})]}),t.account&&f.jsx("button",{type:"button",className:"button secondary full",disabled:x.busy,onClick:()=>void x.run(async()=>{const _=await hl().auth.signOut({scope:"local"});if(_.error)throw _.error;Qt.disconnect()}),children:"退出本浏览器账号"})]}):f.jsxs("form",{className:"pairing-form",onSubmit:_=>{_.preventDefault(),x.run(async()=>{await Qt.pair(m,y),n()})},children:[f.jsx(qR,{found:v}),f.jsx("label",{htmlFor:"gateway",children:"网关地址"}),f.jsx("input",{id:"gateway",placeholder:"wss://gateway.example.com",value:m,onChange:_=>p(_.target.value),required:!y.startsWith("linkshell:")}),f.jsx("p",{className:"field-hint",children:"电脑需先连接同一个网关。"}),f.jsx("label",{htmlFor:"pairing",children:"配对码或配对链接"}),f.jsx("input",{id:"pairing",value:y,onChange:_=>v(_.target.value),placeholder:"6 位配对码,或粘贴 linkshell://pair 链接",required:!0}),f.jsxs("p",{className:"field-hint",children:["在电脑运行 ",f.jsx("code",{children:"linkshell pair"}),"。有效期 10 分钟,成功后此浏览器会记住设备。"]}),f.jsx("button",{className:"button primary full",disabled:x.busy||t.locked,children:"配对并连接"}),f.jsx("p",{className:"field-hint",children:"自托管不使用 iTool 登录凭证。清除网站数据后需要重新配对。"})]}),f.jsx(Dt,{error:x.error}),x.busy&&f.jsx("p",{className:"muted",role:"status",children:"正在连接…"})]})}function PR({...n}){return f.jsx(jk,{"data-slot":"popover",...n})}function FR({className:n,align:t="center",sideOffset:s=4,...r}){return f.jsx(Rk,{children:f.jsx(Dk,{"data-slot":"popover-content",align:t,sideOffset:s,className:qe("z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",n),...r})})}function GR({...n}){return f.jsx(kk,{"data-slot":"popover-anchor",...n})}var i1=1,ZR=.9,YR=.8,KR=.17,bm=.1,xm=.999,XR=.9999,QR=.99,WR=/[\\\/_+.#"@\[\(\{&]/,JR=/[\\\/_+.#"@\[\(\{&]/g,eD=/[\s-]/,J2=/[\s-]/g;function fp(n,t,s,r,o,l,u){if(l===t.length)return o===n.length?i1:QR;var d=`${o},${l}`;if(u[d]!==void 0)return u[d];for(var m=r.charAt(l),p=s.indexOf(m,o),y=0,v,x,_,E;p>=0;)v=fp(n,t,s,r,p+1,l+1,u),v>y&&(p===o?v*=i1:WR.test(n.charAt(p-1))?(v*=YR,_=n.slice(o,p-1).match(JR),_&&o>0&&(v*=Math.pow(xm,_.length))):eD.test(n.charAt(p-1))?(v*=ZR,E=n.slice(o,p-1).match(J2),E&&o>0&&(v*=Math.pow(xm,E.length))):(v*=KR,o>0&&(v*=Math.pow(xm,p-o))),n.charAt(p)!==t.charAt(l)&&(v*=XR)),(v<bm&&s.charAt(p-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&s.charAt(p-1)!==r.charAt(l))&&(x=fp(n,t,s,r,p+1,l+2,u),x*bm>v&&(v=x*bm)),v>y&&(y=v),p=s.indexOf(m,p+1);return u[d]=y,y}function o1(n){return n.toLowerCase().replace(J2," ")}function tD(n,t,s){return n=s&&s.length>0?`${n+" "+s.join(" ")}`:n,fp(n,t,o1(n),o1(t),0,0,{})}function Is(n,t,{checkForDefaultPrevented:s=!0}={}){return function(o){if(n?.(o),s===!1||!o.defaultPrevented)return t?.(o)}}function l1(n,t){if(typeof n=="function")return n(t);n!=null&&(n.current=t)}function Br(...n){return t=>{let s=!1;const r=n.map(o=>{const l=l1(o,t);return!s&&typeof l=="function"&&(s=!0),l});if(s)return()=>{for(let o=0;o<r.length;o++){const l=r[o];typeof l=="function"?l():l1(n[o],null)}}}}function Kr(...n){return b.useCallback(Br(...n),n)}function nD(n,t){const s=b.createContext(t),r=l=>{const{children:u,...d}=l,m=b.useMemo(()=>d,Object.values(d));return f.jsx(s.Provider,{value:m,children:u})};r.displayName=n+"Provider";function o(l){const u=b.useContext(s);if(u)return u;if(t!==void 0)return t;throw new Error(`\`${l}\` must be used within \`${n}\``)}return[r,o]}function aD(n,t=[]){let s=[];function r(l,u){const d=b.createContext(u),m=s.length;s=[...s,u];const p=v=>{const{scope:x,children:_,...E}=v,A=x?.[n]?.[m]||d,S=b.useMemo(()=>E,Object.values(E));return f.jsx(A.Provider,{value:S,children:_})};p.displayName=l+"Provider";function y(v,x){const _=x?.[n]?.[m]||d,E=b.useContext(_);if(E)return E;if(u!==void 0)return u;throw new Error(`\`${v}\` must be used within \`${l}\``)}return[p,y]}const o=()=>{const l=s.map(u=>b.createContext(u));return function(d){const m=d?.[n]||l;return b.useMemo(()=>({[`__scope${n}`]:{...d,[n]:m}}),[d,m])}};return o.scopeName=n,[r,sD(o,...t)]}function sD(...n){const t=n[0];if(n.length===1)return t;const s=()=>{const r=n.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(l){const u=r.reduce((d,{useScope:m,scopeName:p})=>{const v=m(l)[`__scope${p}`];return{...d,...v}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return s.scopeName=t.scopeName,s}var _l=globalThis?.document?b.useLayoutEffect:()=>{},rD=Zs[" useId ".trim().toString()]||(()=>{}),iD=0;function Ya(n){const[t,s]=b.useState(rD());return _l(()=>{s(r=>r??String(iD++))},[n]),t?`radix-${t}`:""}var oD=Zs[" useInsertionEffect ".trim().toString()]||_l;function lD({prop:n,defaultProp:t,onChange:s=()=>{},caller:r}){const[o,l,u]=cD({defaultProp:t,onChange:s}),d=n!==void 0,m=d?n:o;{const y=b.useRef(n!==void 0);b.useEffect(()=>{const v=y.current;v!==d&&console.warn(`${r} is changing from ${v?"controlled":"uncontrolled"} to ${d?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=d},[d,r])}const p=b.useCallback(y=>{if(d){const v=uD(y)?y(n):y;v!==n&&u.current?.(v)}else l(y)},[d,n,l,u]);return[m,p]}function cD({defaultProp:n,onChange:t}){const[s,r]=b.useState(n),o=b.useRef(s),l=b.useRef(t);return oD(()=>{l.current=t},[t]),b.useEffect(()=>{o.current!==s&&(l.current?.(s),o.current=s)},[s,o]),[s,r,l]}function uD(n){return typeof n=="function"}function eE(n){const t=dD(n),s=b.forwardRef((r,o)=>{const{children:l,...u}=r,d=b.Children.toArray(l),m=d.find(hD);if(m){const p=m.props.children,y=d.map(v=>v===m?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:v);return f.jsx(t,{...u,ref:o,children:b.isValidElement(p)?b.cloneElement(p,void 0,y):null})}return f.jsx(t,{...u,ref:o,children:l})});return s.displayName=`${n}.Slot`,s}function dD(n){const t=b.forwardRef((s,r)=>{const{children:o,...l}=s;if(b.isValidElement(o)){const u=pD(o),d=mD(l,o.props);return o.type!==b.Fragment&&(d.ref=r?Br(r,u):u),b.cloneElement(o,d)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${n}.SlotClone`,t}var fD=Symbol("radix.slottable");function hD(n){return b.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===fD}function mD(n,t){const s={...t};for(const r in t){const o=n[r],l=t[r];/^on[A-Z]/.test(r)?o&&l?s[r]=(...d)=>{const m=l(...d);return o(...d),m}:o&&(s[r]=o):r==="style"?s[r]={...o,...l}:r==="className"&&(s[r]=[o,l].filter(Boolean).join(" "))}return{...n,...s}}function pD(n){let t=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?n.ref:(t=Object.getOwnPropertyDescriptor(n,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?n.props.ref:n.props.ref||n.ref)}var gD=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Jt=gD.reduce((n,t)=>{const s=eE(`Primitive.${t}`),r=b.forwardRef((o,l)=>{const{asChild:u,...d}=o,m=u?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(m,{...d,ref:l})});return r.displayName=`Primitive.${t}`,{...n,[t]:r}},{});function vD(n,t){n&&qr.flushSync(()=>n.dispatchEvent(t))}function Cl(n){const t=b.useRef(n);return b.useEffect(()=>{t.current=n}),b.useMemo(()=>(...s)=>t.current?.(...s),[])}function yD(n,t=globalThis?.document){const s=Cl(n);b.useEffect(()=>{const r=o=>{o.key==="Escape"&&s(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[s,t])}var bD="DismissableLayer",hp="dismissableLayer.update",xD="dismissableLayer.pointerDownOutside",wD="dismissableLayer.focusOutside",c1,tE=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),nE=b.forwardRef((n,t)=>{const{disableOutsidePointerEvents:s=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...m}=n,p=b.useContext(tE),[y,v]=b.useState(null),x=y?.ownerDocument??globalThis?.document,[,_]=b.useState({}),E=Kr(t,M=>v(M)),A=Array.from(p.layers),[S]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),j=A.indexOf(S),T=y?A.indexOf(y):-1,k=p.layersWithOutsidePointerEventsDisabled.size>0,C=T>=j,R=_D(M=>{const z=M.target,L=[...p.branches].some(q=>q.contains(z));!C||L||(o?.(M),u?.(M),M.defaultPrevented||d?.())},x),O=CD(M=>{const z=M.target;[...p.branches].some(q=>q.contains(z))||(l?.(M),u?.(M),M.defaultPrevented||d?.())},x);return yD(M=>{T===p.layers.size-1&&(r?.(M),!M.defaultPrevented&&d&&(M.preventDefault(),d()))},x),b.useEffect(()=>{if(y)return s&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(c1=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),u1(),()=>{s&&p.layersWithOutsidePointerEventsDisabled.size===1&&(x.body.style.pointerEvents=c1)}},[y,x,s,p]),b.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),u1())},[y,p]),b.useEffect(()=>{const M=()=>_({});return document.addEventListener(hp,M),()=>document.removeEventListener(hp,M)},[]),f.jsx(Jt.div,{...m,ref:E,style:{pointerEvents:k?C?"auto":"none":void 0,...n.style},onFocusCapture:Is(n.onFocusCapture,O.onFocusCapture),onBlurCapture:Is(n.onBlurCapture,O.onBlurCapture),onPointerDownCapture:Is(n.onPointerDownCapture,R.onPointerDownCapture)})});nE.displayName=bD;var SD="DismissableLayerBranch",ED=b.forwardRef((n,t)=>{const s=b.useContext(tE),r=b.useRef(null),o=Kr(t,r);return b.useEffect(()=>{const l=r.current;if(l)return s.branches.add(l),()=>{s.branches.delete(l)}},[s.branches]),f.jsx(Jt.div,{...n,ref:o})});ED.displayName=SD;function _D(n,t=globalThis?.document){const s=Cl(n),r=b.useRef(!1),o=b.useRef(()=>{});return b.useEffect(()=>{const l=d=>{if(d.target&&!r.current){let m=function(){aE(xD,s,p,{discrete:!0})};const p={originalEvent:d};d.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},u=window.setTimeout(()=>{t.addEventListener("pointerdown",l)},0);return()=>{window.clearTimeout(u),t.removeEventListener("pointerdown",l),t.removeEventListener("click",o.current)}},[t,s]),{onPointerDownCapture:()=>r.current=!0}}function CD(n,t=globalThis?.document){const s=Cl(n),r=b.useRef(!1);return b.useEffect(()=>{const o=l=>{l.target&&!r.current&&aE(wD,s,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function u1(){const n=new CustomEvent(hp);document.dispatchEvent(n)}function aE(n,t,s,{discrete:r}){const o=s.originalEvent.target,l=new CustomEvent(n,{bubbles:!1,cancelable:!0,detail:s});t&&o.addEventListener(n,t,{once:!0}),r?vD(o,l):o.dispatchEvent(l)}var wm="focusScope.autoFocusOnMount",Sm="focusScope.autoFocusOnUnmount",d1={bubbles:!1,cancelable:!0},AD="FocusScope",sE=b.forwardRef((n,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:l,...u}=n,[d,m]=b.useState(null),p=Cl(o),y=Cl(l),v=b.useRef(null),x=Kr(t,A=>m(A)),_=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let A=function(k){if(_.paused||!d)return;const C=k.target;d.contains(C)?v.current=C:Ms(v.current,{select:!0})},S=function(k){if(_.paused||!d)return;const C=k.relatedTarget;C!==null&&(d.contains(C)||Ms(v.current,{select:!0}))},j=function(k){if(document.activeElement===document.body)for(const R of k)R.removedNodes.length>0&&Ms(d)};document.addEventListener("focusin",A),document.addEventListener("focusout",S);const T=new MutationObserver(j);return d&&T.observe(d,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",S),T.disconnect()}}},[r,d,_.paused]),b.useEffect(()=>{if(d){h1.add(_);const A=document.activeElement;if(!d.contains(A)){const j=new CustomEvent(wm,d1);d.addEventListener(wm,p),d.dispatchEvent(j),j.defaultPrevented||(jD(RD(rE(d)),{select:!0}),document.activeElement===A&&Ms(d))}return()=>{d.removeEventListener(wm,p),setTimeout(()=>{const j=new CustomEvent(Sm,d1);d.addEventListener(Sm,y),d.dispatchEvent(j),j.defaultPrevented||Ms(A??document.body,{select:!0}),d.removeEventListener(Sm,y),h1.remove(_)},0)}}},[d,p,y,_]);const E=b.useCallback(A=>{if(!s&&!r||_.paused)return;const S=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,j=document.activeElement;if(S&&j){const T=A.currentTarget,[k,C]=TD(T);k&&C?!A.shiftKey&&j===C?(A.preventDefault(),s&&Ms(k,{select:!0})):A.shiftKey&&j===k&&(A.preventDefault(),s&&Ms(C,{select:!0})):j===T&&A.preventDefault()}},[s,r,_.paused]);return f.jsx(Jt.div,{tabIndex:-1,...u,ref:x,onKeyDown:E})});sE.displayName=AD;function jD(n,{select:t=!1}={}){const s=document.activeElement;for(const r of n)if(Ms(r,{select:t}),document.activeElement!==s)return}function TD(n){const t=rE(n),s=f1(t,n),r=f1(t.reverse(),n);return[s,r]}function rE(n){const t=[],s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function f1(n,t){for(const s of n)if(!kD(s,{upTo:t}))return s}function kD(n,{upTo:t}){if(getComputedStyle(n).visibility==="hidden")return!0;for(;n;){if(t!==void 0&&n===t)return!1;if(getComputedStyle(n).display==="none")return!0;n=n.parentElement}return!1}function ND(n){return n instanceof HTMLInputElement&&"select"in n}function Ms(n,{select:t=!1}={}){if(n&&n.focus){const s=document.activeElement;n.focus({preventScroll:!0}),n!==s&&ND(n)&&t&&n.select()}}var h1=OD();function OD(){let n=[];return{add(t){const s=n[0];t!==s&&s?.pause(),n=m1(n,t),n.unshift(t)},remove(t){n=m1(n,t),n[0]?.resume()}}}function m1(n,t){const s=[...n],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function RD(n){return n.filter(t=>t.tagName!=="A")}var DD="Portal",iE=b.forwardRef((n,t)=>{const{container:s,...r}=n,[o,l]=b.useState(!1);_l(()=>l(!0),[]);const u=s||o&&globalThis?.document?.body;return u?cj.createPortal(f.jsx(Jt.div,{...r,ref:t}),u):null});iE.displayName=DD;function MD(n,t){return b.useReducer((s,r)=>t[s][r]??s,n)}var Ad=n=>{const{present:t,children:s}=n,r=zD(t),o=typeof s=="function"?s({present:r.isPresent}):b.Children.only(s),l=Kr(r.ref,LD(o));return typeof s=="function"||r.isPresent?b.cloneElement(o,{ref:l}):null};Ad.displayName="Presence";function zD(n){const[t,s]=b.useState(),r=b.useRef(null),o=b.useRef(n),l=b.useRef("none"),u=n?"mounted":"unmounted",[d,m]=MD(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const p=mu(r.current);l.current=d==="mounted"?p:"none"},[d]),_l(()=>{const p=r.current,y=o.current;if(y!==n){const x=l.current,_=mu(p);n?m("MOUNT"):_==="none"||p?.display==="none"?m("UNMOUNT"):m(y&&x!==_?"ANIMATION_OUT":"UNMOUNT"),o.current=n}},[n,m]),_l(()=>{if(t){let p;const y=t.ownerDocument.defaultView??window,v=_=>{const A=mu(r.current).includes(CSS.escape(_.animationName));if(_.target===t&&A&&(m("ANIMATION_END"),!o.current)){const S=t.style.animationFillMode;t.style.animationFillMode="forwards",p=y.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=S)})}},x=_=>{_.target===t&&(l.current=mu(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",v),t.addEventListener("animationend",v),()=>{y.clearTimeout(p),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",v),t.removeEventListener("animationend",v)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:b.useCallback(p=>{r.current=p?getComputedStyle(p):null,s(p)},[])}}function mu(n){return n?.animationName||"none"}function LD(n){let t=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?n.ref:(t=Object.getOwnPropertyDescriptor(n,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?n.props.ref:n.props.ref||n.ref)}var Em=0;function UD(){b.useEffect(()=>{const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",n[0]??p1()),document.body.insertAdjacentElement("beforeend",n[1]??p1()),Em++,()=>{Em===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Em--}},[])}function p1(){const n=document.createElement("span");return n.setAttribute("data-radix-focus-guard",""),n.tabIndex=0,n.style.outline="none",n.style.opacity="0",n.style.position="fixed",n.style.pointerEvents="none",n}var jd="Dialog",[oE]=aD(jd),[BD,ta]=oE(jd),lE=n=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:o,onOpenChange:l,modal:u=!0}=n,d=b.useRef(null),m=b.useRef(null),[p,y]=lD({prop:r,defaultProp:o??!1,onChange:l,caller:jd});return f.jsx(BD,{scope:t,triggerRef:d,contentRef:m,contentId:Ya(),titleId:Ya(),descriptionId:Ya(),open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(v=>!v),[y]),modal:u,children:s})};lE.displayName=jd;var cE="DialogTrigger",ID=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(cE,s),l=Kr(t,o.triggerRef);return f.jsx(Jt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":fg(o.open),...r,ref:l,onClick:Is(n.onClick,o.onOpenToggle)})});ID.displayName=cE;var ug="DialogPortal",[HD,uE]=oE(ug,{forceMount:void 0}),dE=n=>{const{__scopeDialog:t,forceMount:s,children:r,container:o}=n,l=ta(ug,t);return f.jsx(HD,{scope:t,forceMount:s,children:b.Children.map(r,u=>f.jsx(Ad,{present:s||l.open,children:f.jsx(iE,{asChild:!0,container:o,children:u})}))})};dE.displayName=ug;var Ju="DialogOverlay",fE=b.forwardRef((n,t)=>{const s=uE(Ju,n.__scopeDialog),{forceMount:r=s.forceMount,...o}=n,l=ta(Ju,n.__scopeDialog);return l.modal?f.jsx(Ad,{present:r||l.open,children:f.jsx(qD,{...o,ref:t})}):null});fE.displayName=Ju;var VD=eE("DialogOverlay.RemoveScroll"),qD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(Ju,s);return f.jsx(so,{as:VD,allowPinchZoom:!0,shards:[o.contentRef],children:f.jsx(Jt.div,{"data-state":fg(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ir="DialogContent",hE=b.forwardRef((n,t)=>{const s=uE(Ir,n.__scopeDialog),{forceMount:r=s.forceMount,...o}=n,l=ta(Ir,n.__scopeDialog);return f.jsx(Ad,{present:r||l.open,children:l.modal?f.jsx($D,{...o,ref:t}):f.jsx(PD,{...o,ref:t})})});hE.displayName=Ir;var $D=b.forwardRef((n,t)=>{const s=ta(Ir,n.__scopeDialog),r=b.useRef(null),o=Kr(t,s.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return jl(l)},[]),f.jsx(mE,{...n,ref:o,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Is(n.onCloseAutoFocus,l=>{l.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Is(n.onPointerDownOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0;(u.button===2||d)&&l.preventDefault()}),onFocusOutside:Is(n.onFocusOutside,l=>l.preventDefault())})}),PD=b.forwardRef((n,t)=>{const s=ta(Ir,n.__scopeDialog),r=b.useRef(!1),o=b.useRef(!1);return f.jsx(mE,{...n,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{n.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||s.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:l=>{n.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=l.target;s.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&o.current&&l.preventDefault()}})}),mE=b.forwardRef((n,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:l,...u}=n,d=ta(Ir,s),m=b.useRef(null),p=Kr(t,m);return UD(),f.jsxs(f.Fragment,{children:[f.jsx(sE,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:l,children:f.jsx(nE,{role:"dialog",id:d.contentId,"aria-describedby":d.descriptionId,"aria-labelledby":d.titleId,"data-state":fg(d.open),...u,ref:p,onDismiss:()=>d.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(YD,{titleId:d.titleId}),f.jsx(XD,{contentRef:m,descriptionId:d.descriptionId})]})]})}),dg="DialogTitle",FD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(dg,s);return f.jsx(Jt.h2,{id:o.titleId,...r,ref:t})});FD.displayName=dg;var pE="DialogDescription",GD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(pE,s);return f.jsx(Jt.p,{id:o.descriptionId,...r,ref:t})});GD.displayName=pE;var gE="DialogClose",ZD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(gE,s);return f.jsx(Jt.button,{type:"button",...r,ref:t,onClick:Is(n.onClick,()=>o.onOpenChange(!1))})});ZD.displayName=gE;function fg(n){return n?"open":"closed"}var vE="DialogTitleWarning",[W8,yE]=nD(vE,{contentName:Ir,titleName:dg,docsSlug:"dialog"}),YD=({titleId:n})=>{const t=yE(vE),s=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
159
+ `))}).catch(o=>{o?.code!==-32601&&r()})}close(){this.stopped=!0,this.drop();for(const t of this.remove)t()}}const NR="https://mkbeusztkzffnzjdwmqk.supabase.co",OR="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1rYmV1c3p0a3pmZm56amR3bXFrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjU5Nzc0NzgsImV4cCI6MjA4MTU1MzQ3OH0.2wlT6q6687Z5rpEYsdp01IQpNNl_XWv0IAfBgwPyDP0";let RR;function hl(){return RR??=mA(window.__LINKSHELL_CONFIG__?.account?.url??NR,window.__LINKSHELL_CONFIG__?.account?.anonKey??OR,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"linkshell.web.account.v2"}})}async function DR(){const n=hl().auth,{data:t,error:s}=await n.getSession();if(s)throw s;if(!t.session)return;if((t.session.expires_at??0)*1e3>Date.now()+12e4)return t.session.access_token;const r=await n.refreshSession();if(r.error)throw r.error;if(!r.data.session)throw new Error("登录已失效,请重新登录");return r.data.session.access_token}function Fs(n,t){try{return JSON.parse(localStorage.getItem(`linkshell.web.${n}`)??"null")??t}catch{return t}}function ua(n,t){localStorage.setItem(`linkshell.web.${n}`,JSON.stringify(t))}let MR;function zR(){return MR??=new Promise((n,t)=>{const s=indexedDB.open("linkshell.web.identity",1);s.onupgradeneeded=()=>s.result.createObjectStore("keys"),s.onerror=()=>t(new Error("无法保存浏览器设备身份,请允许此网站使用本地存储")),s.onsuccess=()=>{const r=s.result,o=r.transaction("keys","readwrite"),l=o.objectStore("keys"),u=l.get("device");let d;u.onsuccess=()=>{d=u.result??QO(),u.result||l.put(d,"device")},o.oncomplete=()=>{r.close(),n(d)},o.onerror=()=>{r.close(),t(new Error("设备身份保存失败"))}}})}const LR=n=>{const t=new RTCPeerConnection({iceServers:n.map(r=>({urls:r}))}),s=t.createDataChannel(dR,{ordered:!0});return s.binaryType="arraybuffer",{async offer(){if(await t.setLocalDescription(await t.createOffer()),t.iceGatheringState!=="complete"&&await new Promise(r=>{const o=()=>{clearTimeout(u),t.removeEventListener("icegatheringstatechange",l),r()},l=()=>{t.iceGatheringState==="complete"&&o()},u=setTimeout(o,2e3);t.addEventListener("icegatheringstatechange",l)}),!t.localDescription?.sdp)throw new Error("无法建立直连通道");return t.localDescription.sdp},accept:r=>t.setRemoteDescription({type:"answer",sdp:r}),send(r){s.send(r)},onState(r){s.addEventListener("open",()=>r("open")),s.addEventListener("close",()=>r("closed")),t.addEventListener("connectionstatechange",()=>{["failed","closed"].includes(t.connectionState)&&r("closed")})},onMessage(r){s.addEventListener("message",o=>{o.data instanceof ArrayBuffer&&r(new Uint8Array(o.data))})},close(){t.close()}}},UR=Fs("source",qs),X2=qs==="self-hosted"?"self-hosted":UR,BR=X2==="official"?Er:Fs("gateway",sN);class IR{state=WS(()=>({source:X2,gateway:BR,computers:[],relayStatus:{},locked:!1,ready:!1}));identity;relays=new Map;paired=Fs("paired",[]);selected=Fs("selected","");releaseLock;starting;authUser;authSubscribed=!1;generation=0;channel=typeof BroadcastChannel<"u"?new BroadcastChannel("linkshell.web.owner"):void 0;constructor(){this.channel?.addEventListener("message",t=>{t.data==="yield"&&(this.stop(),this.state.setState({locked:!0}))}),window.addEventListener("pagehide",()=>this.stop()),window.addEventListener("pageshow",()=>{this.start()}),window.addEventListener("online",()=>this.reconnect()),document.addEventListener("visibilitychange",()=>{document.hidden||this.reconnect()})}report(t){this.state.setState({error:t instanceof Error?t.message:String(t)})}async start(){return this.releaseLock||this.starting?this.starting:(this.starting=this.acquire(!1).finally(()=>{this.starting=void 0}),this.starting)}async claim(){this.channel?.postMessage("yield"),await this.acquire(!0)}async acquire(t){if(!navigator.locks){this.report(new Error("此浏览器不支持设备连接锁,请使用最新版 Chrome、Edge、Safari 或 Firefox"));return}await new Promise((s,r)=>{navigator.locks.request("linkshell.web.connection",{ifAvailable:!t},async o=>{if(!o){this.state.setState({locked:!0,ready:!0}),s();return}await new Promise(l=>{this.releaseLock=l,this.state.setState({locked:!1}),this.boot().then(s,r)})}).catch(r)}).catch(s=>this.report(s))}async boot(){const t=++this.generation;if(this.identity=await zR(),t===this.generation){this.state.setState({computers:this.paired.map(s=>({...s,machine:{...s.machine,online:!1}})),ready:!0});for(const s of this.paired)this.relay(s.gateway);this.state.getState().source==="official"?await this.connectAccount():this.state.getState().gateway&&this.relay(om(this.state.getState().gateway))}}async connectAccount(){if(qs==="self-hosted")throw new Error("私有部署使用设备配对");const t=hl().auth,{data:s,error:r}=await t.getSession();if(r)throw r;this.authUser=s.session?.user.id,this.state.setState({account:s.session?.user.email,source:"official",gateway:Er}),this.authSubscribed||(this.authSubscribed=!0,t.onAuthStateChange((o,l)=>{const u=this.authUser!==l?.user.id;this.authUser=l?.user.id,this.state.setState({account:l?.user.email}),u&&this.releaseLock&&setTimeout(()=>{this.relays.get(Er)?.reauthenticate(),l&&this.relay(Er)},0)})),ua("source","official"),s.session&&this.relay(Er).reauthenticate()}relay(t){if(!this.identity||!this.releaseLock)throw new Error("请先在本标签页启用连接");const s=om(t),r=this.relays.get(s);if(r)return r;const o=s===Er&&qs!=="self-hosted",l=new uR({url:s+sR,identity:this.identity,role:"device",name:"LinkShell Web",platform:"web",token:o?async()=>{try{return await DR()}catch(u){throw this.report(u),u}}:void 0,createSocket:u=>{const d=new WebSocket(u),m=d.send.bind(d);return d.send=p=>{if(typeof p=="string"&&o&&this.authUser){const y=JSON.parse(p);if(y.t==="auth"&&!y.token){d.close(4001,"账号续期失败,正在重试");return}}m(p)},d}});return this.relays.set(s,l),l.onStatus((u,d)=>{this.state.setState(m=>({relayStatus:{...m.relayStatus,[s]:u},...d?{error:d.message}:{}})),u==="online"&&this.refresh(s).catch(m=>this.report(m))}),l.on("machines.changed",()=>{this.refresh(s).catch(u=>this.report(u))}),l.on("presence",({id:u,online:d})=>this.state.setState(m=>({computers:m.computers.map(p=>p.gateway===s&&p.machine.id===u?{...p,machine:{...p.machine,online:d}}:p)}))),l.start(),l}async refresh(t){const s=this.relays.get(t);if(!s)return;const{machines:r}=await s.request("machines.list",{}),o=r.map(u=>({gateway:t,machine:u,key:`${t}#${u.id}`}));this.state.setState(u=>({computers:[...u.computers.filter(d=>d.gateway!==t),...o]}));const l=this.state.getState();if(!l.connection){const u=l.computers.find(d=>d.key===this.selected)??l.computers.find(d=>d.machine.online);u&&this.select(u)}}select(t){if(!this.identity)throw new Error("设备身份尚未就绪");this.disconnect();const s=this.identity,r=this.relay(t.gateway),o=new vR({url:t.key,createSocket:()=>new CR(r,s,t.machine),lazyImages:!0}),l=_R(o,{lazyImages:!0}),u=new TR(o,{connector:LR,iceServers:()=>l.getState().machine?.direct?.iceServers});l.subscribe((d,m)=>{d.machine!==m.machine&&u.connect()}),this.state.setState({connection:{computer:t,link:o,store:l,streams:u},error:void 0}),this.selected=t.key,ua("selected",t.key),l.getState().connect(),u.start()}async pair(t,s){const r=s.trim().startsWith("linkshell:")?G2(s.trim()):void 0;if(s.trim().startsWith("linkshell:")&&!r)throw new Error("配对链接格式不正确");if(!r&&!/^\d{6}$/.test(s.trim()))throw new Error("请输入 6 位配对码");const o=om((r?.gateway??t).replace(/^http/,"ws")),l=this.relay(o),u=r?await AR(l,this.identity,r):await jR(l,this.identity,s.trim()),d={key:`${o}#${u.id}`,gateway:o,machine:u};this.paired=[...this.paired.filter(m=>m.key!==d.key),d],ua("paired",this.paired),ua("source","self-hosted"),ua("gateway",o),this.state.setState({source:"self-hosted",gateway:o}),await this.refresh(o),this.select(d)}async forget(t){await this.relay(t.gateway).request("machines.forget",{machineId:t.machine.id}),this.paired=this.paired.filter(s=>s.key!==t.key),ua("paired",this.paired),this.state.getState().connection?.computer.key===t.key&&this.disconnect(),this.state.setState(s=>({computers:s.computers.filter(r=>r.key!==t.key)}))}reconnect(){if(this.releaseLock){for(const t of this.relays.values())t.reconnectNow();this.state.getState().connection?.link.reconnectNow()}}disconnect(){const t=this.state.getState().connection;t?.streams.stop(),t?.store.getState().disconnect(),this.state.setState({connection:void 0})}stop(){this.generation++,this.disconnect();for(const t of this.relays.values())t.stop();this.relays.clear(),this.releaseLock?.(),this.releaseLock=void 0}}const Qt=new IR,HR={codex:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.503 0H4.496A4.496 4.496 0 000 4.496v15.007A4.496 4.496 0 004.496 24h15.007A4.496 4.496 0 0024 19.503V4.496A4.496 4.496 0 0019.503 0z" fill="#fff"></path><path d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" fill="url(#lobe-icons-codex-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-codex-_R_0_" x1="12" x2="12" y1="3" y2="21"><stop stop-color="#B1A7FF"></stop><stop offset=".5" stop-color="#7A9DFF"></stop><stop offset="1" stop-color="#3941FF"></stop></linearGradient></defs></svg>',full:!0},gemini:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 4.391A4.391 4.391 0 014.391 0h15.217A4.391 4.391 0 0124 4.391v15.217A4.391 4.391 0 0119.608 24H4.391A4.391 4.391 0 010 19.608V4.391z" fill="url(#lobe-icons-gemini-cli-_R_0_)"></path><path clip-rule="evenodd" d="M19.74 1.444a2.816 2.816 0 012.816 2.816v15.48a2.816 2.816 0 01-2.816 2.816H4.26a2.816 2.816 0 01-2.816-2.816V4.26A2.816 2.816 0 014.26 1.444h15.48zM7.236 8.564l7.752 3.728-7.752 3.727v2.802l9.557-4.596v-3.866L7.236 5.763v2.801z" fill="#1E1E2E" fill-rule="evenodd"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-cli-_R_0_" x1="24" x2="0" y1="6.587" y2="16.494"><stop stop-color="#EE4D5D"></stop><stop offset=".328" stop-color="#B381DD"></stop><stop offset=".476" stop-color="#207CFE"></stop></linearGradient></defs></svg>',full:!0},claude:{svg:'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path clip-rule="evenodd" d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z" fill="#D97757" fill-rule="evenodd"></path></svg>',full:!1,bg:{light:"#F4F1EA",dark:"#2A2926"}},copilot:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.245 5.364c1.322 1.36 1.877 3.216 2.11 5.817.622 0 1.2.135 1.592.654l.73.964c.21.278.323.61.323.955v2.62c0 .339-.173.669-.453.868C20.239 19.602 16.157 21.5 12 21.5c-4.6 0-9.205-2.583-11.547-4.258-.28-.2-.452-.53-.453-.868v-2.62c0-.345.113-.679.321-.956l.73-.963c.392-.517.974-.654 1.593-.654l.029-.297c.25-2.446.81-4.213 2.082-5.52 2.461-2.54 5.71-2.851 7.146-2.864h.198c1.436.013 4.685.323 7.146 2.864zm-7.244 4.328c-.284 0-.613.016-.962.05-.123.447-.305.85-.57 1.108-1.05 1.023-2.316 1.18-2.994 1.18-.638 0-1.306-.13-1.851-.464-.516.165-1.012.403-1.044.996a65.882 65.882 0 00-.063 2.884l-.002.48c-.002.563-.005 1.126-.013 1.69.002.326.204.63.51.765 2.482 1.102 4.83 1.657 6.99 1.657 2.156 0 4.504-.555 6.985-1.657a.854.854 0 00.51-.766c.03-1.682.006-3.372-.076-5.053-.031-.596-.528-.83-1.046-.996-.546.333-1.212.464-1.85.464-.677 0-1.942-.157-2.993-1.18-.266-.258-.447-.661-.57-1.108-.32-.032-.64-.049-.96-.05zm-2.525 4.013c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zm5 0c.539 0 .976.426.976.95v1.753c0 .525-.437.95-.976.95a.964.964 0 01-.976-.95v-1.752c0-.525.437-.951.976-.951zM7.635 5.087c-1.05.102-1.935.438-2.385.906-.975 1.037-.765 3.668-.21 4.224.405.394 1.17.657 1.995.657h.09c.649-.013 1.785-.176 2.73-1.11.435-.41.705-1.433.675-2.47-.03-.834-.27-1.52-.63-1.813-.39-.336-1.275-.482-2.265-.394zm6.465.394c-.36.292-.6.98-.63 1.813-.03 1.037.24 2.06.675 2.47.968.957 2.136 1.104 2.776 1.11h.044c.825 0 1.59-.263 1.995-.657.555-.556.765-3.187-.21-4.224-.45-.468-1.335-.804-2.385-.906-.99-.088-1.875.058-2.265.394zM12 7.615c-.24 0-.525.015-.84.044.03.16.045.336.06.526l-.001.159a2.94 2.94 0 01-.014.25c.225-.022.425-.027.612-.028h.366c.187 0 .387.006.612.028-.015-.146-.015-.277-.015-.409.015-.19.03-.365.06-.526a9.29 9.29 0 00-.84-.044z"></path></svg>',full:!1,bg:{light:"#0D1117",dark:"#F0F3F6"},fg:{light:"#FFFFFF",dark:"#0D1117"}},grok:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>',full:!1,bg:{light:"#000000",dark:"#FFFFFF"},fg:{light:"#FFFFFF",dark:"#000000"}},opencode:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M16 6H8v12h8V6zm4 16H4V2h16v20z"></path></svg>',full:!1,bg:{light:"#131010",dark:"#F1ECEC"},fg:{light:"#F1ECEC",dark:"#131010"}},cursor:{svg:'<svg fill="currentColor" fill-rule="evenodd" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M22.106 5.68L12.5.135a.998.998 0 00-.998 0L1.893 5.68a.84.84 0 00-.419.726v11.186c0 .3.16.577.42.727l9.607 5.547a.999.999 0 00.998 0l9.608-5.547a.84.84 0 00.42-.727V6.407a.84.84 0 00-.42-.726zm-.603 1.176L12.228 22.92c-.063.108-.228.064-.228-.061V12.34a.59.59 0 00-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264 0 .428.286.296.514z"></path></svg>',full:!1,bg:{light:"#14120B",dark:"#EDECEC"},fg:{light:"#EDECEC",dark:"#14120B"}}},Q2=b.createContext(null);function Lt(){const n=b.useContext(Q2);if(!n)throw new Error("尚未连接电脑");return n}function yt(n){return xd(Lt().store,n)}function Jn(){return Lt().store.getState()}const W2=n=>n instanceof Error?n.message:String(n),Wu=n=>n.replace(/\/$/,"").split("/").pop()??n,Cr=n=>n.title||Wu(n.cwd)||"未命名会话",VR=n=>({idle:"已完成",waiting:"需要你",running:"进行中",error:"出错",offline:"离线",completed:"已完成",failed:"失败",stopped:"已停止",pending:"等待中",active:"进行中",paused:"已暂停",complete:"已完成",blocked:"待处理",usageLimited:"用量受限",budgetLimited:"预算已用完",unknown:"未知"})[n]??n;function Cd({agent:n}){const t=HR[n.toLowerCase()];return f.jsx("span",{className:`agent-mark ${n.toLowerCase()} ${t?.full?"full-mark":""}`,children:t?f.jsx("img",{src:`data:image/svg+xml,${encodeURIComponent(t.svg.replaceAll("currentColor",t.fg?.light??"#333"))}`,alt:n}):n.slice(0,1).toUpperCase()})}function Ur({state:n}){return f.jsxs("span",{className:`badge ${n==="idle"||n==="completed"?"done":n}`,children:[f.jsx("span",{className:"status-dot"}),VR(n)]})}function Dt({error:n}){return n?f.jsx("p",{role:"alert",className:"form-error",children:n}):null}function El({title:n,children:t,close:s,wide:r=!1,returnFocus:o}){return f.jsx(FS,{open:!0,onOpenChange:l=>{l||s()},children:f.jsxs(GS,{onCloseAutoFocus:o?l=>{l.preventDefault(),o()}:void 0,className:qe("max-h-[85dvh] overflow-y-auto p-6 sm:max-w-xl",r&&"sm:max-w-5xl"),children:[f.jsxs(ZS,{children:[f.jsx(YS,{children:n}),f.jsxs(KS,{className:"sr-only",children:[n,"设置与操作"]})]}),t]})})}function Wt(){const[n,t]=b.useState(),[s,r]=b.useState(!1),o=b.useRef(!1);async function l(u){if(!o.current){o.current=!0,r(!0),t(void 0);try{return await u()}catch(d){t(W2(d))}finally{o.current=!1,r(!1)}}}return{error:n,busy:s,run:l,clear:()=>t(void 0)}}function ea(n,t,s=0){const[r,o]=b.useState({loading:!0}),[l,u]=b.useState(0),d=b.useRef(n);return d.current=n,b.useEffect(()=>{let m=!0,p=!1;const y=async()=>{if(!p){p=!0;try{const x=await d.current();m&&o({value:x,loading:!1})}catch(x){m&&o(_=>({..._,error:W2(x),loading:!1}))}finally{p=!1}}};o({loading:!0}),y();const v=s?setInterval(()=>void y(),s):void 0;return()=>{m=!1,clearInterval(v)}},[...t,l,s]),{...r,reload:()=>u(m=>m+1)}}function ba({loading:n,error:t}){return f.jsxs(f.Fragment,{children:[n&&f.jsx("p",{className:"muted loading-copy",role:"status",children:"正在加载…"}),f.jsx(Dt,{error:t})]})}function qR({found:n}){const t=b.useRef(null),[s,r]=b.useState(!1),[o,l]=b.useState(),u=b.useRef(n);u.current=n;function d(p){if(!G2(p)){l("这不是有效的 LinkShell 配对二维码");return}u.current(p),r(!1),l(void 0)}const m=b.useRef(d);return m.current=d,b.useEffect(()=>{if(!s||!t.current)return;let p=!1,y;return Ym(()=>import("./qr-scanner.min--SdQwB7X.js"),__vite__mapDeps([0,1,2,3,4])).then(async({default:v})=>{p||!t.current||(y=new v(t.current,x=>m.current(x.data),{preferredCamera:"environment",returnDetailedScanResult:!0,highlightScanRegion:!0}),await y.start())}).catch(v=>{p||(l(v instanceof Error?v.message:"无法打开摄像头,请使用图片或配对码"),r(!1))}),()=>{p=!0,y?.destroy()}},[s]),f.jsxs("div",{className:"qr-scan",children:[f.jsxs("div",{className:"permission-buttons",children:[f.jsx("button",{className:"button secondary",type:"button",onClick:()=>r(!s),children:s?"关闭摄像头":"扫描二维码"}),f.jsxs("label",{className:"button secondary",children:["从图片识别",f.jsx("input",{type:"file",accept:"image/*",hidden:!0,onChange:p=>{const y=p.target.files?.[0];p.target.value="",y&&Ym(()=>import("./qr-scanner.min--SdQwB7X.js"),__vite__mapDeps([0,1,2,3,4])).then(v=>v.default.scanImage(y,{returnDetailedScanResult:!0})).then(v=>d(v.data),()=>l("没有识别到二维码,请换一张图片或输入配对码"))}})]})]}),s&&f.jsx("video",{ref:t,className:"qr-video",muted:!0,playsInline:!0}),f.jsx(Dt,{error:o})]})}function $R({close:n}){const t=xd(Qt.state),[s,r]=b.useState(t.source),[o,l]=b.useState(""),[u,d]=b.useState(""),[m,p]=b.useState(s==="self-hosted"?t.gateway:""),[y,v]=b.useState(""),x=Wt();return f.jsxs(El,{title:"连接你的电脑",close:n,children:[f.jsx("p",{className:"muted modal-subtitle",children:"电脑保持运行,网页即可继续你的会话。"}),qs==="official"&&f.jsxs("div",{className:"source-options",children:[f.jsxs("button",{className:`source-option ${s==="official"?"selected":""}`,"aria-pressed":s==="official",onClick:()=>r("official"),children:[f.jsx(_t,{name:"globe"}),f.jsx("strong",{children:"官方账号"}),f.jsx("span",{children:"同一 iTool 账号发现电脑"})]}),f.jsxs("button",{className:`source-option ${s==="self-hosted"?"selected":""}`,"aria-pressed":s==="self-hosted",onClick:()=>r("self-hosted"),children:[f.jsx(_t,{name:"server"}),f.jsx("strong",{children:"配对电脑"}),f.jsx("span",{children:"官方或自托管网关的配对码"})]})]}),s==="official"?f.jsxs("form",{className:"new-form",onSubmit:_=>{_.preventDefault(),x.run(async()=>{const E=await hl().auth.signInWithPassword({email:o.trim(),password:u});if(E.error)throw E.error;await Qt.connectAccount(),n()})},children:[t.account?f.jsx("div",{className:"private-note",children:f.jsxs("div",{children:[f.jsx("strong",{children:t.account}),f.jsx("p",{children:"电脑端运行 linkshell login,使用同一账号。电脑接入官方网关需要 Pro 订阅。"}),f.jsx("button",{type:"button",className:"text-button",onClick:()=>void x.run(async()=>{await Qt.connectAccount(),n()}),children:"刷新账号电脑"})]})}):f.jsxs(f.Fragment,{children:[f.jsx("label",{htmlFor:"email",children:"邮箱"}),f.jsx("input",{id:"email",type:"email",autoComplete:"username",value:o,onChange:_=>l(_.target.value),required:!0}),f.jsx("label",{htmlFor:"password",children:"密码"}),f.jsx("input",{id:"password",type:"password",autoComplete:"current-password",value:u,onChange:_=>d(_.target.value),required:!0}),f.jsx("button",{className:"button primary full",disabled:x.busy,children:"登录"}),f.jsx("div",{className:"form-columns",children:["github","google"].map(_=>f.jsx("button",{type:"button",className:"button secondary",disabled:x.busy,onClick:()=>void x.run(async()=>{const E=await hl().auth.signInWithOAuth({provider:_,options:{redirectTo:location.origin+location.pathname}});if(E.error)throw E.error}),children:_==="github"?"GitHub 登录":"Google 登录"},_))}),f.jsxs("p",{className:"field-hint",children:["登录状态自动续期。",f.jsx("a",{href:"https://itool.tech/zh/register",target:"_blank",rel:"noreferrer",children:"注册 iTool 账号 ↗"})]})]}),t.account&&f.jsx("button",{type:"button",className:"button secondary full",disabled:x.busy,onClick:()=>void x.run(async()=>{const _=await hl().auth.signOut({scope:"local"});if(_.error)throw _.error;Qt.disconnect()}),children:"退出本浏览器账号"})]}):f.jsxs("form",{className:"pairing-form",onSubmit:_=>{_.preventDefault(),x.run(async()=>{await Qt.pair(m,y),n()})},children:[f.jsx(qR,{found:v}),f.jsx("label",{htmlFor:"gateway",children:"网关地址"}),f.jsx("input",{id:"gateway",placeholder:"wss://gateway.example.com",value:m,onChange:_=>p(_.target.value),required:!y.startsWith("linkshell:")}),f.jsx("p",{className:"field-hint",children:"电脑需先连接同一个网关。"}),f.jsx("label",{htmlFor:"pairing",children:"配对码或配对链接"}),f.jsx("input",{id:"pairing",value:y,onChange:_=>v(_.target.value),placeholder:"6 位配对码,或粘贴 linkshell://pair 链接",required:!0}),f.jsxs("p",{className:"field-hint",children:["在电脑运行 ",f.jsx("code",{children:"linkshell pair"}),"。有效期 10 分钟,成功后此浏览器会记住设备。"]}),f.jsx("button",{className:"button primary full",disabled:x.busy||t.locked,children:"配对并连接"}),f.jsx("p",{className:"field-hint",children:"自托管不使用 iTool 登录凭证。清除网站数据后需要重新配对。"})]}),f.jsx(Dt,{error:x.error}),x.busy&&f.jsx("p",{className:"muted",role:"status",children:"正在连接…"})]})}function PR({...n}){return f.jsx(jk,{"data-slot":"popover",...n})}function FR({className:n,align:t="center",sideOffset:s=4,...r}){return f.jsx(Rk,{children:f.jsx(Dk,{"data-slot":"popover-content",align:t,sideOffset:s,className:qe("z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",n),...r})})}function GR({...n}){return f.jsx(kk,{"data-slot":"popover-anchor",...n})}var i1=1,ZR=.9,YR=.8,KR=.17,bm=.1,xm=.999,XR=.9999,QR=.99,WR=/[\\\/_+.#"@\[\(\{&]/,JR=/[\\\/_+.#"@\[\(\{&]/g,eD=/[\s-]/,J2=/[\s-]/g;function fp(n,t,s,r,o,l,u){if(l===t.length)return o===n.length?i1:QR;var d=`${o},${l}`;if(u[d]!==void 0)return u[d];for(var m=r.charAt(l),p=s.indexOf(m,o),y=0,v,x,_,E;p>=0;)v=fp(n,t,s,r,p+1,l+1,u),v>y&&(p===o?v*=i1:WR.test(n.charAt(p-1))?(v*=YR,_=n.slice(o,p-1).match(JR),_&&o>0&&(v*=Math.pow(xm,_.length))):eD.test(n.charAt(p-1))?(v*=ZR,E=n.slice(o,p-1).match(J2),E&&o>0&&(v*=Math.pow(xm,E.length))):(v*=KR,o>0&&(v*=Math.pow(xm,p-o))),n.charAt(p)!==t.charAt(l)&&(v*=XR)),(v<bm&&s.charAt(p-1)===r.charAt(l+1)||r.charAt(l+1)===r.charAt(l)&&s.charAt(p-1)!==r.charAt(l))&&(x=fp(n,t,s,r,p+1,l+2,u),x*bm>v&&(v=x*bm)),v>y&&(y=v),p=s.indexOf(m,p+1);return u[d]=y,y}function o1(n){return n.toLowerCase().replace(J2," ")}function tD(n,t,s){return n=s&&s.length>0?`${n+" "+s.join(" ")}`:n,fp(n,t,o1(n),o1(t),0,0,{})}function Is(n,t,{checkForDefaultPrevented:s=!0}={}){return function(o){if(n?.(o),s===!1||!o.defaultPrevented)return t?.(o)}}function l1(n,t){if(typeof n=="function")return n(t);n!=null&&(n.current=t)}function Br(...n){return t=>{let s=!1;const r=n.map(o=>{const l=l1(o,t);return!s&&typeof l=="function"&&(s=!0),l});if(s)return()=>{for(let o=0;o<r.length;o++){const l=r[o];typeof l=="function"?l():l1(n[o],null)}}}}function Kr(...n){return b.useCallback(Br(...n),n)}function nD(n,t){const s=b.createContext(t),r=l=>{const{children:u,...d}=l,m=b.useMemo(()=>d,Object.values(d));return f.jsx(s.Provider,{value:m,children:u})};r.displayName=n+"Provider";function o(l){const u=b.useContext(s);if(u)return u;if(t!==void 0)return t;throw new Error(`\`${l}\` must be used within \`${n}\``)}return[r,o]}function aD(n,t=[]){let s=[];function r(l,u){const d=b.createContext(u),m=s.length;s=[...s,u];const p=v=>{const{scope:x,children:_,...E}=v,A=x?.[n]?.[m]||d,S=b.useMemo(()=>E,Object.values(E));return f.jsx(A.Provider,{value:S,children:_})};p.displayName=l+"Provider";function y(v,x){const _=x?.[n]?.[m]||d,E=b.useContext(_);if(E)return E;if(u!==void 0)return u;throw new Error(`\`${v}\` must be used within \`${l}\``)}return[p,y]}const o=()=>{const l=s.map(u=>b.createContext(u));return function(d){const m=d?.[n]||l;return b.useMemo(()=>({[`__scope${n}`]:{...d,[n]:m}}),[d,m])}};return o.scopeName=n,[r,sD(o,...t)]}function sD(...n){const t=n[0];if(n.length===1)return t;const s=()=>{const r=n.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(l){const u=r.reduce((d,{useScope:m,scopeName:p})=>{const v=m(l)[`__scope${p}`];return{...d,...v}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return s.scopeName=t.scopeName,s}var _l=globalThis?.document?b.useLayoutEffect:()=>{},rD=Zs[" useId ".trim().toString()]||(()=>{}),iD=0;function Ya(n){const[t,s]=b.useState(rD());return _l(()=>{s(r=>r??String(iD++))},[n]),t?`radix-${t}`:""}var oD=Zs[" useInsertionEffect ".trim().toString()]||_l;function lD({prop:n,defaultProp:t,onChange:s=()=>{},caller:r}){const[o,l,u]=cD({defaultProp:t,onChange:s}),d=n!==void 0,m=d?n:o;{const y=b.useRef(n!==void 0);b.useEffect(()=>{const v=y.current;v!==d&&console.warn(`${r} is changing from ${v?"controlled":"uncontrolled"} to ${d?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=d},[d,r])}const p=b.useCallback(y=>{if(d){const v=uD(y)?y(n):y;v!==n&&u.current?.(v)}else l(y)},[d,n,l,u]);return[m,p]}function cD({defaultProp:n,onChange:t}){const[s,r]=b.useState(n),o=b.useRef(s),l=b.useRef(t);return oD(()=>{l.current=t},[t]),b.useEffect(()=>{o.current!==s&&(l.current?.(s),o.current=s)},[s,o]),[s,r,l]}function uD(n){return typeof n=="function"}function eE(n){const t=dD(n),s=b.forwardRef((r,o)=>{const{children:l,...u}=r,d=b.Children.toArray(l),m=d.find(hD);if(m){const p=m.props.children,y=d.map(v=>v===m?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:v);return f.jsx(t,{...u,ref:o,children:b.isValidElement(p)?b.cloneElement(p,void 0,y):null})}return f.jsx(t,{...u,ref:o,children:l})});return s.displayName=`${n}.Slot`,s}function dD(n){const t=b.forwardRef((s,r)=>{const{children:o,...l}=s;if(b.isValidElement(o)){const u=pD(o),d=mD(l,o.props);return o.type!==b.Fragment&&(d.ref=r?Br(r,u):u),b.cloneElement(o,d)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${n}.SlotClone`,t}var fD=Symbol("radix.slottable");function hD(n){return b.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===fD}function mD(n,t){const s={...t};for(const r in t){const o=n[r],l=t[r];/^on[A-Z]/.test(r)?o&&l?s[r]=(...d)=>{const m=l(...d);return o(...d),m}:o&&(s[r]=o):r==="style"?s[r]={...o,...l}:r==="className"&&(s[r]=[o,l].filter(Boolean).join(" "))}return{...n,...s}}function pD(n){let t=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?n.ref:(t=Object.getOwnPropertyDescriptor(n,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?n.props.ref:n.props.ref||n.ref)}var gD=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Jt=gD.reduce((n,t)=>{const s=eE(`Primitive.${t}`),r=b.forwardRef((o,l)=>{const{asChild:u,...d}=o,m=u?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(m,{...d,ref:l})});return r.displayName=`Primitive.${t}`,{...n,[t]:r}},{});function vD(n,t){n&&qr.flushSync(()=>n.dispatchEvent(t))}function Cl(n){const t=b.useRef(n);return b.useEffect(()=>{t.current=n}),b.useMemo(()=>(...s)=>t.current?.(...s),[])}function yD(n,t=globalThis?.document){const s=Cl(n);b.useEffect(()=>{const r=o=>{o.key==="Escape"&&s(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[s,t])}var bD="DismissableLayer",hp="dismissableLayer.update",xD="dismissableLayer.pointerDownOutside",wD="dismissableLayer.focusOutside",c1,tE=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),nE=b.forwardRef((n,t)=>{const{disableOutsidePointerEvents:s=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...m}=n,p=b.useContext(tE),[y,v]=b.useState(null),x=y?.ownerDocument??globalThis?.document,[,_]=b.useState({}),E=Kr(t,M=>v(M)),A=Array.from(p.layers),[S]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),j=A.indexOf(S),T=y?A.indexOf(y):-1,k=p.layersWithOutsidePointerEventsDisabled.size>0,C=T>=j,R=_D(M=>{const z=M.target,L=[...p.branches].some(q=>q.contains(z));!C||L||(o?.(M),u?.(M),M.defaultPrevented||d?.())},x),O=CD(M=>{const z=M.target;[...p.branches].some(q=>q.contains(z))||(l?.(M),u?.(M),M.defaultPrevented||d?.())},x);return yD(M=>{T===p.layers.size-1&&(r?.(M),!M.defaultPrevented&&d&&(M.preventDefault(),d()))},x),b.useEffect(()=>{if(y)return s&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(c1=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),u1(),()=>{s&&p.layersWithOutsidePointerEventsDisabled.size===1&&(x.body.style.pointerEvents=c1)}},[y,x,s,p]),b.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),u1())},[y,p]),b.useEffect(()=>{const M=()=>_({});return document.addEventListener(hp,M),()=>document.removeEventListener(hp,M)},[]),f.jsx(Jt.div,{...m,ref:E,style:{pointerEvents:k?C?"auto":"none":void 0,...n.style},onFocusCapture:Is(n.onFocusCapture,O.onFocusCapture),onBlurCapture:Is(n.onBlurCapture,O.onBlurCapture),onPointerDownCapture:Is(n.onPointerDownCapture,R.onPointerDownCapture)})});nE.displayName=bD;var SD="DismissableLayerBranch",ED=b.forwardRef((n,t)=>{const s=b.useContext(tE),r=b.useRef(null),o=Kr(t,r);return b.useEffect(()=>{const l=r.current;if(l)return s.branches.add(l),()=>{s.branches.delete(l)}},[s.branches]),f.jsx(Jt.div,{...n,ref:o})});ED.displayName=SD;function _D(n,t=globalThis?.document){const s=Cl(n),r=b.useRef(!1),o=b.useRef(()=>{});return b.useEffect(()=>{const l=d=>{if(d.target&&!r.current){let m=function(){aE(xD,s,p,{discrete:!0})};const p={originalEvent:d};d.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},u=window.setTimeout(()=>{t.addEventListener("pointerdown",l)},0);return()=>{window.clearTimeout(u),t.removeEventListener("pointerdown",l),t.removeEventListener("click",o.current)}},[t,s]),{onPointerDownCapture:()=>r.current=!0}}function CD(n,t=globalThis?.document){const s=Cl(n),r=b.useRef(!1);return b.useEffect(()=>{const o=l=>{l.target&&!r.current&&aE(wD,s,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function u1(){const n=new CustomEvent(hp);document.dispatchEvent(n)}function aE(n,t,s,{discrete:r}){const o=s.originalEvent.target,l=new CustomEvent(n,{bubbles:!1,cancelable:!0,detail:s});t&&o.addEventListener(n,t,{once:!0}),r?vD(o,l):o.dispatchEvent(l)}var wm="focusScope.autoFocusOnMount",Sm="focusScope.autoFocusOnUnmount",d1={bubbles:!1,cancelable:!0},AD="FocusScope",sE=b.forwardRef((n,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:l,...u}=n,[d,m]=b.useState(null),p=Cl(o),y=Cl(l),v=b.useRef(null),x=Kr(t,A=>m(A)),_=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(r){let A=function(k){if(_.paused||!d)return;const C=k.target;d.contains(C)?v.current=C:Ms(v.current,{select:!0})},S=function(k){if(_.paused||!d)return;const C=k.relatedTarget;C!==null&&(d.contains(C)||Ms(v.current,{select:!0}))},j=function(k){if(document.activeElement===document.body)for(const R of k)R.removedNodes.length>0&&Ms(d)};document.addEventListener("focusin",A),document.addEventListener("focusout",S);const T=new MutationObserver(j);return d&&T.observe(d,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",S),T.disconnect()}}},[r,d,_.paused]),b.useEffect(()=>{if(d){h1.add(_);const A=document.activeElement;if(!d.contains(A)){const j=new CustomEvent(wm,d1);d.addEventListener(wm,p),d.dispatchEvent(j),j.defaultPrevented||(jD(RD(rE(d)),{select:!0}),document.activeElement===A&&Ms(d))}return()=>{d.removeEventListener(wm,p),setTimeout(()=>{const j=new CustomEvent(Sm,d1);d.addEventListener(Sm,y),d.dispatchEvent(j),j.defaultPrevented||Ms(A??document.body,{select:!0}),d.removeEventListener(Sm,y),h1.remove(_)},0)}}},[d,p,y,_]);const E=b.useCallback(A=>{if(!s&&!r||_.paused)return;const S=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,j=document.activeElement;if(S&&j){const T=A.currentTarget,[k,C]=TD(T);k&&C?!A.shiftKey&&j===C?(A.preventDefault(),s&&Ms(k,{select:!0})):A.shiftKey&&j===k&&(A.preventDefault(),s&&Ms(C,{select:!0})):j===T&&A.preventDefault()}},[s,r,_.paused]);return f.jsx(Jt.div,{tabIndex:-1,...u,ref:x,onKeyDown:E})});sE.displayName=AD;function jD(n,{select:t=!1}={}){const s=document.activeElement;for(const r of n)if(Ms(r,{select:t}),document.activeElement!==s)return}function TD(n){const t=rE(n),s=f1(t,n),r=f1(t.reverse(),n);return[s,r]}function rE(n){const t=[],s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function f1(n,t){for(const s of n)if(!kD(s,{upTo:t}))return s}function kD(n,{upTo:t}){if(getComputedStyle(n).visibility==="hidden")return!0;for(;n;){if(t!==void 0&&n===t)return!1;if(getComputedStyle(n).display==="none")return!0;n=n.parentElement}return!1}function ND(n){return n instanceof HTMLInputElement&&"select"in n}function Ms(n,{select:t=!1}={}){if(n&&n.focus){const s=document.activeElement;n.focus({preventScroll:!0}),n!==s&&ND(n)&&t&&n.select()}}var h1=OD();function OD(){let n=[];return{add(t){const s=n[0];t!==s&&s?.pause(),n=m1(n,t),n.unshift(t)},remove(t){n=m1(n,t),n[0]?.resume()}}}function m1(n,t){const s=[...n],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function RD(n){return n.filter(t=>t.tagName!=="A")}var DD="Portal",iE=b.forwardRef((n,t)=>{const{container:s,...r}=n,[o,l]=b.useState(!1);_l(()=>l(!0),[]);const u=s||o&&globalThis?.document?.body;return u?cj.createPortal(f.jsx(Jt.div,{...r,ref:t}),u):null});iE.displayName=DD;function MD(n,t){return b.useReducer((s,r)=>t[s][r]??s,n)}var Ad=n=>{const{present:t,children:s}=n,r=zD(t),o=typeof s=="function"?s({present:r.isPresent}):b.Children.only(s),l=Kr(r.ref,LD(o));return typeof s=="function"||r.isPresent?b.cloneElement(o,{ref:l}):null};Ad.displayName="Presence";function zD(n){const[t,s]=b.useState(),r=b.useRef(null),o=b.useRef(n),l=b.useRef("none"),u=n?"mounted":"unmounted",[d,m]=MD(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const p=mu(r.current);l.current=d==="mounted"?p:"none"},[d]),_l(()=>{const p=r.current,y=o.current;if(y!==n){const x=l.current,_=mu(p);n?m("MOUNT"):_==="none"||p?.display==="none"?m("UNMOUNT"):m(y&&x!==_?"ANIMATION_OUT":"UNMOUNT"),o.current=n}},[n,m]),_l(()=>{if(t){let p;const y=t.ownerDocument.defaultView??window,v=_=>{const A=mu(r.current).includes(CSS.escape(_.animationName));if(_.target===t&&A&&(m("ANIMATION_END"),!o.current)){const S=t.style.animationFillMode;t.style.animationFillMode="forwards",p=y.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=S)})}},x=_=>{_.target===t&&(l.current=mu(r.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",v),t.addEventListener("animationend",v),()=>{y.clearTimeout(p),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",v),t.removeEventListener("animationend",v)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:b.useCallback(p=>{r.current=p?getComputedStyle(p):null,s(p)},[])}}function mu(n){return n?.animationName||"none"}function LD(n){let t=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning;return s?n.ref:(t=Object.getOwnPropertyDescriptor(n,"ref")?.get,s=t&&"isReactWarning"in t&&t.isReactWarning,s?n.props.ref:n.props.ref||n.ref)}var Em=0;function UD(){b.useEffect(()=>{const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",n[0]??p1()),document.body.insertAdjacentElement("beforeend",n[1]??p1()),Em++,()=>{Em===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Em--}},[])}function p1(){const n=document.createElement("span");return n.setAttribute("data-radix-focus-guard",""),n.tabIndex=0,n.style.outline="none",n.style.opacity="0",n.style.position="fixed",n.style.pointerEvents="none",n}var jd="Dialog",[oE]=aD(jd),[BD,ta]=oE(jd),lE=n=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:o,onOpenChange:l,modal:u=!0}=n,d=b.useRef(null),m=b.useRef(null),[p,y]=lD({prop:r,defaultProp:o??!1,onChange:l,caller:jd});return f.jsx(BD,{scope:t,triggerRef:d,contentRef:m,contentId:Ya(),titleId:Ya(),descriptionId:Ya(),open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(v=>!v),[y]),modal:u,children:s})};lE.displayName=jd;var cE="DialogTrigger",ID=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(cE,s),l=Kr(t,o.triggerRef);return f.jsx(Jt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":fg(o.open),...r,ref:l,onClick:Is(n.onClick,o.onOpenToggle)})});ID.displayName=cE;var ug="DialogPortal",[HD,uE]=oE(ug,{forceMount:void 0}),dE=n=>{const{__scopeDialog:t,forceMount:s,children:r,container:o}=n,l=ta(ug,t);return f.jsx(HD,{scope:t,forceMount:s,children:b.Children.map(r,u=>f.jsx(Ad,{present:s||l.open,children:f.jsx(iE,{asChild:!0,container:o,children:u})}))})};dE.displayName=ug;var Ju="DialogOverlay",fE=b.forwardRef((n,t)=>{const s=uE(Ju,n.__scopeDialog),{forceMount:r=s.forceMount,...o}=n,l=ta(Ju,n.__scopeDialog);return l.modal?f.jsx(Ad,{present:r||l.open,children:f.jsx(qD,{...o,ref:t})}):null});fE.displayName=Ju;var VD=eE("DialogOverlay.RemoveScroll"),qD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(Ju,s);return f.jsx(so,{as:VD,allowPinchZoom:!0,shards:[o.contentRef],children:f.jsx(Jt.div,{"data-state":fg(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ir="DialogContent",hE=b.forwardRef((n,t)=>{const s=uE(Ir,n.__scopeDialog),{forceMount:r=s.forceMount,...o}=n,l=ta(Ir,n.__scopeDialog);return f.jsx(Ad,{present:r||l.open,children:l.modal?f.jsx($D,{...o,ref:t}):f.jsx(PD,{...o,ref:t})})});hE.displayName=Ir;var $D=b.forwardRef((n,t)=>{const s=ta(Ir,n.__scopeDialog),r=b.useRef(null),o=Kr(t,s.contentRef,r);return b.useEffect(()=>{const l=r.current;if(l)return jl(l)},[]),f.jsx(mE,{...n,ref:o,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Is(n.onCloseAutoFocus,l=>{l.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Is(n.onPointerDownOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0;(u.button===2||d)&&l.preventDefault()}),onFocusOutside:Is(n.onFocusOutside,l=>l.preventDefault())})}),PD=b.forwardRef((n,t)=>{const s=ta(Ir,n.__scopeDialog),r=b.useRef(!1),o=b.useRef(!1);return f.jsx(mE,{...n,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{n.onCloseAutoFocus?.(l),l.defaultPrevented||(r.current||s.triggerRef.current?.focus(),l.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:l=>{n.onInteractOutside?.(l),l.defaultPrevented||(r.current=!0,l.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=l.target;s.triggerRef.current?.contains(u)&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&o.current&&l.preventDefault()}})}),mE=b.forwardRef((n,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:l,...u}=n,d=ta(Ir,s),m=b.useRef(null),p=Kr(t,m);return UD(),f.jsxs(f.Fragment,{children:[f.jsx(sE,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:l,children:f.jsx(nE,{role:"dialog",id:d.contentId,"aria-describedby":d.descriptionId,"aria-labelledby":d.titleId,"data-state":fg(d.open),...u,ref:p,onDismiss:()=>d.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(YD,{titleId:d.titleId}),f.jsx(XD,{contentRef:m,descriptionId:d.descriptionId})]})]})}),dg="DialogTitle",FD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(dg,s);return f.jsx(Jt.h2,{id:o.titleId,...r,ref:t})});FD.displayName=dg;var pE="DialogDescription",GD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(pE,s);return f.jsx(Jt.p,{id:o.descriptionId,...r,ref:t})});GD.displayName=pE;var gE="DialogClose",ZD=b.forwardRef((n,t)=>{const{__scopeDialog:s,...r}=n,o=ta(gE,s);return f.jsx(Jt.button,{type:"button",...r,ref:t,onClick:Is(n.onClick,()=>o.onOpenChange(!1))})});ZD.displayName=gE;function fg(n){return n?"open":"closed"}var vE="DialogTitleWarning",[W8,yE]=nD(vE,{contentName:Ir,titleName:dg,docsSlug:"dialog"}),YD=({titleId:n})=>{const t=yE(vE),s=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
160
160
 
161
161
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
162
162
 
@@ -164,7 +164,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
164
164
  `).map((t,s)=>f.jsxs("span",{className:t.startsWith("+")?"diff-add-line":t.startsWith("-")?"diff-remove-line":"",children:[t,`
165
165
  `]},s))})]})}function NM({blocks:n,sessionId:t,onFile:s}){const r=n.length===1&&n[0].type==="text"?n[0].text:void 0,o=r===void 0?void 0:JS(r);return o?f.jsx(f.Fragment,{children:o.map((l,u)=>f.jsxs("div",{className:"question-reply",children:[f.jsx("small",{children:l.question}),f.jsx("p",{children:l.answer})]},u))}):f.jsx(gp,{blocks:n,sessionId:t,onFile:s})}function OM({questions:n,answered:t,onAnswer:s}){const[r,o]=b.useState({});return f.jsx("div",{className:"async-questions",children:n.map(l=>{if(l.options.length===0)return null;const u=r[l.id]??t.get(l.id),d=u!==void 0;return f.jsxs("div",{children:[n.length>1&&f.jsx("small",{children:l.title}),f.jsx("div",{className:"async-options",children:l.options.map(m=>f.jsx("button",{type:"button",disabled:d,"aria-pressed":u===m,className:u===m?"chosen":void 0,onClick:()=>{o(p=>({...p,[l.id]:m})),s(l,m)},children:m},m))})]},l.id)})})}function mg({items:n,sessionId:t,agent:s,onFile:r,onFork:o,onTerminal:l}){const u=Jn(),d=Wt(),m=b.useRef(null),[p,y]=b.useState(!1),v=p?n:n.slice(-180),x=new Map(n.flatMap(E=>E.kind==="user"?E.blocks.flatMap(A=>A.type==="text"?gN(A.text):[]):[])),_=(E,A)=>void d.run(()=>u.send(t,[{type:"text",text:pN([{question:E,answer:A}])}]));return f.jsxs("div",{className:"live-timeline",children:[n.length>v.length&&f.jsxs("button",{className:"text-button",onClick:()=>y(!0),children:["显示本次已加载的更早消息(",n.length-v.length,")"]}),v.map(E=>E.kind==="turn-end"||E.kind==="driver"?f.jsx("p",{className:"timeline-divider",children:E.kind==="driver"?`会话控制:${E.driver==="desktop"?"电脑端":E.driver==="remote"?"远程端":"空闲"}`:E.stopReason==="cancelled"?"本轮已停止":E.stopReason==="error"?"本轮执行失败":"本轮结束"},E.id):E.kind==="user"?f.jsxs("article",{className:"user-message",children:[f.jsxs("span",{className:"message-label",children:["你"," ",f.jsxs("small",{children:[new Date(E.ts).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),E.pending?" · 发送中":""]})]}),f.jsx(NM,{blocks:E.blocks,sessionId:t,onFile:r}),E.failed&&f.jsxs("div",{children:[f.jsx("span",{className:"form-error",children:"发送失败,草稿仍在"}),f.jsx("button",{className:"text-button",onClick:()=>void d.run(()=>u.retry(E.id)),children:"重试"}),f.jsx("button",{className:"text-button",onClick:()=>u.discard(E.id),children:"移除"})]}),o&&!E.pending&&f.jsx("button",{className:"message-fork",onClick:()=>o(E.id),children:"从这里分叉"})]},E.id):E.kind==="agent"?f.jsxs("article",{className:"assistant-message",children:[f.jsxs("div",{className:"message-author",children:[f.jsx(Cd,{agent:s}),f.jsx("strong",{children:s}),E.streaming&&f.jsx("span",{children:"正在回复…"})]}),f.jsx(pp,{text:E.text}),E.questions&&!E.streaming&&f.jsx(OM,{questions:E.questions,answered:x,onAnswer:_}),E.attachments&&f.jsx(gp,{blocks:E.attachments,sessionId:t,onFile:r}),o&&!E.streaming&&f.jsx("button",{className:"message-fork",onClick:()=>o(E.id),children:"从这里分叉"})]},E.id):E.kind==="thought"?f.jsxs("details",{className:"thought-block",children:[f.jsx("summary",{children:E.streaming?"正在思考…":"思考过程"}),f.jsx(pp,{text:E.text})]},E.id):E.kind==="notice"||E.kind==="error"?f.jsxs("section",{className:`notice-card ${E.kind}`,children:[f.jsx("strong",{children:E.kind==="notice"?E.title:E.message}),f.jsx("pre",{children:E.kind==="notice"?E.detail:E.hint})]},E.id):E.kind==="plan"?f.jsxs("section",{className:"plan-card",children:[f.jsx("strong",{children:"执行计划"}),f.jsx("ul",{children:E.entries.map((A,S)=>f.jsxs("li",{children:[f.jsx("span",{children:A.status==="completed"?"✓":A.status==="in_progress"?"◉":"○"}),A.content]},S))})]},E.id):E.kind==="permission-result"?f.jsxs("details",{className:"notice-card",children:[f.jsxs("summary",{children:[E.asked?"已回答":E.allowed?"已允许":"已拒绝"," ·"," ",E.title]}),f.jsx("p",{children:E.optionName}),E.answers?.map((A,S)=>f.jsxs("p",{children:[A.question,":",A.answer]},S))]},E.id):f.jsxs("details",{className:`tool-record ${E.status}`,children:[f.jsxs("summary",{children:[f.jsx("span",{className:"tool-state",children:E.status==="completed"?"✓":E.status==="failed"?"!":"◌"}),f.jsx("strong",{children:E.title}),f.jsx("small",{children:E.detail?.type==="mcp"?`MCP · ${E.detail.server}`:E.status==="in_progress"?"执行中":""})]}),E.detail?.type==="mcp"&&f.jsxs("p",{className:"muted",children:["服务:",E.detail.server," · 工具:",E.detail.tool]}),E.output&&f.jsx("pre",{className:"tool-output-text",children:E.output}),E.content.map((A,S)=>A.type==="content"?f.jsx(gp,{blocks:[A.content],sessionId:t,onFile:r},S):A.type==="terminal"?f.jsx("button",{className:"text-button",onClick:()=>l?.(A.terminalId),children:"打开关联终端"},S):f.jsx(UE,{change:A},S)),E.locations?.map((A,S)=>f.jsxs("button",{className:"resource-chip",onClick:()=>r(A.path),children:[A.path,A.line?`:${A.line}`:""]},S)),E.rawInput!==void 0&&f.jsxs("details",{children:[f.jsx("summary",{children:"工具参数"}),f.jsx("pre",{children:JSON.stringify(E.rawInput,null,2)})]}),E.rawOutput!==void 0&&f.jsxs("details",{children:[f.jsx("summary",{children:"原始结果"}),f.jsx("pre",{children:JSON.stringify(E.rawOutput,null,2)})]}),E.sub&&f.jsx(mg,{items:E.sub.items,sessionId:t,agent:s,onFile:r,onTerminal:l})]},E.id)),f.jsx(Dt,{error:d.error}),f.jsx("div",{ref:m})]})}async function pg(n){if(n.size>30*1024*1024)throw new Error(`${n.name} 超过 30 MB`);return new Promise((t,s)=>{const r=new FileReader;r.onerror=()=>s(new Error("文件读取失败")),r.onload=()=>t(String(r.result).split(",")[1]??""),r.readAsDataURL(n)})}function BE({path:n,line:t}){const s=b.useRef(null),{link:r}=Lt(),o=Wt(),l=ea(()=>r.call("fs.read",{path:n}),[r,n]),[u,d]=b.useState(),m=l.value,p=u?.path===n?u:void 0;return b.useEffect(()=>{s.current?.scrollIntoView({block:"center"})},[n,t,m,p]),f.jsxs("div",{className:"file-reader",children:[f.jsx(ba,{...l}),f.jsx(Dt,{error:o.error}),m&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"reader-meta",children:[f.jsx("strong",{children:Wu(n)}),f.jsxs("span",{children:[Math.ceil(m.size/1024)," KB"]})]}),m.kind==="image"?f.jsx("img",{className:"file-image",src:`data:${m.mimeType};base64,${m.data}`,alt:Wu(n)}):m.kind==="text"?f.jsxs(f.Fragment,{children:[f.jsx("pre",{className:"source-code",children:t?((m.text??"")+(p?.text??"")).split(`
166
166
  `).map((y,v)=>f.jsxs("span",{ref:v+1===t?s:void 0,className:v+1===t?"file-highlight-line":void 0,children:[y,`
167
- `]},v)):f.jsxs(f.Fragment,{children:[m.text,p?.text]})}),(p?p.next:m.nextOffset)!==void 0&&f.jsx("button",{className:"button secondary",disabled:o.busy,onClick:()=>void o.run(async()=>{const y=await r.call("fs.read",{path:n,offset:p?p.next:m.nextOffset});d({path:n,text:(p?.text??"")+(y.text??""),next:y.nextOffset})}),children:"加载下一部分"})]}):f.jsx("p",{className:"muted",children:"二进制文件 · App 和网页都不直接显示内容。"})]})]})}function gg({start:n,onPick:t,directoriesOnly:s=!1}){const r=co(),{link:o}=Lt(),[l,u]=b.useState(n),[d,m]=b.useState(!1),[p,y]=b.useState(),[v,x]=b.useState(""),_=Wt(),E=ea(()=>o.call("fs.list",{path:l,hidden:d,files:!s}),[o,l,d]),[A,S]=b.useState(),j=v&&A?A.entries:E.value?.entries??[];return f.jsxs("div",{className:"file-browser",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("button",{className:"button secondary",disabled:!E.value?.parent,onClick:()=>{y(void 0),u(E.value?.parent),x("")},children:"上一级"}),f.jsx("span",{className:"path-label",children:E.value?.path??l??"主目录"}),f.jsxs("label",{children:[f.jsx("input",{type:"checkbox",checked:d,onChange:T=>m(T.target.checked)}),"隐藏文件"]})]}),f.jsxs("form",{className:"inline-form",onSubmit:T=>{T.preventDefault(),v.trim()&&_.run(async()=>S(await o.call("fs.search",{query:v.trim()})))},children:[f.jsx("input",{"aria-label":"搜索远程目录",placeholder:"搜索目录",value:v,onChange:T=>{x(T.target.value),T.target.value||S(void 0)}}),f.jsx("button",{className:"button secondary",disabled:_.busy,children:"搜索"})]}),f.jsx(ba,{...E}),f.jsx(Dt,{error:_.error}),f.jsxs("div",{className:"file-browser-layout",children:[f.jsxs("div",{className:"remote-file-list",children:[j.map(T=>f.jsxs("button",{className:p===T.path?"selected":"",onClick:()=>{T.file?y(T.path):(u(T.path),x(""),y(void 0))},children:[f.jsx(_t,{name:T.file?"file":"folder",size:17}),f.jsx("span",{children:T.name}),T.size!==void 0&&f.jsxs("small",{children:[Math.ceil(T.size/1024)," KB"]})]},T.path)),!E.loading&&j.length===0&&f.jsx("p",{className:"muted",children:"此目录为空"}),(E.value?.truncated||A?.truncated)&&f.jsx("p",{className:"muted",children:"结果较多,请缩小搜索范围。"})]}),p&&f.jsx(BE,{path:p},p)]}),s?f.jsx("button",{className:"button primary",disabled:!E.value,onClick:()=>{E.value&&t?.(E.value.path)},children:"选择此目录"}):f.jsxs("div",{className:"file-actions",children:[f.jsxs("label",{className:"button secondary",children:["上传文件",f.jsx("input",{type:"file",multiple:!0,hidden:!0,disabled:_.busy||!E.value,onChange:T=>{const k=Array.from(T.target.files??[]);T.target.value="",_.run(async()=>{for(const C of k)await o.call("fs.upload",{dir:E.value.path,name:C.name,data:await pg(C)},18e4);E.reload()})}})]}),f.jsx("button",{className:"button secondary",disabled:_.busy||!E.value,onClick:async()=>{const T=await r.prompt("新目录名称");T?.trim()&&_.run(async()=>{await o.call("fs.mkdir",{parent:E.value.path,name:T.trim()}),E.reload()})},children:"新建目录"}),f.jsx("button",{className:"text-button",onClick:E.reload,children:"刷新"})]})]})}function RM({commands:n,choose:t,close:s,returnFocus:r}){const[o,l]=b.useState(""),u=ME(n,o);return f.jsx(El,{title:"命令与技能",close:s,returnFocus:r,children:f.jsxs(AE,{shouldFilter:!1,children:[f.jsx(bM,{"aria-label":"搜索命令",placeholder:"搜索命令或 Skills",value:o,onValueChange:l}),f.jsxs(jE,{children:[f.jsx(TE,{children:n.length?"没有匹配的命令":"Agent 尚未报告命令,连接或接管后会自动更新。"}),f.jsx(kE,{children:u.map(d=>f.jsx(NE,{value:d.name,onSelect:()=>t(d),children:f.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[f.jsxs("strong",{children:["/",d.name,d.hint&&f.jsxs("small",{children:[" ",d.hint]})]}),f.jsx("span",{className:"text-muted-foreground",children:DE(d)})]})},d.name))})]})]})})}function DM({session:n,view:t}){const s=Jn(),r=yt(l=>l.status==="online"),o=Wt();return f.jsxs("div",{className:"settings-panel",children:[f.jsx("h3",{children:"会话设置"}),f.jsxs("p",{className:"muted",children:[n.agent," · ",n.cwd]}),f.jsx(Qp,{children:t?.config.map(l=>f.jsxs(ku,{"data-disabled":!r||o.busy,children:[f.jsx(Nu,{htmlFor:`config-${l.id}`,children:l.name}),f.jsx(bd,{id:`config-${l.id}`,label:l.name,value:l.current,disabled:!r||o.busy,onValueChange:u=>void o.run(()=>s.setConfig(n.id,l.id,u)),options:l.values.map(u=>({value:u.value,label:u.name+(u.description?` · ${u.description}`:"")}))})]},l.id))}),!t?.config.length&&f.jsx("p",{className:"muted",children:"当前 Agent 尚未提供可调整的配置。"}),f.jsx(Dt,{error:o.error})]})}function MM({view:n}){const t=n?.items.flatMap(s=>s.kind==="tool"&&s.status!=="failed"?s.content.filter(r=>r.type==="diff"||r.type==="patch"):[])??[];return f.jsxs("section",{children:[f.jsx("h3",{children:"文件变更"}),f.jsx("p",{className:"muted",children:"来自已加载的会话记录;加载更早历史可查看更多变更。"}),t.map((s,r)=>(s.type==="diff"||s.type==="patch")&&f.jsx(UE,{change:s},r)),!t.length&&f.jsx("p",{className:"muted",children:"当前没有已报告的文件变更。"})]})}function zM({session:n,view:t}){const s=co(),{link:r}=Lt(),o=Jn(),l=yt(R=>R.status==="online"),u=Wt(),d=n.agent==="codex",m=d&&n.driver==="desktop",p=u.busy||!l||m,y=ea(async()=>d&&l?r.call("sessions.goal",{sessionId:n.id,change:{action:"get"}}):{goal:null},[r,n.id,d,l]),v=t?.goal===void 0?y.value?.goal:t.goal,[x,_]=b.useState(""),[E,A]=b.useState(""),[S,j]=b.useState(!1),[T,k]=b.useState("");b.useEffect(()=>{S||(_(v?.objective??""),A(v?.tokenBudget?.toString()??""))},[v?.objective,v?.tokenBudget,S]);async function C(R){if(!p){if(d)await r.call("sessions.goal",{sessionId:n.id,change:R}),y.reload();else{const O=R.action==="set"?`/goal ${R.objective}`:R.action==="clear"?"/goal clear":"/goal";if(await o.send(n.id,[{type:"text",text:O}],{now:!0})==="failed")throw new Error("目标命令未发送成功,请重试");k("已发送目标命令,执行结果会显示在会话中。")}j(!1)}}return f.jsxs("section",{className:"settings-panel",children:[f.jsx("h3",{children:"持续目标"}),f.jsx(ba,{...y}),v&&f.jsxs("div",{className:"notice-card",children:[f.jsx(Ur,{state:v.status}),f.jsx("p",{children:v.objective}),f.jsxs("small",{children:["已用 ",v.tokensUsed??"—"," tokens",v.tokenBudget?` / ${v.tokenBudget}`:""," ·"," ",v.iterations??0," 轮"]}),v.lastReason&&f.jsx("p",{children:v.lastReason}),f.jsxs("div",{className:"permission-buttons",children:[d&&f.jsx("button",{className:"button secondary",disabled:p||["complete","budgetLimited"].includes(v.status),onClick:()=>void u.run(()=>C({action:v.status==="active"?"pause":"resume"})),children:v.status==="active"?"暂停":"继续"}),f.jsx("button",{className:"button secondary",disabled:p,onClick:async()=>{await s.confirm("清除当前持续目标?")&&u.run(()=>C({action:"clear"}))},children:"清除目标"})]})]}),f.jsx("form",{onSubmit:R=>{R.preventDefault(),u.run(()=>C({action:"set",objective:x.trim(),...E?{tokenBudget:Number(E)}:{}}))},children:f.jsxs(Qp,{children:[f.jsxs(ku,{children:[f.jsx(Nu,{htmlFor:"goal-objective",children:"目标"}),f.jsx("textarea",{id:"goal-objective",value:x,onChange:R=>{j(!0),_(R.target.value)},rows:4,required:!0,maxLength:d?4e3:void 0,placeholder:"你希望 Agent 持续完成什么?"})]}),d&&f.jsxs(ku,{children:[f.jsx(Nu,{htmlFor:"goal-budget",children:"Token 预算(可选)"}),f.jsx("input",{id:"goal-budget",type:"number",min:"1",step:"1",value:E,onChange:R=>{j(!0),A(R.target.value)}})]}),f.jsx("button",{className:"button primary",disabled:p||!x.trim(),children:v?"更新目标":"设置目标"})]})}),!d&&f.jsx("button",{className:"text-button",disabled:p,onClick:()=>void u.run(()=>C({action:"get"})),children:"查询当前目标"}),m&&f.jsx("p",{className:"muted",children:"会话由电脑端控制,请在电脑端修改目标。"}),T&&f.jsx("p",{role:"status",children:T}),f.jsx(Dt,{error:u.error})]})}function LM({session:n,onFile:t,onTerminal:s}){const r=Jn(),{store:o}=Lt(),l=yt(v=>v.tasks[n.id]),u=yt(v=>v.workflows[n.id]),d=Wt(),m=ea(async()=>({tasks:await r.loadTasks(n.id),subagents:await r.loadSubagents(n.id)}),[o,n.id],5e3),[p,y]=b.useState();return f.jsxs("section",{children:[f.jsx("h3",{children:"后台任务、子 Agent 与工作流"}),f.jsx(ba,{...m}),f.jsx(Dt,{error:d.error}),f.jsxs("div",{className:"activity-list",children:[(l?Object.values(l).sort((v,x)=>x.startedAt-v.startedAt):m.value?.tasks??[]).map(v=>f.jsxs("article",{children:[f.jsxs("button",{onClick:()=>{y({kind:"task",id:v.id})},children:[f.jsx(Ur,{state:v.state}),f.jsx("strong",{children:v.title}),f.jsx("small",{children:v.command})]}),v.state==="running"&&f.jsx("button",{className:"text-button",onClick:()=>void d.run(async()=>{await r.stopTask(n.id,v.id),m.reload()}),children:"停止任务"})]},v.id)),m.value?.subagents.map(v=>f.jsxs("article",{children:[f.jsxs("button",{onClick:()=>y({kind:"agent",id:v.toolCallId}),children:[f.jsx(Ur,{state:v.state??(v.running?"running":v.failed?"failed":"completed")}),f.jsx("strong",{children:v.task}),f.jsx("small",{children:v.agentType??(v.workflow?"工作流":"子 Agent")})]}),(u?.[v.toolCallId]?.workflow??v.workflow)&&f.jsx(b1,{workflow:u?.[v.toolCallId]?.workflow??v.workflow,open:x=>{y({kind:"agent",id:x})}})]},v.toolCallId)),Object.values(u??{}).filter(v=>!m.value?.subagents.some(x=>x.toolCallId===v.toolCallId)).map(v=>f.jsxs("article",{children:[f.jsx("strong",{children:v.task}),f.jsx(b1,{workflow:v.workflow,open:x=>y({kind:"agent",id:x})})]},v.toolCallId))]}),m.value&&!m.value.tasks.length&&!m.value.subagents.length&&!Object.keys(u??{}).length&&f.jsx("p",{className:"muted",children:"尚无后台任务或子 Agent。"}),p?.kind==="task"&&f.jsx(UM,{sessionId:n.id,taskId:p.id},p.id),p?.kind==="agent"&&f.jsx(BM,{session:n,id:p.id,onFile:t,onTerminal:s},p.id)]})}function UM({sessionId:n,taskId:t}){const s=Jn(),{store:r}=Lt(),o=yt(y=>y.tasks[n]?.[t]?.state==="running"),[l,u]=b.useState(),d=ea(()=>s.loadTaskOutput(n,t),[r,n,t],o&&!l?2e3:0),m=l??d.value,p=Wt();return f.jsxs("div",{className:"task-output",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("strong",{children:"任务输出"}),f.jsx("button",{className:"text-button",onClick:()=>{u(void 0),d.reload()},children:"刷新"})]}),f.jsx(ba,{loading:!m&&d.loading,error:d.error??p.error}),!!m?.start&&f.jsx("button",{className:"text-button",disabled:p.busy,onClick:()=>{u(m),p.run(async()=>{const y=await s.loadTaskOutput(n,t,m.start);u({...m,text:y.text+m.text,start:y.start})})},children:"加载更早输出"}),f.jsx("pre",{children:m?.text||(m?"没有可读的输出":"加载中…")})]})}function BM({session:n,id:t,onFile:s,onTerminal:r}){const{store:o}=Lt(),l=yt(x=>x.status==="online"),u=yt(x=>x.ready[n.id]),d=yt(x=>x.subagentViews[dp(n.id,t)]),[m,p]=b.useState(!1),[y,v]=b.useState(0);return b.useEffect(()=>{if(!l||!u)return;let x=!0;return p(!1),o.getState().openSubagent(n.id,t).then(_=>{x&&p(!_)}),()=>{x=!1,o.getState().closeSubagent(n.id,t)}},[o,n.id,t,l,u,y]),f.jsxs("div",{children:[f.jsx("h3",{children:"子 Agent 会话"}),d?f.jsx(mg,{items:d.items,sessionId:n.id,agent:n.agent,onFile:s,onTerminal:r}):m?f.jsxs("div",{role:"alert",children:[f.jsx("p",{children:"未能读取子 Agent 会话,它可能已关闭或暂时不可用。"}),f.jsx("button",{className:"text-button",onClick:()=>v(x=>x+1),children:"重试"})]}):f.jsx("p",{className:"muted",children:l?"正在加载…":"等待电脑重新连接…"})]})}function b1({workflow:n,open:t}){return f.jsxs("details",{className:"workflow-panel",children:[f.jsxs("summary",{children:[n.name??"工作流"," · ",n.completed??0," /"," ",n.started??n.agents?.length??0," 已完成"]}),f.jsxs("div",{className:"browser-toolbar",children:[n.state&&f.jsx(Ur,{state:n.state}),f.jsxs("small",{children:[n.tokens??0," tokens",n.durationMs!==void 0?` · ${Math.round(n.durationMs/1e3)} 秒`:""]})]}),n.phases?.map(s=>f.jsxs("div",{className:"workflow-phase",children:[s.order+1,". ",s.title]},s.id)),n.agents?.map(s=>f.jsxs("div",{className:"workflow-agent",children:[f.jsx(Ur,{state:s.state}),f.jsx("strong",{children:s.title}),f.jsxs("small",{children:[s.model??"",s.tokens!==void 0?` · ${s.tokens} tokens`:"",s.toolCalls!==void 0?` · ${s.toolCalls} 次工具调用`:""]}),s.result&&f.jsx("p",{children:s.result}),s.toolCallId&&f.jsx("button",{className:"text-button",onClick:()=>t(s.toolCallId),children:"查看会话"})]},s.id))]})}function IM(){const n=co(),t=Jn(),{store:s}=Lt(),r=Wt(),o=ea(()=>t.listWorktrees(),[s]);return f.jsxs("section",{children:[f.jsx("h2",{children:"工作目录与分支"}),f.jsx(ba,{...o}),f.jsx(Dt,{error:r.error}),o.value?.map(l=>f.jsxs("article",{className:"notice-card",children:[f.jsx("strong",{children:l.branch}),f.jsx("p",{children:l.path}),f.jsxs("p",{className:"muted",children:[l.sessions.length," 个会话 ·"," ",l.dirty?"有未提交改动":"工作区干净"," · ",l.ahead," ","个新提交"]}),f.jsx("button",{className:"button secondary",disabled:l.sessions.length>0||r.busy,onClick:async()=>{const u=l.dirty||l.ahead>0;await n.confirm(u?"此 worktree 有未提交改动或新提交。确定永久删除它及分支?":"移除此 worktree 及分支?")&&r.run(async()=>{await t.removeWorktree(l.path,u),o.reload()})},children:"移除 worktree"})]},l.path)),o.value?.length===0&&f.jsx("p",{className:"muted",children:"尚无由 LinkShell 创建的 worktree。"})]})}async function HM(n,t,s,r=()=>!0){await n.beginReplay(t.afterFrame===0);try{let o=t.afterFrame;for(;o<t.throughFrame;){if(!r())throw new Error("终端恢复已取消");const l=await s(o,t.throughFrame);if(!r())throw new Error("终端恢复已取消");if(l.nextFrame<=o||l.nextFrame>t.throughFrame||l.frames.length===0)throw new Error("终端回放数据不完整");for(const u of l.frames){if(u.frame!==o+1||u.cols<1||u.rows<1)throw new Error("终端回放顺序无效");await n.replay(u.data,u.cols,u.rows),o=u.frame}if(o!==l.nextFrame||l.done!==(o===t.throughFrame))throw new Error("终端回放范围不一致")}}finally{await n.endReplay()}}function vp(n,t){return t?new Promise(s=>n.write(t,s)):Promise.resolve()}async function VM(n,t,s,r){t.recording?await HM({beginReplay:async o=>{o&&n.reset()},replay:async(o,l,u)=>{n.resize(l,u),await vp(n,o)},endReplay:async()=>{}},t.recording,s,r):(t.reset&&n.reset(),n.resize(t.terminal.cols,t.terminal.rows),await vp(n,t.replay))}function IE({id:n}){const{link:t}=Lt(),s=b.useRef(null),r=b.useRef(null),o=b.useRef(null),l=b.useRef(!1),u=yt(T=>T.status==="online"),[d,m]=b.useState(!0),[p,y]=b.useState(0),[v,x]=b.useState(()=>Math.max(10,Math.min(24,Fs("terminalFontSize",13)))),_=Wt(),E=b.useRef(v);E.current=v;async function A(T){const k=r.current;if(!k||!l.current||!T.length)return;const R=(await t.call("terminals.list",{})).terminals.find(O=>O.id===n);if(!R||R.exitCode!=null||R.interrupted)throw new Error("终端已停止");for(const O of T){const M=await t.call("fs.upload",{dir:R.cwd,name:O.name,data:await pg(O)},18e4);if(r.current!==k)return;if(!l.current)throw new Error(`文件已上传到 ${M.path},请在终端恢复后粘贴路径。`);k.paste("'"+M.path.replaceAll("'",`'"'"'`)+"' ")}k.focus()}const[S,j]=b.useState();return b.useEffect(()=>{if(!s.current)return;const T=new pA({fontFamily:"Menlo, Consolas, monospace",fontSize:E.current,cursorBlink:!0,scrollback:1e4,theme:{background:"#17181d",foreground:"#e4e4ec",cursor:"#7d95ff"},allowProposedApi:!1}),k=new gA;T.loadAddon(k),r.current=T,o.current=k,T.open(s.current);const C=()=>{const te=getComputedStyle(document.documentElement);T.options.theme={background:te.getPropertyValue("--code").trim(),foreground:te.getPropertyValue("--codeText").trim(),cursor:te.getPropertyValue("--accent").trim()}};C();const R=new MutationObserver(C);R.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),k.fit();let O=!0,M=!1,z,L=0,q,V=Promise.resolve(),G=0,Z=!1;const ee=[],re=async te=>{te.seq<=(z??-1)||(te.cols&&te.rows&&(T.cols!==te.cols||T.rows!==te.rows)&&T.resize(te.cols,te.rows),await vp(T,te.data),O&&(q=te.frame,z=te.seq))},U=()=>{if(!O||t.status!=="online")return;M=!0,l.current=!1,m(!0);const te=++L;ee.length=0,G=0,Z=!1,V=V.catch(()=>{}).then(async()=>{if(!(!O||L!==te))try{const de=await t.call("terminals.attach",{terminalId:n,fromSeq:z,replayFormat:"frames-v1",fromFrame:q});if(!O||L!==te||(await VM(T,de,(ce,ie)=>t.call("terminals.replay",{terminalId:n,afterFrame:ce,throughFrame:ie}),()=>O&&L===te),!O||L!==te))return;if(z=de.seq,q=de.recording?.throughFrame,Z){U();return}for(;ee.length&&O&&L===te;){const ce=ee.shift();G-=ce.data.length,await re(ce)}if(!O||L!==te)return;M=!1,j(void 0),k.fit(),await t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)})}catch(de){O&&L===te&&(M=!1,z=void 0,q=void 0,j(de instanceof Error?de.message:String(de)))}})},$=t.on("terminal.output",te=>{te.terminalId===n&&(M?Z||(G+=te.data.length,G>4*1024*1024?(ee.length=0,Z=!0):ee.push(te)):V=V.then(()=>O?re(te):void 0).catch(()=>U()))}),W=T.onData(te=>{if(!M){if(t.status!=="online"){j("连接已断开,输入未发送");return}t.call("terminals.input",{terminalId:n,data:te}).catch(de=>{O&&j(String(de))})}}),J=t.onOnline(U),Q=t.onStatus(te=>{te!=="online"&&(L++,M=!0,l.current=!1,m(!0))});let pe;const F=new ResizeObserver(()=>{clearTimeout(pe),pe=setTimeout(()=>{!O||M||(k.fit(),t.status==="online"&&t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)}).catch(()=>{}))},120)});return F.observe(s.current),U(),()=>{O=!1,L++,clearTimeout(pe),F.disconnect(),R.disconnect(),$(),J(),Q(),W.dispose(),r.current=null,o.current=null,l.current=!1,T.dispose(),t.status==="online"&&t.call("terminals.detach",{terminalId:n}).catch(()=>{})}},[t,n,p]),b.useEffect(()=>{const T=r.current;T&&(T.options.fontSize=v,ua("terminalFontSize",v),l.current&&(o.current?.fit(),t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)}).catch(()=>{})))},[v,t,n]),f.jsxs("div",{className:"terminal-live",onDragOver:T=>T.preventDefault(),onDrop:T=>{T.preventDefault(),_.run(()=>A(Array.from(T.dataTransfer.files)))},onPaste:T=>{T.clipboardData.files.length&&(T.preventDefault(),_.run(()=>A(Array.from(T.clipboardData.files))))},children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("button",{className:"text-button","aria-label":"缩小终端字号",disabled:v<=10,onClick:()=>x(T=>T-1),children:"A−"}),f.jsxs("span",{children:[v,"px"]}),f.jsx("button",{className:"text-button","aria-label":"放大终端字号",disabled:v>=24,onClick:()=>x(T=>T+1),children:"A+"}),f.jsxs("label",{className:"text-button",children:["上传文件",f.jsx("input",{type:"file",multiple:!0,hidden:!0,disabled:_.busy||d||!u,onChange:T=>{const k=Array.from(T.target.files??[]);T.target.value="",_.run(()=>A(k))}})]}),d&&f.jsx("span",{role:"status",children:"正在恢复终端…"}),S&&f.jsx("button",{className:"text-button",onClick:()=>y(T=>T+1),children:"重新连接终端"})]}),f.jsx(Dt,{error:S??_.error}),f.jsx("div",{className:"xterm-mount",ref:s})]})}function HE({cwd:n,selected:t,onSelect:s}){const r=co(),{link:o}=Lt(),l=ea(()=>o.call("terminals.list",{}),[o],5e3),u=Wt(),[d,m]=b.useState(n??""),[p,y]=b.useState(""),v=yt(x=>x.status==="online");return f.jsxs("section",{className:"terminals-page",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("h2",{children:"终端"}),f.jsx("input",{"aria-label":"终端工作目录",placeholder:"工作目录(默认主目录)",value:d,onChange:x=>m(x.target.value)}),f.jsx("input",{"aria-label":"终端启动命令",placeholder:"启动命令(可选)",value:p,onChange:x=>y(x.target.value)}),f.jsx("button",{className:"button primary",disabled:u.busy||!v,onClick:()=>void u.run(async()=>{const x=await o.call("terminals.create",{cwd:d||void 0,command:p.trim()||void 0});s(x.terminal.id),l.reload()}),children:"新建终端"})]}),f.jsx(ba,{...l}),f.jsx(Dt,{error:u.error}),f.jsx("div",{className:"terminal-tabs",children:l.value?.terminals.map(x=>f.jsxs("div",{className:x.id===t?"selected":"",children:[f.jsxs("button",{onClick:()=>s(x.id),children:[x.title,f.jsx("small",{children:x.exitCode!=null?`已退出 ${x.exitCode}`:x.interrupted?"已中断":x.cwd})]}),(x.exitCode!=null||x.interrupted)&&f.jsx("button",{className:"text-button",disabled:u.busy||!v,onClick:()=>void u.run(async()=>{const _=await o.call("terminals.create",{cwd:x.cwd,command:x.command});s(_.terminal.id),l.reload()}),children:"重新运行"}),f.jsx("button",{"aria-label":`关闭终端 ${x.title}`,onClick:async()=>{await r.confirm("关闭这个终端?其中运行的进程会结束。")&&u.run(async()=>{await o.call("terminals.close",{terminalId:x.id}),x.id===t&&s(void 0),l.reload()})},children:"×"})]},x.id))}),t?f.jsx(IE,{id:t},t):f.jsx("p",{className:"muted",children:"选择一个终端,或新建 Shell。"})]})}const to=n=>{const t=new Uint8Array(n.reduce((r,o)=>r+o.length,0));let s=0;for(const r of n)t.set(r,s),s+=r.length;return t},Su=new TextEncoder;function VE(n,t=!1){const s=new TextDecoder("latin1").decode(n),r=s.indexOf(`\r
167
+ `]},v)):f.jsxs(f.Fragment,{children:[m.text,p?.text]})}),(p?p.next:m.nextOffset)!==void 0&&f.jsx("button",{className:"button secondary",disabled:o.busy,onClick:()=>void o.run(async()=>{const y=await r.call("fs.read",{path:n,offset:p?p.next:m.nextOffset});d({path:n,text:(p?.text??"")+(y.text??""),next:y.nextOffset})}),children:"加载下一部分"})]}):f.jsx("p",{className:"muted",children:"二进制文件 · App 和网页都不直接显示内容。"})]})]})}function gg({start:n,onPick:t,directoriesOnly:s=!1}){const r=co(),{link:o}=Lt(),[l,u]=b.useState(n),[d,m]=b.useState(!1),[p,y]=b.useState(),[v,x]=b.useState(""),_=Wt(),E=ea(()=>o.call("fs.list",{path:l,hidden:d,files:!s}),[o,l,d]),[A,S]=b.useState(),j=v&&A?A.entries:E.value?.entries??[];return f.jsxs("div",{className:"file-browser",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("button",{className:"button secondary",disabled:!E.value?.parent,onClick:()=>{y(void 0),u(E.value?.parent),x("")},children:"上一级"}),f.jsx("span",{className:"path-label",children:E.value?.path??l??"主目录"}),f.jsxs("label",{children:[f.jsx("input",{type:"checkbox",checked:d,onChange:T=>m(T.target.checked)}),"隐藏文件"]})]}),f.jsxs("form",{className:"inline-form",onSubmit:T=>{T.preventDefault(),v.trim()&&_.run(async()=>S(await o.call("fs.search",{query:v.trim()})))},children:[f.jsx("input",{"aria-label":"搜索远程目录",placeholder:"搜索目录",value:v,onChange:T=>{x(T.target.value),T.target.value||S(void 0)}}),f.jsx("button",{className:"button secondary",disabled:_.busy,children:"搜索"})]}),f.jsx(ba,{...E}),f.jsx(Dt,{error:_.error}),f.jsxs("div",{className:"file-browser-layout",children:[f.jsxs("div",{className:"remote-file-list",children:[j.map(T=>f.jsxs("button",{className:p===T.path?"selected":"",onClick:()=>{T.file?y(T.path):(u(T.path),x(""),y(void 0))},children:[f.jsx(_t,{name:T.file?"file":"folder",size:17}),f.jsx("span",{children:T.name}),T.size!==void 0&&f.jsxs("small",{children:[Math.ceil(T.size/1024)," KB"]})]},T.path)),!E.loading&&j.length===0&&f.jsx("p",{className:"muted",children:"此目录为空"}),(E.value?.truncated||A?.truncated)&&f.jsx("p",{className:"muted",children:"结果较多,请缩小搜索范围。"})]}),p&&f.jsx(BE,{path:p},p)]}),s?f.jsx("button",{className:"button primary",disabled:!E.value,onClick:()=>{E.value&&t?.(E.value.path)},children:"选择此目录"}):f.jsxs("div",{className:"file-actions",children:[f.jsxs("label",{className:"button secondary",children:["上传文件",f.jsx("input",{type:"file",multiple:!0,hidden:!0,disabled:_.busy||!E.value,onChange:T=>{const k=Array.from(T.target.files??[]);T.target.value="",_.run(async()=>{for(const C of k)await o.call("fs.upload",{dir:E.value.path,name:C.name,data:await pg(C)},18e4);E.reload()})}})]}),f.jsx("button",{className:"button secondary",disabled:_.busy||!E.value,onClick:async()=>{const T=await r.prompt("新目录名称");T?.trim()&&_.run(async()=>{await o.call("fs.mkdir",{parent:E.value.path,name:T.trim()}),E.reload()})},children:"新建目录"}),f.jsx("button",{className:"text-button",onClick:E.reload,children:"刷新"})]})]})}function RM({commands:n,choose:t,close:s,returnFocus:r}){const[o,l]=b.useState(""),u=ME(n,o);return f.jsx(El,{title:"命令与技能",close:s,returnFocus:r,children:f.jsxs(AE,{shouldFilter:!1,children:[f.jsx(bM,{"aria-label":"搜索命令",placeholder:"搜索命令或 Skills",value:o,onValueChange:l}),f.jsxs(jE,{children:[f.jsx(TE,{children:n.length?"没有匹配的命令":"Agent 尚未报告命令,连接或接管后会自动更新。"}),f.jsx(kE,{children:u.map(d=>f.jsx(NE,{value:d.name,onSelect:()=>t(d),children:f.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[f.jsxs("strong",{children:["/",d.name,d.hint&&f.jsxs("small",{children:[" ",d.hint]})]}),f.jsx("span",{className:"text-muted-foreground",children:DE(d)})]})},d.name))})]})]})})}function DM({session:n,view:t}){const s=Jn(),r=yt(l=>l.status==="online"),o=Wt();return f.jsxs("div",{className:"settings-panel",children:[f.jsx("h3",{children:"会话设置"}),f.jsxs("p",{className:"muted",children:[n.agent," · ",n.cwd]}),f.jsx(Qp,{children:t?.config.map(l=>f.jsxs(ku,{"data-disabled":!r||o.busy,children:[f.jsx(Nu,{htmlFor:`config-${l.id}`,children:l.name}),f.jsx(bd,{id:`config-${l.id}`,label:l.name,value:l.current,disabled:!r||o.busy,onValueChange:u=>void o.run(()=>s.setConfig(n.id,l.id,u)),options:l.values.map(u=>({value:u.value,label:u.name+(u.description?` · ${u.description}`:"")}))})]},l.id))}),!t?.config.length&&f.jsx("p",{className:"muted",children:"当前 Agent 尚未提供可调整的配置。"}),f.jsx(Dt,{error:o.error})]})}function MM({view:n}){const t=n?.items.flatMap(s=>s.kind==="tool"&&s.status!=="failed"?s.content.filter(r=>r.type==="diff"||r.type==="patch"):[])??[];return f.jsxs("section",{children:[f.jsx("h3",{children:"文件变更"}),f.jsx("p",{className:"muted",children:"来自已加载的会话记录;加载更早历史可查看更多变更。"}),t.map((s,r)=>(s.type==="diff"||s.type==="patch")&&f.jsx(UE,{change:s},r)),!t.length&&f.jsx("p",{className:"muted",children:"当前没有已报告的文件变更。"})]})}function zM({session:n,view:t}){const s=co(),{link:r}=Lt(),o=Jn(),l=yt(R=>R.status==="online"),u=Wt(),d=n.agent==="codex",m=d&&n.driver==="desktop",p=u.busy||!l||m,y=ea(async()=>d&&l?r.call("sessions.goal",{sessionId:n.id,change:{action:"get"}}):{goal:null},[r,n.id,d,l]),v=t?.goal===void 0?y.value?.goal:t.goal,[x,_]=b.useState(""),[E,A]=b.useState(""),[S,j]=b.useState(!1),[T,k]=b.useState("");b.useEffect(()=>{S||(_(v?.objective??""),A(v?.tokenBudget?.toString()??""))},[v?.objective,v?.tokenBudget,S]);async function C(R){if(!p){if(d)await r.call("sessions.goal",{sessionId:n.id,change:R}),y.reload();else{const O=R.action==="set"?`/goal ${R.objective}`:R.action==="clear"?"/goal clear":"/goal";if(await o.send(n.id,[{type:"text",text:O}],{now:!0})==="failed")throw new Error("目标命令未发送成功,请重试");k("已发送目标命令,执行结果会显示在会话中。")}j(!1)}}return f.jsxs("section",{className:"settings-panel",children:[f.jsx("h3",{children:"持续目标"}),f.jsx(ba,{...y}),v&&f.jsxs("div",{className:"notice-card",children:[f.jsx(Ur,{state:v.status}),f.jsx("p",{children:v.objective}),f.jsxs("small",{children:["已用 ",v.tokensUsed??"—"," tokens",v.tokenBudget?` / ${v.tokenBudget}`:""," ·"," ",v.iterations??0," 轮"]}),v.lastReason&&f.jsx("p",{children:v.lastReason}),f.jsxs("div",{className:"permission-buttons",children:[d&&f.jsx("button",{className:"button secondary",disabled:p||["complete","budgetLimited"].includes(v.status),onClick:()=>void u.run(()=>C({action:v.status==="active"?"pause":"resume"})),children:v.status==="active"?"暂停":"继续"}),f.jsx("button",{className:"button secondary",disabled:p,onClick:async()=>{await s.confirm("清除当前持续目标?")&&u.run(()=>C({action:"clear"}))},children:"清除目标"})]})]}),f.jsx("form",{onSubmit:R=>{R.preventDefault(),u.run(()=>C({action:"set",objective:x.trim(),...E?{tokenBudget:Number(E)}:{}}))},children:f.jsxs(Qp,{children:[f.jsxs(ku,{children:[f.jsx(Nu,{htmlFor:"goal-objective",children:"目标"}),f.jsx("textarea",{id:"goal-objective",value:x,onChange:R=>{j(!0),_(R.target.value)},rows:4,required:!0,maxLength:d?4e3:void 0,placeholder:"你希望 Agent 持续完成什么?"})]}),d&&f.jsxs(ku,{children:[f.jsx(Nu,{htmlFor:"goal-budget",children:"Token 预算(可选)"}),f.jsx("input",{id:"goal-budget",type:"number",min:"1",step:"1",value:E,onChange:R=>{j(!0),A(R.target.value)}})]}),f.jsx("button",{className:"button primary",disabled:p||!x.trim(),children:v?"更新目标":"设置目标"})]})}),!d&&f.jsx("button",{className:"text-button",disabled:p,onClick:()=>void u.run(()=>C({action:"get"})),children:"查询当前目标"}),m&&f.jsx("p",{className:"muted",children:"会话由电脑端控制,请在电脑端修改目标。"}),T&&f.jsx("p",{role:"status",children:T}),f.jsx(Dt,{error:u.error})]})}function LM({session:n,onFile:t,onTerminal:s}){const r=Jn(),{store:o}=Lt(),l=yt(v=>v.tasks[n.id]),u=yt(v=>v.workflows[n.id]),d=Wt(),m=ea(async()=>({tasks:await r.loadTasks(n.id),subagents:await r.loadSubagents(n.id)}),[o,n.id],5e3),[p,y]=b.useState();return f.jsxs("section",{children:[f.jsx("h3",{children:"后台任务、子 Agent 与工作流"}),f.jsx(ba,{...m}),f.jsx(Dt,{error:d.error}),f.jsxs("div",{className:"activity-list",children:[(l?Object.values(l).sort((v,x)=>x.startedAt-v.startedAt):m.value?.tasks??[]).map(v=>f.jsxs("article",{children:[f.jsxs("button",{onClick:()=>{y({kind:"task",id:v.id})},children:[f.jsx(Ur,{state:v.state}),f.jsx("strong",{children:v.title}),f.jsx("small",{children:v.command})]}),v.state==="running"&&f.jsx("button",{className:"text-button",onClick:()=>void d.run(async()=>{await r.stopTask(n.id,v.id),m.reload()}),children:"停止任务"})]},v.id)),m.value?.subagents.map(v=>f.jsxs("article",{children:[f.jsxs("button",{onClick:()=>y({kind:"agent",id:v.toolCallId}),children:[f.jsx(Ur,{state:v.state??(v.running?"running":v.failed?"failed":"completed")}),f.jsx("strong",{children:v.task}),f.jsx("small",{children:v.agentType??(v.workflow?"工作流":"子 Agent")})]}),(u?.[v.toolCallId]?.workflow??v.workflow)&&f.jsx(b1,{workflow:u?.[v.toolCallId]?.workflow??v.workflow,open:x=>{y({kind:"agent",id:x})}})]},v.toolCallId)),Object.values(u??{}).filter(v=>!m.value?.subagents.some(x=>x.toolCallId===v.toolCallId)).map(v=>f.jsxs("article",{children:[f.jsx("strong",{children:v.task}),f.jsx(b1,{workflow:v.workflow,open:x=>y({kind:"agent",id:x})})]},v.toolCallId))]}),m.value&&!m.value.tasks.length&&!m.value.subagents.length&&!Object.keys(u??{}).length&&f.jsx("p",{className:"muted",children:"尚无后台任务或子 Agent。"}),p?.kind==="task"&&f.jsx(UM,{sessionId:n.id,taskId:p.id},p.id),p?.kind==="agent"&&f.jsx(BM,{session:n,id:p.id,onFile:t,onTerminal:s},p.id)]})}function UM({sessionId:n,taskId:t}){const s=Jn(),{store:r}=Lt(),o=yt(y=>y.tasks[n]?.[t]?.state==="running"),[l,u]=b.useState(),d=ea(()=>s.loadTaskOutput(n,t),[r,n,t],o&&!l?2e3:0),m=l??d.value,p=Wt();return f.jsxs("div",{className:"task-output",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("strong",{children:"任务输出"}),f.jsx("button",{className:"text-button",onClick:()=>{u(void 0),d.reload()},children:"刷新"})]}),f.jsx(ba,{loading:!m&&d.loading,error:d.error??p.error}),!!m?.start&&f.jsx("button",{className:"text-button",disabled:p.busy,onClick:()=>{u(m),p.run(async()=>{const y=await s.loadTaskOutput(n,t,m.start);u({...m,text:y.text+m.text,start:y.start})})},children:"加载更早输出"}),f.jsx("pre",{children:m?.text||(m?"没有可读的输出":"加载中…")})]})}function BM({session:n,id:t,onFile:s,onTerminal:r}){const{store:o}=Lt(),l=yt(x=>x.status==="online"),u=yt(x=>x.ready[n.id]),d=yt(x=>x.subagentViews[dp(n.id,t)]),[m,p]=b.useState(!1),[y,v]=b.useState(0);return b.useEffect(()=>{if(!l||!u)return;let x=!0;return p(!1),o.getState().openSubagent(n.id,t).then(_=>{x&&p(!_)}),()=>{x=!1,o.getState().closeSubagent(n.id,t)}},[o,n.id,t,l,u,y]),f.jsxs("div",{children:[f.jsx("h3",{children:"子 Agent 会话"}),d?f.jsx(mg,{items:d.items,sessionId:n.id,agent:n.agent,onFile:s,onTerminal:r}):m?f.jsxs("div",{role:"alert",children:[f.jsx("p",{children:"未能读取子 Agent 会话,它可能已关闭或暂时不可用。"}),f.jsx("button",{className:"text-button",onClick:()=>v(x=>x+1),children:"重试"})]}):f.jsx("p",{className:"muted",children:l?"正在加载…":"等待电脑重新连接…"})]})}function b1({workflow:n,open:t}){return f.jsxs("details",{className:"workflow-panel",children:[f.jsxs("summary",{children:[n.name??"工作流"," · ",n.completed??0," /"," ",n.started??n.agents?.length??0," 已完成"]}),f.jsxs("div",{className:"browser-toolbar",children:[n.state&&f.jsx(Ur,{state:n.state}),f.jsxs("small",{children:[n.tokens??0," tokens",n.durationMs!==void 0?` · ${Math.round(n.durationMs/1e3)} 秒`:""]})]}),n.phases?.map(s=>f.jsxs("div",{className:"workflow-phase",children:[s.order+1,". ",s.title]},s.id)),n.agents?.map(s=>f.jsxs("div",{className:"workflow-agent",children:[f.jsx(Ur,{state:s.state}),f.jsx("strong",{children:s.title}),f.jsxs("small",{children:[s.model??"",s.tokens!==void 0?` · ${s.tokens} tokens`:"",s.toolCalls!==void 0?` · ${s.toolCalls} 次工具调用`:""]}),s.result&&f.jsx("p",{children:s.result}),s.toolCallId&&f.jsx("button",{className:"text-button",onClick:()=>t(s.toolCallId),children:"查看会话"})]},s.id))]})}function IM(){const n=co(),t=Jn(),{store:s}=Lt(),r=Wt(),o=ea(()=>t.listWorktrees(),[s]);return f.jsxs("section",{children:[f.jsx("h2",{children:"工作目录与分支"}),f.jsx(ba,{...o}),f.jsx(Dt,{error:r.error}),o.value?.map(l=>f.jsxs("article",{className:"notice-card",children:[f.jsx("strong",{children:l.branch}),f.jsx("p",{children:l.path}),f.jsxs("p",{className:"muted",children:[l.sessions.length," 个会话 ·"," ",l.dirty?"有未提交改动":"工作区干净"," · ",l.ahead," ","个新提交"]}),f.jsx("button",{className:"button secondary",disabled:l.sessions.length>0||r.busy,onClick:async()=>{const u=l.dirty||l.ahead>0;await n.confirm(u?"此 worktree 有未提交改动或新提交。确定永久删除它及分支?":"移除此 worktree 及分支?")&&r.run(async()=>{await t.removeWorktree(l.path,u),o.reload()})},children:"移除 worktree"})]},l.path)),o.value?.length===0&&f.jsx("p",{className:"muted",children:"尚无由 LinkShell 创建的 worktree。"})]})}async function HM(n,t,s,r=()=>!0){await n.beginReplay(t.afterFrame===0);try{let o=t.afterFrame;for(;o<t.throughFrame;){if(!r())throw new Error("终端恢复已取消");const l=await s(o,t.throughFrame);if(!r())throw new Error("终端恢复已取消");if(l.nextFrame<=o||l.nextFrame>t.throughFrame||l.frames.length===0)throw new Error("终端回放数据不完整");let u;for(const d of l.frames){if(d.frame!==o+1||d.cols<1||d.rows<1)throw new Error("终端回放顺序无效");u&&(u.cols!==d.cols||u.rows!==d.rows)&&(await n.replay(u.data,u.cols,u.rows),u=void 0),u?u.data+=d.data:u={data:d.data,cols:d.cols,rows:d.rows},o=d.frame}if(o!==l.nextFrame||l.done!==(o===t.throughFrame))throw new Error("终端回放范围不一致");u&&await n.replay(u.data,u.cols,u.rows)}}finally{await n.endReplay()}}function vp(n,t){return t?new Promise(s=>n.write(t,s)):Promise.resolve()}async function VM(n,t,s,r){t.recording?await HM({beginReplay:async o=>{o&&n.reset()},replay:async(o,l,u)=>{n.resize(l,u),await vp(n,o)},endReplay:async()=>{}},t.recording,s,r):(t.reset&&n.reset(),n.resize(t.terminal.cols,t.terminal.rows),await vp(n,t.replay))}function IE({id:n}){const{link:t}=Lt(),s=b.useRef(null),r=b.useRef(null),o=b.useRef(null),l=b.useRef(!1),u=yt(T=>T.status==="online"),[d,m]=b.useState(!0),[p,y]=b.useState(0),[v,x]=b.useState(()=>Math.max(10,Math.min(24,Fs("terminalFontSize",13)))),_=Wt(),E=b.useRef(v);E.current=v;async function A(T){const k=r.current;if(!k||!l.current||!T.length)return;const R=(await t.call("terminals.list",{})).terminals.find(O=>O.id===n);if(!R||R.exitCode!=null||R.interrupted)throw new Error("终端已停止");for(const O of T){const M=await t.call("fs.upload",{dir:R.cwd,name:O.name,data:await pg(O)},18e4);if(r.current!==k)return;if(!l.current)throw new Error(`文件已上传到 ${M.path},请在终端恢复后粘贴路径。`);k.paste("'"+M.path.replaceAll("'",`'"'"'`)+"' ")}k.focus()}const[S,j]=b.useState();return b.useEffect(()=>{if(!s.current)return;const T=new pA({fontFamily:"Menlo, Consolas, monospace",fontSize:E.current,cursorBlink:!0,scrollback:1e4,theme:{background:"#17181d",foreground:"#e4e4ec",cursor:"#7d95ff"},allowProposedApi:!1}),k=new gA;T.loadAddon(k),r.current=T,o.current=k,T.open(s.current);const C=()=>{const te=getComputedStyle(document.documentElement);T.options.theme={background:te.getPropertyValue("--code").trim(),foreground:te.getPropertyValue("--codeText").trim(),cursor:te.getPropertyValue("--accent").trim()}};C();const R=new MutationObserver(C);R.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),k.fit();let O=!0,M=!1,z,L=0,q,V=Promise.resolve(),G=0,Z=!1;const ee=[],re=async te=>{te.seq<=(z??-1)||(te.cols&&te.rows&&(T.cols!==te.cols||T.rows!==te.rows)&&T.resize(te.cols,te.rows),await vp(T,te.data),O&&(q=te.frame,z=te.seq))},U=()=>{if(!O||t.status!=="online")return;M=!0,l.current=!1,m(!0);const te=++L;ee.length=0,G=0,Z=!1,V=V.catch(()=>{}).then(async()=>{if(!(!O||L!==te))try{const de=await t.call("terminals.attach",{terminalId:n,fromSeq:z,replayFormat:"frames-v1",fromFrame:q});if(!O||L!==te||(await VM(T,de,(ce,ie)=>t.call("terminals.replay",{terminalId:n,afterFrame:ce,throughFrame:ie}),()=>O&&L===te),!O||L!==te))return;if(z=de.seq,q=de.recording?.throughFrame,Z){U();return}for(;ee.length&&O&&L===te;){const ce=ee.shift();G-=ce.data.length,await re(ce)}if(!O||L!==te)return;M=!1,j(void 0),k.fit(),await t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)})}catch(de){O&&L===te&&(M=!1,z=void 0,q=void 0,j(de instanceof Error?de.message:String(de)))}})},$=t.on("terminal.output",te=>{te.terminalId===n&&(M?Z||(G+=te.data.length,G>4*1024*1024?(ee.length=0,Z=!0):ee.push(te)):V=V.then(()=>O?re(te):void 0).catch(()=>U()))}),W=T.onData(te=>{if(!M){if(t.status!=="online"){j("连接已断开,输入未发送");return}t.call("terminals.input",{terminalId:n,data:te}).catch(de=>{O&&j(String(de))})}}),J=t.onOnline(U),Q=t.onStatus(te=>{te!=="online"&&(L++,M=!0,l.current=!1,m(!0))});let pe;const F=new ResizeObserver(()=>{clearTimeout(pe),pe=setTimeout(()=>{!O||M||(k.fit(),t.status==="online"&&t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)}).catch(()=>{}))},120)});return F.observe(s.current),U(),()=>{O=!1,L++,clearTimeout(pe),F.disconnect(),R.disconnect(),$(),J(),Q(),W.dispose(),r.current=null,o.current=null,l.current=!1,T.dispose(),t.status==="online"&&t.call("terminals.detach",{terminalId:n}).catch(()=>{})}},[t,n,p]),b.useEffect(()=>{const T=r.current;T&&(T.options.fontSize=v,ua("terminalFontSize",v),l.current&&(o.current?.fit(),t.call("terminals.resize",{terminalId:n,cols:Math.max(10,T.cols),rows:Math.max(4,T.rows)}).catch(()=>{})))},[v,t,n]),f.jsxs("div",{className:"terminal-live",onDragOver:T=>T.preventDefault(),onDrop:T=>{T.preventDefault(),_.run(()=>A(Array.from(T.dataTransfer.files)))},onPaste:T=>{T.clipboardData.files.length&&(T.preventDefault(),_.run(()=>A(Array.from(T.clipboardData.files))))},children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("button",{className:"text-button","aria-label":"缩小终端字号",disabled:v<=10,onClick:()=>x(T=>T-1),children:"A−"}),f.jsxs("span",{children:[v,"px"]}),f.jsx("button",{className:"text-button","aria-label":"放大终端字号",disabled:v>=24,onClick:()=>x(T=>T+1),children:"A+"}),f.jsxs("label",{className:"text-button",children:["上传文件",f.jsx("input",{type:"file",multiple:!0,hidden:!0,disabled:_.busy||d||!u,onChange:T=>{const k=Array.from(T.target.files??[]);T.target.value="",_.run(()=>A(k))}})]}),d&&f.jsx("span",{role:"status",children:"正在恢复终端…"}),S&&f.jsx("button",{className:"text-button",onClick:()=>y(T=>T+1),children:"重新连接终端"})]}),f.jsx(Dt,{error:S??_.error}),f.jsx("div",{className:"xterm-mount",ref:s})]})}function HE({cwd:n,selected:t,onSelect:s}){const r=co(),{link:o}=Lt(),l=ea(()=>o.call("terminals.list",{}),[o],5e3),u=Wt(),[d,m]=b.useState(n??""),[p,y]=b.useState(""),v=yt(x=>x.status==="online");return f.jsxs("section",{className:"terminals-page",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("h2",{children:"终端"}),f.jsx("input",{"aria-label":"终端工作目录",placeholder:"工作目录(默认主目录)",value:d,onChange:x=>m(x.target.value)}),f.jsx("input",{"aria-label":"终端启动命令",placeholder:"启动命令(可选)",value:p,onChange:x=>y(x.target.value)}),f.jsx("button",{className:"button primary",disabled:u.busy||!v,onClick:()=>void u.run(async()=>{const x=await o.call("terminals.create",{cwd:d||void 0,command:p.trim()||void 0});s(x.terminal.id),l.reload()}),children:"新建终端"})]}),f.jsx(ba,{...l}),f.jsx(Dt,{error:u.error}),f.jsx("div",{className:"terminal-tabs",children:l.value?.terminals.map(x=>f.jsxs("div",{className:x.id===t?"selected":"",children:[f.jsxs("button",{onClick:()=>s(x.id),children:[x.title,f.jsx("small",{children:x.exitCode!=null?`已退出 ${x.exitCode}`:x.interrupted?"已中断":x.cwd})]}),(x.exitCode!=null||x.interrupted)&&f.jsx("button",{className:"text-button",disabled:u.busy||!v,onClick:()=>void u.run(async()=>{const _=await o.call("terminals.create",{cwd:x.cwd,command:x.command});s(_.terminal.id),l.reload()}),children:"重新运行"}),f.jsx("button",{"aria-label":`关闭终端 ${x.title}`,onClick:async()=>{await r.confirm("关闭这个终端?其中运行的进程会结束。")&&u.run(async()=>{await o.call("terminals.close",{terminalId:x.id}),x.id===t&&s(void 0),l.reload()})},children:"×"})]},x.id))}),t?f.jsx(IE,{id:t},t):f.jsx("p",{className:"muted",children:"选择一个终端,或新建 Shell。"})]})}const to=n=>{const t=new Uint8Array(n.reduce((r,o)=>r+o.length,0));let s=0;for(const r of n)t.set(r,s),s+=r.length;return t},Su=new TextEncoder;function VE(n,t=!1){const s=new TextDecoder("latin1").decode(n),r=s.indexOf(`\r
168
168
  \r
169
169
  `);if(r<0)throw new Error("HTTP 响应头不完整");const o=s.slice(0,r).split(`\r
170
170
  `),l=Number(o.shift()?.split(" ")[1]);if(!Number.isFinite(l))throw new Error("无效的 HTTP 响应");const u=o.map(p=>{const y=p.indexOf(":");return[p.slice(0,y).toLowerCase(),p.slice(y+1).trim()]});let d=n.slice(r+4);if(t||[204,205,304].includes(l))return{status:l,headers:u,body:new Uint8Array};if(u.some(([p,y])=>p==="transfer-encoding"&&/chunked/i.test(y))){const p=[];let y=0;for(;y<d.length;){let v=y;for(;v<d.length-1&&!(d[v]===13&&d[v+1]===10);)v++;const x=parseInt(new TextDecoder().decode(d.slice(y,v)).split(";")[0],16);if(!Number.isFinite(x)||x<0||v+2+x>d.length)throw new Error("HTTP 分块响应不完整");if(x===0)return{status:l,headers:u,body:to(p)};p.push(d.slice(v+2,v+2+x)),y=v+2+x+2}throw new Error("HTTP 分块响应未结束")}const m=u.find(([p])=>p==="content-length");if(m&&!t&&d.length<Number(m[1]))throw new Error("HTTP 响应被截断");return m&&(d=d.slice(0,Number(m[1]))),{status:l,headers:u,body:d}}async function qM(n,t,s,r="GET",o=[],l=new Uint8Array){if(!s.startsWith("/")||/[\r\n]/.test(s)||!/^[A-Z]+$/.test(r))throw new Error("无效的预览请求");return new Promise((u,d)=>{const m=[];let p=0,y,v=!1;const x=E=>{if(!v){if(v=!0,clearTimeout(_),y?.close(),E){d(new Error(E));return}try{u(VE(to(m),r==="HEAD"))}catch(A){d(A)}}},_=setTimeout(()=>x("预览请求超时"),6e4);n.open(t,{data(E){if(p+=E.length,p>32*1024*1024)return x("单次预览响应超过 32 MB");m.push(E)},closed:x}).then(E=>{if(v)return E.close();y=E;const A=o.filter(([j,T])=>!/[\r\n]/.test(j+T)&&!/^(host|connection|content-length|transfer-encoding|accept-encoding|origin|referer)$/i.test(j)),S=`${r} ${s} HTTP/1.1\r
@@ -195,7 +195,7 @@ Accept-Encoding: identity\r
195
195
  Content-Length: ${l.length}\r
196
196
  ${k.map(([C,R])=>`${C}: ${R}\r
197
197
  `).join("")}\r
198
- `)),l.length&&T.write(l)},T=>A(new Error(String(T))))})}function KM(){const n=window.__LINKSHELL_CONFIG__?.previewOrigin,t=void 0;if(!n&&!t)return;const s=new URL(n??t);if(!(s.origin===location.origin||!["http:","https:"].includes(s.protocol)||s.username||s.password)&&!(location.protocol==="https:"&&s.protocol!=="https:"))return s.origin}function XM({port:n}){const{streams:t}=Lt(),s=b.useRef(null),[r,o]=b.useState(),[l]=b.useState(()=>crypto.randomUUID()),u=KM();return b.useEffect(()=>{if(!u)return;let d=!0;const m=new Map,p=new Set;let y=0;const v=new Map,x=new Map,_=A=>{d&&s.current?.contentWindow?.postMessage({...A,channel:l},u)},E=A=>{if(A.source!==s.current?.contentWindow||A.origin!==u||A.data?.channel!==l)return;const S=A.data;if(S.type==="preview-ready"&&_({type:"preview-init",bootstrap:yp.toString()}),S.type==="http-cancel"&&x.get(S.id)?.abort(),S.type==="http-request"){if(++y>128){y--,_({type:"http-error",id:S.id,error:"同时请求过多"});return}const j=(S.headers??[]).filter(([k])=>!/^(cookie|proxy-authorization)$/i.test(k));v.size&&j.push(["cookie",[...v].map(([k,C])=>`${k}=${C}`).join("; ")]);const T=new AbortController;x.set(S.id,T),YM(t,n,S.path??"/",S.method??"GET",j,S.body?new Uint8Array(S.body):new Uint8Array,T.signal).then(async k=>{for(const[M,z]of k.headers)if(M==="set-cookie"){const L=z.split(";")[0],q=L.indexOf("=");if(q>0){const V=L.slice(0,q);/max-age=0/i.test(z)?v.delete(V):v.set(V,L.slice(q+1))}}let C=k.body;const R=k.headers.find(([M])=>M==="content-encoding")?.[1];if(S.method!=="HEAD"&&![204,205,304].includes(k.status)&&(R==="gzip"||R==="deflate"))C=C.pipeThrough(new DecompressionStream(R));else if(R&&!["identity","gzip","deflate"].includes(R))throw new Error(`预览暂不支持 ${R} 压缩`);_({type:"http-head",id:S.id,status:k.status,headers:k.headers});const O=C.getReader();try{for(;d;){const M=await O.read();if(M.done)break;_({type:"http-chunk",id:S.id,body:M.value})}}finally{O.releaseLock(),d||T.abort()}_({type:"http-end",id:S.id})}).catch(k=>{T.abort(),_({type:"http-error",id:S.id,error:String(k)})}).finally(()=>{x.delete(S.id),y--})}if(S.type==="ws-open"){if(m.has(S.id)||p.has(S.id)||m.size+p.size>=24)return;try{const j=new URL(S.url,u);if(![new URL(u).hostname,"localhost","127.0.0.1"].includes(j.hostname)||!["ws:","wss:"].includes(j.protocol))throw new Error("仅代理当前预览端口的 WebSocket");const k=j.pathname.replace(new RegExp(`^/preview/view/${l}/`),"/")+j.search;p.add(S.id),qE(t,n,k,{open:()=>_({type:"ws-open",id:S.id}),data:C=>_({type:"ws-data",id:S.id,data:C}),close:C=>{p.delete(S.id),m.delete(S.id),_({type:"ws-close",id:S.id,reason:C})}},S.protocols).then(C=>{!d||!p.has(S.id)?C.close():(p.delete(S.id),m.set(S.id,C))},C=>{p.delete(S.id),_({type:"ws-close",id:S.id,reason:String(C)})})}catch(j){_({type:"ws-close",id:S.id,reason:String(j)})}}S.type==="ws-send"&&(typeof S.data=="string"||S.data instanceof ArrayBuffer)&&m.get(S.id)?.send(S.data),S.type==="ws-close"&&(p.delete(S.id),m.get(S.id)?.close(),m.delete(S.id))};return window.addEventListener("message",E),()=>{d=!1,window.removeEventListener("message",E);for(const A of m.values())A.close();p.clear();for(const A of x.values())A.abort();x.clear()}},[t,n,l,u]),u?f.jsxs(f.Fragment,{children:[f.jsx(Dt,{error:r}),f.jsx("iframe",{className:"port-frame",ref:s,title:`端口 ${n} 预览`,src:`${u}/preview/bridge.html#${l}`,sandbox:"allow-scripts allow-same-origin allow-forms allow-downloads allow-modals allow-pointer-lock",allow:"autoplay; fullscreen",onLoad:()=>s.current?.contentWindow?.postMessage({channel:l,type:"preview-init",bootstrap:yp.toString()},u),onError:()=>o("隔离预览页面加载失败,请检查预览域名配置")})]}):f.jsxs("p",{className:"notice-card",children:["此部署尚未配置独立的预览域名。管理员需要设置 ",f.jsx("code",{children:"previewOrigin"})," ","并在该域名部署网页制品中的 preview 目录。开发网页与账号页面隔离,避免项目脚本读取登录凭证。"]})}function QM(){const{link:n}=Lt(),t=ea(()=>n.call("ports.list",{}),[n],1e4),[s,r]=b.useState(),[o,l]=b.useState("");return f.jsxs("section",{className:"ports-page",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("h2",{children:"端口预览"}),f.jsxs("form",{className:"inline-form",onSubmit:u=>{u.preventDefault(),r(Number(o))},children:[f.jsx("input",{"aria-label":"预览端口",type:"number",min:"1",max:"65535",value:o,onChange:u=>l(u.target.value),required:!0,placeholder:"端口号"}),f.jsx("button",{className:"button secondary",children:"打开"})]})]}),f.jsx(ba,{...t}),f.jsx("div",{className:"terminal-tabs",children:t.value?.ports.map(u=>f.jsxs("button",{className:s===u.port?"selected":"",onClick:()=>r(u.port),children:[u.port," · ",u.title??u.process,!u.http&&"(未识别为 HTTP)"]},u.port))}),s?f.jsx(XM,{port:s},s):f.jsx("p",{className:"muted",children:"选择电脑上的 HTTP 服务。请求通过加密通道传输。"})]})}const WM=b.lazy(()=>Ym(()=>import("./Prototype-BPv0rB08.js"),__vite__mapDeps([5,1,2,3,4])).then(n=>({default:n.Prototype})));function JM(){return new URLSearchParams(location.search).get("demo")==="1"?f.jsx(b.Suspense,{fallback:f.jsx("p",{children:"加载原型…"}),children:f.jsx(WM,{})}):f.jsx(e8,{})}function e8(){const n=xd(Qt.state),[t,s]=b.useState(!1),[r,o]=b.useState(()=>new URLSearchParams(location.hash.slice(1)).get("view")??Fs("lastView","home")),[l,u]=b.useState(!1),[d,m]=b.useState(()=>Fs("theme",matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"));b.useEffect(()=>{Qt.start()},[]),b.useEffect(()=>{document.documentElement.dataset.theme=d,ua("theme",d)},[d]),b.useEffect(()=>{const y=()=>o(new URLSearchParams(location.hash.slice(1)).get("view")??"home");return window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]);function p(y){ua("lastView",y),location.hash=new URLSearchParams({view:y}).toString(),o(y),u(!1)}return f.jsxs("div",{className:`app-shell ${l?"nav-open":""}`,children:[l&&f.jsx("button",{className:"nav-backdrop","aria-label":"关闭导航",onClick:()=>u(!1)}),f.jsxs("aside",{className:"sidebar",children:[f.jsxs("a",{className:"brand",href:"#home",onClick:y=>{y.preventDefault(),p("home")},children:[f.jsx("img",{src:cx,className:"brand-symbol",alt:""}),"LinkShell",f.jsx("span",{className:"brand-web",children:"web"})]}),f.jsxs("button",{className:"connection-switch",onClick:()=>s(!0),children:[f.jsx("span",{className:"source-icon",children:f.jsx(_t,{name:n.source==="official"?"globe":"server"})}),f.jsxs("span",{children:[f.jsx("strong",{children:n.source==="official"?"官方工作空间":"配对工作空间"}),f.jsx("small",{children:n.source==="official"?n.account??"登录或连接电脑":n.gateway?n.gateway.replace(/^wss?:\/\//,""):"设置你的网关"})]}),f.jsx(_t,{name:"down",size:14})]}),f.jsx("nav",{"aria-label":"主导航",children:[{id:"home",title:"首页",icon:"grid"},{id:"projects",title:"项目",icon:"folder"},{id:"computers",title:"电脑",icon:"computer"},{id:"files",title:"文件",icon:"file"},{id:"terminals",title:"终端",icon:"terminal"},{id:"ports",title:"端口预览",icon:"globe"},{id:"screen",title:"电脑屏幕",icon:"computer"},{id:"worktrees",title:"Worktree",icon:"branch"},{id:"archive",title:"已归档",icon:"clock"}].map(y=>f.jsxs("button",{className:`nav-item ${r===y.id?"active":""}`,onClick:()=>p(y.id),children:[f.jsx(_t,{name:y.icon}),y.title]},y.id))}),f.jsxs("div",{className:"sidebar-bottom",children:[f.jsxs("label",{className:"computer-select-label",children:["当前电脑",f.jsx(bd,{label:"切换电脑",value:n.connection?.computer.key??"",placeholder:"选择电脑",onValueChange:y=>{const v=n.computers.find(x=>x.key===y);v&&(Qt.select(v),p("home"))},options:n.computers.map(y=>({value:y.key,label:`${y.machine.name} · ${y.machine.online?"在线":"离线"}`}))})]}),f.jsxs("button",{className:"profile-button",onClick:()=>s(!0),children:[f.jsx("span",{className:"avatar",children:f.jsx(_t,{name:n.account?"globe":"server"})}),f.jsxs("span",{children:[f.jsx("strong",{children:n.account??"浏览器设备"}),f.jsx("small",{children:n.source==="official"?"账号连接":"配对连接"})]}),f.jsx(_t,{name:"settings"})]})]})]}),f.jsxs("main",{className:"main",children:[f.jsxs("header",{className:"topbar",children:[f.jsxs("div",{className:"breadcrumbs",children:[f.jsx("button",{className:"icon-button mobile-menu","aria-label":"打开导航",onClick:()=>u(!0),children:f.jsx(_t,{name:"menu"})}),f.jsx("strong",{children:n.connection?.computer.machine.name??"LinkShell"}),f.jsx("span",{className:"breadcrumb-slash",children:"/"}),f.jsx("span",{children:"网页工作台"})]}),f.jsxs("div",{className:"topbar-right",children:[f.jsx("button",{className:"icon-button","aria-label":"切换外观",onClick:()=>m(d==="light"?"dark":"light"),children:f.jsx(_t,{name:"moon"})}),f.jsx("button",{className:"button secondary",onClick:()=>s(!0),children:"连接设置"})]})]}),n.error&&f.jsxs("div",{className:"connection-banner",role:"alert",children:[f.jsx("span",{children:n.error}),f.jsx("button",{onClick:()=>{Qt.state.setState({error:void 0}),Qt.reconnect()},children:"重试"}),f.jsx("button",{onClick:()=>Qt.state.setState({error:void 0}),children:"关闭"})]}),n.locked?f.jsxs("div",{className:"welcome-live",children:[f.jsx("h1",{children:"工作台已在另一个标签页打开"}),f.jsx("p",{className:"muted",children:"同一个浏览器设备只保持一条连接,避免标签页相互挤掉。"}),f.jsx("button",{className:"button primary",onClick:()=>void Qt.claim(),children:"在此标签页继续"})]}):n.connection?f.jsx(Q2,{value:n.connection,children:f.jsx(t8,{view:r,navigate:p,connect:()=>s(!0)},n.connection.computer.key)}):f.jsxs("div",{className:"welcome-live",children:[f.jsx("img",{src:cx,alt:"LinkShell"}),f.jsx("h1",{children:"连接你的电脑"}),f.jsx("p",{className:"muted",children:"会话在电脑上运行,网页让你继续对话、审批和操作。"}),f.jsxs("pre",{children:["npm i -g linkshell-cli",`
198
+ `)),l.length&&T.write(l)},T=>A(new Error(String(T))))})}function KM(){const n=window.__LINKSHELL_CONFIG__?.previewOrigin,t=void 0;if(!n&&!t)return;const s=new URL(n??t);if(!(s.origin===location.origin||!["http:","https:"].includes(s.protocol)||s.username||s.password)&&!(location.protocol==="https:"&&s.protocol!=="https:"))return s.origin}function XM({port:n}){const{streams:t}=Lt(),s=b.useRef(null),[r,o]=b.useState(),[l]=b.useState(()=>crypto.randomUUID()),u=KM();return b.useEffect(()=>{if(!u)return;let d=!0;const m=new Map,p=new Set;let y=0;const v=new Map,x=new Map,_=A=>{d&&s.current?.contentWindow?.postMessage({...A,channel:l},u)},E=A=>{if(A.source!==s.current?.contentWindow||A.origin!==u||A.data?.channel!==l)return;const S=A.data;if(S.type==="preview-ready"&&_({type:"preview-init",bootstrap:yp.toString()}),S.type==="http-cancel"&&x.get(S.id)?.abort(),S.type==="http-request"){if(++y>128){y--,_({type:"http-error",id:S.id,error:"同时请求过多"});return}const j=(S.headers??[]).filter(([k])=>!/^(cookie|proxy-authorization)$/i.test(k));v.size&&j.push(["cookie",[...v].map(([k,C])=>`${k}=${C}`).join("; ")]);const T=new AbortController;x.set(S.id,T),YM(t,n,S.path??"/",S.method??"GET",j,S.body?new Uint8Array(S.body):new Uint8Array,T.signal).then(async k=>{for(const[M,z]of k.headers)if(M==="set-cookie"){const L=z.split(";")[0],q=L.indexOf("=");if(q>0){const V=L.slice(0,q);/max-age=0/i.test(z)?v.delete(V):v.set(V,L.slice(q+1))}}let C=k.body;const R=k.headers.find(([M])=>M==="content-encoding")?.[1];if(S.method!=="HEAD"&&![204,205,304].includes(k.status)&&(R==="gzip"||R==="deflate"))C=C.pipeThrough(new DecompressionStream(R));else if(R&&!["identity","gzip","deflate"].includes(R))throw new Error(`预览暂不支持 ${R} 压缩`);_({type:"http-head",id:S.id,status:k.status,headers:k.headers});const O=C.getReader();try{for(;d;){const M=await O.read();if(M.done)break;_({type:"http-chunk",id:S.id,body:M.value})}}finally{O.releaseLock(),d||T.abort()}_({type:"http-end",id:S.id})}).catch(k=>{T.abort(),_({type:"http-error",id:S.id,error:String(k)})}).finally(()=>{x.delete(S.id),y--})}if(S.type==="ws-open"){if(m.has(S.id)||p.has(S.id)||m.size+p.size>=24)return;try{const j=new URL(S.url,u);if(![new URL(u).hostname,"localhost","127.0.0.1"].includes(j.hostname)||!["ws:","wss:"].includes(j.protocol))throw new Error("仅代理当前预览端口的 WebSocket");const k=j.pathname.replace(new RegExp(`^/preview/view/${l}/`),"/")+j.search;p.add(S.id),qE(t,n,k,{open:()=>_({type:"ws-open",id:S.id}),data:C=>_({type:"ws-data",id:S.id,data:C}),close:C=>{p.delete(S.id),m.delete(S.id),_({type:"ws-close",id:S.id,reason:C})}},S.protocols).then(C=>{!d||!p.has(S.id)?C.close():(p.delete(S.id),m.set(S.id,C))},C=>{p.delete(S.id),_({type:"ws-close",id:S.id,reason:String(C)})})}catch(j){_({type:"ws-close",id:S.id,reason:String(j)})}}S.type==="ws-send"&&(typeof S.data=="string"||S.data instanceof ArrayBuffer)&&m.get(S.id)?.send(S.data),S.type==="ws-close"&&(p.delete(S.id),m.get(S.id)?.close(),m.delete(S.id))};return window.addEventListener("message",E),()=>{d=!1,window.removeEventListener("message",E);for(const A of m.values())A.close();p.clear();for(const A of x.values())A.abort();x.clear()}},[t,n,l,u]),u?f.jsxs(f.Fragment,{children:[f.jsx(Dt,{error:r}),f.jsx("iframe",{className:"port-frame",ref:s,title:`端口 ${n} 预览`,src:`${u}/preview/bridge.html#${l}`,sandbox:"allow-scripts allow-same-origin allow-forms allow-downloads allow-modals allow-pointer-lock",allow:"autoplay; fullscreen",onLoad:()=>s.current?.contentWindow?.postMessage({channel:l,type:"preview-init",bootstrap:yp.toString()},u),onError:()=>o("隔离预览页面加载失败,请检查预览域名配置")})]}):f.jsxs("p",{className:"notice-card",children:["此部署尚未配置独立的预览域名。管理员需要设置 ",f.jsx("code",{children:"previewOrigin"})," ","并在该域名部署网页制品中的 preview 目录。开发网页与账号页面隔离,避免项目脚本读取登录凭证。"]})}function QM(){const{link:n}=Lt(),t=ea(()=>n.call("ports.list",{}),[n],1e4),[s,r]=b.useState(),[o,l]=b.useState("");return f.jsxs("section",{className:"ports-page",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("h2",{children:"端口预览"}),f.jsxs("form",{className:"inline-form",onSubmit:u=>{u.preventDefault(),r(Number(o))},children:[f.jsx("input",{"aria-label":"预览端口",type:"number",min:"1",max:"65535",value:o,onChange:u=>l(u.target.value),required:!0,placeholder:"端口号"}),f.jsx("button",{className:"button secondary",children:"打开"})]})]}),f.jsx(ba,{...t}),f.jsx("div",{className:"terminal-tabs",children:t.value?.ports.map(u=>f.jsxs("button",{className:s===u.port?"selected":"",onClick:()=>r(u.port),children:[u.port," · ",u.title??u.process,!u.http&&"(未识别为 HTTP)"]},u.port))}),s?f.jsx(XM,{port:s},s):f.jsx("p",{className:"muted",children:"选择电脑上的 HTTP 服务。请求通过加密通道传输。"})]})}const WM=b.lazy(()=>Ym(()=>import("./Prototype-CXD_ISo-.js"),__vite__mapDeps([5,1,2,3,4])).then(n=>({default:n.Prototype})));function JM(){return new URLSearchParams(location.search).get("demo")==="1"?f.jsx(b.Suspense,{fallback:f.jsx("p",{children:"加载原型…"}),children:f.jsx(WM,{})}):f.jsx(e8,{})}function e8(){const n=xd(Qt.state),[t,s]=b.useState(!1),[r,o]=b.useState(()=>new URLSearchParams(location.hash.slice(1)).get("view")??Fs("lastView","home")),[l,u]=b.useState(!1),[d,m]=b.useState(()=>Fs("theme",matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"));b.useEffect(()=>{Qt.start()},[]),b.useEffect(()=>{document.documentElement.dataset.theme=d,ua("theme",d)},[d]),b.useEffect(()=>{const y=()=>o(new URLSearchParams(location.hash.slice(1)).get("view")??"home");return window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]);function p(y){ua("lastView",y),location.hash=new URLSearchParams({view:y}).toString(),o(y),u(!1)}return f.jsxs("div",{className:`app-shell ${l?"nav-open":""}`,children:[l&&f.jsx("button",{className:"nav-backdrop","aria-label":"关闭导航",onClick:()=>u(!1)}),f.jsxs("aside",{className:"sidebar",children:[f.jsxs("a",{className:"brand",href:"#home",onClick:y=>{y.preventDefault(),p("home")},children:[f.jsx("img",{src:cx,className:"brand-symbol",alt:""}),"LinkShell",f.jsx("span",{className:"brand-web",children:"web"})]}),f.jsxs("button",{className:"connection-switch",onClick:()=>s(!0),children:[f.jsx("span",{className:"source-icon",children:f.jsx(_t,{name:n.source==="official"?"globe":"server"})}),f.jsxs("span",{children:[f.jsx("strong",{children:n.source==="official"?"官方工作空间":"配对工作空间"}),f.jsx("small",{children:n.source==="official"?n.account??"登录或连接电脑":n.gateway?n.gateway.replace(/^wss?:\/\//,""):"设置你的网关"})]}),f.jsx(_t,{name:"down",size:14})]}),f.jsx("nav",{"aria-label":"主导航",children:[{id:"home",title:"首页",icon:"grid"},{id:"projects",title:"项目",icon:"folder"},{id:"computers",title:"电脑",icon:"computer"},{id:"files",title:"文件",icon:"file"},{id:"terminals",title:"终端",icon:"terminal"},{id:"ports",title:"端口预览",icon:"globe"},{id:"screen",title:"电脑屏幕",icon:"computer"},{id:"worktrees",title:"Worktree",icon:"branch"},{id:"archive",title:"已归档",icon:"clock"}].map(y=>f.jsxs("button",{className:`nav-item ${r===y.id?"active":""}`,onClick:()=>p(y.id),children:[f.jsx(_t,{name:y.icon}),y.title]},y.id))}),f.jsxs("div",{className:"sidebar-bottom",children:[f.jsxs("label",{className:"computer-select-label",children:["当前电脑",f.jsx(bd,{label:"切换电脑",value:n.connection?.computer.key??"",placeholder:"选择电脑",onValueChange:y=>{const v=n.computers.find(x=>x.key===y);v&&(Qt.select(v),p("home"))},options:n.computers.map(y=>({value:y.key,label:`${y.machine.name} · ${y.machine.online?"在线":"离线"}`}))})]}),f.jsxs("button",{className:"profile-button",onClick:()=>s(!0),children:[f.jsx("span",{className:"avatar",children:f.jsx(_t,{name:n.account?"globe":"server"})}),f.jsxs("span",{children:[f.jsx("strong",{children:n.account??"浏览器设备"}),f.jsx("small",{children:n.source==="official"?"账号连接":"配对连接"})]}),f.jsx(_t,{name:"settings"})]})]})]}),f.jsxs("main",{className:"main",children:[f.jsxs("header",{className:"topbar",children:[f.jsxs("div",{className:"breadcrumbs",children:[f.jsx("button",{className:"icon-button mobile-menu","aria-label":"打开导航",onClick:()=>u(!0),children:f.jsx(_t,{name:"menu"})}),f.jsx("strong",{children:n.connection?.computer.machine.name??"LinkShell"}),f.jsx("span",{className:"breadcrumb-slash",children:"/"}),f.jsx("span",{children:"网页工作台"})]}),f.jsxs("div",{className:"topbar-right",children:[f.jsx("button",{className:"icon-button","aria-label":"切换外观",onClick:()=>m(d==="light"?"dark":"light"),children:f.jsx(_t,{name:"moon"})}),f.jsx("button",{className:"button secondary",onClick:()=>s(!0),children:"连接设置"})]})]}),n.error&&f.jsxs("div",{className:"connection-banner",role:"alert",children:[f.jsx("span",{children:n.error}),f.jsx("button",{onClick:()=>{Qt.state.setState({error:void 0}),Qt.reconnect()},children:"重试"}),f.jsx("button",{onClick:()=>Qt.state.setState({error:void 0}),children:"关闭"})]}),n.locked?f.jsxs("div",{className:"welcome-live",children:[f.jsx("h1",{children:"工作台已在另一个标签页打开"}),f.jsx("p",{className:"muted",children:"同一个浏览器设备只保持一条连接,避免标签页相互挤掉。"}),f.jsx("button",{className:"button primary",onClick:()=>void Qt.claim(),children:"在此标签页继续"})]}):n.connection?f.jsx(Q2,{value:n.connection,children:f.jsx(t8,{view:r,navigate:p,connect:()=>s(!0)},n.connection.computer.key)}):f.jsxs("div",{className:"welcome-live",children:[f.jsx("img",{src:cx,alt:"LinkShell"}),f.jsx("h1",{children:"连接你的电脑"}),f.jsx("p",{className:"muted",children:"会话在电脑上运行,网页让你继续对话、审批和操作。"}),f.jsxs("pre",{children:["npm i -g linkshell-cli",`
199
199
  `,"linkshell host --daemon"]}),f.jsx("button",{className:"button primary",disabled:!n.ready,onClick:()=>s(!0),children:n.ready?qs==="self-hosted"?"配对电脑":"登录或配对电脑":"正在准备设备身份…"}),f.jsx("p",{className:"muted",children:qs==="self-hosted"?"运行 linkshell pair,输入此网关的配对码即可连接。":"官方服务使用 iTool 账号,自托管使用自己的网关与配对码。"}),n.computers.map(y=>f.jsxs("button",{className:"button secondary",onClick:()=>Qt.select(y),children:[y.machine.name," ·"," ",y.machine.online?"在线":"离线"]},y.key)),f.jsx("a",{className:"text-button",href:"?demo=1",children:"查看独立 UI 演示"})]})]}),t&&f.jsx($R,{close:()=>s(!1)})]})}function t8({view:n,navigate:t,connect:s}){const r=yt(y=>y),[o,l]=b.useState(),[u,d]=b.useState(),{store:m}=Lt(),p=r.sessions[n];return b.useEffect(()=>{n==="archive"&&m.getState().loadArchived()},[m,n]),f.jsxs(f.Fragment,{children:[r.status!=="online"&&f.jsxs("div",{className:"connection-banner",role:"status",children:[f.jsx("span",{children:r.statusDetail??"正在连接电脑…"}),f.jsx("button",{onClick:()=>Qt.reconnect(),children:"重新连接"})]}),p?f.jsx(GM,{session:p,navigate:t},p.id):f.jsxs("div",{className:"overview live-overview",children:[["home","archive"].includes(n)&&f.jsx(n8,{archived:n==="archive",navigate:t,create:()=>l(null)}),n==="projects"&&f.jsxs("section",{children:[f.jsxs("div",{className:"page-heading",children:[f.jsx("h1",{children:"项目"}),f.jsx("button",{className:"button primary",onClick:()=>l(null),children:"新建会话"})]}),r.projects.map(y=>f.jsxs("article",{className:"notice-card",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("strong",{children:y.name}),f.jsx("span",{className:"muted",children:y.branch}),f.jsx("button",{className:"text-button",onClick:()=>l(y.cwd),children:"在此新建"})]}),f.jsx("p",{className:"muted",children:y.cwd}),f.jsx("div",{className:"task-list",children:Object.values(r.sessions).filter(v=>v.cwd===y.cwd||v.worktree?.source===y.cwd).map(v=>f.jsx($E,{session:v,open:()=>t(v.id)},v.id))})]},y.cwd))]}),n==="computers"&&f.jsx(s8,{connect:s}),n==="files"&&f.jsxs(f.Fragment,{children:[f.jsx("h1",{children:"文件"}),f.jsx(gg,{})]}),n==="terminals"&&f.jsx(HE,{selected:u,onSelect:d}),n==="worktrees"&&f.jsx(IM,{}),n==="ports"&&f.jsx(QM,{}),n==="screen"&&f.jsx(FM,{}),!["home","archive","projects","computers","files","terminals","worktrees","ports","screen"].includes(n)&&f.jsxs("div",{className:"empty-state",children:[f.jsx("h2",{children:"会话尚未加载或已被移除"}),f.jsx("button",{className:"text-button",onClick:()=>t("home"),children:"返回首页"})]})]}),o!==void 0&&f.jsx(a8,{initialDirectory:o??void 0,close:()=>l(void 0),created:y=>{l(void 0),t(y.id)}})]})}function $E({session:n,open:t}){return f.jsxs("button",{className:"task-row",onClick:t,children:[f.jsxs("span",{className:"row-avatar",children:[f.jsx(Cd,{agent:n.agent}),f.jsx("span",{className:`tiny-status ${n.state}`})]}),f.jsxs("span",{className:"task-info",children:[f.jsx("strong",{children:Cr(n)}),f.jsxs("span",{children:[f.jsx("span",{className:"project-label",children:Wu(n.worktree?.source??n.cwd)}),f.jsx("span",{className:"separator",children:"·"}),f.jsx("span",{className:n.state==="running"?"running-copy":"",children:n.activity?.title??n.preview??n.agent})]})]}),f.jsxs("span",{className:"task-meta",children:[f.jsx("small",{children:new Date(n.updatedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),f.jsx(Ur,{state:n.state})]}),f.jsx(_t,{name:"chevron",size:14})]})}function n8({archived:n,navigate:t,create:s}){const r=yt(v=>v),o=Jn(),[l,u]=b.useState(""),[d,m]=b.useState("all"),p=Wt(),y=Object.values(r.sessions).filter(v=>v.archived===n&&`${Cr(v)} ${v.cwd} ${v.agent} ${v.preview??""}`.toLowerCase().includes(l.toLowerCase())&&(d==="all"||v.state===d)).sort((v,x)=>x.updatedAt-v.updatedAt);return f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"page-heading",children:[f.jsxs("div",{children:[f.jsx("h1",{children:n?"已归档":"首页"}),f.jsxs("p",{className:"host-summary",children:[f.jsx("span",{className:r.status==="online"?"online-dot":"offline-dot"}),r.machine?.hostname??"正在连接",f.jsxs("span",{className:"waiting-copy",children:[y.filter(v=>v.state==="waiting").length," ","项需要你"]})]})]}),f.jsxs("button",{className:"button primary",disabled:r.status!=="online",onClick:s,children:[f.jsx(_t,{name:"plus"}),"新建任务"]})]}),f.jsxs("div",{className:"home-controls",children:[f.jsxs("label",{className:"search-box",children:[f.jsx(_t,{name:"search"}),f.jsx("input",{"aria-label":"搜索会话",placeholder:"搜索会话、项目或 Agent",value:l,onChange:v=>u(v.target.value)})]}),f.jsx("div",{className:"filters",children:[{id:"all",name:"全部"},{id:"running",name:"进行中"},{id:"waiting",name:"需要你"},{id:"idle",name:"已完成"}].map(v=>f.jsx("button",{className:d===v.id?"selected":"",onClick:()=>m(v.id),children:v.name},v.id))})]}),f.jsx(Dt,{error:r.sessionsError??p.error}),!r.sessionsLoaded&&!r.sessionsError&&f.jsx("p",{className:"muted",children:"正在加载会话…"}),["waiting","running","recent"].map(v=>{const x=y.filter(_=>v==="recent"?!["waiting","running"].includes(_.state):_.state===v);return x.length?f.jsxs("section",{className:"session-group",children:[f.jsx("div",{className:`section-heading ${v==="waiting"?"waiting-heading":""}`,children:f.jsxs("h2",{children:[v==="waiting"?"需要你":v==="running"?"进行中":"最近",f.jsx("span",{children:x.length})]})}),f.jsx("div",{className:"task-list",children:x.map(_=>f.jsxs("div",{children:[f.jsx($E,{session:_,open:()=>t(_.id)}),_.permission&&v==="waiting"&&f.jsx(zE,{permission:_.permission,sessionId:_.id})]},_.id))})]},v):null}),r.sessionsLoaded&&!y.length&&f.jsxs("div",{className:"empty-state",children:[f.jsx("h3",{children:l?"没有找到会话":n?"暂无已归档会话":"开始第一个任务"}),f.jsx("p",{children:"会话保存在当前电脑,手机与网页共享同一份记录。"})]}),f.jsx("button",{className:"text-button",disabled:p.busy,onClick:()=>void p.run(()=>o.refresh()),children:"刷新列表"})]})}function a8({initialDirectory:n,close:t,created:s}){const r=yt(z=>z.machine),o=yt(z=>z.projects),l=Jn(),{store:u}=Lt(),d=yt(z=>z.status==="online"),m=Wt(),[p,y]=b.useState(r?.agents.find(z=>z.installed&&!z.problem&&z.auth?.state!=="missing"&&z.tier!=="terminal")?.id??""),[v,x]=b.useState(n??o[0]?.cwd??r?.home??""),[_,E]=b.useState(""),[A,S]=b.useState(!1),[j,T]=b.useState(!1),[k,C]=b.useState(v);b.useEffect(()=>{S(!1);const z=setTimeout(()=>C(v),250);return()=>clearTimeout(z)},[v]);const R=ea(()=>k.trim()?l.gitInfo(k):Promise.resolve(void 0),[u,k]),O=r?.agents.find(z=>z.id===p),M=!!O&&O.installed&&!O.problem&&O.auth?.state!=="missing"&&O.tier!=="terminal";return f.jsx(El,{title:"新建任务",close:t,wide:j,children:j?f.jsx(gg,{start:v,directoriesOnly:!0,onPick:z=>{x(z),T(!1)}}):f.jsxs("form",{className:"new-form",onSubmit:z=>{z.preventDefault(),!(!d||!M||!v.trim())&&m.run(async()=>s(await l.createSession({agent:p,cwd:v,worktree:A&&!!R.value&&k===v,prompt:_.trim()?[{type:"text",text:_.trim()}]:void 0})))},children:[f.jsxs("label",{children:["任务描述",f.jsx("textarea",{value:_,onChange:z=>E(z.target.value),rows:4,placeholder:"想让 Agent 完成什么?"})]}),f.jsxs("label",{children:["Agent",f.jsx(bd,{label:"Agent",value:p,onValueChange:y,options:(r?.agents??[]).map(z=>({value:z.id,label:z.label+(z.installed?z.auth?.state==="missing"?" · 未登录":z.tier==="terminal"?" · 请从终端打开":z.problem?` · ${z.problem}`:"":" · 未安装"),disabled:!z.installed||!!z.problem||z.auth?.state==="missing"||z.tier==="terminal"}))})]}),f.jsxs("label",{children:["工作目录",f.jsx("input",{value:v,onChange:z=>x(z.target.value),required:!0})]}),f.jsx("button",{type:"button",className:"text-button",onClick:()=>T(!0),children:"浏览电脑目录"}),R.value&&k===v&&f.jsxs("label",{className:"choice-option",children:[f.jsx("input",{type:"checkbox",checked:A,onChange:z=>S(z.target.checked)}),"在新 worktree 中工作"]}),f.jsx(Dt,{error:m.error}),f.jsx("button",{className:"button primary full",disabled:m.busy||!d||!M||!v.trim(),children:"创建任务"})]})})}function s8({connect:n}){const t=co(),s=xd(Qt.state),r=yt(d=>d.machine),{link:o}=Lt(),l=Wt(),u=ea(()=>o.call("gateway.status",{}),[o],1e4);return f.jsxs("section",{children:[f.jsxs("div",{className:"page-heading",children:[f.jsx("h1",{children:"电脑"}),f.jsx("button",{className:"button primary",onClick:n,children:"添加电脑"})]}),f.jsx(Dt,{error:l.error}),s.computers.map(d=>f.jsxs("article",{className:"notice-card",children:[f.jsxs("div",{className:"browser-toolbar",children:[f.jsx(_t,{name:"computer"}),f.jsx("strong",{children:d.machine.name}),f.jsx("span",{className:"muted",children:d.machine.online?"在线":"离线"}),f.jsx("button",{className:"text-button",onClick:()=>Qt.select(d),children:"切换到此电脑"}),f.jsx("button",{className:"text-button danger-text",onClick:async()=>{await t.confirm(`移除「${d.machine.name}」的连接关系?需要时可重新登录或配对。`)&&l.run(()=>Qt.forget(d))},children:"移除"})]}),f.jsx("p",{className:"muted",children:d.gateway})]},d.key)),f.jsx("h2",{children:"当前电脑"}),f.jsxs("p",{className:"muted",children:[r?.hostname," · ",r?.platform," · Host ",r?.hostVersion]}),f.jsx("h3",{children:"Agent"}),f.jsx("div",{className:"agent-list",children:r?.agents.map(d=>f.jsxs("article",{children:[f.jsx(Cd,{agent:d.id}),f.jsxs("div",{children:[f.jsx("strong",{children:d.label}),f.jsxs("p",{children:[d.installed?d.version??"已安装":"未安装"," ·"," ",d.auth?.state==="ok"?"已登录":d.auth?.state==="missing"?"需要登录":"登录状态未知"]}),(d.problem||d.auth?.hint)&&f.jsx("p",{className:"muted",children:d.problem??d.auth?.hint})]})]},d.id))}),f.jsx("h3",{children:"配对设备"}),f.jsx(ba,{...u}),u.value?.devices.map(d=>f.jsx("article",{className:"notice-card",children:f.jsxs("div",{className:"browser-toolbar",children:[f.jsx("strong",{children:d.name}),f.jsx("span",{className:"muted",children:d.online?"在线":"离线"}),f.jsx("button",{className:"text-button danger-text",onClick:async()=>{await t.confirm(`撤销「${d.name}」的配对?该设备将需要重新配对。`)&&l.run(async()=>{await o.call("devices.revoke",{deviceId:d.id}),u.reload()})},children:"撤销配对"})]})},d.id))]})}const r8=["#4a6cf7","#7d95ff"],i8=["rgba(74,108,247,0.11)","rgba(125,149,255,0.18)"],o8=["#4a6cf7","#7d95ff"],l8=["rgba(232,131,12,0.12)","rgba(255,166,61,0.16)"],c8=["rgba(15,149,96,0.12)","rgba(61,214,140,0.15)"],u8=["rgba(220,61,61,0.10)","rgba(255,107,107,0.15)"],d8=["#F0F0F4","#26262B"],f8=["#f1f1f6","#1c1c22"],h8=["#2a2b35","#e4e4ec"],m8=["rgba(15,149,96,0.12)","rgba(61,214,140,0.14)"],p8=["rgba(220,61,61,0.10)","rgba(255,107,107,0.14)"],g8=["#0b7a4f","#7fddb4"],v8=["#b42f2f","#ff9a9a"],y8=["#000000","#FFFFFF"],b8=["rgba(60,60,67,0.6)","rgba(235,235,245,0.6)"],x8=["rgba(60,60,67,0.3)","rgba(235,235,245,0.3)"],w8=["rgba(60,60,67,0.3)","rgba(235,235,245,0.3)"],S8=["rgba(60,60,67,0.18)","rgba(84,84,88,0.6)"],E8=["#F2F2F7","#000000"],_8=["#FFFFFF","#1C1C1E"],C8=["#FFFFFF","#2C2C2E"],A8=["#F2F2F7","#1C1C1E"],j8=["#FFFFFF","#000000"],T8=["rgba(118,118,128,0.12)","rgba(118,118,128,0.24)"],k8=["rgba(120,120,128,0.16)","rgba(120,120,128,0.32)"],N8=["#E8830C","#FF9F0A"],O8=["#0F9560","#30D158"],R8=["#DC3D3D","#FF453A"],D8=["#F2F2F7","#1C1C1E"],M8=["#FFFFFF","#2C2C2E"],z8={accent:r8,accentSoft:i8,running:o8,waitingSoft:l8,okSoft:c8,dangerSoft:u8,userBubble:d8,code:f8,codeText:h8,diffAdd:m8,diffDel:p8,diffAddText:g8,diffDelText:v8,label:y8,secondaryLabel:b8,tertiaryLabel:x8,placeholder:w8,separator:S8,background:E8,card:_8,cardRaised:C8,inset:A8,plain:j8,fill:T8,fillStrong:k8,waiting:N8,ok:O8,danger:R8,sheet:D8,sheetCard:M8},Am=n=>Object.entries(z8).map(([t,s])=>`--${t}: ${s[n]};`).join(`
200
200
  `),L8=`
201
201
  :root { ${Am(0)} color-scheme: light; }