9remote 3.0.49 → 3.0.51

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.
Files changed (197) hide show
  1. package/dist/cli.cjs +2 -2
  2. package/dist/server.cjs +221 -220
  3. package/dist/ui/assets/index-DBIJ-xKe.js +8 -0
  4. package/dist/ui/index.html +1 -1
  5. package/dist/web/404.html +1 -1
  6. package/dist/web/__next.__PAGE__.txt +2 -2
  7. package/dist/web/__next._full.txt +3 -3
  8. package/dist/web/__next._head.txt +1 -1
  9. package/dist/web/__next._index.txt +2 -2
  10. package/dist/web/__next._tree.txt +2 -2
  11. package/dist/web/_next/static/chunks/{8126-a5f1dc08132cc504.js → 8126-f4d44cf6bcc47fd8.js} +1 -1
  12. package/dist/web/_next/static/chunks/app/{page-08396a6df5b1d417.js → page-7214428f117eb5c3.js} +1 -1
  13. package/dist/web/_next/static/chunks/app/workspace/{layout-a0cc68d6cac6faac.js → layout-ff89db2ea6f5ca76.js} +4 -4
  14. package/dist/web/_next/static/css/6fa39aa9632abb78.css +1 -0
  15. package/dist/web/_not-found/__next._full.txt +2 -2
  16. package/dist/web/_not-found/__next._head.txt +1 -1
  17. package/dist/web/_not-found/__next._index.txt +2 -2
  18. package/dist/web/_not-found/__next._not-found.__PAGE__.txt +1 -1
  19. package/dist/web/_not-found/__next._not-found.txt +1 -1
  20. package/dist/web/_not-found/__next._tree.txt +2 -2
  21. package/dist/web/_not-found.html +1 -1
  22. package/dist/web/_not-found.txt +2 -2
  23. package/dist/web/admin/__next._full.txt +2 -2
  24. package/dist/web/admin/__next._head.txt +1 -1
  25. package/dist/web/admin/__next._index.txt +2 -2
  26. package/dist/web/admin/__next._tree.txt +2 -2
  27. package/dist/web/admin/__next.admin.__PAGE__.txt +1 -1
  28. package/dist/web/admin/__next.admin.txt +1 -1
  29. package/dist/web/admin/access/__next._full.txt +2 -2
  30. package/dist/web/admin/access/__next._head.txt +1 -1
  31. package/dist/web/admin/access/__next._index.txt +2 -2
  32. package/dist/web/admin/access/__next._tree.txt +2 -2
  33. package/dist/web/admin/access/__next.admin.access.__PAGE__.txt +1 -1
  34. package/dist/web/admin/access/__next.admin.access.txt +1 -1
  35. package/dist/web/admin/access/__next.admin.txt +1 -1
  36. package/dist/web/admin/access.html +1 -1
  37. package/dist/web/admin/access.txt +2 -2
  38. package/dist/web/admin/login/__next._full.txt +2 -2
  39. package/dist/web/admin/login/__next._head.txt +1 -1
  40. package/dist/web/admin/login/__next._index.txt +2 -2
  41. package/dist/web/admin/login/__next._tree.txt +2 -2
  42. package/dist/web/admin/login/__next.admin.login.__PAGE__.txt +1 -1
  43. package/dist/web/admin/login/__next.admin.login.txt +1 -1
  44. package/dist/web/admin/login/__next.admin.txt +1 -1
  45. package/dist/web/admin/login.html +1 -1
  46. package/dist/web/admin/login.txt +2 -2
  47. package/dist/web/admin/ota/__next._full.txt +2 -2
  48. package/dist/web/admin/ota/__next._head.txt +1 -1
  49. package/dist/web/admin/ota/__next._index.txt +2 -2
  50. package/dist/web/admin/ota/__next._tree.txt +2 -2
  51. package/dist/web/admin/ota/__next.admin.ota.__PAGE__.txt +1 -1
  52. package/dist/web/admin/ota/__next.admin.ota.txt +1 -1
  53. package/dist/web/admin/ota/__next.admin.txt +1 -1
  54. package/dist/web/admin/ota.html +1 -1
  55. package/dist/web/admin/ota.txt +2 -2
  56. package/dist/web/admin/turn/__next._full.txt +2 -2
  57. package/dist/web/admin/turn/__next._head.txt +1 -1
  58. package/dist/web/admin/turn/__next._index.txt +2 -2
  59. package/dist/web/admin/turn/__next._tree.txt +2 -2
  60. package/dist/web/admin/turn/__next.admin.turn.__PAGE__.txt +1 -1
  61. package/dist/web/admin/turn/__next.admin.turn.txt +1 -1
  62. package/dist/web/admin/turn/__next.admin.txt +1 -1
  63. package/dist/web/admin/turn.html +1 -1
  64. package/dist/web/admin/turn.txt +2 -2
  65. package/dist/web/admin.html +1 -1
  66. package/dist/web/admin.txt +2 -2
  67. package/dist/web/download/__next._full.txt +2 -2
  68. package/dist/web/download/__next._head.txt +1 -1
  69. package/dist/web/download/__next._index.txt +2 -2
  70. package/dist/web/download/__next._tree.txt +2 -2
  71. package/dist/web/download/__next.download.__PAGE__.txt +1 -1
  72. package/dist/web/download/__next.download.txt +1 -1
  73. package/dist/web/download.html +1 -1
  74. package/dist/web/download.txt +2 -2
  75. package/dist/web/index.html +1 -1
  76. package/dist/web/index.txt +3 -3
  77. package/dist/web/login/__next._full.txt +3 -3
  78. package/dist/web/login/__next._head.txt +1 -1
  79. package/dist/web/login/__next._index.txt +2 -2
  80. package/dist/web/login/__next._tree.txt +2 -2
  81. package/dist/web/login/__next.login.__PAGE__.txt +2 -2
  82. package/dist/web/login/__next.login.txt +1 -1
  83. package/dist/web/login.html +1 -1
  84. package/dist/web/login.txt +3 -3
  85. package/dist/web/workspace/__next._full.txt +3 -3
  86. package/dist/web/workspace/__next._head.txt +1 -1
  87. package/dist/web/workspace/__next._index.txt +2 -2
  88. package/dist/web/workspace/__next._tree.txt +2 -2
  89. package/dist/web/workspace/__next.workspace.__PAGE__.txt +1 -1
  90. package/dist/web/workspace/__next.workspace.txt +2 -2
  91. package/dist/web/workspace/browse/__next._full.txt +3 -3
  92. package/dist/web/workspace/browse/__next._head.txt +1 -1
  93. package/dist/web/workspace/browse/__next._index.txt +2 -2
  94. package/dist/web/workspace/browse/__next._tree.txt +2 -2
  95. package/dist/web/workspace/browse/__next.workspace.browse.__PAGE__.txt +1 -1
  96. package/dist/web/workspace/browse/__next.workspace.browse.txt +1 -1
  97. package/dist/web/workspace/browse/__next.workspace.txt +2 -2
  98. package/dist/web/workspace/browse.html +1 -1
  99. package/dist/web/workspace/browse.txt +3 -3
  100. package/dist/web/workspace/editor/__next._full.txt +3 -3
  101. package/dist/web/workspace/editor/__next._head.txt +1 -1
  102. package/dist/web/workspace/editor/__next._index.txt +2 -2
  103. package/dist/web/workspace/editor/__next._tree.txt +2 -2
  104. package/dist/web/workspace/editor/__next.workspace.editor.__PAGE__.txt +1 -1
  105. package/dist/web/workspace/editor/__next.workspace.editor.txt +1 -1
  106. package/dist/web/workspace/editor/__next.workspace.txt +2 -2
  107. package/dist/web/workspace/editor.html +1 -1
  108. package/dist/web/workspace/editor.txt +3 -3
  109. package/dist/web/workspace/files/__next._full.txt +3 -3
  110. package/dist/web/workspace/files/__next._head.txt +1 -1
  111. package/dist/web/workspace/files/__next._index.txt +2 -2
  112. package/dist/web/workspace/files/__next._tree.txt +2 -2
  113. package/dist/web/workspace/files/__next.workspace.files.__PAGE__.txt +1 -1
  114. package/dist/web/workspace/files/__next.workspace.files.txt +1 -1
  115. package/dist/web/workspace/files/__next.workspace.txt +2 -2
  116. package/dist/web/workspace/files.html +1 -1
  117. package/dist/web/workspace/files.txt +3 -3
  118. package/dist/web/workspace/git/__next._full.txt +3 -3
  119. package/dist/web/workspace/git/__next._head.txt +1 -1
  120. package/dist/web/workspace/git/__next._index.txt +2 -2
  121. package/dist/web/workspace/git/__next._tree.txt +2 -2
  122. package/dist/web/workspace/git/__next.workspace.git.__PAGE__.txt +1 -1
  123. package/dist/web/workspace/git/__next.workspace.git.txt +1 -1
  124. package/dist/web/workspace/git/__next.workspace.txt +2 -2
  125. package/dist/web/workspace/git.html +1 -1
  126. package/dist/web/workspace/git.txt +3 -3
  127. package/dist/web/workspace/mobile/__next._full.txt +3 -3
  128. package/dist/web/workspace/mobile/__next._head.txt +1 -1
  129. package/dist/web/workspace/mobile/__next._index.txt +2 -2
  130. package/dist/web/workspace/mobile/__next._tree.txt +2 -2
  131. package/dist/web/workspace/mobile/__next.workspace.mobile.__PAGE__.txt +1 -1
  132. package/dist/web/workspace/mobile/__next.workspace.mobile.txt +1 -1
  133. package/dist/web/workspace/mobile/__next.workspace.txt +2 -2
  134. package/dist/web/workspace/mobile.html +1 -1
  135. package/dist/web/workspace/mobile.txt +3 -3
  136. package/dist/web/workspace/pair/__next._full.txt +3 -3
  137. package/dist/web/workspace/pair/__next._head.txt +1 -1
  138. package/dist/web/workspace/pair/__next._index.txt +2 -2
  139. package/dist/web/workspace/pair/__next._tree.txt +2 -2
  140. package/dist/web/workspace/pair/__next.workspace.pair.__PAGE__.txt +1 -1
  141. package/dist/web/workspace/pair/__next.workspace.pair.txt +1 -1
  142. package/dist/web/workspace/pair/__next.workspace.txt +2 -2
  143. package/dist/web/workspace/pair.html +1 -1
  144. package/dist/web/workspace/pair.txt +3 -3
  145. package/dist/web/workspace/remote/__next._full.txt +3 -3
  146. package/dist/web/workspace/remote/__next._head.txt +1 -1
  147. package/dist/web/workspace/remote/__next._index.txt +2 -2
  148. package/dist/web/workspace/remote/__next._tree.txt +2 -2
  149. package/dist/web/workspace/remote/__next.workspace.remote.__PAGE__.txt +1 -1
  150. package/dist/web/workspace/remote/__next.workspace.remote.txt +1 -1
  151. package/dist/web/workspace/remote/__next.workspace.txt +2 -2
  152. package/dist/web/workspace/remote.html +1 -1
  153. package/dist/web/workspace/remote.txt +3 -3
  154. package/dist/web/workspace/settings/__next._full.txt +3 -3
  155. package/dist/web/workspace/settings/__next._head.txt +1 -1
  156. package/dist/web/workspace/settings/__next._index.txt +2 -2
  157. package/dist/web/workspace/settings/__next._tree.txt +2 -2
  158. package/dist/web/workspace/settings/__next.workspace.settings.__PAGE__.txt +1 -1
  159. package/dist/web/workspace/settings/__next.workspace.settings.txt +1 -1
  160. package/dist/web/workspace/settings/__next.workspace.txt +2 -2
  161. package/dist/web/workspace/settings.html +1 -1
  162. package/dist/web/workspace/settings.txt +3 -3
  163. package/dist/web/workspace/terminal/default/__next._full.txt +3 -3
  164. package/dist/web/workspace/terminal/default/__next._head.txt +1 -1
  165. package/dist/web/workspace/terminal/default/__next._index.txt +2 -2
  166. package/dist/web/workspace/terminal/default/__next._tree.txt +2 -2
  167. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.__PAGE__.txt +1 -1
  168. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.txt +1 -1
  169. package/dist/web/workspace/terminal/default/__next.workspace.terminal.txt +1 -1
  170. package/dist/web/workspace/terminal/default/__next.workspace.txt +2 -2
  171. package/dist/web/workspace/terminal/default.html +1 -1
  172. package/dist/web/workspace/terminal/default.txt +3 -3
  173. package/dist/web/workspace/welcome/__next._full.txt +3 -3
  174. package/dist/web/workspace/welcome/__next._head.txt +1 -1
  175. package/dist/web/workspace/welcome/__next._index.txt +2 -2
  176. package/dist/web/workspace/welcome/__next._tree.txt +2 -2
  177. package/dist/web/workspace/welcome/__next.workspace.txt +2 -2
  178. package/dist/web/workspace/welcome/__next.workspace.welcome.__PAGE__.txt +1 -1
  179. package/dist/web/workspace/welcome/__next.workspace.welcome.txt +1 -1
  180. package/dist/web/workspace/welcome.html +1 -1
  181. package/dist/web/workspace/welcome.txt +3 -3
  182. package/dist/web/workspace/workspaces/__next._full.txt +3 -3
  183. package/dist/web/workspace/workspaces/__next._head.txt +1 -1
  184. package/dist/web/workspace/workspaces/__next._index.txt +2 -2
  185. package/dist/web/workspace/workspaces/__next._tree.txt +2 -2
  186. package/dist/web/workspace/workspaces/__next.workspace.txt +2 -2
  187. package/dist/web/workspace/workspaces/__next.workspace.workspaces.__PAGE__.txt +1 -1
  188. package/dist/web/workspace/workspaces/__next.workspace.workspaces.txt +1 -1
  189. package/dist/web/workspace/workspaces.html +1 -1
  190. package/dist/web/workspace/workspaces.txt +3 -3
  191. package/dist/web/workspace.html +1 -1
  192. package/dist/web/workspace.txt +3 -3
  193. package/package.json +1 -1
  194. package/dist/ui/assets/index-BlDioy5o.js +0 -8
  195. package/dist/web/_next/static/css/316b0ddc7b4a58b9.css +0 -1
  196. /package/dist/web/_next/static/{i311IptpwHw7-DoFsaASO → LIdIrEk-ouqVQIPGxkDup}/_buildManifest.js +0 -0
  197. /package/dist/web/_next/static/{i311IptpwHw7-DoFsaASO → LIdIrEk-ouqVQIPGxkDup}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8126],{189:(e,t,r)=>{r.d(t,{Fo:()=>u,U0:()=>o,vd:()=>d});var n=r(7620),i=r(89228);let s="9remote_auth",a="9remote_auth_state",l=["apiKey","tunnelUrl","mode","localIp"];function o(){try{localStorage.removeItem(a)}catch{}}function c(e){"u">typeof document&&(document.cookie=`${s}=${e}; path=/; max-age=86400; SameSite=Lax`)}function d(e){let{apiKey:t,tunnelUrl:r,mode:n="remote",tempKey:s=null,localIp:l=null}=e;if(!t){try{localStorage.removeItem(a)}catch{}return}try{sessionStorage.setItem("apiKey",t),sessionStorage.setItem("tunnelUrl",r),sessionStorage.setItem("mode",n||"remote"),s?sessionStorage.setItem("tempKey",s):sessionStorage.removeItem("tempKey"),l?sessionStorage.setItem("localIp",l):sessionStorage.removeItem("localIp")}catch{}c(t);try{sessionStorage.removeItem("9remote_manual_disconnect")}catch{}try{!function(){try{return"false"!==localStorage.getItem("9remote_remember_key_preference")}catch{return!1}}()?localStorage.removeItem(a):localStorage.setItem(a,JSON.stringify({apiKey:t,tunnelUrl:r,mode:n,localIp:l}))}catch{}i.d.getState().setAuthKey(t)}function u(){let e=(0,n.useCallback)(()=>{let e,t,r,n,i;try{e=sessionStorage.getItem("apiKey"),t=sessionStorage.getItem("tunnelUrl"),r=sessionStorage.getItem("mode"),n=sessionStorage.getItem("tempKey"),i=sessionStorage.getItem("localIp")}catch{return null}if(!e){let n=function(){try{return JSON.parse(localStorage.getItem(a)||"null")}catch{return null}}();if(!n?.apiKey)return null;try{for(let e of l)n[e]&&sessionStorage.setItem(e,n[e])}catch{}e=n.apiKey,t=n.tunnelUrl??null,r=n.mode??null,i=n.localIp??null}return c(e),{apiKey:e,tunnelUrl:t,mode:r,tempKey:n,localIp:i}},[]);return{getAuth:e,setAuth:(0,n.useCallback)(e=>d(e),[]),clearAuth:(0,n.useCallback)(()=>{try{sessionStorage.clear()}catch{}try{localStorage.removeItem(a)}catch{}"u">typeof document&&(document.cookie=`${s}=; path=/; max-age=0`)},[])}}},6134:(e,t,r)=>{r.d(t,{FQ:()=>o,Lq:()=>f,UX:()=>l,k_:()=>d,yO:()=>c});var n=r(96631);let i=[],s=new Set,a=location.hostname.startsWith("dev.")||"localhost"===location.hostname&&!(0,n.gJ)()||"1"===localStorage.getItem("9remote:termLog");function l(){return a}function o(){return i}function c(e){return s.add(e),()=>s.delete(e)}function d(){for(let e of(i.length=0,s))try{e(null)}catch(e){}}function u(e){if(null==e)return"";if(e instanceof Uint8Array||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return`<${e.byteLength}b>`;if("string"==typeof e)return e.length>120?`${e.slice(0,60)}…${e.length}b`:e;if("object"==typeof e)try{return JSON.stringify(e)}catch(e){}return String(e)}let h=new Set(["recv"]),p=null;function f(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if(!a)return;let l=Date.now(),o=r.map(u).join(" ");if(p&&p.category===e&&p.baseMsg===o&&l-p.ts<3e3||h.has(e)&&p&&p.category===e&&l-p.ts<300){p.count=(p.count||1)+1,p.ts=l,p.msg=`${o} \xd7${p.count}`,queueMicrotask(()=>{for(let e of s)try{e(p)}catch(e){}});return}let c={ts:l,category:e,msg:o,baseMsg:o,count:1};p=c,i.push(c),i.length>800&&i.shift(),queueMicrotask(()=>{for(let e of s)try{e(c)}catch(e){}})}},14337:(e,t,r)=>{r.d(t,{A:()=>i});var n=r(54568);function i(e){let{size:t="md",text:r,className:i=""}=e;return(0,n.jsxs)("div",{className:`flex flex-col items-center justify-center gap-3 ${i}`,children:[(0,n.jsx)("div",{className:`animate-spin rounded-full border-brand-500 border-t-transparent ${{sm:"h-4 w-4 border-2",md:"h-8 w-8 border-2",lg:"h-12 w-12 border-b-2"}[t]}`}),r&&(0,n.jsx)("p",{className:"text-brand-500 text-sm font-medium",children:r})]})}},14511:(e,t,r)=>{r.d(t,{freshAuth:()=>s});var n=r(99022),i=r(68469);async function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r={...e,connectionMode:t},s=(0,n.lz)(e.apiKey),a=e.tempKey?(0,n.lz)(e.tempKey):null,l=a?.tail?a:s?.tail?s:s||a,o=l?.tail;if(delete r.keyTail,delete r.keyTailSealed,!o)return r;if(l?.hostSealKey){let e=await (0,i.Y)(o,l.hostSealKey);if(e)return r.keyTailSealed=e,r}return r.keyTail=o,r}},14757:(e,t,r)=>{r.d(t,{k:()=>n});function n(e){let t=String(e||"").trim(),r=e=>({tempKey:e.slice(0,6).toUpperCase(),tail:e.slice(6,8).toUpperCase()}),n=/#([A-NP-Z1-9]{6}-?[a-np-z1-9]{2})$/i.exec(t);if(n)return r(n[1].replace(/-/g,""));let i=/^([A-NP-Z1-9]{6}-?[a-np-z1-9]{2})$/i.exec(t);if(i)return r(i[1].replace(/-/g,""));let s=/[?&]k=([A-NP-Z1-9]{6})(?:[^A-NP-Z1-9]|$)/i.exec(t);return s?{tempKey:s[1].toUpperCase()}:/^[A-NP-Z1-9]{6}$/i.test(t)?{tempKey:t.toUpperCase()}:null}},18179:(e,t,r)=>{r.d(t,{A:()=>d});var n=r(54568),i=r(7620),s=r(97509),a=r(96605),l=r(14652),o=r(9121),c=r(33879);function d(e){let{isOpen:t,onClose:r}=e,{t:d,locale:u,setLocale:h}=(0,o.s)();return((0,i.useEffect)(()=>{if(!t)return;let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t,r]),t)?!t||"u"<typeof document?null:(0,s.createPortal)((0,n.jsxs)("div",{className:"modal-overlay z-[70]",children:[(0,n.jsx)("div",{className:"absolute inset-0 scrim fade-in",onClick:r}),(0,n.jsxs)("div",{className:"relative card-elev max-w-lg w-full my-auto flex flex-col pop-in",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:d("menu.language")}),(0,n.jsx)("button",{onClick:r,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":d("common.close"),children:(0,n.jsx)(a.X,{size:20})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable p-3",children:(0,n.jsx)("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.dI.map(e=>{let t=e.code===u;return(0,n.jsxs)("button",{onClick:()=>{var t;return t=e.code,void((0,l.e)(),h(t),r())},className:`px-2 py-2 rounded-brand flex items-center gap-2 transition-all duration-150 ease-out active:scale-[0.97] min-w-0 ${t?"bg-brand-500 text-white":"text-text hover:bg-surface-2"}`,children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w80/${e.country}.png`,alt:e.label,className:"w-5 h-[14px] object-cover rounded-[2px] flex-shrink-0",loading:"lazy"}),(0,n.jsx)("span",{className:"flex-1 text-sm font-medium truncate text-left",children:e.label}),t&&(0,n.jsx)(a.aJ,{size:14,className:"flex-shrink-0"})]},e.code)})})})]})]}),document.body):null}},18753:(e,t,r)=>{r.d(t,{U:()=>n});function n(e,t){if(!e||!t)return!1;let r=String(e).split(".").map(Number),n=String(t).split(".").map(Number);for(let e=0;e<3;e++){let t=r[e]||0,i=n[e]||0;if(t!==i)return t>i}return!1}},23084:(e,t,r)=>{r.d(t,{A:()=>c});var n=r(54568),i=r(7620),s=r(97509),a=r(14652),l=r(9121),o=r(96605);function c(e){let{isOpen:t,onClose:r,onConfirm:c,title:d,message:u,confirmText:h,cancelText:p}=e,{t:f}=(0,l.s)(),m=(0,i.useRef)(null),g=(0,i.useRef)(null),y=h??f("common.confirm"),_=p??f("common.cancel");return((0,i.useEffect)(()=>{if(!t)return;let e=requestAnimationFrame(()=>{g.current?.focus()});return()=>cancelAnimationFrame(e)},[t]),(0,i.useEffect)(()=>{if(!t)return;let e=e=>{if("Escape"===e.key)e.preventDefault(),e.stopPropagation(),r();else if("Enter"===e.key){if(m.current&&document.activeElement===m.current){e.preventDefault(),e.stopPropagation(),r();return}e.preventDefault(),e.stopPropagation(),(0,a.e)(),c?.(),r()}};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[t,r,c]),!t||"u"<typeof document)?null:(0,s.createPortal)((0,n.jsxs)("div",{className:"modal-overlay z-[100]",children:[(0,n.jsx)("div",{className:"absolute inset-0 scrim fade-in",onClick:r}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",className:"relative card-elev max-w-md w-full my-auto overflow-y-auto pop-in",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsx)("div",{className:"px-6 py-4",children:(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:d})}),(0,n.jsx)("div",{className:"px-6 pb-4",children:(0,n.jsx)("p",{className:"text-text whitespace-pre-line",children:u})}),(0,n.jsxs)("div",{className:"px-6 py-4 flex justify-end gap-3",children:[(0,n.jsxs)("button",{ref:m,onClick:()=>{(0,a.e)(),r()},className:"px-4 py-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.98] font-medium flex items-center gap-1.5",children:[(0,n.jsx)("span",{children:_}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{ref:g,onClick:()=>{(0,a.e)(),c?.(),r()},className:"px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-brand transition-all duration-150 ease-out active:scale-[0.98] font-medium flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-red-500/50",children:[(0,n.jsx)("span",{children:y}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(o.Lt,{size:10,strokeWidth:2.5})})]})]})]})]}),document.body)}},23635:(e,t,r)=>{r.d(t,{B:()=>p});var n=r(94245),i=r(59055),s=r(36487),a=r(30368),l=r(72627);let o=(e,t)=>{let{min:r,max:n}=t;return Math.max(r,Math.min(n,Math.round(e)))};var c=r(92571);let d={name:null,value:null},u=null,h=()=>{if(u&&(clearTimeout(u),u=null),null===d.name)return;let{name:e,value:t}=d;d.name=null,d.value=null;try{localStorage.setItem(e,JSON.stringify(t))}catch{}};window.addEventListener("pagehide",h),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&h()});let p=(0,n.v)((0,i.Zr)((e,t,r)=>({...{viewStack:[{type:"list"}],navDir:"forward",openedSessions:[],activeWorkspaceId:null,setActiveWorkspaceId:t=>e(e=>({activeWorkspaceId:t,fullMode:!!e.fullModes?.[t??l.AD]})),livePanes:[],touchLivePane:t=>e(e=>{let r=Array.isArray(t)?t:[t];return{livePanes:[...e.livePanes.filter(e=>!r.includes(e)),...r].slice(-s.kn)}}),mountedWorkspaces:{},markWorkspaceMounted:t=>e(e=>{let r=t??l.AD;return e.mountedWorkspaces[r]?e:{mountedWorkspaces:{...e.mountedWorkspaces,[r]:!0}}}),isWorkspaceMounted:e=>{let r=e??l.AD;return!!t().mountedWorkspaces[r]},drafts:{},setDraft:(t,r)=>e(e=>({drafts:{...e.drafts,[t]:r}})),collapsedWorkspaces:{},toggleWorkspace:t=>e(e=>({collapsedWorkspaces:{...e.collapsedWorkspaces,[t]:!e.collapsedWorkspaces[t]}})),cwdBySession:{},setCwd:(t,r)=>{if(!t||!r)return;let n=(0,c.kb)(r);e(e=>e.cwdBySession[t]===n?e:{cwdBySession:{...e.cwdBySession,[t]:n}})},selectTab:t=>e(e=>{let r=a.x0.includes(t?.type)?t:e.viewStack[0]||{type:"list"},n=a.XG.indexOf(e.viewStack[e.viewStack.length-1]?.type),i=a.XG.indexOf(r.type);return{viewStack:[r],navDir:-1!==n&&-1!==i&&i<n?"back":"forward"}}),pushView:t=>e(e=>{let r=Array.isArray(e.viewStack)?e.viewStack:[],n=a.yP.includes(t?.type),i=n?r:r.filter((e,t)=>!(a.yP.includes(e?.type)&&t===r.length-1));if(n&&i.length&&i[i.length-1]?.type===t?.type){let e=[...i];return e[e.length-1]=t,{viewStack:e}}return{viewStack:[...i,t]}}),popView:()=>e(e=>{let t=Array.isArray(e.viewStack)?e.viewStack:[];return{viewStack:t.length>1?t.slice(0,-1):[{type:"list"}]}}),setViewStack:t=>e({viewStack:t}),addOpenedSession:t=>e(e=>({openedSessions:e.openedSessions.includes(t)?e.openedSessions:[...e.openedSessions,t]})),removeOpenedSession:t=>e(e=>{let{[t]:r,...n}=e.drafts,{[t]:i,...s}=e.pendingStartup,{[t]:a,...l}=e.artifactsBySession;return{artifactsBySession:l,openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),hiddenPaneSessionIds:e.hiddenPaneSessionIds?e.hiddenPaneSessionIds.filter(e=>e!==t):[],drafts:n,pendingStartup:s}}),replaceOpenedSession:(t,r)=>e(e=>{if(!r||t===r)return e;let n=e=>e===t?r:e;return{openedSessions:!t||e.openedSessions.includes(t)?e.openedSessions.map(n):e.openedSessions.includes(r)?e.openedSessions:[...e.openedSessions,r],livePanes:e.livePanes.map(n)}}),clearOpenedSessions:()=>e({openedSessions:[],livePanes:[]}),reorderOpenedSessions:t=>e(e=>{let r=new Set(t),n=t.filter(t=>e.openedSessions.includes(t));if(n.length<2)return{};let i=0;return{openedSessions:e.openedSessions.map(e=>r.has(e)?n[i++]:e)}}),closeSession:t=>e(e=>{let{[t]:r,...n}=e.drafts,{[t]:i,...s}=e.pendingStartup,{[t]:a,...l}=e.agentBySession,o=((e,t)=>{let r={};for(let[n,i]of Object.entries(e))r[n]={at:0,sessions:t?i.sessions.map(t):i.sessions};return r})(e.agentHistory,e=>e.openSessionId===t?{...e,openSessionId:null}:e);return{openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),drafts:n,pendingStartup:s,agentBySession:l,agentHistory:o}}),getCurrentView:()=>{let{viewStack:e}=t();return e[e.length-1]},getSelectedSession:()=>{let{viewStack:e}=t();for(let t=e.length-1;t>=0;t--)if("terminal"===e[t].type)return e[t].sessionId;return null},reset:()=>e({viewStack:[{type:"list"}],openedSessions:[],livePanes:[],activeWorkspaceId:null})},...{sidebarCollapsed:!1,toggleSidebar:()=>e(e=>({sidebarCollapsed:!e.sidebarCollapsed})),setSidebarCollapsed:t=>e({sidebarCollapsed:!!t}),sidebarWidth:s.gH.default,setSidebarWidth:t=>e({sidebarWidth:o(t,s.gH)}),fullModes:{},fullMode:!1,toggleFullMode:t=>e(e=>{let r=t??e.activeWorkspaceId??l.AD,n=!e.fullModes[r];return{fullModes:{...e.fullModes,[r]:n},fullMode:r===(e.activeWorkspaceId??l.AD)?n:e.fullMode}}),setFullMode:(t,r)=>e(e=>{let n="boolean"==typeof t?e.activeWorkspaceId??l.AD:t??e.activeWorkspaceId??l.AD,i="boolean"==typeof t?t:!!r;return{fullModes:{...e.fullModes,[n]:i},fullMode:n===(e.activeWorkspaceId??l.AD)?i:e.fullMode}}),hiddenPaneSessionIds:[],toggleHidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.includes(t)?e.hiddenPaneSessionIds.filter(e=>e!==t):[...e.hiddenPaneSessionIds,t]})),unhidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.filter(e=>e!==t)})),paneWidths:{},setPaneWidth:(t,r)=>e(e=>({paneWidths:{...e.paneWidths,[t]:null==r?null:o(r,s.k9)}})),rightPanelOpen:window.innerWidth>=s.jK,rightPanelTabs:{},rightPanelWidth:s.Ds.default,toggleRightPanel:()=>e(e=>({rightPanelOpen:!e.rightPanelOpen,rightPanelWasOpen:null})),closeRightPanel:()=>e({rightPanelOpen:!1,rightPanelWasOpen:null}),openRightPanel:()=>e({rightPanelOpen:!0,rightPanelWasOpen:null}),setRightPanelTab:(t,r)=>e(e=>({rightPanelOpen:!0,rightPanelWasOpen:null,...null!=r?{rightPanelTabs:{...e.rightPanelTabs,[r]:t}}:{}})),rightPanelRoots:{},setRightPanelRoot:(t,r)=>e(e=>{if(null==t)return e;let n=e.rightPanelRoots[t],i=r&&r!==t?r:void 0;if(n===i)return e;let s={...e.rightPanelRoots};return i?s[t]=i:delete s[t],{rightPanelRoots:s}}),setRightPanelWidth:t=>e({rightPanelWidth:o(t,s.Ds)}),editorFilePath:null,editorPanelWidth:s.Ao.default,setEditorPanelWidth:t=>e({editorPanelWidth:o(t,s.Ao)}),editorPreviewSeq:0,artifactTitle:null,rightPanelWasOpen:null,artifactSessionId:null,editorJump:null,openEditorFile:function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e(e=>({editorFilePath:t,editorPreviewSeq:r.preview?e.editorPreviewSeq+1:0,artifactTitle:r.artifactTitle||null,artifactSessionId:r.artifactSessionId||null,editorJump:r.line?{line:r.line,column:r.column,seq:(e.editorJump?.seq||0)+1}:null,...r.artifactTitle?{rightPanelWasOpen:e.rightPanelWasOpen??e.rightPanelOpen,rightPanelOpen:!1}:{}}))},closeEditorFile:()=>e(e=>({editorFilePath:null,editorPreviewSeq:0,artifactTitle:null,artifactSessionId:null,rightPanelWasOpen:null,...e.rightPanelWasOpen?{rightPanelOpen:!0}:{},...e.artifactSessionId&&e.editorFilePath?{artifactsBySession:((e,t,r)=>{let n=e[t];if(!n)return e;let i=n.filter(e=>e.path!==r);if(i.length===n.length)return e;let{[t]:s,...a}=e;return i.length?{...a,[t]:i}:a})(e.artifactsBySession,e.artifactSessionId,e.editorFilePath)}:{}})),hiddenHeaderButtons:["mobile"],hiddenHeaderButtonsMigrated:!1,toggleHeaderButton:t=>e(e=>({hiddenHeaderButtons:e.hiddenHeaderButtons.includes(t)?e.hiddenHeaderButtons.filter(e=>e!==t):[...e.hiddenHeaderButtons,t]})),mobileLowPower:!1,setMobileLowPower:t=>e({mobileLowPower:!!t}),mobileOpen:!1,mobileMode:"float",mobilePanelWidth:s.b5.default,mobileFloatRect:null,setMobileOpen:t=>e({mobileOpen:!!t}),setMobileMode:t=>e({mobileMode:t,mobileOpen:!0}),setMobilePanelWidth:t=>e({mobilePanelWidth:o(t,s.b5)}),setMobileFloatRect:t=>e({mobileFloatRect:t}),mobileSession:null,setMobileSession:t=>e(e=>({mobileSession:"function"==typeof t?t(e.mobileSession):t}))},...{webglEnabled:!1,setWebglEnabled:t=>e({webglEnabled:!!t}),fontSize:null,setFontSize:t=>e({fontSize:t?Math.max(10,Math.min(18,Math.round(t))):null}),terminalTheme:"default",setTerminalTheme:t=>e({terminalTheme:t||"default"}),terminalBackgrounds:["art8"],setTerminalBackgrounds:t=>e({terminalBackgrounds:Array.isArray(t)?t.filter(Boolean):[]}),terminalBackgroundOpacity:null,setTerminalBackgroundOpacity:t=>e({terminalBackgroundOpacity:null==t?s._z:Number(Math.max(s.DW.min,Math.min(s.DW.max,Math.round(t/s.DW.step)*s.DW.step)).toFixed(2))}),customBackgrounds:[],setCustomBackgrounds:t=>e({customBackgrounds:Array.isArray(t)?t.filter(e=>e?.id&&e?.dataUrl):[]}),backgroundBySession:{},setSessionBackground:(t,r)=>e(e=>{let n={...e.backgroundBySession};return r?n[t]=r:delete n[t],{backgroundBySession:n}}),showFolderButton:!0,showNoteButton:!1,setShowFolderButton:t=>e({showFolderButton:!!t}),setShowNoteButton:t=>e({showNoteButton:!!t}),noteChips:[],addNoteChip:t=>e(e=>({noteChips:[...e.noteChips,t]})),removeNoteChip:t=>e(e=>({noteChips:e.noteChips.filter(e=>e!==t)})),pinnedNotes:{},setNotePinned:(t,r)=>e(e=>{let n={...e.pinnedNotes};return r?n[t]=!0:delete n[t],{pinnedNotes:n}})},...{agentCaps:{},setAgentCaps:t=>e({agentCaps:t||{}}),artifactEnabled:!1,setArtifactEnabled:t=>e({artifactEnabled:!!t}),mcpClients:[],setMcpClients:t=>e({mcpClients:Array.isArray(t)?t:[]}),agentClisBy:{},setAgentClis:(t,r)=>e(e=>({agentClisBy:{...e.agentClisBy,[t]:{list:Array.isArray(r)?r:[],at:Date.now()}}})),agentHistory:{},setAgentHistory:(t,r)=>e(e=>({agentHistory:{...e.agentHistory,[t]:{at:Date.now(),sessions:Array.isArray(r)?r:[]}}})),invalidateAgentHistory:()=>e(e=>({agentHistory:((e,t)=>{let r={};for(let[n,i]of Object.entries(e))r[n]={at:0,sessions:t?i.sessions.map(t):i.sessions};return r})(e.agentHistory)})),agentBySession:{},setSessionAgent:(t,r)=>e(e=>e.agentBySession[t]===r?e:{agentBySession:{...e.agentBySession,[t]:r}}),pendingStartup:{},queueStartup:(t,r)=>e(e=>({pendingStartup:{...e.pendingStartup,[t]:r}})),consumeStartup:r=>{let n=t().pendingStartup[r];return void 0===n?null:(e(e=>{let{[r]:t,...n}=e.pendingStartup;return{pendingStartup:n}}),n)},artifactsBySession:{},pushArtifact:(t,r)=>e(e=>{if(!t||!r?.path)return{};let n=(e.artifactsBySession[t]||[]).filter(e=>e.path!==r.path);return{artifactsBySession:{...e.artifactsBySession,[t]:[r,...n].slice(0,s.zv)}}}),removeArtifact:(t,r)=>e(e=>({artifactsBySession:((e,t,r)=>{let n=e[t];if(!n)return e;let i=n.filter(e=>e.path!==r);if(i.length===n.length)return e;let{[t]:s,...a}=e;return i.length?{...a,[t]:i}:a})(e.artifactsBySession,t,r)}))}}),{name:"terminal-ui-state",partialize:e=>({viewStack:e.viewStack,openedSessions:e.openedSessions,agentBySession:e.agentBySession,activeWorkspaceId:e.activeWorkspaceId,collapsedWorkspaces:e.collapsedWorkspaces,webglEnabled:e.webglEnabled,fontSize:e.fontSize,terminalTheme:e.terminalTheme,terminalBackgrounds:e.terminalBackgrounds,terminalBackgroundOpacity:e.terminalBackgroundOpacity,backgroundBySession:e.backgroundBySession,showFolderButton:e.showFolderButton,showNoteButton:e.showNoteButton,noteChips:e.noteChips,pinnedNotes:e.pinnedNotes,sidebarCollapsed:e.sidebarCollapsed,sidebarWidth:e.sidebarWidth,fullModes:e.fullModes||{},fullMode:e.fullMode,hiddenPaneSessionIds:e.hiddenPaneSessionIds||[],paneWidths:e.paneWidths,rightPanelOpen:e.rightPanelOpen,rightPanelTabs:e.rightPanelTabs,rightPanelWidth:e.rightPanelWidth,editorPanelWidth:e.editorPanelWidth,hiddenHeaderButtons:e.hiddenHeaderButtons,hiddenHeaderButtonsMigrated:e.hiddenHeaderButtonsMigrated,mobileLowPower:e.mobileLowPower,mobileMode:e.mobileMode,mobilePanelWidth:e.mobilePanelWidth,mobileFloatRect:e.mobileFloatRect,artifactsBySession:e.artifactsBySession}),storage:{getItem:e=>{try{let t=localStorage.getItem(e);if(!t)return null;let r=JSON.parse(t);return r&&!Array.isArray(r.viewStack)&&(r.viewStack=[{type:"list"}]),r}catch{return null}},setItem:(e,t)=>{d.name=e,d.value=t,u||(u=setTimeout(h,s.eu))},removeItem:e=>{d.name===e&&(d.name=null,d.value=null),localStorage.removeItem(e)}},onRehydrateStorage:()=>e=>{e&&(Array.isArray(e.viewStack)&&0!==e.viewStack.length||(e.viewStack=[{type:"list"}]),window.location.pathname.replace(/\/+$/,"")===a.U2&&(e.viewStack=[{type:"list"}]),e.viewStack=e.viewStack.filter(e=>e?.type==="browser"||!a.yP.includes(e?.type)&&e?.type!=="site"),0===e.viewStack.length&&(e.viewStack=[{type:"list"}]),Array.isArray(e.terminalBackgrounds)||(e.terminalBackgrounds=[]),e.terminalBackground&&"none"!==e.terminalBackground&&0===e.terminalBackgrounds.length&&(e.terminalBackgrounds=[e.terminalBackground]),e.agentBySession&&"object"==typeof e.agentBySession||(e.agentBySession={}),window.innerWidth<s.jK&&(e.rightPanelOpen=!1),!e.hiddenHeaderButtonsMigrated&&(e.hiddenHeaderButtonsMigrated=!0,Array.isArray(e.hiddenHeaderButtons)?e.hiddenHeaderButtons.includes("mobile")||(e.hiddenHeaderButtons=[...e.hiddenHeaderButtons,"mobile"]):e.hiddenHeaderButtons=["mobile"]))}}))},30068:(e,t,r)=>{r.d(t,{D5:()=>a,FO:()=>c,I9:()=>o,Ic:()=>l,eR:()=>n,ij:()=>s,tC:()=>i});let n={namespace:"/remote",enableWebRTC:!0,enableTurn:!1,debug:{transport:!1,remote:!1,panel:!1,showButton:!1},dcChunkSize:8,dcReliable:!1,dcOrdered:!1,hashRequestInterval:1500,lastDataThreshold:500,restreamDelay:200,mouseThrottle:8,keyThrottle:25,scrollInterval:100,tileLoadTimeout:600,batchSize:16,batchDelay:3,decodeQueueCap:48,resizeDebounceMs:100,resizeStableFrames:3,resizeMaxFrames:30,focusDebounce:50,longPressDelay:1e3,doubleClickDelay:300,moveThreshold:10,edgeScrollThreshold:15,edgeScrollMultiplier:1.5,momentumFriction:.94,momentumMinVelocity:.3,pointerMode:"trackpad",trackpadSensitivity:1.3,trackpadAcceleration:1.5,trackpadTapMaxMove:8,trackpadTapMaxDuration:220,trackpadCursorSize:20,trackpadEdgeMarginRatio:.25,clipboardBadgeTimeout:1e4,gestureLockDelay:80,gestureDistanceThreshold:15,gestureCentroidThreshold:10,gestureDominanceRatio:2,wheelScrollMultiplier:2.5,wheelLineHeight:40,wheelPageHeight:400,wheelZoomStep:.1,wheelBoostInterval:250,mouseButtonMap:{0:"left",1:"middle",2:"right"},pcModeControls:{rectangleSelect:!1,pointerModeToggle:!1,handMode:!1,keyboardToggle:!1,textPanel:!0,modifierRow:!0,help:!0}},i={ctrl:"control",cmd:"command",alt:"alt",shift:"shift"},s=[{id:"ctrl",label:"Ctrl",modifier:"ctrl",type:"modifier"},{id:"alt",label:"Alt",modifier:"alt",type:"modifier"},{id:"shift",label:"Shift",modifier:"shift",type:"modifier"},{id:"cmd",label:"⌘",modifier:"cmd",type:"modifier"},{id:"esc",label:"Esc",key:"escape",type:"key"},{id:"tab",label:"Tab",key:"tab",type:"key"},{id:"enter",label:"↵",key:"enter",type:"key",primary:!0},{id:"backspace",label:"⌫",key:"backspace",type:"key"},{id:"undo",label:"Undo",key:"z",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"redo",label:"Redo",key:"z",modifiers:["control","shift"],type:"combo",osAdaptive:!0},{id:"up",label:"↑",key:"up",type:"arrow"},{id:"down",label:"↓",key:"down",type:"arrow"},{id:"left",label:"←",key:"left",type:"arrow"},{id:"right",label:"→",key:"right",type:"arrow"},{id:"home",label:"Home",key:"home",type:"key"},{id:"end",label:"End",key:"end",type:"key"},{id:"pgup",label:"PgUp",key:"pageup",type:"key"},{id:"pgdn",label:"PgDn",key:"pagedown",type:"key"},{id:"del",label:"Del",key:"delete",type:"key"},{id:"ins",label:"Ins",key:"insert",type:"key"},{id:"f1",label:"F1",key:"f1",type:"key"},{id:"f2",label:"F2",key:"f2",type:"key"},{id:"f3",label:"F3",key:"f3",type:"key"},{id:"f4",label:"F4",key:"f4",type:"key"},{id:"f5",label:"F5",key:"f5",type:"key"},{id:"f6",label:"F6",key:"f6",type:"key"},{id:"f7",label:"F7",key:"f7",type:"key"},{id:"f8",label:"F8",key:"f8",type:"key"},{id:"f9",label:"F9",key:"f9",type:"key"},{id:"f10",label:"F10",key:"f10",type:"key"},{id:"f11",label:"F11",key:"f11",type:"key"},{id:"f12",label:"F12",key:"f12",type:"key"},{id:"ctrlAltDel",label:"Ctl+Alt+Del",key:"delete",modifiers:["control","alt"],type:"combo"},{id:"ctrlShiftEsc",label:"Task Mgr",key:"escape",modifiers:["control","shift"],type:"combo"},{id:"altTab",label:"Alt+Tab",key:"tab",modifiers:["alt"],type:"combo"},{id:"altF4",label:"Alt+F4",key:"f4",modifiers:["alt"],type:"combo"},{id:"winKey",label:"Win",key:"command",type:"key"},{id:"printScreen",label:"PrtSc",key:"printscreen",type:"key"},{id:"paste",label:"Paste",key:"v",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"cut",label:"Cut",key:"x",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"selectAll",label:"All",key:"a",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"desktopPrev",label:"◀ Desk",type:"desktop",direction:"prev"},{id:"desktopNext",label:"Desk ▶",type:"desktop",direction:"next"},{id:"desktopNew",label:"+ Desk",type:"desktop",direction:"new"}],a=["esc","undo","up","down","tab","ctrl","alt","shift","cmd","backspace"],l="enter",o=[["left","right","home","end","pgup","pgdn","del"],["f1","f2","f3","f4","f5","f6","f7","altTab"],["f9","f10","f11","f12","ctrlAltDel",,"desktopPrev","desktopNext","desktopNew"]],c={enter:"enter",return:"enter",space:" ",backspace:"backspace",tab:"tab",escape:"escape",Enter:"enter"," ":"space",Backspace:"backspace",Tab:"tab",Escape:"escape",ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Home:"home",End:"end",PageUp:"pageup",PageDown:"pagedown",Delete:"delete",Insert:"insert",F1:"f1",F2:"f2",F3:"f3",F4:"f4",F5:"f5",F6:"f6",F7:"f7",F8:"f8",F9:"f9",F10:"f10",F11:"f11",F12:"f12",CapsLock:"capslock",NumLock:"numlock",ScrollLock:"scrolllock",PrintScreen:"printscreen",ContextMenu:"menu"}},30368:(e,t,r)=>{r.d(t,{O5:()=>u,U2:()=>n,XG:()=>a,dX:()=>h,mn:()=>d,x0:()=>s,yP:()=>l});let n="/workspace",i={list:()=>n,terminal:e=>`${n}/terminal/${encodeURIComponent(e.sessionId||"")}`,files:e=>c(`${n}/files`,{ws:e.workspace,p:e.currentPath}),editor:e=>c(`${n}/editor`,{path:e.path,line:e.line,col:e.column}),git:e=>c(`${n}/git`,{ws:e.workspace}),remote:()=>`${n}/remote`,mobile:()=>`${n}/mobile`,workspaces:()=>`${n}/workspaces`,browse:e=>c(`${n}/browse`,{path:e.path}),pair:()=>`${n}/pair`,settings:()=>`${n}/settings`,welcome:()=>`${n}/welcome`},s=["list","remote","settings"],a=s,l=["browser"],o={"":"list",terminal:"terminal",files:"files",editor:"editor",git:"git",remote:"remote",mobile:"mobile",workspaces:"workspaces",browse:"browse",pair:"pair",settings:"settings",welcome:"welcome"};function c(e,t){let r=Object.entries(t).filter(e=>{let[,t]=e;return null!=t&&""!==t}).map(e=>{let[t,r]=e;return`${t}=${encodeURIComponent(r)}`}).join("&");return r?`${e}?${r}`:e}function d(e,t){if(!e?.startsWith(n))return null;let[r,i]=e.slice(n.length).replace(/^\//,"").split("/"),s=o[r||""];if(!s)return null;let a=e=>t?.get(e)||void 0;switch(s){case"terminal":return{type:s,sessionId:i?decodeURIComponent(i):void 0};case"files":return{type:s,workspace:a("ws"),currentPath:a("p")};case"editor":return{type:s,path:a("path"),line:p(a("line")),column:p(a("col"))};case"git":return{type:s,workspace:a("ws")};case"browse":return{type:s,path:a("path")};default:return{type:s}}}function u(e){return(i[e?.type]||i.list)(e)}function h(e,t){let r=u(t);if(s.includes(t.type))return[t];let n=e.findIndex(e=>u(e)===r);if(-1!==n)return e.slice(0,n+1);if("terminal"===t.type&&e[e.length-1]?.type==="terminal"){let r=[...e];return r[r.length-1]=t,r}return null}function p(e){let t=Number(e);return Number.isFinite(t)?t:void 0}},30562:(e,t,r)=>{r.d(t,{O:()=>n,Sn:()=>c,TR:()=>o,_8:()=>s,cC:()=>p,dM:()=>u,fm:()=>i,jP:()=>d,lE:()=>l,qn:()=>h,w:()=>a});let n="https://9remote.cc",i="https://9remote.cc/",s=2208,a=`http://127.0.0.1:${s}`,l=a,o=`${a}/api/ui/state`,c={connect:`${n}/api/connect`,tempKeyCreate:`${n}/api/temp-key/create`,tempKeyVerify:`${n}/api/temp-key/verify`,tempKeyRemove:`${n}/api/temp-key/remove`,turnCredentials:`${n}/api/webrtc/turn-credentials`},d=5,u=2e3,h=5e3,p=1e4},31856:(e,t,r)=>{r.d(t,{U:()=>p,x$:()=>h,zm:()=>f});var n=r(30562),i=r(70658),s=r(67841),a=r(189),l=r(69469),o=r(81353),c=r(99022),d=r(81851);let u=0;async function h(e){let{currentKey:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=++u,c=o.rh.getState(),d=t||c.hosts[c.currentKey]?.full||c.currentKey;d&&((0,s.d6)(d,window.location.pathname+window.location.search),o.rh.getState().setAutoConnect((0,l.Uo)(d),!0));let h=await fetch(n.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!h.ok)throw Error("connect failed");let p=await h.json(),f=!1;for(let t=0;t<n.jP&&!f;t++)(f=await (0,i.zg)(p.tunnelUrl,e))||!(t<n.jP-1)||await new Promise(e=>setTimeout(e,n.dM));if(!f)throw Error("unreachable");r===u&&(0,a.vd)({apiKey:e,tunnelUrl:p.tunnelUrl,mode:"remote",localIp:p.localIp||null})}function p(e){try{e?sessionStorage.setItem(d.aS,"1"):sessionStorage.removeItem(d.aS)}catch{}}function f(e){let{remember:t=!0,leavingHead:r=null,navigate:n=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e?.tail&&e.tempKey&&(0,c.LG)(e.tempKey,{tail:e.tail}),p(t),r&&((0,s.d6)(r,window.location.pathname+window.location.search),o.rh.getState().setAutoConnect((0,l.Uo)(r),!0)),n&&(window.location.href="/workspace/")}},32763:(e,t,r)=>{r.d(t,{A:()=>o});var n=r(54568),i=r(7620),s=r(96605),a=r(56156),l=r(9121);function o(e){let{isOpen:t,onClose:o,onScan:c}=e,{t:d}=(0,l.s)(),u=(0,i.useRef)(null),h=(0,i.useRef)(null),p=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null),[g,y]=(0,i.useState)(""),[_,b]=(0,i.useState)(""),w=(0,i.useCallback)(async e=>{if(h.current)try{await h.current.stop()}catch(e){}b("detected"),await new Promise(e=>setTimeout(e,300)),b("authenticating"),await c(e)||(b(""),m.current?.())},[c]),k=(0,i.useCallback)(async()=>{if(!p.current){let e=await Promise.all([r.e(2732),r.e(9700)]).then(r.bind(r,89700)).catch(()=>null);if(!e)return void y(d("login.qrLibFail"));p.current=e.Html5Qrcode}let e=document.getElementById("qr-reader");if(!e)return void y(d("login.qrInitFail"));try{e.innerHTML="";let t=new p.current("qr-reader");h.current=t,await t.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},e=>{f.current?.(e)},()=>{})}catch(t){let e=t.toString();e.includes("NotAllowedError")?y(d("login.qrCamDenied")):e.includes("NotFoundError")?y(d("login.qrNoCamera")):e.includes("NotReadableError")?y(d("login.qrCamBusy")):y(d("login.qrCamError"))}},[d]),v=(0,i.useCallback)(async()=>{if(h.current){try{await h.current.stop()}catch(e){}h.current=null}y(""),b(""),o()},[o]);return((0,i.useEffect)(()=>{f.current=w},[w]),(0,i.useEffect)(()=>{if(!t)return;let e=!1;m.current=async()=>{h.current=null,await new Promise(e=>setTimeout(e,400)),e||k()};let r=setTimeout(()=>{e||k()},200);return()=>{if(e=!0,clearTimeout(r),m.current=null,h.current){try{h.current.stop()}catch(e){}h.current=null}}},[t,k]),t)?(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm fade-in",children:(0,n.jsxs)("div",{className:"relative card-elev max-w-md w-full mx-4 overflow-hidden pop-in",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[(0,n.jsx)("h2",{className:"text-xl font-bold text-text",children:d("login.qrScanTitle")}),(0,n.jsx)("button",{onClick:v,className:"text-text-muted hover:text-text transition-colors p-1",children:(0,n.jsx)(s.X,{size:24})})]}),(0,n.jsx)("div",{className:"relative bg-black",children:(0,n.jsx)("div",{id:"qr-reader",ref:u,className:"w-full",style:{minHeight:"300px"}})}),(0,n.jsxs)("div",{className:"p-4",children:[g?(0,n.jsxs)("div",{className:"flex items-start gap-2 p-3 bg-red-500/10 rounded-brand text-red-400",children:[(0,n.jsx)(s.RI,{size:20,className:"flex-shrink-0 mt-0.5"}),(0,n.jsx)("p",{className:"text-sm",children:g})]}):"detected"===_?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 p-3 bg-green-500/10 rounded-brand text-green-400",children:[(0,n.jsx)(s.vW,{size:22}),(0,n.jsx)("p",{className:"text-sm font-medium",children:d("login.qrDetected")})]}):"authenticating"===_?(0,n.jsx)("div",{className:"flex items-center justify-center gap-2 p-3 bg-brand-500/10 rounded-brand text-brand-400",children:(0,n.jsx)("p",{className:"text-sm font-medium",children:d("login.qrAuthenticating")})}):(0,n.jsx)("p",{className:"text-sm text-text-muted text-center",children:d("login.qrHint")}),(0,n.jsx)(a.A,{variant:"secondary",onClick:v,disabled:"authenticating"===_,className:"w-full mt-4",children:"authenticating"===_?d("login.qrPleaseWait"):d("common.cancel")})]})]})}):null}},36487:(e,t,r)=>{r.d(t,{$Z:()=>ee,A_:()=>c,Ao:()=>p,B$:()=>K,BM:()=>es,DW:()=>H,Ds:()=>h,EE:()=>I,FC:()=>e_,Fz:()=>f,G:()=>w,Gp:()=>et,IJ:()=>Y,Il:()=>ey,Jv:()=>l,KA:()=>_,KN:()=>$,Lo:()=>X,M8:()=>er,Mg:()=>ex,Nz:()=>ev,OM:()=>ep,Pj:()=>U,Pz:()=>Z,Qe:()=>d,RF:()=>eb,RS:()=>V,TM:()=>D,Tb:()=>v,Tk:()=>b,Uc:()=>ea,VE:()=>ec,W$:()=>E,YA:()=>eg,YS:()=>x,ZU:()=>q,_C:()=>eC,_O:()=>Q,_z:()=>N,aD:()=>M,am:()=>T,ar:()=>B,b5:()=>m,b9:()=>ek,bl:()=>ew,bs:()=>C,c:()=>F,cK:()=>eS,dU:()=>ei,de:()=>eP,dt:()=>n,eE:()=>eh,eu:()=>P,fw:()=>ef,g$:()=>eT,gH:()=>u,hp:()=>R,i5:()=>em,iW:()=>k,j4:()=>en,jK:()=>i,k9:()=>s,kn:()=>o,ll:()=>S,ok:()=>eI,pS:()=>a,pZ:()=>W,pl:()=>eu,pt:()=>J,qQ:()=>A,qj:()=>g,qw:()=>el,sB:()=>ed,t:()=>j,vP:()=>L,vk:()=>z,wu:()=>O,y:()=>eA,zm:()=>eo,zv:()=>y});let n=["git status","git add .",'git commit -m ""',"git push","git pull","git fetch","git diff","git log --oneline","git branch","git checkout","git checkout -b","git switch","git stash","git stash pop","git merge","git rebase","git clone","git remote -v","git restore","npm install","npm ci","npm run dev","npm run build","npm run test","npm run lint","npm outdated","pnpm install","pnpm dev","yarn dev","bun install","cd ..","cd ~","cd -","ls -la","ll","mkdir -p","cp -r","find . -name","du -sh","chmod +x","ln -s","grep -rn","grep -i","wc -l","tail -f","ps aux","df -h","free -h","lsof -i","netstat -tlnp","docker ps","docker ps -a","docker images","docker logs -f","docker exec -it","docker compose up -d","docker compose down","docker build -t","code .","claude","claude --continue","claude --resume","claude --dangerously-skip-permissions","claude mcp","codex","codex --full-auto"],i=760,s={min:400,max:1/0},a=2,l=0,o=12,c=250,d=8,u={default:190,min:180,max:1/0},h={default:190,min:190,max:1/0},p={default:420,min:280,max:1/0},f=[{id:"remote",labelKey:"menu.remoteDesktop",descKey:"menu.remoteDesktopHint",group:"header",section:"remote"},{id:"sites",labelKey:"menu.sites",descKey:"menu.sitesHint",group:"header",section:"remote"},{id:"mobile",labelKey:"mobile.androidDevice",descKey:"mobile.androidDeviceHint",group:"header",section:"remote"},{id:"notifications",labelKey:"menu.bellButton",descKey:"menu.bellButtonHint",group:"header",section:"plugins"},{id:"folder",labelKey:"menu.showFolder",group:"pane",section:"terminal",storeKey:"showFolderButton",setterKey:"setShowFolderButton"},{id:"note",labelKey:"menu.showNote",group:"pane",section:"terminal",storeKey:"showNoteButton",setterKey:"setShowNoteButton"}],m={default:300,min:240,max:1/0},g={width:{default:300,min:240,max:900},height:{default:620,min:320},margin:12,defaultOffset:24},y=20,_=1e4,b={maxDepth:1,deepMaxDepth:3,cacheTtlMs:3e4,retryBaseMs:1e3,retryMaxMs:16e3},w=["main","master"],k={topThresholdLines:5,guardMs:600,minFetchBytes:256,chainMax:3,chainDebounceMs:300,disabled:!1},v=5242880,A=5,S=3e3,T=150,x=100,C=101,R=200,I={Escape:{data:"\x1b"},c:{ctrl:!0,data:"\x03",requireNoSelection:!0},d:{ctrl:!0,data:"\x04"},z:{ctrl:!0,data:"\x1a"},l:{ctrl:!0,data:"\f"}},P=250,$=999,D=["check again","continue","summarize"],M="terminal:noteSync",L="terminal:openSession",O=5e3,q=250,E=90,U={cursorBlink:!0,fontSize:12,fontSizeMobile:12,fontFamily:'ui-monospace, "SF Mono", "Cascadia Code", "Roboto Mono", "Noto Sans Mono", Menlo, Monaco, "Courier New", monospace',scrollback:15e3,convertEol:!0,allowProposedApi:!0,scrollOnUserInput:!0,fastScrollModifier:"none",smoothScrollDuration:0,rescaleOverlappingGlyphs:!0,minimumContrastRatio:4.5,macOptionIsMeta:!0};function B(e){return null!=e?e:window.innerWidth<768?U.fontSizeMobile:U.fontSize}let N=.8,j=.25,F="16,16,20",W="116,120,136",K=.28,H={min:.3,max:.95,step:.01},z={none:{label:"None"},art1:{label:"Anime 1",src:"/backgrounds/bg9.jpg"},art2:{label:"Anime 2",src:"/backgrounds/bg2.jpg"},art3:{label:"Anime 3",src:"/backgrounds/bg3.jpg"},art4:{label:"Anime 4",src:"/backgrounds/bg4.jpg"},art5:{label:"Anime 5",src:"/backgrounds/bg5.jpg"},art7:{label:"Anime 7",src:"/backgrounds/bg7.jpg"},art8:{label:"Anime 8",src:"/backgrounds/bg8.jpg"},art9:{label:"Anime 9",src:"/backgrounds/bg10.jpg"},art10:{label:"Anime 10",src:"/backgrounds/bg11.jpg"},art11:{label:"Anime 11",src:"/backgrounds/bg12.jpg"},art12:{label:"Anime 12",src:"/backgrounds/bg13.jpg"}};function J(e,t){return e&&t&&"none"!==t&&(z[t]||String(t).startsWith("custom"))?{...e,background:"#10101400"}:e}function G(e){return"custom"===e?"custom":"string"==typeof e&&e.startsWith("custom:")?e.slice(7):null}function V(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=G(e);return r?t.find(e=>e?.id===r)?.dataUrl||null:z[e]?.src||null}function Z(e){return z[e]?.label||(G(e)?"Custom":z.none.label)}let Q=4e3,X=2e4;function Y(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Array.isArray(e)?e.filter(e=>{let r=G(e);return r?t.some(e=>e?.id===r):"none"===e||!!z[e]}):[]}function ee(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return Y([e],n)[0]||(r=Y(t,n),Array.isArray(r)&&0!==r.length&&r[i%r.length]||"none")}let et={gpuAcceleration:"auto",smoothScrollDuration:125},er={clipboard:!0,search:!0,image:!0},en=30,ei=2,es=100,ea=600,el=150,eo=4e3,ec=3e3,ed=5e3,eu=2e3,eh=8e3,ep=6e4,ef=3e4,em="28%",eg=400,ey={lineHeight:18,sensitivity:1,friction:.95,minVelocity:.3,maxVelocity:55,wheelStepLines:1,tuiThrottleMs:50,momentumRenderCadenceMs:33,tuiBackpressureTimeoutMs:120,sgrUp:(e,t)=>`\x1b[<64;${e};${t}M`,sgrDown:(e,t)=>`\x1b[<65;${e};${t}M`},e_={longPressMs:450,moveTolerance:10,wordChars:/[A-Za-z0-9._\-/~:@]/},eb={verbs:["cd","ls","ll","cat","less","more","head","tail","vim","nvim","nano","bat","code","code-insiders","rm","cp","mv","mkdir","touch","chmod","open","grep"],ttlMs:1e4,debounceMs:120,maxDirs:20,maxResults:8},ew={minDistance:60,ratio:1.5,maxDuration:500},ek=e=>!!e&&27!==e.charCodeAt(0),ev=e=>"string"==typeof e&&(/^\x1b\[[?>=][0-9;]*c$/.test(e)||/^\x1b\[[0-9]+;[0-9]+R$/.test(e)||/^\x1b\[0n$/.test(e)||/^\x1b\]\d+;/.test(e)),eA=[{id:"ctrl",label:"Ctrl",key:"Ctrl",type:"modifier"},{id:"opt",label:"Opt",key:"Alt",type:"modifier"},{id:"shift",label:"Shift",key:"Shift",type:"modifier"},{id:"meta",label:"⌘",key:"Meta",type:"modifier"},{id:"esc",label:"Esc",key:"Escape",type:"key"},{id:"tab",label:"Tab",key:"Tab",type:"key"},{id:"enter",label:"↵",key:"Enter",type:"key"},{id:"backspace",label:"⌫",key:"Backspace",type:"key"},{id:"up",label:"↑",key:"ArrowUp",type:"arrow"},{id:"down",label:"↓",key:"ArrowDown",type:"arrow"},{id:"left",label:"←",key:"ArrowLeft",type:"arrow"},{id:"right",label:"→",key:"ArrowRight",type:"arrow"},{id:"home",label:"Home",key:"Home",type:"key"},{id:"end",label:"End",key:"End",type:"key"},{id:"pgup",label:"PgUp",key:"PageUp",type:"key"},{id:"pgdn",label:"PgDn",key:"PageDown",type:"key"},{id:"del",label:"Del",key:"Delete",type:"key"},{id:"ins",label:"Ins",key:"Insert",type:"key"},{id:"ctrlA",label:"^A",key:"a",type:"ctrl"},{id:"ctrlC",label:"^C",key:"c",type:"ctrl"},{id:"ctrlD",label:"^D",key:"d",type:"ctrl"},{id:"ctrlE",label:"^E",key:"e",type:"ctrl"},{id:"ctrlK",label:"^K",key:"k",type:"ctrl"},{id:"ctrlL",label:"^L",key:"l",type:"ctrl"},{id:"ctrlN",label:"^N",key:"n",type:"ctrl"},{id:"ctrlP",label:"^P",key:"p",type:"ctrl"},{id:"ctrlR",label:"^R",key:"r",type:"ctrl"},{id:"ctrlT",label:"^T",key:"t",type:"ctrl"},{id:"ctrlU",label:"^U",key:"u",type:"ctrl"},{id:"ctrlW",label:"^W",key:"w",type:"ctrl"},{id:"ctrlX",label:"^X",key:"x",type:"ctrl"},{id:"ctrlY",label:"^Y",key:"y",type:"ctrl"},{id:"ctrlZ",label:"^Z",key:"z",type:"ctrl"},{id:"f1",label:"F1",key:"F1",type:"key"},{id:"f2",label:"F2",key:"F2",type:"key"},{id:"f3",label:"F3",key:"F3",type:"key"},{id:"f4",label:"F4",key:"F4",type:"key"},{id:"f5",label:"F5",key:"F5",type:"key"},{id:"f6",label:"F6",key:"F6",type:"key"},{id:"f7",label:"F7",key:"F7",type:"key"},{id:"f8",label:"F8",key:"F8",type:"key"},{id:"f9",label:"F9",key:"F9",type:"key"},{id:"f10",label:"F10",key:"F10",type:"key"},{id:"f11",label:"F11",key:"F11",type:"key"},{id:"f12",label:"F12",key:"F12",type:"key"},{id:"pipe",label:"|",key:"|",type:"key"},{id:"tilde",label:"~",key:"~",type:"key"},{id:"slash",label:"/",key:"/",type:"key"},{id:"backslash",label:"\\",key:"\\",type:"key"},{id:"dash",label:"-",key:"-",type:"key"},{id:"underscore",label:"_",key:"_",type:"key"}],eS=["esc","up","down","ctrlC","ctrl","opt","shift","tab","slash"],eT="enter",ex=[["left","right","home","end","pgup","pgdn","del"],["ctrlZ","ctrlR","ctrlL","ctrlA","ctrlE","ctrlW","ctrlD"],["f1","f2","f3","f4","f5","f10","f11"]],eC={base:"flex items-center justify-center rounded-brand font-semibold transition-all duration-150 ease-out active:scale-[0.94]",textNormal:"text-xs",textSmall:"text-[11px]",normal:"bg-surface-2 hover:bg-surface-3 text-text",arrow:"bg-surface-2 hover:bg-surface-3 text-text text-sm",modifierActive:"bg-brand-500 text-white shadow-sm",pinned:"bg-brand-500/15 hover:bg-brand-500/25 text-brand-400",size:{minWidth:"34px",height:"32px",paddingLeft:"6px",paddingRight:"6px"},sizeLarge:{minWidth:"38px",height:"32px",paddingLeft:"8px",paddingRight:"8px"},sizeSmall:{width:"28px",height:"28px"}},eR=["main","master"],eI=e=>eR.includes(e),eP={DELAY_MS:400,GAP_PX:6,EDGE_PX:8,MAX_WIDTH_PX:320,EST_HEIGHT_PX:48,SLACK_PX:.5}},42126:(e,t,r)=>{r.d(t,{g:()=>ei});var n=r(81851);class i{static #e=this.id="base";static #t=this.capabilities={control:!1,binary:!1,signaling:"none"};static #r=this.priority={control:0,binary:0};constructor(){this._listeners=new Map,this._state=n.Of.idle}get state(){return this._state}get ready(){return this._state===n.Of.open}supports(e){return!!this.constructor.capabilities[e]}getPriority(e){return this.constructor.priority[e]??0}on(e,t){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];let i=this._listeners.get(e);if(i)for(let e of i)e(...r)}_setState(e){this._state!==e&&(this._state=e,this._emit("stateChange",e))}connect(e){throw Error("Not implemented: connect")}disconnect(){throw Error("Not implemented: disconnect")}send(e,t){throw Error("Not implemented: send")}}var s=r(80514),a=r(14511);let l={transports:["websocket"],reconnection:!1,reconnectionDelay:1e3,reconnectionDelayMax:5e3};class o{constructor({tunnelUrl:e,namespace:t="",socketOptions:r={}}){this._tunnelUrl=e,this._namespace=t,this._socketOptions=r}connect(e){let{onSocket:t,onFail:r}=e,n=this._namespace?`${this._tunnelUrl}${this._namespace}`:this._tunnelUrl,i=this._tunnelUrl===window.location.origin?"local":"tunnel",o=(0,s.io)(n,{...l,...this._socketOptions,path:"/socket.io",auth:e=>{(0,a.freshAuth)(this._socketOptions.auth,i).then(e)}}),c=!1;o.once("connect",()=>{c||(c=!0,t(o,i))}),o.once("connect_error",()=>{c||(c=!0,r?.())})}}let c={transports:["websocket"],reconnection:!1};class d{constructor({tunnelUrl:e,localIp:t,namespace:r="",socketOptions:n={}}){this._tunnelUrl=e,this._localIp=t,this._namespace=r,this._socketOptions=n}connect(e){let{onSocket:t,onFail:r}=e,n=!1,i=(e,r)=>{if(n){try{e.disconnect()}catch{}return}n=!0,t(e,r)},l=e=>this._namespace?`${e}${this._namespace}`:e,o=e=>({...c,...this._socketOptions,path:"/socket.io",auth:t=>{(0,a.freshAuth)(this._socketOptions.auth,e).then(t)}}),d=()=>{let e=this._tunnelUrl===window.location.origin?"local":"tunnel",t=(0,s.io)(l(this._tunnelUrl),o(e));t.once("connect",()=>i(t,e)),t.once("connect_error",()=>void(!n&&(n=!0,r?.())))};if(!this._localIp||"https:"===window.location.protocol)return void d();let u=(0,s.io)(l(`http://${this._localIp}`),o("local"));u.once("connect",()=>i(u,"local")),u.once("connect_error",()=>{n||(u.disconnect(),d())})}}var u=r(30562);let h=3;var p=r(55285),f=r(6134);let m=2e3,g=15,y=15,_=15,b=45;class w extends i{static #e=this.id="ws";static #t=this.capabilities={control:!0,binary:!0,file:!0,browser:!0,signaling:"ws"};static #r=this.priority={control:100,binary:10,file:10,browser:10};constructor(){super(),this._socket=null,this._connectionMode="local",this._retryTimer=null,this._retryAttempt=0,this._retryScheduled=!1,this._retryNowTimer=null,this._destroyed=!1,this._blocked=!1,this._updating=!1,this._connecting=!1,this._visibilityHandler=null,this._lastInboundAt=Date.now(),this._lastMsgAt=0,this._zombieWatchdogTimer=null,this._outboundWatchdogTimer=null,this._lastBufferedAmount=0,this._retrySeq=0}get lastInboundAt(){return this._lastInboundAt}get lastMsgAt(){return this._lastMsgAt}get socket(){return this._socket}get connectionMode(){return this._connectionMode}get blocked(){return this._blocked}setUpdating(e){this._updating=e,e&&(this._maxAttempts=b,this._retryAttempt=0,(0,p.c)("transport",`[ws] updating=true maxAttempts=${this._maxAttempts}`))}forceReconnect(){this._destroyed||this._forceReconnect()}retryNow(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";if(this._blocked)return void(0,f.Lq)("switch",`ws retryNow SKIP by=${e} (blocked)`);let t=Date.now(),r=t-(this._lastRetryNowAt||0);if(r<3e3){this._retryNowTimer||(this._retryNowTimer=setTimeout(()=>{this._retryNowTimer=null,this.retryNow(`${e}-deferred`)},3e3-r)),(0,p.c)("transport","[ws] retryNow throttled → deferred"),(0,f.Lq)("switch",`ws retryNow DEFER by=${e} (${3e3-r}ms left)`);return}(0,f.Lq)("switch",`ws retryNow GO by=${e} (drops attempt ${this._retryAttempt})`),this._retrySeq++,this._lastRetryNowAt=t,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,clearTimeout(this._retryTimer),clearTimeout(this._connectingTimer),this._retryTimer=null,this._retryScheduled=!1,this._retryAttempt=0,this._connecting=!1,this._destroyed=!0,this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._destroyed=!1,this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:1,maxAttempts:this._maxAttempts,failed:!1}),this._setState(n.Of.connecting),this._connectInternal()}setBlocked(e){this._blocked=e,(0,p.c)("transport",`[ws] blocked=${e}`),e?(this._cancelRetry(),this._socket?.disconnect()):this._socket?.connected||this._destroyed||this._connectInternal()}connect(e){this._ctx=e,this._auth=e.auth,this._maxAttempts=this._auth.tempKey?g:y,this._reconnectMaxAttempts=_,this._destroyed=!1,this._attachNetworkListeners(),this._setState(n.Of.connecting),this._connectInternal()}disconnect(){this._destroyed=!0,this._retrySeq++,this._cancelRetry(),clearTimeout(this._zombieWatchdogTimer),clearTimeout(this._outboundWatchdogTimer),this._removeNetworkListeners(),this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._setState(n.Of.closed)}send(e,t){if(!this._socket?.connected)return!1;if(e===n.l_.control){let{event:e,args:r=[],cb:n}=t;return n?this._socket.emit(e,...r,n):this._socket.emit(e,...r),!0}return e===n.l_.binary?(this._socket.emit("tiles-bin-v2",t),!0):e===n.l_.browser?(this._socket.emit("browser:tiles-bin",t),!0):e===n.l_.file&&(this._socket.emit("file-bin",t),!0)}_outboundStalled(e){try{let t=e?.io?.engine?.transport?.ws,r="number"==typeof t?.bufferedAmount?t.bufferedAmount:0,n=r>0&&this._lastBufferedAmount>0&&r>=this._lastBufferedAmount;return this._lastBufferedAmount=r,n}catch{return this._lastBufferedAmount=0,!1}}_connectInternal(){if(this._connecting||this._socket?.connected||this._destroyed)return;if(!this._auth.tunnelUrl&&!this._auth.localIp){(0,p.c)("transport","[ws] connect HOLD (no tunnelUrl/localIp yet) → retry"),(0,f.Lq)("switch","ws connect HOLD (no url yet) → fetch on retry"),this._setState(n.Of.degraded),this._scheduleRetry();return}this._connecting=!0,clearTimeout(this._connectingTimer),this._connectingTimer=setTimeout(()=>{this._connecting=!1},m);let e={tunnelUrl:this._auth.tunnelUrl,namespace:this._auth.namespace||"",socketOptions:this._auth.socketOptions||{}};(0,p.c)("transport",`[ws] connect: tunnelUrl=${this._auth.tunnelUrl} localIp=${this._auth.localIp||"none"}`),new o(e).connect({onSocket:(e,t)=>{if(this._connecting=!1,clearTimeout(this._connectingTimer),this._socket?.connected&&this._socket!==e){try{e.disconnect()}catch{}return}this._connectionMode=t,this._socket=e,this._retryAttempt=0,this._updating=!1,this._maxAttempts=this._reconnectMaxAttempts,this._cancelRetry(),this._attachSocketEvents(e),(0,p.c)("transport",`[ws] connect mode=${t}`),(0,f.Lq)("switch",`ws open mode=${t}`),this._setState(n.Of.open)},onFail:()=>{this._connecting=!1,clearTimeout(this._connectingTimer),(0,p.c)("transport","[ws] connect FAIL → schedule retry"),this._scheduleRetry()}})}_attachSocketEvents(e){e.on("disconnect",e=>{(0,p.c)("transport",`[ws] disconnect reason=${e}`),(0,f.Lq)("switch",`ws disconnect reason=${e}`),this._setState(n.Of.degraded),this._destroyed||this._forceReconnect()}),e.on("connect_error",e=>{(0,p.c)("transport",`[ws] connect_error ${e?.message||e}`),this._setState(n.Of.degraded),this._forceReconnect()});let t=()=>{clearTimeout(this._zombieWatchdogTimer),this._zombieWatchdogTimer=setTimeout(()=>{if(!this._destroyed&&this._socket===e){if(Date.now()-this._lastInboundAt<n.Rh)return void t();(0,f.Lq)("switch","ws zombie watchdog → force reconnect"),this.forceReconnect()}},n.Rh)};t(),e.io?.on?.("ping",()=>{this._lastInboundAt=Date.now(),t()}),e.on("connect",()=>{this._lastInboundAt=Date.now(),t()});let r=()=>{clearTimeout(this._outboundWatchdogTimer),this._outboundWatchdogTimer=setTimeout(()=>{if(!this._destroyed&&this._socket===e){if(this._outboundStalled(e)){(0,f.Lq)("switch","ws outbound stall (send buffer frozen) → force reconnect"),this.forceReconnect();return}r()}},n.KP)};r(),e.onAny((e,t)=>{this._lastMsgAt=Date.now(),this._emit("message",{event:e,data:t,source:"ws"})})}_attachNetworkListeners(){this._visibilityHandler||(this._visibilityHandler=()=>{"visible"!==document.visibilityState||this._socket?.connected||this._connecting||this.retryNow("visible")},this._offlineHandler=()=>{(0,f.Lq)("switch","ws offline event → drop socket, degraded"),this._socket?.disconnect(),this._socket=null,this._setState(n.Of.degraded)},this._onlineHandler=()=>{this._socket?.connected||this._connecting?(0,f.Lq)("switch",`ws online event → skip (${this._connecting?"handshaking":"already up"})`):this.retryNow("online")},this._pagehideHandler=()=>{try{this._socket?.disconnect()}catch{}},window.addEventListener("pagehide",this._pagehideHandler),document.addEventListener("visibilitychange",this._visibilityHandler),window.addEventListener("offline",this._offlineHandler),window.addEventListener("online",this._onlineHandler))}_detachSocketEvents(){if(this._socket)try{this._socket.offAny()}catch{}}_removeNetworkListeners(){this._pagehideHandler&&(window.removeEventListener("pagehide",this._pagehideHandler),this._pagehideHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._offlineHandler&&(window.removeEventListener("offline",this._offlineHandler),this._offlineHandler=null),this._onlineHandler&&(window.removeEventListener("online",this._onlineHandler),this._onlineHandler=null)}_forceReconnect(){if(!this._destroyed&&!this._blocked&&!this._retryScheduled&&!this._connecting){if(this._retrySeq++,this._retryAttempt++,this._retryAttempt>h){this._retryAttempt=0,this._scheduleRetry();return}this._socket?.disconnect(),this._socket=null,this._connectInternal()}}_scheduleRetry(){this._retryScheduled||this._destroyed||this._blocked||(this._retryScheduled=!0,this._retryTimer=setTimeout(()=>this._doRetry(),m))}async _doRetry(){if(this._destroyed)return;if("u">typeof document&&"hidden"===document.visibilityState){(0,f.Lq)("switch",`ws retry HOLD (hidden, still at ${this._retryAttempt}/${this._maxAttempts})`),this._retryScheduled=!1,this._scheduleRetry();return}this._retryAttempt++;let e=this._retryAttempt,t=this._retrySeq;if(e>this._maxAttempts){this._retryScheduled=!1,(0,f.Lq)("switch",`ws GAVE UP after ${this._maxAttempts} attempts → closed`),this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:e,maxAttempts:this._maxAttempts,failed:!0}),this._setState(n.Of.closed);return}(0,p.c)("transport",`[ws] retry attempt=${e}/${this._maxAttempts}`),(0,f.Lq)("switch",`ws retry ${e}/${this._maxAttempts}`),this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:e,maxAttempts:this._maxAttempts,failed:!1});try{let e=await fetch(u.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this._auth.apiKey})});if(!e.ok){if(503===e.status){let t=await e.json().catch(()=>({}));t?.error==="agent-offline"&&this._ctx?.onHostOffline?.()}throw Error("Failed")}let{tunnelUrl:r,localIp:n}=await e.json();if(t!==this._retrySeq)return void(0,f.Lq)("switch","ws retry ABORT (superseded mid-fetch)");this._auth.tunnelUrl=r,this._auth.localIp=n||null,this._connectionMode="local",this._ctx?.onUrlUpdate?.({tunnelUrl:r,localIp:n}),this._socket?.disconnect(),this._retryScheduled=!1,this._connectInternal()}catch{if(t!==this._retrySeq)return;this._retryScheduled=!1,this._scheduleRetry()}}_cancelRetry(){clearTimeout(this._retryTimer),this._retryTimer=null,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,this._retrySeq++,this._retryAttempt=0,this._retryScheduled=!1,this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:0,maxAttempts:this._maxAttempts,failed:!1})}}function k(e,t){if(t instanceof Uint8Array){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return{__b:btoa(e)}}return t}function v(e,t){if(t&&"object"==typeof t&&"string"==typeof t.__b){let e=atob(t.__b),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return t}function A(e){return JSON.stringify(e,k)}function S(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=[],n={event:e.event,args:function e(t,r){if(t instanceof ArrayBuffer)return r.push(new Uint8Array(t)),{__B:r.length-1};if(ArrayBuffer.isView(t))return r.push(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),{__B:r.length-1};if(Array.isArray(t))return t.map(t=>e(t,r));if(t&&"object"==typeof t){let n={};for(let i of Object.keys(t))n[i]=e(t[i],r);return n}return t}(e.args||[],r),ackId:e.ackId??null,sq:e.sq??null,ep:e.ep??null,rs:e.rs??null,lens:r.map(e=>e.length)};t&&(n.frag=t.id,n.part=t.part,n.parts=t.parts);let i=new TextEncoder().encode(JSON.stringify(n)),s=new Uint8Array(4+i.length+r.reduce((e,t)=>e+t.length,0));new DataView(s.buffer).setUint32(0,i.length,!0),s.set(i,4);let a=4+i.length;for(let e of r)s.set(e,a),a+=e.length;return s}function T(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<4)throw Error("frame too short");let r=4+new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!0);if(r>t.length)throw Error("frame header truncated");let n=JSON.parse(new TextDecoder().decode(t.subarray(4,r))),i=[],s=r;for(let e of n.lens||[]){if(s+e>t.length)throw Error("frame part truncated");i.push(t.subarray(s,s+e)),s+=e}return{event:n.event,args:function e(t,r){if(Array.isArray(t))return t.map(t=>e(t,r));if(t&&"object"==typeof t){if("number"==typeof t.__B)return r[t.__B]??null;let n={};for(let i of Object.keys(t))n[i]=e(t[i],r);return n}return t}(n.args||[],i),ackId:n.ackId??null,sq:n.sq??null,ep:n.ep??null,rs:n.rs??null,frag:n.frag,part:n.part,parts:n.parts}}function x(){let e=new Map;return{push(t){let{frag:r,part:n,parts:i}=t;if(null==r)return t;if(!Number.isInteger(n)||!Number.isInteger(i)||n<0||i<1||n>=i||i>4096)return null;let s=e.get(r);s||(e.size>=4&&e.delete(e.keys().next().value),s={slices:Array(i),got:0},e.set(r,s));let a=t.args?.[0];if(null==a||(!s.slices[n]&&(s.slices[n]=a,s.got++),s.got<i))return null;e.delete(r);let l=new Uint8Array(s.slices.reduce((e,t)=>e+t.byteLength,0)),o=0;for(let e of s.slices)l.set(e,o),o+=e.byteLength;return T(l)}}}var C=r(99022),R=r(30068);let I=null,P=0,$=new Map,D=0;async function M(e,t){let r=`9remote_turn_cache_${t?.slice(0,12)||"anon"}`;try{let e="u">typeof localStorage?localStorage.getItem(r):null;if(e){let t=JSON.parse(e);if(t?.expiresAt>Date.now()&&Array.isArray(t.iceServers)&&t.iceServers.length)return t.iceServers}}catch{}try{let n=await fetch(e,{headers:{"X-API-Key":t},signal:AbortSignal.timeout(4e3)});if(n.ok){let e=await n.json();if(e?.iceServers?.length){try{"u">typeof localStorage&&localStorage.setItem(r,JSON.stringify({iceServers:e.iceServers,expiresAt:Date.now()+828e5}))}catch{}return e.iceServers}}}catch(e){console.warn("[WebRtcProtocol] TURN fetch failed:",e.message)}return null}class L extends i{static #e=this.id="rtc";static #t=this.capabilities={control:!0,binary:!0,file:!0,browser:!0,signaling:"external"};static #r=this.priority={control:50,binary:100,file:100,browser:100};constructor(){super(),this._pc=null,this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._dcMobile=null,this._typeDetail="dc-stun",this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._pendingEmit=null,this._flushTimer=null,this._latestTileTs=new Map,this._hbTimer=null,this._hbLastPing=0,this._hbFastCadence=!1,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._peerEnv2=!1,this._peerFragCtl=!1,this._v2Announced=!1,this._v2RxSeen=!1,this._fragSeq=0,this._reassemble=x(),this._lastInboundAt=0,this._signalingHandlers={},this._signaling=null,this._useTurn=!1}get lastInboundAt(){return this._lastInboundAt}getPriority(e){return"dc-turn"===this._typeDetail?5:150}async connect(e){this._ctx=e,this._cleanupPeer(),this._peerEpoch=(this._peerEpoch??0)+1,this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._hbFastCadence=!1,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._typeDetail="dc-stun",this._lastMid=null,this._remoteGatheringDone=!1,this._setState(n.Of.connecting),this.connectingSince=Date.now(),this.connectDeadline=this.connectingSince+n.AC,clearTimeout(this._connectTimer),this._connectTimer=setTimeout(()=>{this._state!==n.Of.open&&((0,p.c)("transport",`[rtc] connect timeout (${n.AC}ms, state=${this._state}) → close + retry`),this._closePeer(`connect-timeout (state=${this._state})`))},n.AC);let t=[{urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302","stun:stun3.l.google.com:19302","stun:stun4.l.google.com:19302"]},{urls:"stun:global.stun.twilio.com:3478"},{urls:"stun:stun.cloudflare.com:3478"}];if(this._useTurn=!!(e.useTurn||e.profile?.rtc?.enableTurn),e.iceServers?.length)t=e.iceServers;else if(this._useTurn){let r=await M(u.Sn.turnCredentials,e.auth?.apiKey);r?.length&&(t=r)}let r=new RTCPeerConnection({iceServers:t,iceCandidatePoolSize:4,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});this._pc=r;let i=e.profile?.rtc?.dcControl?.ordered??!0,s=r.createDataChannel("control",{ordered:i}),a=r.createDataChannel("binary",{ordered:!1,maxPacketLifeTime:500}),l=r.createDataChannel("file",{ordered:!0}),o=r.createDataChannel("mobile",{ordered:!0}),c=r.createDataChannel("browser",{ordered:!1,maxPacketLifeTime:500});a.binaryType="arraybuffer",s.binaryType="arraybuffer",l.binaryType="arraybuffer",o.binaryType="arraybuffer",c.binaryType="arraybuffer",this._dcControl=s,this._dcBinary=a,this._dcFile=l,this._dcMobile=o,this._dcBrowser=c;let d=async()=>{if("open"!==s.readyState||"open"!==a.readyState)return;let e="";try{let t=await r.getStats();t.forEach(r=>{if("candidate-pair"===r.type&&"succeeded"===r.state){let n=[...t.values()].find(e=>e.id===r.localCandidateId),i=[...t.values()].find(e=>e.id===r.remoteCandidateId);(n?.candidateType==="relay"||i?.candidateType==="relay")&&(this._typeDetail="dc-turn");let s=n?.address||n?.ip||"",a=i?.address||i?.ip||"";("127.0.0.1"===s||"::1"===s||"127.0.0.1"===a||"::1"===a)&&(this._isLoopback=!0),e=`local=${n?.candidateType}/${n?.protocol} remote=${i?.candidateType}/${i?.protocol}`}})}catch{}this.send(n.l_.control,{event:"rtc:linkType",args:[this._typeDetail]}),(0,p.c)("transport",`[rtc] dc OPEN type=${this._typeDetail} ${e}`),(0,f.Lq)("switch",`rtc dc OPEN (${this._typeDetail} ${e})`),clearTimeout(this._connectTimer),this._connectTimer=null,this._everOpened=!0,this._lastInboundAt=Date.now(),this._setState(n.Of.open)};s.onopen=d,a.onopen=d;let h=()=>{let e=!this._dcControl||"closed"===this._dcControl.readyState,t=!this._dcBinary||"closed"===this._dcBinary.readyState;(0,f.Lq)("switch",`rtc dc-close (ctrl=${this._dcControl?.readyState} bin=${this._dcBinary?.readyState})`),e&&t?this._setState(n.Of.closed):this._setState(n.Of.degraded)};s.onclose=h,a.onclose=h,l.onclose=()=>{this._dcFile=null},o.onclose=()=>{this._dcMobile=null},c.onclose=()=>{this._dcBrowser=null},s.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcControl ERROR:",t)},a.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcBinary ERROR:",t)},l.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcFile ERROR:",t)},s.onmessage=e=>{let t,{data:r}=e;this._lastInboundAt=Date.now();try{let e;if("string"==typeof r)e=JSON.parse("string"==typeof r?r:new TextDecoder().decode(r),v);else e=T(r),this._v2RxSeen||(this._v2RxSeen=!0,(0,f.Lq)("switch","env2: first v2 binary frame DECODED from agent (mutual upgrade confirmed)"));t=this._reassemble.push(e)}catch(e){console.error("[rtc] control parse error:",e.message);return}if(t){if("__ping"===t.event){this._hbTimer||this._startHeartbeatWatch(),(this._hbLastPing?Date.now()-this._hbLastPing:1/0)<=2*n.KF&&(this._hbFastCadence=!0),this._hbLastPing=Date.now();try{s.send(A({event:"__pong",args:t.args||[]}))}catch{}return}this._emit("message",{event:t.event,data:t,source:"rtc"})}},a.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._receiveTile(t,"tiles-data")},c.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._receiveTile(t,"browser:tiles-data")},l.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._emit("binary",{channel:"file",buffer:t,source:"rtc"})},o.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._emit("binary",{channel:"mobile",buffer:t,source:"rtc"})},r.onicecandidate=e=>{var t;let{candidate:r}=e;if(!r)return void this._sendSignaling({type:"ice",candidate:"",mid:this._lastMid||"0"});this._lastMid=r.sdpMid;let n=/typ (host|srflx|relay|prflx)/.exec(r.candidate||"");n&&this._localCandidateTypes.add(n[1]);let i=(t=r.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;i&&this._emit("netFingerprint",i),this._sendSignaling({type:"ice",candidate:r.candidate,mid:r.sdpMid})},r.oniceconnectionstatechange=()=>{(0,p.c)("transport",`[rtc] iceState=${r.iceConnectionState}`),(0,f.Lq)("switch",`rtc ice=${r.iceConnectionState} types=[${[...this._localCandidateTypes].join(",")}]`),"checking"===r.iceConnectionState&&(this._iceReachedChecking=!0),"disconnected"===r.iceConnectionState?this._setState(n.Of.degraded):"failed"===r.iceConnectionState?this._closePeer("ice-failed"):"connected"===r.iceConnectionState&&this._dcControl?.readyState==="open"&&this._dcBinary?.readyState==="open"&&this._setState(n.Of.open)},this._signaling=e.signaling,this._signaling?.on?.(e=>this._handleSignal(e));try{let e=await r.createOffer();await r.setLocalDescription(e),(0,p.c)("transport","[rtc] offer sent"),(0,f.Lq)("switch","rtc offer sent"),this._sendSignaling({type:"offer",sdp:e.sdp,useTurn:this._useTurn})}catch(e){console.error("[rtc] createOffer error:",e.message),this._closePeer(`create-offer:${e.message}`)}}disconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";this._closePeer(`manual-disconnect by=${e} state=${this._state}`),this._signaling?.off?.(),this._signaling=null}send(e,t){if(e===n.l_.control){if(this._dcControl?.readyState!=="open")return!1;let e={event:t.event,args:t.args||[],ackId:t.ackId||null,sq:t.sq??null,ep:t.ep??null,rs:t.rs??null},r=this._sendControlStallChecked(this._dcControl,e);return r&&this._peerEnv2&&!this._v2Announced&&(this._v2Announced=!0,(0,f.Lq)("switch","env2: client→agent control now SENT as v2 binary frames")),r}if(e===n.l_.binary){if(this._dcBinary?.readyState!=="open")return!1;try{return this._dcBinary.send(t),!0}catch(e){return console.error("[rtc] send binary error:",e.message),!1}}if(e===n.l_.file){if(this._dcFile?.readyState!=="open")return!1;try{if(this._dcFile.bufferedAmount>n.HE.dcBufferThreshold)return!1;return this._dcFile.send(t),!0}catch(e){console.error("[rtc] send file error:",e.message)}}return!1}_sendControlStallChecked(e,t){let r,i=e.bufferedAmount;if(i>0&&i>=this._dcPrevQueued){0===this._dcStallCount&&(this._dcStallSince=Date.now()),this._dcStallCount++;let e=Date.now()-this._dcStallSince;if(this._dcStallCount>=n.fP&&e>=n.b4)return this._closePeer(`dc-drain-stall (${i}B stuck ${e}ms)`),!1}else this._dcStallCount=0;if(this._peerEnv2)r=this._sendFramed(t);else try{e.send(A(t)),r=!0}catch(e){r=!1}return this._dcPrevQueued=e.bufferedAmount,r}get typeDetail(){return this._typeDetail}get isLoopback(){return this._isLoopback}_closePeer(e){(0,f.Lq)("switch",`rtc→closed reason=${e}`),this._cleanupPeer(),this._setState(n.Of.closed)}setPeerCaps(e){this._peerEnv2=!!e?.env2,this._peerFragCtl=!!e?.fragCtl}get maxControlBytes(){return this._pc?.sctp?.maxMessageSize||n.dT}_sendFramed(e){var t;let r,n,i=this._peerFragCtl?this.maxControlBytes:1/0,s=(t=++this._fragSeq,(n=function(e,t){if(e.byteLength<=t)return[e];let r=t-192;if(r<=0)return null;let n=Math.ceil(e.byteLength/r);if(n>4096)return null;let i=[];for(let t=0;t<n;t++)i.push(e.subarray(t*r,Math.min((t+1)*r,e.byteLength)));return i}(r=S(e),i))?1===n.length?[r]:n.map((r,i)=>S({event:e.event,args:[r]},{id:t,part:i,parts:n.length})):null);if(!s)return!1;try{for(let e of s)this._dcControl.send(e);return!0}catch(e){return(0,p.c)("transport",`[rtc] control send refused: ${e.message}`),!1}}_startHeartbeatWatch(){this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),this._hbLastPing=Date.now(),this._hbTimer=setInterval(()=>{if(this._state!==n.Of.open){clearInterval(this._hbTimer),this._hbTimer=null;return}let e=Date.now()-this._hbLastPing;e>(this._hbFastCadence?n.An:n.mk)&&((0,p.c)("transport",`[rtc] heartbeat: no ping for ${e}ms → closing stalled peer`),this._closePeer(`heartbeat-stale (${e}ms)`))},n.KF)}async _addRemoteCandidate(e){let{candidate:t,mid:r}=e;t||(this._remoteGatheringDone=!0),await this._pc.addIceCandidate(new RTCIceCandidate(t?{candidate:t,sdpMid:r}:{candidate:"",sdpMid:r||"0"})).catch(()=>{})}_startDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=setInterval(async()=>{if(this._state===n.Of.open||!this._pc)return this._stopDeadPathWatch();if(!this._remoteGatheringDone||"complete"!==this._pc.iceGatheringState)return;let e=0,t=0;try{(await this._pc.getStats()).forEach(r=>{"candidate-pair"===r.type&&(e++,"failed"===r.state&&t++)})}catch{return}e&&!(t<e)&&(this._stopDeadPathWatch(),this._closePeer(`dead-path (${t} pair(s) failed)`))},n.QS)}_stopDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=null}_sendSignaling(e){this._signaling?.send?.(e)}async _handleSignal(e){if((0,p.c)("transport",`[rtc] signal: ${e.type}`),(0,f.Lq)("switch",`rtc signal recv=${e.type}`),this._pc)try{if("answer"===e.type){if(this._answerApplied||"stable"===this._pc.signalingState){(0,p.c)("transport","[rtc] duplicate answer ignored"),(0,f.Lq)("switch","rtc duplicate answer ignored");return}if(e.pub&&e.sig){let t=await this._verifyHostAnswer(e);if(t){console.error(`[rtc] host key verification FAILED (${t}) — relayed answer rejected`),this._closePeer(`host-key-rejected:${t}`);return}}await this._pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp})),this._answerApplied=!0,(0,p.c)("transport","[rtc] answer set"),(0,f.Lq)("switch","rtc answer applied");let t=this._pendingCandidates;for(let e of(this._pendingCandidates=[],t))await this._addRemoteCandidate(e);clearTimeout(this._connectTimer),this.connectDeadline=Date.now()+n.HJ,this._startDeadPathWatch(),this._connectTimer=setTimeout(async()=>{if(this._state!==n.Of.open){try{let e=await this._pc.getStats();e.forEach(t=>{if("candidate-pair"!==t.type)return;let r=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId),i=(r?.address||r?.ip||"?").split(":")[0].slice(-12),s=n?.address||n?.ip||"?";(0,f.Lq)("switch",`pair ${t.state} ${r?.candidateType}:${i}→${n?.candidateType}:${s}`)})}catch{}this._closePeer(`ice-timeout (state=${this._state})`)}},n.HJ)}else if("ice"===e.type){if(!this._answerApplied)return void this._pendingCandidates.push(e);await this._addRemoteCandidate(e)}else"error"===e.type&&((0,p.c)("transport",`[rtc] server error: ${e.message}`),this._closePeer(`server-error:${e.message}`))}catch(e){console.error("[rtc] signal handle error:",e.message)}}async _verifyHostAnswer(e){let t=this._ctx?.auth?.apiKey;if(!t)return null;let r=(0,C.lz)(t),n=r?.hostPubKey?r:null,i=!!r?.hostSealKey;if((0,p.c)("auth","[seal] verify answer:",{hostSentXpub:!!e.xpub,agentSentXpub:!!e.xpub,pinned:!!n,stalePin:!!(r?.hostPubKey&&!i),pendingFp2:(0,C.e1)()}),n){if(n.hostPubKey!==e.pub){let r=(0,C.e1)();return r&&await (0,C.t8)(e.pub,e.xpub)===r?((0,C.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:r}),(0,p.c)("transport","[rtc] host key re-pinned via fresh pairing fp2"),null):((0,p.c)("auth","[seal] REJECT answer — pinned pub differs (host key rotated?) and no fresh fp2 to re-pin"),"pinned-pub-mismatch")}let r=await (0,C.D5)(e.pub,e.sdp,e.sig);if(!1===r)return(0,p.c)("auth","[seal] REJECT answer — signature invalid (relay tampering?)"),"sig-invalid";if(null===r){if(!i)return(0,p.c)("auth","[seal] REJECT answer — no Ed25519 in browser and pinned fp2 predates sealing"),"no-ed25519-old-pin";let t=await (0,C.t8)(e.pub,e.xpub)===n.fp2;return t||(0,p.c)("auth","[seal] REJECT answer — fp2 fallback mismatch vs pinned",n.fp2),t?null:"fp2-mismatch"}return null}let s=(0,C.e1)();if(s){let r=await (0,C.t8)(e.pub,e.xpub);if(r!==s)return(0,p.c)("auth","[seal] REJECTED — fp2",r,"!= code",s,e.xpub?"":"(agent sent no sealing key — needs the source build)"),(0,C.HY)(),"pairing-fp2-mismatch";(0,C.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:r}),(0,p.c)("auth","[seal] pinned via RTC — fp2",r,"sealing key stored"),(0,p.c)("transport","[rtc] host key pinned via pairing fp2")}return null}natVerdict(){let e=this._localCandidateTypes;return this._everOpened||e.has("relay")?"ok":0===e.size||e.has("srflx")&&(!this._answerApplied||this._iceReachedChecking)?"unknown":"hard"}_cleanupPeer(){for(let e of(clearTimeout(this._connectTimer),this._connectTimer=null,this._stopDeadPathWatch(),this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),[this._dcControl,this._dcBinary,this._dcFile,this._dcMobile]))if(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null;try{e.close()}catch{}}if(this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._dcMobile=null,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._isLoopback=!1,this._typeDetail="dc-stun",this._pc){this._pc.onicecandidate=null,this._pc.oniceconnectionstatechange=null;try{this._pc.close()}catch{}this._pc=null}this._pendingEmit=null,this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null),this._latestTileTs.clear(),this._reassemble=x()}_receiveTile(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"tiles-data",n=++P,i=e.byteLength;new Promise(t=>{let i=setTimeout(()=>{$.has(n)&&($.delete(n),t(null))},8e3),s=R.eR.decodeQueueCap;for(;$.size>=s;){let e=$.keys().next().value,t=$.get(e);if(!t)break;clearTimeout(t.timer),$.delete(e),t.resolve(null)}let a=function(){if(!1===I)return null;if(I)return I;try{I=new Worker(r.tu(new URL(r.p+r.u(6153),r.b)))}catch{return I=!1,null}return I.onmessage=e=>{let{data:{tiles:t,timestamp:r,id:n,hasBitmap:i,error:s}}=e;D=0;let a=$.get(n);if(!a){if(t)for(let e of t)e.bitmap?.close?.();return}clearTimeout(a.timer),$.delete(n),a.resolve(s?null:{tiles:t,timestamp:r,hasBitmap:i})},I.onerror=e=>{console.error("[Worker] tileDecoder:",e.message),function(){if(I)try{I.terminate()}catch{}for(let{resolve:e}of(I=null,$.values()))try{e(null)}catch{}$.clear()}(),++D>=3&&(I=!1)},I}();if(!a){clearTimeout(i),$.delete(n),t(null);return}$.set(n,{resolve:t,timer:i}),a.postMessage({buffer:e,id:n,v:2},[e])}).then(e=>{if(!e)return;let{tiles:r,timestamp:n,hasBitmap:s}=e;this._pendingEmits??=new Map,this._latestTsMaps??=new Map;let a=this._pendingEmits.get(t);a||(a={tiles:new Map,timestamp:n,hasBitmap:s,bytes:0},this._pendingEmits.set(t,a));let l=this._latestTsMaps.get(t);for(let e of(l||(l=new Map,this._latestTsMaps.set(t,l)),a.bytes+=i,r))n>=(l.get(e.tileIndex)??0)?(l.set(e.tileIndex,n),a.tiles.get(e.tileIndex)?.bitmap?.close?.(),a.tiles.set(e.tileIndex,e),n>a.timestamp&&(a.timestamp=n)):e.bitmap?.close?.();this._flushTimers??=new Map,this._flushTimers.has(t)&&clearTimeout(this._flushTimers.get(t));let o=setTimeout(()=>{this._flushTimers.delete(t);let e=this._pendingEmits.get(t);if(!e)return;this._pendingEmits.delete(t);let r=[...e.tiles.values()];r.length&&this._emit("message",{event:t,data:{tiles:r,timestamp:e.timestamp,hasBitmap:e.hasBitmap,bytes:e.bytes,transport:this._typeDetail},source:"rtc"})},0);this._flushTimers.set(t,o)})}}let O=new Map;function q(e){if(!e?.id)throw Error("Adapter missing static id");O.set(e.id,e)}function E(){let{urls:e,timeoutMs:t,PeerConnection:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r||("u">typeof RTCPeerConnection?RTCPeerConnection:null);if(!i)return Promise.resolve(null);let s=[{urls:e||n.cx.urls}];return new Promise(e=>{let r,a,l=!1,o=t=>{if(!l){l=!0,clearTimeout(a);try{r.onicecandidate=null,r.close()}catch{}e(t)}};try{r=new i({iceServers:s,iceCandidatePoolSize:0})}catch{return e(null)}a=setTimeout(()=>o(null),t??n.cx.timeoutMs),r.onicecandidate=e=>{var t;let{candidate:r}=e;if(!r)return o(null);let n=(t=r.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;n&&o(n)};try{r.createDataChannel("probe"),r.createOffer().then(e=>r.setLocalDescription(e)).catch(()=>o(null))}catch{o(null)}})}let U="no-public-ip";function B(e){let t=0,r=!1;for(let n of e.values())"candidate-pair"===n.type&&(n.nominated||n.selected)&&(r=!0,t+=(n.bytesReceived??0)+(n.responsesReceived??0));return r?t:null}function N(e){let{connectingSince:t,connectDeadline:r,connectTimeoutMs:n}=e;return r??(t??0)+n}function j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"stale",r=e._adapters.get("ws"),i=Math.max(r?.lastInboundAt??0,r?.lastMsgAt??0),s=r?.ready&&function(){let{ready:e=!0,lastInboundAt:t=0,now:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return!!e&&(!t||r-t>=n.Rh)}({ready:!0,lastInboundAt:i,now:Date.now()});if(r){let e=r.lastInboundAt??0,n=r.lastMsgAt??0,i=Date.now();(0,f.Lq)("switch",`zombie check (${t}): verdict=${!!s} ready=${!!r.ready} lastPong=${e?`${i-e}ms`:"never"} lastMsg=${n?`${i-n}ms`:"never"}`)}if(!s)return!1;(0,p.c)("transport",`[pm] ws zombie (${t}) → force reconnect`);try{r.forceReconnect?.()}catch{}return!0}function F(e,t){let r=e._adapters.get("rtc"),i=r?._pc;if(!i||"failed"===i.connectionState)return void e._forceRestartRtc(`${t}-pc-failed`);if(e._probeLive?.rtc===r)return void(0,f.Lq)("switch",`${t} probe shared (already measuring this peer)`);clearTimeout(e._resumeProbeTimer);let s=++e._probeToken;e._probeLive={rtc:r,token:s},(async()=>{let t=B(await i.getStats());return null==t||(await new Promise(t=>{e._resumeProbeTimer=setTimeout(t,n.UT)}),s!==e._probeToken)?null:B(await i.getStats())-t})().then(i=>{if(s!==e._probeToken)return;let a=r?.lastInboundAt&&Date.now()-r.lastInboundAt<n.mk;null!=i&&i>0||a?(0,f.Lq)("switch",`${t} probe alive (Δ=${i}, recent=${!!a})`):((0,f.Lq)("switch",`${t} probe DEAD (Δ=${i}) → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-dead`))}).catch(()=>{s!==e._probeToken||(r?.lastInboundAt&&Date.now()-r.lastInboundAt<n.mk?(0,f.Lq)("switch",`${t} probe error ignored (rtc recently active)`):((0,f.Lq)("switch",`${t} probe error → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-error`)))}).finally(()=>{e._probeLive?.token===s&&(e._probeLive=null)})}let W="__env",K="__gap",H="__gapmiss";function z(e){let t=e._pickAdapter(n.l_.control);if(t)for(let r of e._outLog.unsentList()){if(!J(e,t,r))return;e._outLog.markSent(r.sq)}}function J(e,t,r){let i={event:r.event,args:r.args||[],ackId:r.ackId??null,sq:r.sq??null,ep:e._seqEpoch,rs:e._intakeSeq.applied};if("ws"===t.constructor.id){if(!e._peerSeqCtl){let i=r.ackId?function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return G(e,r.ackId,n)}:null;return t.send(n.l_.control,i?{event:r.event,args:r.args,cb:i}:{event:r.event,args:r.args})}return t.send(n.l_.control,{event:W,args:[i]})}return t.send(n.l_.control,i)}function G(e,t,r){let i=e._pendingAcks.get(t);if(!i)return;let s=e._ackReqs?.get(t);if(r?.[0]?.error===n.dE&&s&&s.tries<n.mH.admitRetryMax){s.tries++,e._admitQueue.includes(t)||e._admitQueue.push(t),(0,f.Lq)("switch",`not-admitted ${s.event} → hold for re-admission (try ${s.tries})`),Z(e,"ack");return}Number.isInteger(s?.sq)&&e._outLog.markAcked(s.sq),e._ackReqs?.delete(t),e._pendingAcks.delete(t);let a=e._ackTimers.get(t);a&&(clearTimeout(a),e._ackTimers.delete(t)),i(...r||[])}function V(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;e._outLog.append({event:t,args:void 0===r?[]:[r],ackId:n}),z(e)}function Z(e,t){let r=Date.now();if(r-e._admitKickAt<n.mH.admitKickMinMs)return;e._admitKickAt=r;let i=e._adapters.get("ws");if((0,f.Lq)("switch",`admission stale (${t}) → re-dial ${i?"ws":"rtc"}`),i?.forceReconnect){try{i.forceReconnect()}catch{}return}e._forceRestartRtc?.("not-admitted")}let Q=new Set(["getSessions","getWorkspaces","bg:get","bg:list","ai:create","ai:peekSeq","aiSince"]),X=new Set(["ai:prompt"]);function Y(e,t){if(t?.type!=="error")return!1;let r=t.message===n.bg.pending?"pending":t.message===n.bg.rejected?"rejected":null;return!!r&&((0,p.c)("transport",`[pm] device ${r} → approval UI`),e._awaitingApproval=!0,e._wsCallbacks.onApproval?.(r),!0)}function ee(e){if((0,f.Lq)("switch","signaling ready"),er(e),e._awaitingApproval)return;let t=e._adapters.get("rtc");if(!t){(0,f.Lq)("switch","sig-ready → start rtc (was deferred)"),e._startSecondaryAdapters();return}t.state===n.Of.closed&&((0,f.Lq)("switch","sig-ready → restartRtc (rtc was closed)"),e._restartRtc("sig-ready"))}function et(e,t){!(e._sig?.ready&&e._sig.send(t))&&("offer"===t.type&&(e._sigBuffer=e._sigBuffer.filter(e=>"offer"!==e.type&&"ice"!==e.type)),e._sigBuffer.push(t),e._sigBuffer.length>32&&e._sigBuffer.shift())}function er(e){if(!e._sigBuffer.length)return;let t=e._sigBuffer;for(let r of(e._sigBuffer=[],t))et(e,r)}async function en(e){if(e._auth.tunnelUrl!==window.location.origin)try{(0,p.c)("transport",`[pm] refreshTunnelUrl: fetching from ${u.O}/api/connect`);let t=await fetch(`${u.O}/api/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e._auth.apiKey})});if(!t.ok){(0,p.c)("transport",`[pm] refreshTunnelUrl: HTTP ${t.status}`);let r=await t.json().catch(()=>({}));503===t.status&&r?.error==="agent-offline"&&e._wsCallbacks.onHostOffline?.();return}let r=await t.json();(0,p.c)("transport",`[pm] refreshTunnelUrl: got ${r.tunnelUrl} (was ${e._auth.tunnelUrl})`),r.tunnelUrl&&r.tunnelUrl!==e._auth.tunnelUrl&&(e._auth.tunnelUrl=r.tunnelUrl)}catch(e){(0,p.c)("transport",`[pm] refreshTunnelUrl: error ${e.message}`)}}q(w),q(L);class ei{constructor(e,t){const{profile:r,auth:i,wsCallbacks:s,rtcCallbacks:a,peerId:l}=function(e,t){let r=t?.enableWebRTC?"remoteDesktop":"clientApp",i={...n.j3[r]};t?.enableWebRTC||(i.enabled=["ws"]),t?.enableTurn&&(i.rtc={...i.rtc,enableTurn:!0});let s={tunnelUrl:e.tunnelUrl,localIp:e.localIp,apiKey:e.apiKey,tempKey:e.tempKey,deviceId:e.deviceId,namespace:e.namespace,socketOptions:e.socketOptions},a={onConnect:e.onConnect,onDisconnect:e.onDisconnect,onRetryStatus:e.onRetryStatus,onUrlUpdate:e.onUrlUpdate,onApproval:e.onApproval,onHostOffline:e.onHostOffline},l=t?{onUpgrade:t.onUpgrade,onFallback:t.onFallback,onTransportChange:t.onTransportChange}:{},o=`${e.deviceId}:${Math.random().toString(36).slice(2,10)}`;return s.socketOptions?.auth&&(s.socketOptions.auth.peerId=o),{profile:i,auth:s,wsCallbacks:a,rtcCallbacks:l,peerId:o}}(e,t);for(const e of(this._profile=r,this._auth=i,this._wsCallbacks=s,this._rtcCallbacks=a,this._peerId=l,Object.assign(this,{_adapters:new Map,_pendingAcks:new Map,_ackTimers:new Map,_ackSeq:0,_rtcRestartAttempts:0,_rtcRestartTimer:null,_rtcRestartDueAt:0,_probeAttempts:0,_rtcGivenUp:!1,_giveUpIp:null,_lastStunProbeAt:0,_rejoinDebounceTimer:null,_netFingerprint:null,_awaitingApproval:!1,_ackTimeoutMs:n.QZ.ackTimeoutMs,_hiddenAt:null,_resumeProbeTimer:null,_probeToken:0,_probeLive:null,_connected:!1,_type:"ws",_connectionMode:"tunnel",_lastWsState:null,_rawSocket:null,_onConnectFired:!1,_rtcSignalingHandler:null,_sig:null,_sigDestroyed:!1,_sigBuffer:[],_wsFallbackTimer:null,_peerSeqCtl:!1,_ackReqs:new Map,_admitQueue:[],_admitKickAt:0,_seqEpoch:Date.now().toString(36)+Math.random().toString(36).slice(2,8),_outLog:function(e){let{maxBytes:t,maxEntries:r,maxReplayEntries:n=512}=e,i=new Map,s=new Set,a=1,l=1,o=1,c=0,d=0,u=0,h=e=>128+function(e){if(!Array.isArray(e))return 256;let t=64;for(let r of e)null!=r&&("string"==typeof r?t+=r.length:ArrayBuffer.isView(r)||"Buffer"===r.type?t+=r.length||256:"object"==typeof r?t+=512:t+=8);return t}(e.args),p=e=>{let t=[];for(let r=e;r<a;r++){let e=i.get(r);e&&t.push({...e,sq:r})}return t};return{get nextSeq(){return a},get applied(){return c},get droppedUnsent(){return u},append(e){let n=a++,c={event:e.event,args:e.args,ackId:e.ackId??null};for(i.set(n,c),d+=h(c);i.size>1&&(d>t||i.size>r);){let e=i.get(l);if(!e){l++;continue}i.delete(l),s.delete(l),d-=h(e),l>=o&&u++,l++}return{...c,sq:n}},setApplied(e){Number.isInteger(e)&&e>c&&(c=e)},markSent(e){Number.isInteger(e)&&!(e<o)&&(o=e+1)},markAcked(e){Number.isInteger(e)&&e>=l&&s.add(e)},range(e,t){if(!Number.isInteger(e)||!Number.isInteger(t)||e<l||t>=a||t<e)return null;let r=[];for(let n=e;n<=t;n++){let e=i.get(n);if(!e)return null;r.push({...e,sq:n})}return r},unsentList:()=>p(Math.max(o,l)),replayList(){let e=Math.max(c+1,l,a-n);return s.size?p(e).filter(e=>!s.has(e.sq)):p(e)},clear(){i.clear(),s.clear(),a=1,l=1,o=1,c=0,d=0,u=0}}}({maxBytes:n.mH.ringMaxBytes,maxEntries:n.mH.maxEntries}),_intakeSeq:null}),this._intakeSeq=function(e){return function(e){let{holdMax:t,gapDeadlineMs:r,deliver:n,requestGap:i,onLoss:s,onDupe:a,schedule:l=setTimeout,clearFn:o=clearTimeout}=e,c=!1,d=null,u=!1,h=0,p=0,f=new Map,m=null,g=0,y=!1,_=()=>f.size?Math.min(...f.keys()):1/0,b=()=>{for(;f.size;){let e=f.get(h+1);if(!e)break;f.delete(h+1),h++,n(e)}},w=()=>{let e=_()-1;e>h&&(s&&s(h+1,e),h=e),g=0,b(),k()},k=()=>{if(!f.size){m&&(o(m),m=null),g=0;return}let e=h+1,t=_()-1;!(e>t)&&(g!==e&&(g=e,i(e,t)),m||y||(m=l(()=>{m=null,!y&&f.size&&w()},r)))};return{get armed(){return c},get applied(){return h},get maxSeen(){return p},arm(){c=!0,h=p},push(e){(e=>{if(null!=e&&e!==d){if(null===d){d=e;return}d=e,h=0,f.clear(),g=0,m&&(o(m),m=null)}})(e?.ep);let r=e?.sq;if(!c||!Number.isInteger(r)){Number.isInteger(r)&&r>p&&(p=r),n(e);return}if(r>p&&(p=r),!u&&(u=!0,r>h+1&&(h=r-1)),r<=h){a&&a(r);return}if(r===h+1){h++,n(e),b(),k();return}(f.set(r,e),f.size>t)?w():k()},gapMissed(e){c&&e===h+1&&w()},setPaused(e){y=e,e&&m&&(o(m),m=null),!e&&f.size&&(g=0,k())},reset(){c=!1,d=null,u=!1,h=0,p=0,f.clear(),g=0,m&&(o(m),m=null)}}}({holdMax:n.mH.holdMax,gapDeadlineMs:n.mH.gapDeadlineMs,deliver:t=>(function(e,t){switch(t.event){case"__ack":var r;return void G(e,(r=t).ackId,r.args);case K:return function(e){let{from:t,to:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._outLog.range(t,r);if(!i)return void V(e,H,{from:t});let s=e._pickAdapter(n.l_.control);if(s){for(let t of i)if(!J(e,s,t))break}}(e,t.args?.[0]);case H:return e._intakeSeq.gapMissed(t.args?.[0]?.from)}if(t.ackId&&e._pendingAcks.has(t.ackId))return G(e,t.ackId,t.args);!function(e,t){let{event:r}=t,i=Array.isArray(t.args)?t.args:[];if("srvCaps"===r){let r=i[0]??t;(0,p.c)("transport",`[pm] srvCaps from host: ${JSON.stringify(r)}`),e._srvCaps=r||{},r?.seqCtl&&!e._peerSeqCtl&&(e._peerSeqCtl=!0,(0,f.Lq)("switch","host announced seqCtl → sequenced control stream active")),e._adapters.get("rtc")?.setPeerCaps?.(e._srvCaps);return}if("conn:notAdmitted"===r)return Z(e,"notice");if("device:approved"===r){e._awaitingApproval=!1;let t=e._admitQueue.splice(0);if(t.length){for(let r of((0,f.Lq)("switch",`re-admitted → re-send ${t.length} held request(s)`),t)){let t=e._ackReqs.get(r);if(!t||!e._pendingAcks.has(r))continue;let n=e._outLog.append({event:t.event,args:t.args,ackId:r});t.sq=n.sq}z(e)}let r=e._adapters.get("rtc");e._canSignal()&&(!r||r.state===n.Of.closed)&&e._restartRtc("device-approved")}if("rtc:enabled"===r){e._rtcTestDisabled&&(e._rtcTestDisabled=!1,(0,f.Lq)("switch","rtc:enabled by host → clear flag + restart RTC"),e._restartRtc("rtc-enabled"));return}"tunnel:updated"===r?function(e,t){if(!t)return;let{tunnelUrl:r,localIp:n,status:i}=t;if(e._auth.tunnelUrl===window.location?.origin)return(0,f.Lq)("switch",`tunnel:updated ignored (carrier is the page origin; got url=${r||"none"})`);if((0,f.Lq)("switch",`tunnel:updated recv (status=${i} url=${r||"none"})`),"ready"===i&&r){let t=e._auth.tunnelUrl!==r;e._auth.tunnelUrl=r,n&&(e._auth.localIp=n),e._wsCallbacks.onUrlUpdate?.({tunnelUrl:r,localIp:n});let i=e._adapters.get("ws");if(i&&(!i.ready||t)){(0,f.Lq)("switch",`tunnel:updated → ${t?"url changed":"ws not ready"} → retry ws with new URL`);try{i.retryNow("tunnel-updated")}catch{}}}else"down"===i&&(e._auth.tunnelUrl="",e._wsCallbacks.onUrlUpdate?.({tunnelUrl:"",localIp:n}))}(e,i[0]):e._bus?.dispatch(r,i)}(e,t)})(e,t),requestGap:(t,r)=>e._sendStreamEvent(K,{from:t,to:r}),onLoss:(t,r)=>{e._seqLosses=(e._seqLosses||0)+1,(0,f.Lq)("switch",`seq skipped ${t}..${r} (ring evicted)`)},onDupe:()=>{e._seqDupes=(e._seqDupes||0)+1}})}(this),this._bus=function(e){let t=new Map,r=(e,r)=>{t.has(e)||t.set(e,[]),t.get(e).push(r)},n=(e,r)=>{let n=t.get(e);if(!n)return;let i=n.findIndex(e=>e===r||e._original===r);-1!==i&&n.splice(i,1)};return{_listeners:t,get connected(){return e._anyAdapterReady()},get hostCaps(){return e._srvCaps||{}},get id(){return e._rawSocket?.id||null},emit(t){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];e._sendControl(t,n)},on(e,t){r(e,t)},off(e,t){n(e,t)},once(e,t){let i=function(){for(var r=arguments.length,s=Array(r),a=0;a<r;a++)s[a]=arguments[a];n(e,i),t(...s)};i._original=t,r(e,i)},listeners:e=>[...t.get(e)||[]],dispatch(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=t.get(e);if(n?.length){for(let e of[...n])if(n.includes(e))try{e(...r)}catch{}}},clear(){t.clear()},disconnect(){e._rawSocket?.disconnect()},kickWsZombie:t=>e.kickWsZombie(t)}}(this),this.busRef={current:this._bus},C.IU))this._bus.on(e,t=>(0,C.lu)(this,e,t));this._watchers=function(e){let t=()=>{let t;if((0,f.Lq)("switch",`visibility=${document.visibilityState}`),"visible"!==document.visibilityState)return;let r=e._adapters.get("ws"),i=e._adapters.get("rtc");if((0,f.Lq)("switch",`resume check: ws=${r?.ready?"ready":r?.state} rtc=${i?.ready?"ready":i?.state}`),j(e,"resume"),e._awaitingApproval)return;if(e._rtcGivenUp)return void e._maybeRearmRtc();if(t=e._rtcRestartTimer?Math.max(e._rtcRestartDueAt-Date.now(),0):-1,(0,f.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) reason=resume pendingIn=${t}ms`),e._rtcRestartAttempts=0,e._probeAttempts=0,t<=n.QZ.backoffMs[0]||((0,f.Lq)("switch",`resume: pending rung was ${t}ms out → re-arm fast`),e._disarmRestart(),e._scheduleRtcRestart("resume-rearm")),!e._canSignal())return void e._sig?.retryNow("resume-no-carrier");let s=i?.state;i&&s!==n.Of.closed&&s!==n.Of.degraded?function(e){let t=e._adapters.get("rtc");if(!t?.ready)return e._restartRtc("resume-not-ready");let r=e._hiddenAt?Date.now()-e._hiddenAt:0;if("function"==typeof matchMedia&&matchMedia("(pointer: coarse)").matches&&r>n.Tr){(0,f.Lq)("switch",`resume: hidden ${Math.round(r/1e3)}s on touch → skip probe, force restart`),(0,p.c)("transport",`[pm] resume: hidden ${Math.round(r/1e3)}s → immediate restart`),e._forceRestartRtc("resume-hidden-touch");return}F(e,"resume")}(e):((0,f.Lq)("switch",`visibility → restartRtc (rtc=${s||"absent"})`),e._restartRtc("resume-dead-rtc"))},r=()=>{if("hidden"===document.visibilityState){e._hiddenAt=Date.now();return}clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=setTimeout(t,150)};document.addEventListener("visibilitychange",r);let i=!1,s=r=>{let n=!!r.detail?.hidden;if(n!==i){if(i=n,n){e._hiddenAt=Date.now();return}clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=setTimeout(t,150)}};document.addEventListener("app-visibility",s);let a=()=>{"visible"===document.visibilityState&&r()},l=()=>{e._hiddenAt=Date.now()};document.addEventListener("resume",a),document.addEventListener("freeze",l);let o=()=>{clearTimeout(e._netDebounceTimer),e._netDebounceTimer=setTimeout(()=>{!1===navigator.onLine?(0,f.Lq)("switch","net-change: still offline → wait"):((0,p.c)("transport","[pm] network change → probe rtc"),(0,f.Lq)("switch",`net-change: online=${navigator.onLine} → kick sig + ws + rtc`),e._sig?.retryNow("net-change"),e.retryNow("net-change"),(0,f.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) givenUp=${e._rtcGivenUp} reason=net-change`),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._shouldRenegotiate()&&e._restartRtc("net-change"))},n.o_.debounceMs)};return window.addEventListener("online",o),navigator.connection?.addEventListener?.("change",o),{visibilityHandler:r,detach(){document.removeEventListener("visibilitychange",r),document.removeEventListener("app-visibility",s),document.removeEventListener("resume",a),document.removeEventListener("freeze",l),window.removeEventListener("online",o),navigator.connection?.removeEventListener?.("change",o),clearTimeout(e._netDebounceTimer),e._netDebounceTimer=null,clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=null}}}(this)}get type(){return this._type}get connected(){return this._connected}get connectionMode(){return this._connectionMode}get wsBlocked(){return this._adapters.get("ws")?.blocked||!1}setWsBlocked(e){this._adapters.get("ws")?.setBlocked(e)}setUpdating(e){this._adapters.get("ws")?.setUpdating(e)}retryNow(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"user",t=this._adapters.get("ws");t?t.retryNow?.(e):((0,f.Lq)("switch",`retryNow by=${e}: no ws adapter → full connect()`),this.connect())}kickWsZombie(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"stale";return j(this,e)}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];this._sendControl(e,r)}sendBinary(e,t){let r=this._pickAdapter(e);return!!r&&r.send(e,t)}connect(){this._sigDestroyed=!1;let e=this._profile.enabled.includes("rtc");e&&this._initSignalingClient(),e&&(this._canSignal()?this._startSecondaryAdapters():((0,f.Lq)("switch","rtc deferred — waiting for signaling relay"),clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=setTimeout(()=>{this._sigDestroyed||this._adapters.has("rtc")||((0,f.Lq)("switch","rtc defer expired → start anyway"),this._startSecondaryAdapters())},n.BF))),this._startWsFallback(),(0,p.c)("transport","[pm] connect: RTC + WS parallel (RTC preferred, WS warm standby)."),(0,f.Lq)("switch","connect: RTC + WS parallel")}async _startWsFallback(){if(!(this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)){if((0,f.Lq)("switch","ws-fallback: start (refresh url)"),await this._refreshTunnelUrl(),this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)return void(0,f.Lq)("switch","ws-fallback: aborted (destroyed, loopback or already attached)");(0,f.Lq)("switch","ws-fallback: connecting"),this._instantiate("ws"),this._adapters.get("ws")?.connect(this._buildCtx("ws"))}}async _refreshTunnelUrl(){return en(this)}_initSignalingClient(){!function(e){if(!n.gI.enabled||e._sig||e._sigDestroyed||!e._auth.deviceId||!e._auth.apiKey)return;let t=u.O.replace(/^http/,"ws")+"/signaling";r.e(7489).then(r.bind(r,87489)).then(r=>{let{SignalingClient:i}=r;e._sig||e._sigDestroyed||(e._sig=new i({url:t,role:"client",roomId:e._auth.apiKey,apiKey:e._auth.apiKey,from:e._peerId,onReady:()=>ee(e),pingMs:n.gI.pingMs}),e._sig.on(t=>{if("error"===t.type&&"rtc-disabled"===t.message){e._rtcTestDisabled=!0,(0,f.Lq)("switch","rtc-disabled by host → stop RTC retry (use WS)");return}Y(e,t)||e._rtcSignalingHandler?.(t)}),e._sig.connect())}).catch(e=>(0,p.c)("transport",`[pm] SignalingClient load failed: ${e?.message||e}`))}(this)}_instantiate(e){if(this._adapters.has(e))return;let t=O.get(e);if(!t)return;let r=new t;r.on("stateChange",t=>this._onAdapterStateChange(e,t)),r.on("message",e=>{let{event:t,data:r,source:n}=e;return this._dispatch(t,r,n)}),r.on("binary",e=>this._onBinary(e)),"rtc"===e&&(r.on("netFingerprint",e=>this._onNetFingerprint(e)),this._srvCaps&&r.setPeerCaps?.(this._srvCaps)),this._adapters.set(e,r)}_onNetFingerprint(e){if(!e||e===this._netFingerprint)return;let t=this._netFingerprint;this._netFingerprint=e,t&&(0,p.c)("transport",`[pm] net fingerprint ${t}→${e} (same network — no backoff reset)`)}_maybeRearmRtc(){if(!this._rtcGivenUp)return;let e=Date.now();e-this._lastStunProbeAt<n.cx.minIntervalMs||(this._lastStunProbeAt=e,E().then(e=>{var t;if(this._sigDestroyed||!this._rtcGivenUp)return;let r=e||(this._giveUpIp===U?U:null);(t=this._giveUpIp,r&&(!t||r!==t))?((0,f.Lq)("switch",`rearm check: ip ${this._giveUpIp||"unknown"}→${r} changed → re-arm RTC`),(0,p.c)("transport","[pm] public ip changed → re-arm rtc"),this._rtcGivenUp=!1,this._giveUpIp=null,this._probeAttempts=0,this._rtcRestartAttempts=0,this._netFingerprint=e,this._canSignal())?this._shouldRenegotiate()&&this._restartRtc("stun-rearm"):this._sig?.retryNow("stun-rearm"):(0,f.Lq)("switch",`rearm check: ip=${r||"unknown"} same as give-up → stay WS-only`)}).catch(()=>{}))}_startSecondaryAdapters(){for(let e of((0,p.c)("transport",`[pm] startSecondary enabled=${this._profile.enabled}`),(0,p.c)("transport",`[pm] startSecondary rtcTestDisabled=${!!this._rtcTestDisabled}`),this._profile.enabled))"ws"!==e&&("rtc"!==e||!this._rtcTestDisabled)&&(this._adapters.has(e)||((0,p.c)("transport",`[pm] start adapter ${e}`),this._instantiate(e),this._adapters.get(e)?.connect(this._buildCtx(e))))}_handleApprovalSignal(e){return Y(this,e)}_onSignalingReady(){ee(this)}_canSignal(){return!!this._sig?.ready}_shouldRenegotiate(){return!this._awaitingApproval&&this._canSignal()}_restartRtc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";(0,f.Lq)("switch",`restartRtc CALLED by=${e} attempts=${this._rtcRestartAttempts}`);let t=this._adapters.get("rtc"),r=function(e){let{testDisabled:t,givenUp:r,rtcState:i,hasRtc:s}=e;return t?"skip-test-disabled":r?"skip-given-up":s&&(i===n.Of.connecting||i===n.Of.open)?"skip-in-flight":s?"restart":"start-fresh"}({testDisabled:!!this._rtcTestDisabled,givenUp:this._rtcGivenUp,rtcState:t?.state,hasRtc:!!t});if("skip-test-disabled"===r)return void(0,f.Lq)("switch","restartRtc skipped (rtcTestDisabled)");if("skip-given-up"===r)return void(0,f.Lq)("switch","restartRtc skipped (hard NAT → WS-only)");if("skip-in-flight"===r)return void(0,f.Lq)("switch",`restartRtc skipped (rtc=${t.state})`);if("start-fresh"===r){(0,f.Lq)("switch","restartRtc: no rtc → startSecondary"),this._startSecondaryAdapters();return}(0,f.Lq)("switch","restartRtc: tear down + renegotiate"),(0,p.c)("transport","[pm] ws reconnected → restart rtc");try{t.disconnect(`restart:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null,this._startSecondaryAdapters()}_forceRestartRtc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";(0,f.Lq)("switch",`forceRestartRtc CALLED by=${e}`);let t=this._adapters.get("rtc");if(t){try{t.disconnect(`force:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}this._rtcGivenUp?(0,f.Lq)("switch","forceRestartRtc: torn down, no renegotiate (hard NAT)"):this._startSecondaryAdapters()}disconnect(){this._watchers?.detach(),this._watchers=null,clearTimeout(this._resumeProbeTimer),this._resumeProbeTimer=null,clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=null,this._probeToken++;try{this._sig?.disconnect()}catch{}for(let e of(this._sig=null,this._sigDestroyed=!0,this._sigBuffer=[],clearTimeout(this._wsFallbackTimer),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=null,this._adapters.values()))try{e.disconnect("pm-disconnect")}catch{}for(let[e,t]of(this._adapters.clear(),this._bus.clear(),this._intakeSeq?.reset(),this._outLog?.clear(),this._peerSeqCtl=!1,this._connected=!1,this._rawSocket=null,this._disarmRestart(),(0,f.Lq)("switch",`RESET attempts (was ${this._rtcRestartAttempts}) reason=pm-disconnect`),this._rtcRestartAttempts=0,this._probeAttempts=0,this._rtcGivenUp=!1,this._giveUpIp=null,this._lastStunProbeAt=0,this._pendingAcks)){try{t({error:"disconnected"})}catch{}let r=this._ackTimers.get(e);r&&clearTimeout(r)}for(let e of(this._pendingAcks.clear(),this._ackReqs?.clear(),this._admitQueue=[],this._ackTimers.values()))clearTimeout(e);this._ackTimers.clear()}_buildCtx(e,t){let r={auth:this._auth,profile:this._profile};return"ws"===e&&(r.onRetryStatus=this._wsCallbacks.onRetryStatus,r.onHostOffline=this._wsCallbacks.onHostOffline,r.onUrlUpdate=e=>{e.tunnelUrl&&(this._auth.tunnelUrl=e.tunnelUrl),void 0!==e.localIp&&(this._auth.localIp=e.localIp),this._wsCallbacks.onUrlUpdate?.(e)}),"rtc"===e&&(r.signaling={send:e=>this._sendSignaling(e),on:e=>{this._rtcSignalingHandler=e},off:()=>{this._rtcSignalingHandler=null}}),r}_onAdapterStateChange(e,t){(0,p.c)("transport",`[pm] ${e} state=${t}`),("rtc"!==e||t!==n.Of.closed)&&(0,f.Lq)("switch",`${e}→${t}`),"ws"===e&&function(e,t){let r=e._adapters.get("ws");if(t===n.Of.open){let t=e._lastWsState===n.Of.degraded;e._connected=!0,e._connectionMode=r?.connectionMode||"tunnel",e._rawSocket=r?.socket||null,t&&e._maybeFireRejoin("ws","ws reconnect while rtc ready"),e._lastWsState!==n.Of.open&&(e._onConnectFired?e._wsCallbacks.onUrlUpdate?.({}):(e._onConnectFired=!0,(0,f.Lq)("switch",`onConnect FIRE (ws, mode=${e._connectionMode})`),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)))}else e._rawSocket=null,e._lastWsState===n.Of.open&&((0,f.Lq)("switch","ws down"),e._anyAdapterReady()&&(0,f.Lq)("switch","ws down but rtc alive → skip onDisconnect"));e._lastWsState=t}(this,t),"rtc"===e&&function(e,t){if(t===n.Of.open){let t=e._onConnectFired;clearTimeout(e._wsFallbackTimer),e._rtcCallbacks.onUpgrade?.(e._adapters.get("rtc")?.typeDetail||"dc-stun"),e._onConnectFired||(e._onConnectFired=!0,e._connected=!0,e._connectionMode="webrtc",(0,f.Lq)("switch","onConnect FIRE (rtc, mode=webrtc)"),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._disarmRestart(),clearTimeout(e._rejoinDebounceTimer),e._rejoinDebounceTimer=null;let r=e._adapters.get("rtc");if(r?.isLoopback){(0,f.Lq)("switch","rtc loopback detected (same machine) → drop ws standby");let t=e._adapters.get("ws");if(t){try{t.disconnect()}catch{}e._adapters.delete("ws")}}t&&e._maybeFireRejoin("rtc","rtc reconnect while ws ready")}t===n.Of.closed&&(e._rtcCallbacks.onFallback?.("ws"),(0,f.Lq)("switch","rtc closed → startWsFallback + scheduleRtcRestart"),e._startWsFallback(),clearTimeout(e._wsFallbackTimer),e._scheduleRtcRestart("rtc-closed"))}(this,t),"rtc"===e&&t===n.Of.open&&((0,p.c)("auth","[seal] rtc OPEN → sending proof"),(0,C.pV)(this)),this._recomputeType();let r=this._anyAdapterReady();r!==this._connected&&(this._connected=r,r||(this._onConnectFired=!1,(0,f.Lq)("switch",`onDisconnect FIRE (last carrier gone: ${e}→${t})`),this._wsCallbacks.onDisconnect?.(`${e}-${t}`))),(t===n.Of.open||t===n.Of.closed)&&this._flushBuffer(),this._intakeSeq?.setPaused(!r)}_maybeFireRejoin(e,t){let r="ws"===e?this._adapters.get("rtc"):this._adapters.get("ws");if(r?.ready){(0,p.c)("transport",`[pm] ${t} → skip rejoin (other ready)`),(0,f.Lq)("switch",`${t} → skip rejoin (other ready)`);return}if("ws"===e&&r&&r.state===n.Of.connecting){(0,p.c)("transport",`[pm] ${t} → debounce rejoin (rtc connecting)`),(0,f.Lq)("switch",`${t} → debounce rejoin ${n.ZN}ms (rtc connecting)`),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=setTimeout(()=>{this._rejoinDebounceTimer=null;let e=this._adapters.get("rtc");e?.ready?(0,f.Lq)("switch","debounce: rtc opened → skip rejoin"):((0,f.Lq)("switch",`debounce expired → FIRE rejoin (rtc=${e?.state||"absent"})`),this._bus.dispatch("connect",[]))},n.ZN);return}(0,f.Lq)("switch",`${t} → FIRE rejoin`),this._bus.dispatch("connect",[])}_recomputeType(){let e=this._pickAdapter(n.l_.binary)||this._pickAdapter(n.l_.control),t=e&&"rtc"===e.constructor.id?e.typeDetail||"dc-stun":"ws";t!==this._type&&(this._type=t,this._rtcCallbacks.onTransportChange?.(t))}_anyAdapterReady(){for(let e of this._adapters.values())if(e.ready)return!0;return!1}_pickAdapter(e){return function(e,t,r){let n=t.channels[r];if(!n)return null;let i=[...e.values()].filter(e=>e.supports(r)&&e.ready);return i.length?(i.sort((e,t)=>{let i=t.getPriority?t.getPriority(r):t.constructor.priority[r]??0,s=e.getPriority?e.getPriority(r):e.constructor.priority[r]??0;if(i!==s)return i-s;if(n.prefer){if(t.constructor.id===n.prefer)return 1;if(e.constructor.id===n.prefer)return -1}return 0}),i[0]||null):null}(this._adapters,this._profile,e)}_seqActive(){return!0===this._peerSeqCtl}_sendStreamEvent(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;V(this,e,t,r)}_sendControl(e,t){!function(e,t,r){var n,i,s,a;let l,o="function"==typeof r[r.length-1]?r.pop():null,c=o?(n=e,i=t,s=r,a=o,l=`c_${++n._ackSeq}`,n._pendingAcks.set(l,a),n._ackReqs?.set(l,{event:i,args:s,tries:0}),n._scheduleAckTimeout(l,{event:i,args:s,ackId:l}),l):null,d=e._outLog.append({event:t,args:r,ackId:c});if(c){let t=e._ackReqs?.get(c);t&&(t.sq=d.sq)}(0,p.c)("transport",`[pm] send control event=${t} sq=${d.sq}`),z(e)}(this,e,t)}_flushBuffer(){!function(e){let t=e._pickAdapter(n.l_.control);if(t)for(let r of(e._intakeSeq.setPaused(!1),e._outLog.replayList())){if(!J(e,t,r))return;e._outLog.markSent(r.sq)}}(this)}_dispatch(e,t,r){let n;n=e===W?t:"rtc"===r?Array.isArray(t?.args)?{...t,event:e}:{event:e,args:[t],ackId:null,sq:null,ep:null}:{event:e,args:[t],ackId:null},n?.event&&(Number.isInteger(n.rs)&&this._outLog.setApplied(n.rs),Number.isInteger(n.sq)&&!this._intakeSeq.armed&&this._peerSeqCtl&&this._intakeSeq.arm(),this._intakeSeq.push(n))}_onBinary(e){e&&("mobile"===e.channel?this._bus?.dispatch("mobile-bin",[e.buffer]):"file"===e.channel&&this._bus?.dispatch("file-bin",[e.buffer]))}_scheduleAckTimeout(e,t){var r;let i;r=this,i=setTimeout(()=>{r._ackTimers.delete(e),(0,p.c)("transport",`[pm] ack timeout ackId=${e} event=${t?.event} → suspect zombie RTC`);let i=r._pendingAcks.get(e),s=r._adapters.get("rtc"),a=r._adapters.get("ws");if(r._admitQueue?.includes(e))return;if(X.has(t?.event)){let l=r._srvCaps?.promptDedupe&&t.args?.[0]?.promptId;if(i&&a?.ready&&l){let s=r._ackReqs?.get(e);Number.isInteger(s?.sq)&&r._outLog.markAcked(s.sq),r._ackReqs?.delete(e),r._pendingAcks.delete(e),(0,f.Lq)("switch",`ack-timeout ${t.event} → retry via ws (slow ack)`),a.send(n.l_.control,{event:t.event,args:t.args,cb:i});return}(s?.ready||s?.state===n.Of.open)&&F(r,`ack-timeout:${t.event}`)}if(i&&t&&a?.ready&&Q.has(t.event)){if(r._pendingAcks.delete(e),a.send(n.l_.control,{event:t.event,args:t.args,cb:i}))return void(0,f.Lq)("switch",`ack-timeout ${t.event} → retry via ws (rtc zombie?)`);r._pendingAcks.set(e,i)}if(r._seqActive()&&i)return void(0,f.Lq)("switch",`ack-timeout ${t?.event} → keep pending (sequenced stream owns retry)`);let l=Date.now(),o=s?.lastInboundAt||0;s?.ready&&o&&l-o<n.mk?(0,f.Lq)("switch",`ack-timeout ${t?.event||"?"} ignored (rtc active, lastInbound=${l-o}ms ago)`):s?.state===n.Of.open?F(r,`ack-timeout:${t?.event||"?"}`):r._scheduleRtcRestart("ack-timeout")},r._ackTimeoutMs),r._ackTimers.set(e,i)}_armRestart(e,t){clearTimeout(this._rtcRestartTimer),this._rtcRestartDueAt=Date.now()+t,this._rtcRestartTimer=setTimeout(e,t)}_disarmRestart(){let e=this._rtcRestartTimer?Math.max(this._rtcRestartDueAt-Date.now(),0):-1;return clearTimeout(this._rtcRestartTimer),this._rtcRestartTimer=null,this._rtcRestartDueAt=0,e}_scheduleRtcRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";if((0,f.Lq)("switch",`rtcRestart REQ by=${e} attempts=${this._rtcRestartAttempts} probe=${this._probeAttempts} givenUp=${this._rtcGivenUp} pending=${!!this._rtcRestartTimer}`),this._rtcRestartTimer){let t=Math.max(this._rtcRestartDueAt-Date.now(),0);(0,f.Lq)("switch",`rtcRestart SKIP by=${e} (pending rung ${this._rtcRestartAttempts} fires in ${t}ms)`);return}if(this._rtcGivenUp){(0,f.Lq)("switch","scheduleRtcRestart skipped (hard NAT → WS-only)"),(0,p.c)("transport","[pm] rtc probe skipped (given up — hard NAT)");return}let t=function(e){let t,r,{attempts:i,probeAttempts:s,verdict:a}=e,l=i>=n.QZ.maxAttempts,o=s;if(l){if(t=n.QZ.probeBackoffMs[s]??n.QZ.probeBackoffMs.at(-1),(o=s+1)>=n.QZ.classifyAfterProbes){if("hard"===(r=a?.()??"unknown"))return{giveUp:!0,verdict:r,probeAttempts:o};o=0}}else t=n.QZ.backoffMs[i]??n.QZ.backoffMs.at(-1);return{delay:t,isProbe:l,attempts:i+1,probeAttempts:o,verdict:r}}({attempts:this._rtcRestartAttempts,probeAttempts:this._probeAttempts,verdict:()=>this._adapters.get("rtc")?.natVerdict?.()??"unknown"});if(void 0!==t.verdict&&((0,f.Lq)("switch",`scheduleRtcRestart natVerdict=${t.verdict} probeAttempts=${t.probeAttempts}`),(0,p.c)("transport",`[pm] rtc nat verdict=${t.verdict} after ${t.probeAttempts} probes`)),t.giveUp){this._probeAttempts=t.probeAttempts,this._rtcGivenUp=!0,this._giveUpIp=this._netFingerprint,this._giveUpIp||E().then(e=>{this._rtcGivenUp&&!this._giveUpIp&&(this._giveUpIp=e||U,(0,f.Lq)("switch",`give-up baseline from probe: ip=${this._giveUpIp}`))}).catch(()=>{}),(0,f.Lq)("switch",`RTC give-up: hard NAT → WS-only (ip=${this._giveUpIp||"pending"})`);return}let{delay:r,isProbe:i}=t;this._probeAttempts=t.probeAttempts,this._rtcRestartAttempts=t.attempts,(0,f.Lq)("switch",`rtcRestart ARM by=${e} rung=${this._rtcRestartAttempts} delay=${r}ms probe=${i}`),(0,p.c)("transport",`[pm] schedule rtc ${i?"probe":"restart"} #${this._rtcRestartAttempts} in ${r}ms`);let s=()=>{if(this._disarmRestart(),this._awaitingApproval||!this._sig?.ready)return;let e=this._adapters.get("rtc");if(e){let t=function(e){let{state:t,connectingSince:r,connectDeadline:i,now:s,connectTimeoutMs:a}=e;return t!==n.Of.connecting?"restart":s<N({connectingSince:r,connectDeadline:i,connectTimeoutMs:a})?"wait":"teardown"}({state:e.state,connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,now:Date.now(),connectTimeoutMs:n.AC});if("wait"===t){let t=Math.max(N({connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,connectTimeoutMs:n.AC})-Date.now(),r);(0,f.Lq)("switch",`restart tick: peer still young (rung ${this._rtcRestartAttempts}) → re-arm in ${t}ms, no rung spent`),this._armRestart(s,t);return}if("teardown"===t){try{e.disconnect(`rung-${this._rtcRestartAttempts}-teardown`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}}this._restartRtc(`rung-${this._rtcRestartAttempts}`)};this._armRestart(s,r)}_sendSignaling(e){et(this,e)}_flushSigBuffer(){er(this)}}},44964:(e,t,r)=>{r.d(t,{N:()=>i.N0,u:()=>o});var n=r(7620),i=r(81851);let s="9remote_api_keys",a=()=>{window.dispatchEvent(new Event(i.N0))};function l(e){try{return btoa(e)}catch{return e}}function o(){let e=(0,n.useCallback)(()=>{try{let e=localStorage.getItem(s);if(!e)return[];return JSON.parse(e).map(e=>({...e,key:function(e){try{return atob(e)}catch{return e}}(e.key)}))}catch(e){return console.error("Failed to load API keys:",e),[]}},[!0]),t=(0,n.useCallback)(function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(t&&1)try{let n=e(),i=n.findIndex(e=>e.key===t);if(-1!==i){let e=n.map((e,t)=>({...e,key:l(e.key),lastLoginDate:t===i?new Date().toISOString():e.lastLoginDate}));localStorage.setItem(s,JSON.stringify(e));return}let o={id:Date.now().toString(),key:l(t),label:r||`Key ${n.length+1}`,createdAt:new Date().toISOString(),lastLoginDate:new Date().toISOString()},c=[...n.map(e=>({...e,key:l(e.key)})),o];localStorage.setItem(s,JSON.stringify(c)),a()}catch(e){console.error("Failed to save API key:",e)}},[!0,e]),r=(0,n.useCallback)((t,r)=>{try{let n=e(),i=n.findIndex(e=>e.id===t),o=i+r;if(-1===i||o<0||o>=n.length)return;[n[i],n[o]]=[n[o],n[i]],localStorage.setItem(s,JSON.stringify(n.map(e=>({...e,key:l(e.key)})))),a()}catch(e){console.error("Failed to move API key:",e)}},[!0,e]),i=(0,n.useCallback)(t=>{try{let r=e().filter(e=>e.id!==t).map(e=>({...e,key:l(e.key)}));localStorage.setItem(s,JSON.stringify(r)),a()}catch(e){console.error("Failed to remove API key:",e)}},[!0,e]),o=(0,n.useCallback)(()=>{try{localStorage.removeItem(s)}catch(e){console.error("Failed to clear API keys:",e)}},[!0]),c=(0,n.useCallback)(()=>{try{let e=localStorage.getItem(s);if(!e)return!1;return JSON.parse(e).length>0}catch{return!1}},[!0]),d=(0,n.useCallback)((t,r)=>{try{let n=e().map(e=>({...e,key:l(e.key),label:e.id===t?r:e.label||""}));localStorage.setItem(s,JSON.stringify(n)),a()}catch(e){console.error("Failed to rename API key:",e)}},[!0,e]),u=(0,n.useCallback)(t=>{if(t&&1)try{let r=e().map(e=>({...e,key:l(e.key),lastLoginDate:e.key===t?new Date().toISOString():e.lastLoginDate}));localStorage.setItem(s,JSON.stringify(r))}catch(e){console.error("Failed to update last login date:",e)}},[!0,e]);return{saveKey:t,loadKeys:e,moveKey:r,removeKey:i,renameKey:d,clearKeys:o,hasStoredKeys:c,updateLastLogin:u}}},55285:(e,t,r)=>{r.d(t,{c:()=>i});var n=r(30068);function i(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];n.eR.debug?.[e]&&console.log(...r)}},56156:(e,t,r)=>{r.d(t,{A:()=>i});var n=r(54568);function i(e){let{children:t,variant:r="primary",size:i="md",disabled:s=!1,loading:a=!1,onClick:l,className:o="",...c}=e,d=`font-semibold rounded-brand transition-all duration-150 ease-out transform active:scale-[0.97] ${{primary:"bg-brand-500 hover:bg-brand-600 disabled:bg-surface-3 disabled:text-text-muted text-white shadow-sm",secondary:"bg-surface-2 hover:bg-surface-3 disabled:bg-surface disabled:text-text-muted text-text",danger:"bg-red-500 hover:bg-red-600 disabled:bg-surface-3 disabled:text-text-muted text-white",success:"bg-green-600 hover:bg-green-700 disabled:bg-surface-3 disabled:text-text-muted text-white"}[r]} ${{sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-base",lg:"px-6 py-3 text-lg"}[i]} ${s||a?"cursor-not-allowed":""} ${o}`;return(0,n.jsx)("button",{onClick:l,disabled:s||a,className:d,...c,children:a?(0,n.jsxs)("span",{className:"flex items-center justify-center gap-2",children:[(0,n.jsx)("span",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),t]}):t})}},59506:(e,t,r)=>{function n(e,t){if(e===t)return!0;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n of r)if(!(n in t)||e[n]!==t[n])return!1;return!0}function i(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function s(e,t){if(e===t)return!0;if(!e||!t)return!1;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let i of r)if(!(i in t)||!n(e[i],t[i]))return!1;return!0}r.d(t,{dI:()=>n,h3:()=>s,nk:()=>i})},67841:(e,t,r)=>{r.d(t,{H$:()=>a,d6:()=>s});var n=r(7620),i=r(79748);let s=(e,t)=>{if(e&&t)try{localStorage.setItem("9remote_nav:"+e,t)}catch{}};function a(e){let t=(0,i.usePathname)(),r=(0,i.useSearchParams)();(0,n.useEffect)(()=>{if(!e||!t?.startsWith("/workspace"))return;let n=function(e,t){if(!e)return"";let r=t?.toString();return r?`${e}?${r}`:e}(t,r);n&&s(e,n)},[e,t,r])}},68469:(e,t,r)=>{r.d(t,{O:()=>u,Y:()=>c});let n=new Uint8Array([48,42,48,5,6,3,43,101,110,3,33,0]);function i(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function s(e){let t="",r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}function a(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];let n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),i=0;for(let e of t)n.set(e,i),i+=e.length;return n}async function l(e){let t;try{t=i(String(e))}catch{return null}if(32!==t.length)return null;try{return await crypto.subtle.importKey("spki",a(n,t),{name:"X25519"},!0,[])}catch{return null}}async function o(e,t,r,n){let i=await crypto.subtle.deriveBits({name:"X25519",public:t},e,256),s=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a(r,n),info:new TextEncoder().encode("9remote-tail-seal-v1")},s,{name:"AES-GCM",length:256},!1,["encrypt"])}async function c(e,t){if("string"!=typeof e||!e||"string"!=typeof t||!t)return null;let r=await l(t);if(!r)return null;try{let t=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),n=new Uint8Array(await crypto.subtle.exportKey("spki",t.publicKey)).slice(-32),i=new Uint8Array(await crypto.subtle.exportKey("spki",r)).slice(-32),a=await o(t.privateKey,r,n,i),l=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:l},a,new TextEncoder().encode(e));return{epk:s(n),iv:s(l),ct:s(c)}}catch{return null}}let d="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function u(e,t){if("u"<typeof crypto||!crypto.subtle)return null;let r=[e,t].map(e=>{let t;try{t=i(String(e||""))}catch{t=new Uint8Array(0)}let r=new Uint8Array(2);return new DataView(r.buffer).setUint16(0,t.length),a(r,t)}),n=new Uint8Array(await crypto.subtle.digest("SHA-256",a(...r)));return d[n[0]%32]+d[n[1]%32]}},69469:(e,t,r)=>{function n(e){return"string"==typeof e&&!!e&&/^sk-[a-z0-9]{8}-[a-z0-9]{4}-[0-9a-f]{6}$/.test(e.trim().toLowerCase())}function i(e){if("string"!=typeof e||!/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(e))return e||null;let t=e.split("-");return`${t[0]}-${t[1]}-${t[2]}`}function s(e){return"string"==typeof e&&/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(e)?e.split("-")[3]:null}r.d(t,{Cj:()=>s,PF:()=>n,Uo:()=>i})},70658:(e,t,r)=>{r.d(t,{As:()=>m,zg:()=>u});var n=r(7620),i=r(79748),s=r(30562),a=r(69469),l=r(99022),o=r(96631),c=r(189);let d="wrong-key-tail";async function u(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.qn;try{let t=new AbortController,n=setTimeout(()=>t.abort(),r),i=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(n),i.ok}catch{return!1}}async function h(e,t){let{tail:r,tempKey:n}=t,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.qn;try{let t=new AbortController,s=setTimeout(()=>t.abort(),i),a=await fetch(`${e}/api/verify-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tail:r||null,tempKey:n||null}),signal:t.signal});if(clearTimeout(s),!a.ok)return null;return(await a.json())?.ok===!0}catch{return null}}async function p(){return(0,o._r)()?(0,o.rh)(await f()):(0,o.Yr)()?window.location.origin:null}async function f(){try{let e=await fetch(s.TR);return e.ok?await e.json():null}catch{return null}}function m(){let[e,t]=(0,n.useState)(!1),[r,o]=(0,n.useState)(""),u=(0,i.useRouter)(),{setAuth:m}=(0,c.Fo)(),g=(0,n.useCallback)(async function(e){let{persistSession:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t(!0),o("");try{let t,n=await p();if(n){let t=e.tail||(0,a.Cj)(e.apiKey||""),i=e.tempKey||(e.token?.length<=8?e.token:null),s=await f(),c=(0,a.Uo)(s?.permanentKey||""),u=(0,a.Uo)(e.apiKey||e.token||""),p=String(s?.oneTimeKey||"").slice(0,6).toUpperCase(),g=i?!!p&&p===i.toUpperCase():!!c&&!!u&&(0,a.Uo)(c)===u;try{let s=g?await h(n,{tail:t,tempKey:i}):null;if(!0===s){let s=e.apiKey||i||"",o=(0,a.Uo)(s)||"direct";return t&&(0,l.LG)(o,{tail:t}),r&&m({apiKey:o,tunnelUrl:n,mode:"local",tempKey:i?i.toUpperCase():null,localIp:null}),{success:!0,shouldAskToSave:!0,apiKey:o}}if(!1===s)return o(d),{success:!1,wrongTail:!0}}catch{}}let i=new AbortController,c=setTimeout(()=>i.abort(),s.cC);try{t=await fetch(s.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:(0,a.Uo)(e.apiKey)}),signal:i.signal})}catch(e){throw Error(e?.name==="AbortError"?"Connection timed out. Please try again.":"Network error. Please try again.")}finally{clearTimeout(c)}if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error||"Authentication failed")}let u=await t.json(),g=(0,a.Uo)(e.apiKey||u.apiKey);u.hostKeys?.x&&(0,l.LG)(g,{hostSealKey:u.hostKeys.x,hostPubKey:u.hostKeys.ed||null});let y=e.tail||(0,a.Cj)(e.apiKey||"");if(u.tunnelUrl&&(y||e.tempKey)){let t=await h(u.tunnelUrl,{tail:y,tempKey:e.tempKey||null});if(!1===t)return o(d),{success:!1,wrongTail:!0}}return r&&m({apiKey:g,tunnelUrl:u.tunnelUrl||null,mode:"remote",tempKey:e.tempKey?e.tempKey.toUpperCase():null,localIp:u.localIp||null}),{success:!0,shouldAskToSave:!0,apiKey:g}}catch(e){return o(e.message),{success:!1,error:e.message}}finally{t(!1)}},[u,m]);return{loading:e,error:r,setError:o,authenticateWithToken:(0,n.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0;return t?g({token:e,tempKey:e,tail:r},n):g({token:e},n)},[g]),authenticateWithApiKey:(0,n.useCallback)((e,t)=>g({apiKey:e},t),[g])}}},72627:(e,t,r)=>{r.d(t,{AD:()=>n,Jc:()=>o,Mt:()=>a,g4:()=>l,gk:()=>s,xs:()=>i});let n="__ungrouped__",i=e=>e?.workspaceId??e?.groupId??null;function s(e){let{sessions:t,openedSessions:r,livePanes:s,mountedWorkspaces:a,activeWorkspaceId:l,isDesktop:o}=e,c=new Set(t.filter(e=>i(e)===(l??null)).map(e=>e.id)),d=r.filter(e=>c.has(e)),u=new Set([...d,...s.filter(e=>r.includes(e))]),h=r.filter(e=>u.has(e)),p=new Map(t.map(e=>[e.id,i(e)])),f=new Set(r.filter(e=>!!c.has(e)||!!o&&!!a[p.get(e)??n])),m=new Map(d.map((e,t)=>[e,t]));return{workspaceSessionIds:c,workspaceOpenedSessions:d,renderedSessions:h,mountedSet:f,workspaceIndex:m}}let a=(e,t,r)=>!t&&r.has(e)?120*r.get(e):0;function l(e){let{container:t,pane:r}=e;if(!t||!r||r.offsetWidth<=0)return null;let n=r.getBoundingClientRect().left-t.getBoundingClientRect().left;return Math.max(0,Math.min(t.scrollLeft+n-(t.clientWidth-r.offsetWidth)/2,t.scrollWidth-t.clientWidth))}function o(e){let{rowWidth:t,paneCount:r,sidebarWidth:n,sidePx:i,gapPx:s,paddingPx:a,minWidth:l}=e;return!(t>0)||r<=0?null:Math.max(l,Math.floor((t-n-a-i-(r-1)*s)/r))}},75677:(e,t,r)=>{r.d(t,{o:()=>n});function n(e){if(!e)return"";if(e.length<=14)return e;let t=e.substring(0,8),r=e.substring(e.length-6),n="•".repeat(12);return`${t}${n}${r}`}},81353:(e,t,r)=>{r.d(t,{Nw:()=>x,eJ:()=>S,d:()=>T,rh:()=>A});var n=r(94245),i=r(23635),s=r(89228),a=r(42126),l=r(30068),o=r(69469),c=r(99022);let d="9remote_fleet_connected";function u(){try{return JSON.parse(localStorage.getItem(d)||"[]")}catch{return[]}}class h{constructor({hostOf:e,patch:t,bindBus:r,ready:n,probeTargets:i,servedBy:s=null,servedBus:a=null}){this._hostOf=e,this._patch=t,this._bindBus=r,this._ready=n,this._probeTargets=i,this._servedBy=s||(()=>!1),this._servedBus=a||(()=>null),this.buses=new Map,this._connectTimers=new Map,this.pending=new Map,this._probeTimer=null,this._probeVisible=null}busOf(e){return e&&this.buses.get(e)?.busRef?.current||null}pmOf(e){return this.buses.get(e)||null}has(e){return this.buses.has(e)}whenReady(e,t){let r=this._hostOf(e);if(!e||!r)return;if(this._servedBy(e)){let r=this._servedBus(e);r&&t(r);return}let n=this.busOf(e);if(n&&"online"===r.status)return void t(n);if(!this._canOpen(r,e))return;this.open(e,r);let i=this.pending.get(e)||[];i.push(t),this.pending.set(e,i)}persistIntent(e,t){if(e)try{let r=new Set(u());t?r.add(e):r.delete(e),localStorage.setItem(d,JSON.stringify([...r]))}catch{}}_canOpen(e,t){return!(!e||this._servedBy(t))&&!!e.full}open(e,t){if(this.has(e))return;let r=function(){try{return localStorage.getItem("9remote_deviceId")}catch{return null}}();if(!this._canOpen(t,e)||!r)return;this.persistIntent(e,!0);let n=(0,o.Cj)(t.full);n&&(0,c.LG)(e,{tail:n});let i=t=>this._patch(e,t),s=!1,d=new a.g({tunnelUrl:null,localIp:null,namespace:"",socketOptions:{auth:{apiKey:e,tempKey:null,deviceId:r}},apiKey:e,deviceId:r,tempKey:null,onConnect:t=>{clearTimeout(this._connectTimers.get(e)),this._connectTimers.delete(e),i({status:"online",lastSeenAt:Date.now(),updating:!1,approval:null});let r=this.pending.get(e);if(r)for(let n of(this.pending.delete(e),r))try{n(t)}catch{}s||(s=!0,this._bindBus(t,e)),this._ready(t,e)},onDisconnect:()=>{this.pending.delete(e),i({status:"offline",lastSeenAt:Date.now()})}},{enableWebRTC:l.eR.enableWebRTC,enableTurn:l.eR.enableTurn,apiKey:e,onTransportChange:e=>i({carrier:e||"ws"})});this.buses.set(e,d),i({status:"connecting"}),this._connectTimers.set(e,setTimeout(()=>this._onConnectTimeout(e),15e3)),d.connect()}_onConnectTimeout(e){this._connectTimers.delete(e),this.buses.has(e)&&this._hostOf(e)?.status==="connecting"&&(this._patch(e,{status:"offline"}),this._hostOf(e)?.approval!=="pending"&&this.persistIntent(e,!1))}drop(e){let t=this.buses.get(e);t&&(t.disconnect(),this.buses.delete(e)),clearTimeout(this._connectTimers.get(e)),this._connectTimers.delete(e),this.pending.delete(e)}retry(e){this.drop(e),this.open(e,this._hostOf(e))}closeAll(){for(let e of this.buses.values())e.disconnect();for(let e of(this.buses.clear(),this._connectTimers.values()))clearTimeout(e);this._connectTimers.clear(),this.pending.clear(),this.disarmProbe()}armProbe(){this._probeTimer||(this._probeTimer=setInterval(()=>{document.hidden||this.probeOnce()},6e4),this._probeVisible=()=>{"visible"===document.visibilityState&&this.probeOnce()},document.addEventListener("visibilitychange",this._probeVisible))}disarmProbe(){this._probeTimer&&(clearInterval(this._probeTimer),this._probeTimer=null,document.removeEventListener("visibilitychange",this._probeVisible),this._probeVisible=null)}probeOnce(){let e=this._probeTargets().filter(e=>!this.has(e));e.length&&fetch("/api/host-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({heads:e})}).then(e=>e.ok?e.json():null).then(t=>{for(let r of e){if(this.has(r))continue;let e=t?.hosts?.[r];e&&this._patch(r,{status:e.online?"online":"offline"})}}).catch(()=>{})}}var p=r(18753),f=r(59506),m=r(6134);let g="9remote_fleet_cache",y=null;function _(e){clearTimeout(y),y=setTimeout(()=>{y=null;let t={};for(let[r,n]of Object.entries(e().hosts))t[r]={label:n.label,platform:n.platform,version:n.version,sessions:n.sessions,workspaces:n.workspaces,statusMap:n.statusMap,lastSeenAt:n.lastSeenAt};try{localStorage.setItem(g,JSON.stringify(t))}catch{}},1e3)}let b=e=>({key:e,full:null,label:"",status:"offline",carrier:"ws",sessions:[],workspaces:[],statusMap:{},tasksBySession:{},platform:null,version:null,lastSeenAt:null,updateAvailable:null,canSelfUpdate:!1,updating:!1,approval:null,remoteAvailable:!1,remoteStatus:null,mobileAvailable:!1,isCodespaces:!1,mobileDeviceCount:0}),w=(e,t)=>A.getState()._patchHost(e,t),k=(e,t)=>{e?.emit("getSessions",e=>{Array.isArray(e)&&w(t,{sessions:e})}),e?.emit("getWorkspaces",e=>{Array.isArray(e)&&w(t,{workspaces:e})}),e?.emit("getStatusState"),e?.emit("getSessionTasks",e=>A.getState().applySessionTasksState(t,e))},v=null,A=(0,n.v)((e,t)=>({hosts:{},currentKey:null,sync(r,n){let i=n||"",s=new Map;for(let e of r){let t=(0,o.Uo)(e.key);t&&!s.has(t)&&s.set(t,{full:e.key,label:e.label||""})}i&&!s.has(i)&&s.set(i,{full:null,label:""});let a=[...s.keys()].filter(e=>e!==i).slice(0,8),l=new Set(a);for(let e of[...v.buses.keys()])l.has(e)||v.drop(e);let c=function(){try{return JSON.parse(localStorage.getItem(g)||"{}")}catch{return{}}}(),d=new Set(u()),h=!1;try{h="1"===sessionStorage.getItem("9remote_manual_disconnect")}catch{}for(let r of(e(e=>{let t={};for(let[r,n]of s){let s=e.hosts[r]||{...b(r),...c[r]||{}};t[r]={...s,key:r,full:n.full,label:n.label||s.label,status:r===i?h?"offline":"full":l.has(r)&&("online"===s.status||"connecting"===s.status)?s.status:"offline"}}return{hosts:t,currentKey:i}}),a))d.has(r)&&v.open(r,t().hosts[r]);v.probeOnce(),v.armProbe()},_patchHost(r,n){e(e=>{let t=e.hosts[r];return t?{hosts:{...e.hosts,[r]:{...t,...n}}}:e}),_(t)},applyStatusState(r,n){let i=n||{};e(e=>{let t=e.hosts[r];return!t||(0,f.h3)(t.statusMap,i)?e:{hosts:{...e.hosts,[r]:{...t,statusMap:i}}}}),_(t)},applyStatusChange(r){let{sessionId:n,state:i,tool:s,since:a,conversationId:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n&&(e(e=>{let t=e.hosts[r];if(!t)return e;let o=t.statusMap[n],c={state:i,tool:void 0!==s?s:o?.tool,since:a,...l||o?.conversationId?{conversationId:l||o?.conversationId}:{}};return(0,f.dI)(o,c)?e:{hosts:{...e.hosts,[r]:{...t,statusMap:{...t.statusMap,[n]:c}}}}}),_(t))},applyStatusCleared(r,n){n&&(e(e=>{let t=e.hosts[r],i=t?.statusMap?.[n];return i?{hosts:{...e.hosts,[r]:{...t,statusMap:{...t.statusMap,[n]:{...i,state:"idle"}}}}}:e}),_(t))},applySessionTasks(t){let{sessionId:r,records:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r&&e(e=>{let i=e.hosts[t];if(!i)return e;let s={...i.tasksBySession||{}};return Array.isArray(n)&&n.length?s[r]=n:delete s[r],{hosts:{...e.hosts,[t]:{...i,tasksBySession:s}}}})},applySessionTasksState(t,r){e(e=>{let n=e.hosts[t];if(!n)return e;let i={};for(let[e,t]of Object.entries(r||{}))Array.isArray(t)&&t.length&&(i[e]=t);return{hosts:{...e.hosts,[t]:{...n,tasksBySession:i}}}})},_closeHost(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};v.drop(e),t()._patchHost(e,{status:"offline",lastSeenAt:Date.now(),approval:null,...r})},ensureHost(e){e===t().currentKey||v.has(e)||v.open(e,t().hosts[e])},connectHost(e){t().retryHost(e)},requestHostUpdate(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"update",n=t().hosts[e];if(!n||n.updating)return;let i={updating:!0,updateAvailable:null};if("full"===n.status){let n=s.d.getState(),a=n.busRef?.current;if(!a?.connected)return void(0,m.Lq)("update",`request ${r} on ACTIVE ${e} dropped: bus not connected`);t()._patchHost(e,i),n.protocolRef?.current?.setUpdating?.(!0),a.emit("restart"===r?"requestRestart":"requestUpdate")}else t()._patchHost(e,i),v.pmOf(e)?.setUpdating?.(!0),v.whenReady(e,t=>{v.pmOf(e)?.setUpdating?.(!0),(0,m.Lq)("update",`request ${r} sent on fleet bus ${e}`),t.emit("restart"===r?"requestRestart":"requestUpdate")});setTimeout(()=>{t().hosts[e]?.updating&&t()._patchHost(e,{updating:!1})},12e4)},setAutoConnect(e,t){v.persistIntent(e,t)},retryHost(e){v.retry(e)},disconnectHost(e){v.persistIntent(e,!1),t()._closeHost(e)},closeAll(){v.closeAll()}}));function S(e){return v?.busOf(e)||null}function T(e){return v?.pmOf(e)||null}function x(e,t){v?.whenReady(e,t)}v=new h({hostOf:e=>A.getState().hosts[e],patch:w,bindBus:(e,t)=>{e.on("connect",()=>{e.emit("device:clientReady"),k(e,t)}),e.on("serverInfo",e=>{let r=!!A.getState().hosts[t]?.updating;w(t,{platform:e?.platform||null,isCodespaces:!!e?.isCodespaces,version:e?.version||null,updateAvailable:!r&&(0,p.U)(e?.updateAvailable?.version,e?.version)?e.updateAvailable:null,canSelfUpdate:!!e?.canSelfUpdate,remoteAvailable:!!e?.remoteAvailable,remoteStatus:e?.remoteStatus||null,mobileAvailable:!!e?.mobileAvailable})}),e.on("statusState",e=>A.getState().applyStatusState(t,e)),e.on("statusChange",e=>A.getState().applyStatusChange(t,e)),e.on("statusCleared",e=>A.getState().applyStatusCleared(t,e)),e.on("sessionTasks",e=>A.getState().applySessionTasks(t,e)),e.on("sessionsChanged",()=>k(e,t)),e.on("workspacesChanged",()=>k(e,t)),e.on("session-renamed",()=>k(e,t)),e.on("sessionClosed",r=>{r&&i.B.getState().closeSession(r),k(e,t)}),e.on("device:pendingApproval",()=>w(t,{approval:"pending"})),e.on("device:approved",()=>w(t,{approval:null})),e.on("device:rejected",()=>A.getState()._closeHost(t,{approval:"rejected"})),e.on("device:tailRejected",()=>A.getState()._closeHost(t))},ready:(e,t)=>{e.emit("device:clientReady"),k(e,t)},probeTargets:()=>{let e=A.getState(),t=new Set(u());return Object.values(e.hosts).filter(r=>r.key!==e.currentKey&&t.has(r.key)).map(e=>e.key)},servedBy:e=>!!e&&e===A.getState().currentKey,servedBus:()=>{let e=s.d.getState();return e.connected?e.busRef?.current||e.bus:null}})},81851:(e,t,r)=>{r.d(t,{AC:()=>f,An:()=>d,BF:()=>y,El:()=>T,HE:()=>O,HJ:()=>m,Ic:()=>I,J2:()=>A,Jd:()=>R,KF:()=>c,KP:()=>D,ML:()=>v,N0:()=>C,Of:()=>q,QS:()=>g,QZ:()=>s,Rh:()=>$,Tr:()=>b,UT:()=>_,ZN:()=>l,aS:()=>x,b4:()=>p,bg:()=>k,cx:()=>a,dE:()=>M,dT:()=>i,fP:()=>h,gI:()=>w,j3:()=>E,l_:()=>n,mH:()=>L,mk:()=>u,o_:()=>P,qM:()=>S,si:()=>o});let n={control:"control",binary:"binary",file:"file",mobile:"mobile",browser:"browser"},i=65536,s={ackTimeoutMs:5e3,maxAttempts:3,backoffMs:[500,1500,3e3],probeBackoffMs:[3e4,6e4,12e4,3e5],classifyAfterProbes:3},a={urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302"],timeoutMs:2500,minIntervalMs:15e3},l=500,o=3,c=3e3,d=9e3,u=25e3,h=3,p=1e3,f=4e3,m=15e3,g=1e3,y=12e3,_=2e3,b=1e4,w={enabled:!0,pingMs:25e3},k={pending:"pending-approval",rejected:"device-rejected"},v={mismatch:"mismatch",sealUnreadable:"seal-unreadable",timeout:"proof-timeout"},A={pending:"pending",approved:"approved",rejected:"rejected",reconnect:"reconnect"},S=8,T="9remote_pending_save",x="9remote_wants_save",C="9remote:keys-changed",R="9remote_login_error",I="strict",P={debounceMs:500},$=3e4,D=15e3,M="not-admitted",L={admitRetryMax:2,admitKickMinMs:3e3,ringMaxBytes:4194304,maxEntries:2e3,holdMax:256,gapDeadlineMs:3e3,ackMaxLives:3},O={chunkSize:65528,windowSize:64,dcBufferThreshold:8388608,maxUploadSize:0x3200000,maxDownloadSize:0xc800000,maxStreamMediaSize:524288e3},q={idle:"idle",connecting:"connecting",open:"open",degraded:"degraded",closed:"closed"},E={clientApp:{enabled:["ws","rtc"],parallel:!0,channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"},file:{strategy:"priority",prefer:"rtc"},mobile:{strategy:"priority",prefer:"rtc"},browser:{strategy:"priority",prefer:"rtc"}},rtc:{enableTurn:!0,dcControl:{ordered:!0}}},remoteDesktop:{enabled:["ws","rtc"],parallel:!0,channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"},file:{strategy:"priority",prefer:"rtc"},mobile:{strategy:"priority",prefer:"rtc"},browser:{strategy:"priority",prefer:"rtc"}},rtc:{enableTurn:!0,dcControl:{ordered:!0}}}}},89228:(e,t,r)=>{r.d(t,{d:()=>s});var n=r(94245),i=r(81851);let s=(0,n.v)(e=>({bus:null,busRef:{current:null},protocolRef:{current:null},connected:!1,everConnected:!1,deliberate:!1,connectionMode:"tunnel",carrier:"ws",approvalStatus:null,admitted:!1,authKey:null,endpoint:null,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1},hostOffline:!1,setConnection:t=>e(e=>({...e,...t})),setConnected:t=>e({connected:t}),setCarrier:t=>e({carrier:t}),setConnectionMode:t=>e({connectionMode:t}),setRetryStatus:t=>e({retryStatus:t}),setHostOffline:t=>e({hostOffline:t}),setAuthKey:t=>e({authKey:t}),setAdmitted:t=>e({admitted:t}),applyApproval:t=>e(e=>{let r=e.approvalStatus;return t===i.J2.reconnect?r===i.J2.approved?{approvalStatus:null}:{}:r===i.J2.approved&&t===i.J2.pending?{}:{approvalStatus:t}}),reset:()=>e({bus:null,connected:!1,deliberate:!1,everConnected:!1,connectionMode:"tunnel",carrier:"ws",endpoint:null,approvalStatus:null,admitted:!1,hostOffline:!1,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1}})}))},92571:(e,t,r)=>{r.d(t,{$b:()=>b,A0:()=>Z,AE:()=>g,Ax:()=>P,Dk:()=>R,Ez:()=>M,GW:()=>W,HF:()=>K,Jl:()=>F,Kr:()=>V,L0:()=>et,L8:()=>y,LN:()=>U,Qw:()=>L,RV:()=>function e(t){let r;if(!t||"object"!=typeof t)return t;if(Array.isArray(t)){let r=!1,n=t.map(t=>{let n=e(t);return n!==t&&(r=!0),n});return r?n:t}for(let s of Object.keys(t)){let a=t[s];if(i.has(s)&&"string"==typeof a&&a.includes("\\"))(r||={...t})[s]=n(a);else if(a&&"object"==typeof a){let n=e(a);n!==a&&((r||={...t})[s]=n)}}return r||t},Tf:()=>H,W5:()=>er,YO:()=>k,ZH:()=>_,_C:()=>N,aB:()=>z,bd:()=>ee,cv:()=>j,d5:()=>G,gh:()=>x,hh:()=>O,iB:()=>w,kS:()=>B,kb:()=>n,mv:()=>T,n2:()=>$,pA:()=>I,qu:()=>D,rL:()=>X,so:()=>v,u:()=>m,vb:()=>J,vd:()=>q,vs:()=>A,xW:()=>S,xl:()=>Q,xr:()=>Y,zT:()=>E});let n=e=>"string"==typeof e?e.replace(/\\/g,"/"):e,i=new Set(["path","currentPath","parentPath","dirPath","filePath","repoPath","oldPath","newPath","fullPath","relativePath"]),s=[".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".avif",".apng",".tif",".tiff",".heic",".heif"],a=[".mp4",".m4v",".webm",".ogv",".mov",".mkv",".avi",".3gp"],l=[".mp3",".wav",".ogg",".oga",".flac",".m4a",".aac",".opus"],o=[".pdf"],c=[".docx"],d=[".xlsx",".xls",".csv",".tsv"],u=[".html",".htm",".xhtml"],h=[".mmd",".mermaid"],p=[".md",".markdown",".mdx"];function f(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(e=>r.endsWith(e))}let m=e=>f(e,s),g=e=>f(e,a),y=e=>f(e,l),_=e=>f(e,o),b=e=>f(e,c),w=e=>f(e,d);function k(e){return e?f(e,u)?"html":f(e,p)?"markdown":f(e,h)?"mermaid":null:null}let v={".js":"javascript",".jsx":"javascript",".ts":"javascript",".tsx":"javascript",".mjs":"javascript",".cjs":"javascript",".html":"html",".htm":"html",".xhtml":"html",".css":"css",".scss":"css",".sass":"css",".less":"css",".styl":"css",".json":"json",".json5":"json",".jsonc":"json",".md":"markdown",".markdown":"markdown",".mdx":"markdown",".py":"python",".pyw":"python",".rb":"ruby",".php":"php",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".scala":"scala",".clj":"clojure",".cljs":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".ml":"ocaml",".mli":"ocaml",".jl":"julia",".pl":"perl",".pm":"perl",".tcl":"tcl",".lua":"lua",".r":"r",".dart":"dart",".groovy":"groovy",".gradle":"groovy",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".m":"objectivec",".sh":"shell",".bash":"shell",".zsh":"shell",".fish":"shell",".ps1":"powershell",".bat":"batch",".cmd":"batch",".yml":"yaml",".yaml":"yaml",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini",".properties":"ini",".xml":"xml",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".vue":"vue",".svelte":"svelte",".csv":"csv",".tsv":"csv",".log":"log",".diff":"diff",".patch":"diff",".dockerfile":"dockerfile",".makefile":"makefile",".mk":"makefile",".env":"env",".gitignore":"gitignore"},A={M:"text-git-modified",A:"text-git-added",D:"text-git-deleted","?":"text-git-untracked",U:"text-git-modified"},S={normal:{indentBase:12,indentStep:12,icon:16,chevron:14,text:"text-[15px] sm:text-sm",padY:"py-1 sm:py-0.5"},compact:{indentBase:8,indentStep:8,icon:14,chevron:12,text:"text-[13px] sm:text-[12px]",padY:"py-0.5 sm:py-[1px]"}},T=e=>e?"folder-changed"===e?22:32:4,x=768,C="git-diff:",R=(e,t)=>`${C}${e}:${t}`,I=e=>"string"==typeof e&&e.startsWith(C),P=e=>{let t=e.slice(C.length),r=t.indexOf(":");return{status:t.slice(0,r),absPath:t.slice(r+1)}},$=(e,t,r)=>`${C}${e}:${t}\u0000${r}`,D=e=>{let{status:t,absPath:r}=P(e),n=r.indexOf("\0");return -1===n?{status:t,repoPath:null,filePath:r}:{status:t,repoPath:r.slice(0,n),filePath:r.slice(n+1)}},M=(e,t)=>{let{repoPath:r,filePath:n}=D(e);return r?`${r.replace(/\/$/,"")}/${n}`:n.startsWith("/")?n:`${t?.replace(/\/$/,"")||""}/${n}`},L=18,O=12,q=40,E=48,U=30,B=10,N=70,j=20,F={MAX_DIRS:40,DEBOUNCE_MS:300,PREVIEW_DEBOUNCE_MS:1e3,IDLE_UNWATCH_MS:6e4},W="fileExplorer:gitRefresh",K=300,H=200,z=500,J=["fileExplorer:fileSaved","fileExplorer:fileCreated","fileExplorer:fileDeleted","fileExplorer:fileRenamed",W],G={sidebarWidth:"fileExplorer.sidebarWidth",sidebarVisible:"fileExplorer.sidebarVisible",bottomPanelVisible:"fileExplorer.bottomPanelVisible",bottomPanelHeight:"fileExplorer.bottomPanelHeight",activityPanel:"fileExplorer.activityPanel",recentFiles:"fileExplorer.recentFiles",openTabs:"fileExplorer.openTabs",editorFontSize:"fileExplorer.editorFontSize",wordWrap:"fileExplorer.wordWrap",expandedFolders:"fileExplorer.expandedFolders",showHidden:"fileExplorer.showHidden"},V={explorer:"explorer",search:"search",scm:"scm",settings:"settings"},Z=14,Q=4,X=9,Y=10,ee=28,et=5,er=4194304},92673:(e,t,r)=>{r.d(t,{Gf:()=>c,Gi:()=>p,Hu:()=>o,Nn:()=>u,O8:()=>s,cu:()=>d,el:()=>a,ij:()=>h,l7:()=>l,no:()=>f,pe:()=>n,rl:()=>i,xO:()=>m});let n="https://api.github.com",i="https://github.com/decolua/9remote",s=`${n}/repos/decolua/9remote`,a=`${s}/releases?per_page=100`,l=!1,o=".devcontainer/devcontainer.json",c="NREMOTE_API_KEY",d={name:"9Remote",image:"mcr.microsoft.com/devcontainers/universal:latest",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"nohup 9remote start > /tmp/9remote.log 2>&1 &",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"silent",visibility:"public"}}},u=3e3,h=60,p={available:"Available",starting:"Starting",shutdown:"Shutdown",unknown:"Unknown"},f={user:"/user",codespaces:"/user/codespaces",codespaceByName:e=>`/user/codespaces/${e}`,startCodespace:e=>`/user/codespaces/${e}/start`,userReposList:"/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator",repoContents:(e,t,r)=>`/repos/${e}/${t}/contents/${r}`,createCodespaceForRepo:(e,t)=>`/repos/${e}/${t}/codespaces`,codespaceSecretsPublicKey:"/user/codespaces/secrets/public-key",codespaceSecret:e=>`/user/codespaces/secrets/${e}`,codespaceSecretRepos:(e,t)=>`/user/codespaces/secrets/${e}/repositories/${t}`};function m(e){return`https://${e}-2208.app.github.dev`}},96605:(e,t,r)=>{r.d(t,{$o:()=>eU.A,AX:()=>e_.A,Ay:()=>to,BK:()=>e4.A,BZ:()=>X.A,Bm:()=>F.A,Cp:()=>z.A,Do:()=>l.A,F1:()=>o.A,FE:()=>e1.A,FW:()=>eq.A,Fc:()=>eO.A,GD:()=>O.A,GO:()=>em.A,Gr:()=>P.A,Gv:()=>ew.A,Hx:()=>es.A,Ir:()=>d.A,J4:()=>e0.A,JG:()=>g.A,JU:()=>W.A,Jl:()=>f.A,Kq:()=>ta.A,LM:()=>ec.A,Lt:()=>x.A,M6:()=>eY.A,MA:()=>c.A,Mr:()=>eE.A,P6:()=>et.A,QR:()=>T.A,Qp:()=>a.A,RI:()=>i.A,TB:()=>e6.A,Ud:()=>V.A,VA:()=>ey.A,Vn:()=>ez.A,W1:()=>ef.A,WE:()=>b.A,We:()=>e5.A,Wn:()=>S.A,X:()=>ts.A,X_:()=>D.A,ZH:()=>L.A,ZU:()=>e9.A,Ze:()=>eM.A,Zr:()=>K.A,_O:()=>te.A,_V:()=>ee.A,a4:()=>eb.A,aJ:()=>p.A,ak:()=>Z.A,bE:()=>e7.A,bd:()=>e3.A,cC:()=>u.A,c_:()=>y.A,dJ:()=>N.A,de:()=>ti.A,dx:()=>H.A,e6:()=>eS.A,e9:()=>eN.A,eM:()=>eW.A,ek:()=>eZ.A,es:()=>eA.A,f2:()=>G.A,f5:()=>I.A,gH:()=>eP.A,h1:()=>eh.A,iU:()=>U.A,jG:()=>eL.A,jj:()=>eg.A,jl:()=>w.A,jz:()=>eC.A,kU:()=>$.A,kV:()=>er.A,kr:()=>eo.A,kt:()=>eF.A,lM:()=>e8.A,lP:()=>ev.A,m0:()=>k.A,mN:()=>Q.A,nU:()=>eu.A,qz:()=>J.A,rX:()=>_.A,s3:()=>en.A,sU:()=>eX.A,sv:()=>B.A,ue:()=>eT.A,vR:()=>eI.A,vW:()=>eB.A,vd:()=>j.A,vj:()=>eH.A,vv:()=>ea.A,wB:()=>eG.A,wO:()=>eQ.A,ww:()=>Y.A,xq:()=>ep.A,xv:()=>eR.A,y8:()=>el.A,yQ:()=>m.A,yU:()=>eD.A,yd:()=>s.A,zP:()=>h.A,zW:()=>tt.A});var n=r(54568),i=r(14796),s=r(50683),a=r(30307),l=r(62826),o=r(22061),c=r(46480),d=r(77542),u=r(30824),h=r(8631),p=r(34309),f=r(63322),m=r(34041),g=r(8008),y=r(76265),_=r(17156),b=r(11964),w=r(21411),k=r(1173),v=r(72980),A=r(9901),S=r(3129),T=r(59706),x=r(31381),C=r(40414),R=r(91276),I=r(2099),P=r(26083),$=r(20732),D=r(69724),M=r(93675),L=r(96249),O=r(36293),q=r(16556),E=r(14264),U=r(2939),B=r(74206),N=r(52947),j=r(26463),F=r(45894),W=r(72030),K=r(58588),H=r(10280),z=r(57460),J=r(97380),G=r(80172),V=r(7086),Z=r(83667),Q=r(73012),X=r(19773),Y=r(64529),ee=r(31260),et=r(46396),er=r(86163),en=r(45258),ei=r(81167),es=r(7920),ea=r(68476),el=r(53903),eo=r(58299),ec=r(41956),ed=r(1345),eu=r(76710),eh=r(1778),ep=r(81168),ef=r(17212),em=r(32174),eg=r(6906),ey=r(82099),e_=r(39182),eb=r(23428),ew=r(44073),ek=r(26093),ev=r(15217),eA=r(67310),eS=r(45667),eT=r(63742),ex=r(90466),eC=r(16172),eR=r(63253),eI=r(80367),eP=r(794),e$=r(99348),eD=r(81002),eM=r(21126),eL=r(55769),eO=r(28819),eq=r(67447),eE=r(11344),eU=r(49600),eB=r(14858),eN=r(60527),ej=r(16889),eF=r(19293),eW=r(92534),eK=r(14432),eH=r(23555),ez=r(82797),eJ=r(95740),eG=r(37270),eV=r(4326),eZ=r(35198),eQ=r(41684),eX=r(46548),eY=r(3792),e0=r(87130),e1=r(94411),e2=r(27663),e3=r(87547),e5=r(30774),e4=r(88011),e6=r(44968),e8=r(82791),e9=r(70479),e7=r(96466),te=r(63058),tt=r(96553),tr=r(69458),tn=r(1852),ti=r(39075),ts=r(36645),ta=r(56242);let tl={AlertCircle:i.A,ArrowDown:s.A,ArrowRight:a.A,ArrowUp:l.A,ArrowUpRight:o.A,Ban:c.A,Bell:d.A,Bot:u.A,Bug:h.A,Check:p.A,CheckCircle2:f.A,ChevronDown:m.A,ChevronLeft:g.A,ChevronRight:y.A,ChevronUp:_.A,ChevronsDownUp:b.A,Circle:w.A,ClipboardPaste:k.A,Command:v.A,Compass:A.A,Columns2:S.A,Copy:T.A,CornerDownLeft:x.A,Crown:C.A,Delete:R.A,Download:I.A,ExternalLink:P.A,Eye:$.A,EyeOff:D.A,Facebook:M.A,File:L.A,FileCode:O.A,FileJson:q.A,FilePlus:E.A,FileText:U.A,Files:B.A,Filter:N.A,Folder:j.A,FolderOpen:F.A,FolderPlus:W.A,GitBranch:K.A,GitFork:H.A,Github:z.A,Globe:J.A,GripVertical:G.A,Hand:V.A,HardDrive:Z.A,HelpCircle:Q.A,History:X.A,Home:Y.A,Image:ee.A,ImageOff:et.A,KeyRound:er.A,Keyboard:en.A,Laptop:ei.A,LayoutDashboard:es.A,Link2:ea.A,ListChecks:el.A,Loader2:eo.A,Lock:ec.A,LogIn:ed.A,LogOut:eu.A,Maximize2:eh.A,Minimize2:ep.A,Menu:ef.A,Mic:em.A,MicOff:eg.A,Monitor:ey.A,Moon:e_.A,MoreHorizontal:eb.A,MoreVertical:ew.A,MousePointer2:ek.A,Package:ev.A,Palette:eA.A,PanelLeft:eS.A,PanelLeftClose:eT.A,PanelLeftOpen:ex.A,PanelRight:eC.A,Paperclip:eR.A,Pause:eI.A,Pencil:eP.A,Pi:e$.A,Pin:eD.A,PinOff:eM.A,Play:eL.A,Plug:eO.A,Plus:eq.A,Power:eE.A,PowerOff:eU.A,QrCode:eB.A,RefreshCw:eN.A,Replace:ej.A,RotateCw:eF.A,Save:eW.A,Scissors:eK.A,Search:eH.A,Send:ez.A,SendHorizontal:eJ.A,Settings:eG.A,Share:eV.A,Shield:eZ.A,Smartphone:eQ.A,Sparkles:eX.A,Square:eY.A,SquarePen:e0.A,Star:e1.A,StickyNote:e2.A,Sun:e3.A,Target:e5.A,Terminal:e4.A,Trash2:e6.A,Triangle:e8.A,Type:e9.A,Undo2:e7.A,Upload:te.A,Users:tt.A,Volume2:tr.A,VolumeX:tn.A,Wallpaper:ti.A,X:ts.A,Zap:ta.A};function to(e){let{name:t,size:r=20,className:i="",...s}=e,a=tl[t];return a?(0,n.jsx)(a,{size:r,className:i,strokeWidth:2,...s}):(console.warn(`Icon "${t}" not found in the icon registry`),null)}},96631:(e,t,r)=>{r.d(t,{Yr:()=>o,_r:()=>s,gJ:()=>l,rh:()=>c,sP:()=>a});var n=r(30562);let i=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function s(){let e=window.location.hostname;return"localhost"===e||"::1"===e||"[::1]"===e||e.startsWith("127.")||e.endsWith(".localhost")}function a(){return s()||!!window.__TAURI__}function l(){return!!window.__TAURI__||window.location.port===String(n._8)||!0}function o(){if(s())return!0;let e=i.exec(window.location.hostname);if(!e||e.slice(1).some(e=>Number(e)>255))return!1;let t=Number(e[1]),r=Number(e[2]);return 10===t||192===t&&168===r||172===t&&!!(r>=16)&&!!(r<=31)}function c(e){return s()&&window.location.port!==String(n._8)?e?.loopbackOrigin||n.w||n.lE:null}},99022:(e,t,r)=>{r.d(t,{$4:()=>d,D5:()=>b,HY:()=>p,I8:()=>g,IU:()=>w,LG:()=>u,cH:()=>y,e1:()=>f,lu:()=>k,lz:()=>c,pV:()=>v,t8:()=>h});var n=r(81851);r(55285);var i=r(68469);let s="9remote_device_trust",a="9remote_pending_fp2";function l(){try{return JSON.parse(localStorage.getItem(s)||"{}")}catch{return{}}}function o(e){localStorage.setItem(s,JSON.stringify(e))}function c(e){return l()[e]||null}function d(e){if(!e)return e;let t=c(e)?.tail;return t?`${e}-${t}`:e}function u(e,t){let r=l();r[e]={...r[e]||{},...t},o(r)}async function h(e,t){return e&&t?await (0,i.O)(e,t):null}function p(){let e=sessionStorage.getItem(a);return sessionStorage.removeItem(a),e?JSON.parse(e).fp2??null:null}function f(){try{let e=sessionStorage.getItem(a);if(!e)return null;let{fp2:t,exp:r}=JSON.parse(e);if(!t||Date.now()>r)return sessionStorage.removeItem(a),null;return t}catch{return null}}let m="9remote_api_keys";function g(){try{let e=sessionStorage.getItem(n.El);if(!e)return;sessionStorage.removeItem(n.El);let t=JSON.parse(localStorage.getItem(m)||"[]");if(t.some(t=>{try{return atob(t.key)===e}catch{return!1}}))return;t.push({id:String(Date.now()),key:btoa(e),label:`Key ${t.length+1}`,createdAt:new Date().toISOString(),lastLoginDate:new Date().toISOString()}),localStorage.setItem(m,JSON.stringify(t));try{window.dispatchEvent(new Event(n.N0))}catch{}}catch{}}function y(e){if(e)try{let t=l();delete t[e],o(t)}catch{}}function _(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}async function b(e,t,r){try{let n=await crypto.subtle.importKey("raw",_(e),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",n,_(r),new TextEncoder().encode(t))}catch{return null}}let w=["device:keyIssued","device:tailRejected"];function k(e,t,r){let i=e._auth?.apiKey;if(!i)return!1;if("device:keyIssued"===t){e._auth.tempKey=null,e._auth.socketOptions?.auth&&(e._auth.socketOptions.auth.tempKey=null);try{sessionStorage.removeItem("tempKey")}catch{}let t=r?.tail;return!t||(u(i,{tail:t}),e._tailProofSent=e._adapters.get("rtc")?._peerEpoch??0,sessionStorage.getItem(n.aS)&&(sessionStorage.removeItem(n.aS),sessionStorage.setItem(n.El,`${i}-${t}`),g()),!0)}return"device:tailRejected"===t&&(r?.reason===n.ML.sealUnreadable&&u(i,{hostSealKey:null}),!0)}async function v(e){let t=e._auth?.apiKey;if(!t)return;let i=e._adapters.get("rtc");if(!i?.ready)return;let s=i._peerEpoch??0;if(e._tailProofSent===s)return;let{freshAuth:a}=await Promise.resolve().then(r.bind(r,14511)),l=await a({apiKey:t,tempKey:e._auth?.tempKey||null},"rtc");(l.keyTail||l.keyTailSealed)&&i.send(n.l_.control,{event:"device:tailProof",args:[{keyTail:l.keyTail,keyTailSealed:l.keyTailSealed,tempKey:e._auth?.tempKey||null}]})&&(e._tailProofSent=s)}}}]);
1
+ "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8126],{189:(e,t,r)=>{r.d(t,{Fo:()=>u,U0:()=>o,vd:()=>d});var n=r(7620),i=r(89228);let s="9remote_auth",a="9remote_auth_state",l=["apiKey","tunnelUrl","mode","localIp"];function o(){try{localStorage.removeItem(a)}catch{}}function c(e){"u">typeof document&&(document.cookie=`${s}=${e}; path=/; max-age=86400; SameSite=Lax`)}function d(e){let{apiKey:t,tunnelUrl:r,mode:n="remote",tempKey:s=null,localIp:l=null}=e;if(!t){try{localStorage.removeItem(a)}catch{}return}try{sessionStorage.setItem("apiKey",t),sessionStorage.setItem("tunnelUrl",r),sessionStorage.setItem("mode",n||"remote"),s?sessionStorage.setItem("tempKey",s):sessionStorage.removeItem("tempKey"),l?sessionStorage.setItem("localIp",l):sessionStorage.removeItem("localIp")}catch{}c(t);try{sessionStorage.removeItem("9remote_manual_disconnect")}catch{}try{!function(){try{return"false"!==localStorage.getItem("9remote_remember_key_preference")}catch{return!1}}()?localStorage.removeItem(a):localStorage.setItem(a,JSON.stringify({apiKey:t,tunnelUrl:r,mode:n,localIp:l}))}catch{}i.d.getState().setAuthKey(t)}function u(){let e=(0,n.useCallback)(()=>{let e,t,r,n,i;try{e=sessionStorage.getItem("apiKey"),t=sessionStorage.getItem("tunnelUrl"),r=sessionStorage.getItem("mode"),n=sessionStorage.getItem("tempKey"),i=sessionStorage.getItem("localIp")}catch{return null}if(!e){let n=function(){try{return JSON.parse(localStorage.getItem(a)||"null")}catch{return null}}();if(!n?.apiKey)return null;try{for(let e of l)n[e]&&sessionStorage.setItem(e,n[e])}catch{}e=n.apiKey,t=n.tunnelUrl??null,r=n.mode??null,i=n.localIp??null}return c(e),{apiKey:e,tunnelUrl:t,mode:r,tempKey:n,localIp:i}},[]);return{getAuth:e,setAuth:(0,n.useCallback)(e=>d(e),[]),clearAuth:(0,n.useCallback)(()=>{try{sessionStorage.clear()}catch{}try{localStorage.removeItem(a)}catch{}"u">typeof document&&(document.cookie=`${s}=; path=/; max-age=0`)},[])}}},6134:(e,t,r)=>{r.d(t,{FQ:()=>o,Lq:()=>f,UX:()=>l,k_:()=>d,yO:()=>c});var n=r(96631);let i=[],s=new Set,a=location.hostname.startsWith("dev.")||"localhost"===location.hostname&&!(0,n.gJ)()||"1"===localStorage.getItem("9remote:termLog");function l(){return a}function o(){return i}function c(e){return s.add(e),()=>s.delete(e)}function d(){for(let e of(i.length=0,s))try{e(null)}catch(e){}}function u(e){if(null==e)return"";if(e instanceof Uint8Array||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return`<${e.byteLength}b>`;if("string"==typeof e)return e.length>120?`${e.slice(0,60)}…${e.length}b`:e;if("object"==typeof e)try{return JSON.stringify(e)}catch(e){}return String(e)}let h=new Set(["recv"]),p=null;function f(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if(!a)return;let l=Date.now(),o=r.map(u).join(" ");if(p&&p.category===e&&p.baseMsg===o&&l-p.ts<3e3||h.has(e)&&p&&p.category===e&&l-p.ts<300){p.count=(p.count||1)+1,p.ts=l,p.msg=`${o} \xd7${p.count}`,queueMicrotask(()=>{for(let e of s)try{e(p)}catch(e){}});return}let c={ts:l,category:e,msg:o,baseMsg:o,count:1};p=c,i.push(c),i.length>800&&i.shift(),queueMicrotask(()=>{for(let e of s)try{e(c)}catch(e){}})}},14337:(e,t,r)=>{r.d(t,{A:()=>i});var n=r(54568);function i(e){let{size:t="md",text:r,className:i=""}=e;return(0,n.jsxs)("div",{className:`flex flex-col items-center justify-center gap-3 ${i}`,children:[(0,n.jsx)("div",{className:`animate-spin rounded-full border-brand-500 border-t-transparent ${{sm:"h-4 w-4 border-2",md:"h-8 w-8 border-2",lg:"h-12 w-12 border-b-2"}[t]}`}),r&&(0,n.jsx)("p",{className:"text-brand-500 text-sm font-medium",children:r})]})}},14511:(e,t,r)=>{r.d(t,{freshAuth:()=>s});var n=r(99022),i=r(68469);async function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r={...e,connectionMode:t},s=(0,n.lz)(e.apiKey),a=e.tempKey?(0,n.lz)(e.tempKey):null,l=a?.tail?a:s?.tail?s:s||a,o=l?.tail;if(delete r.keyTail,delete r.keyTailSealed,!o)return r;if(l?.hostSealKey){let e=await (0,i.Y)(o,l.hostSealKey);if(e)return r.keyTailSealed=e,r}return r.keyTail=o,r}},14757:(e,t,r)=>{r.d(t,{k:()=>n});function n(e){let t=String(e||"").trim(),r=e=>({tempKey:e.slice(0,6).toUpperCase(),tail:e.slice(6,8).toUpperCase()}),n=/#([A-NP-Z1-9]{6}-?[a-np-z1-9]{2})$/i.exec(t);if(n)return r(n[1].replace(/-/g,""));let i=/^([A-NP-Z1-9]{6}-?[a-np-z1-9]{2})$/i.exec(t);if(i)return r(i[1].replace(/-/g,""));let s=/[?&]k=([A-NP-Z1-9]{6})(?:[^A-NP-Z1-9]|$)/i.exec(t);return s?{tempKey:s[1].toUpperCase()}:/^[A-NP-Z1-9]{6}$/i.test(t)?{tempKey:t.toUpperCase()}:null}},18179:(e,t,r)=>{r.d(t,{A:()=>d});var n=r(54568),i=r(7620),s=r(97509),a=r(96605),l=r(14652),o=r(9121),c=r(33879);function d(e){let{isOpen:t,onClose:r}=e,{t:d,locale:u,setLocale:h}=(0,o.s)();return((0,i.useEffect)(()=>{if(!t)return;let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t,r]),t)?!t||"u"<typeof document?null:(0,s.createPortal)((0,n.jsxs)("div",{className:"modal-overlay z-[70]",children:[(0,n.jsx)("div",{className:"absolute inset-0 scrim fade-in",onClick:r}),(0,n.jsxs)("div",{className:"relative card-elev max-w-lg w-full my-auto flex flex-col pop-in",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:d("menu.language")}),(0,n.jsx)("button",{onClick:r,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":d("common.close"),children:(0,n.jsx)(a.X,{size:20})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable p-3",children:(0,n.jsx)("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.dI.map(e=>{let t=e.code===u;return(0,n.jsxs)("button",{onClick:()=>{var t;return t=e.code,void((0,l.e)(),h(t),r())},className:`px-2 py-2 rounded-brand flex items-center gap-2 transition-all duration-150 ease-out active:scale-[0.97] min-w-0 ${t?"bg-brand-500 text-white":"text-text hover:bg-surface-2"}`,children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w80/${e.country}.png`,alt:e.label,className:"w-5 h-[14px] object-cover rounded-[2px] flex-shrink-0",loading:"lazy"}),(0,n.jsx)("span",{className:"flex-1 text-sm font-medium truncate text-left",children:e.label}),t&&(0,n.jsx)(a.aJ,{size:14,className:"flex-shrink-0"})]},e.code)})})})]})]}),document.body):null}},18753:(e,t,r)=>{r.d(t,{U:()=>n});function n(e,t){if(!e||!t)return!1;let r=String(e).split(".").map(Number),n=String(t).split(".").map(Number);for(let e=0;e<3;e++){let t=r[e]||0,i=n[e]||0;if(t!==i)return t>i}return!1}},23084:(e,t,r)=>{r.d(t,{A:()=>c});var n=r(54568),i=r(7620),s=r(97509),a=r(14652),l=r(9121),o=r(96605);function c(e){let{isOpen:t,onClose:r,onConfirm:c,title:d,message:u,confirmText:h,cancelText:p}=e,{t:f}=(0,l.s)(),m=(0,i.useRef)(null),g=(0,i.useRef)(null),y=h??f("common.confirm"),_=p??f("common.cancel");return((0,i.useEffect)(()=>{if(!t)return;let e=requestAnimationFrame(()=>{g.current?.focus()});return()=>cancelAnimationFrame(e)},[t]),(0,i.useEffect)(()=>{if(!t)return;let e=e=>{if("Escape"===e.key)e.preventDefault(),e.stopPropagation(),r();else if("Enter"===e.key){if(m.current&&document.activeElement===m.current){e.preventDefault(),e.stopPropagation(),r();return}e.preventDefault(),e.stopPropagation(),(0,a.e)(),c?.(),r()}};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[t,r,c]),!t||"u"<typeof document)?null:(0,s.createPortal)((0,n.jsxs)("div",{className:"modal-overlay z-[100]",children:[(0,n.jsx)("div",{className:"absolute inset-0 scrim fade-in",onClick:r}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",className:"relative card-elev max-w-md w-full my-auto overflow-y-auto pop-in",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsx)("div",{className:"px-6 py-4",children:(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:d})}),(0,n.jsx)("div",{className:"px-6 pb-4",children:(0,n.jsx)("p",{className:"text-text whitespace-pre-line",children:u})}),(0,n.jsxs)("div",{className:"px-6 py-4 flex justify-end gap-3",children:[(0,n.jsxs)("button",{ref:m,onClick:()=>{(0,a.e)(),r()},className:"px-4 py-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.98] font-medium flex items-center gap-1.5",children:[(0,n.jsx)("span",{children:_}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{ref:g,onClick:()=>{(0,a.e)(),c?.(),r()},className:"px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-brand transition-all duration-150 ease-out active:scale-[0.98] font-medium flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-red-500/50",children:[(0,n.jsx)("span",{children:y}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(o.Lt,{size:10,strokeWidth:2.5})})]})]})]})]}),document.body)}},23635:(e,t,r)=>{r.d(t,{B:()=>p});var n=r(94245),i=r(59055),s=r(36487),a=r(30368),l=r(72627);let o=(e,t)=>{let{min:r,max:n}=t;return Math.max(r,Math.min(n,Math.round(e)))};var c=r(92571);let d={name:null,value:null},u=null,h=()=>{if(u&&(clearTimeout(u),u=null),null===d.name)return;let{name:e,value:t}=d;d.name=null,d.value=null;try{localStorage.setItem(e,JSON.stringify(t))}catch{}};window.addEventListener("pagehide",h),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&h()});let p=(0,n.v)((0,i.Zr)((e,t,r)=>({...{viewStack:[{type:"list"}],navDir:"forward",openedSessions:[],activeWorkspaceId:null,setActiveWorkspaceId:t=>e(e=>({activeWorkspaceId:t,fullMode:!!e.fullModes?.[t??l.AD]})),livePanes:[],touchLivePane:t=>e(e=>{let r=Array.isArray(t)?t:[t];return{livePanes:[...e.livePanes.filter(e=>!r.includes(e)),...r].slice(-s.kn)}}),mountedWorkspaces:{},markWorkspaceMounted:t=>e(e=>{let r=t??l.AD;return e.mountedWorkspaces[r]?e:{mountedWorkspaces:{...e.mountedWorkspaces,[r]:!0}}}),isWorkspaceMounted:e=>{let r=e??l.AD;return!!t().mountedWorkspaces[r]},drafts:{},setDraft:(t,r)=>e(e=>({drafts:{...e.drafts,[t]:r}})),collapsedWorkspaces:{},toggleWorkspace:t=>e(e=>({collapsedWorkspaces:{...e.collapsedWorkspaces,[t]:!e.collapsedWorkspaces[t]}})),cwdBySession:{},setCwd:(t,r)=>{if(!t||!r)return;let n=(0,c.kb)(r);e(e=>e.cwdBySession[t]===n?e:{cwdBySession:{...e.cwdBySession,[t]:n}})},selectTab:t=>e(e=>{let r=a.x0.includes(t?.type)?t:e.viewStack[0]||{type:"list"},n=a.XG.indexOf(e.viewStack[e.viewStack.length-1]?.type),i=a.XG.indexOf(r.type);return{viewStack:[r],navDir:-1!==n&&-1!==i&&i<n?"back":"forward"}}),pushView:t=>e(e=>{let r=Array.isArray(e.viewStack)?e.viewStack:[],n=a.yP.includes(t?.type),i=n?r:r.filter((e,t)=>!(a.yP.includes(e?.type)&&t===r.length-1));if(n&&i.length&&i[i.length-1]?.type===t?.type){let e=[...i];return e[e.length-1]=t,{viewStack:e}}return{viewStack:[...i,t]}}),popView:()=>e(e=>{let t=Array.isArray(e.viewStack)?e.viewStack:[];return{viewStack:t.length>1?t.slice(0,-1):[{type:"list"}]}}),setViewStack:t=>e({viewStack:t}),addOpenedSession:t=>e(e=>({openedSessions:e.openedSessions.includes(t)?e.openedSessions:[...e.openedSessions,t]})),removeOpenedSession:t=>e(e=>{let{[t]:r,...n}=e.drafts,{[t]:i,...s}=e.pendingStartup,{[t]:a,...l}=e.artifactsBySession;return{artifactsBySession:l,openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),hiddenPaneSessionIds:e.hiddenPaneSessionIds?e.hiddenPaneSessionIds.filter(e=>e!==t):[],drafts:n,pendingStartup:s}}),replaceOpenedSession:(t,r)=>e(e=>{if(!r||t===r)return e;let n=e=>e===t?r:e;return{openedSessions:!t||e.openedSessions.includes(t)?e.openedSessions.map(n):e.openedSessions.includes(r)?e.openedSessions:[...e.openedSessions,r],livePanes:e.livePanes.map(n)}}),clearOpenedSessions:()=>e({openedSessions:[],livePanes:[]}),reorderOpenedSessions:t=>e(e=>{let r=new Set(t),n=t.filter(t=>e.openedSessions.includes(t));if(n.length<2)return{};let i=0;return{openedSessions:e.openedSessions.map(e=>r.has(e)?n[i++]:e)}}),closeSession:t=>e(e=>{let{[t]:r,...n}=e.drafts,{[t]:i,...s}=e.pendingStartup,{[t]:a,...l}=e.agentBySession,o=((e,t)=>{let r={};for(let[n,i]of Object.entries(e))r[n]={at:0,sessions:t?i.sessions.map(t):i.sessions};return r})(e.agentHistory,e=>e.openSessionId===t?{...e,openSessionId:null}:e);return{openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),drafts:n,pendingStartup:s,agentBySession:l,agentHistory:o}}),getCurrentView:()=>{let{viewStack:e}=t();return e[e.length-1]},getSelectedSession:()=>{let{viewStack:e}=t();for(let t=e.length-1;t>=0;t--)if("terminal"===e[t].type)return e[t].sessionId;return null},reset:()=>e({viewStack:[{type:"list"}],openedSessions:[],livePanes:[],activeWorkspaceId:null})},...{sidebarCollapsed:!1,toggleSidebar:()=>e(e=>({sidebarCollapsed:!e.sidebarCollapsed})),setSidebarCollapsed:t=>e({sidebarCollapsed:!!t}),sidebarWidth:s.gH.default,setSidebarWidth:t=>e({sidebarWidth:o(t,s.gH)}),fullModes:{},fullMode:!1,toggleFullMode:t=>e(e=>{let r=t??e.activeWorkspaceId??l.AD,n=!e.fullModes[r];return{fullModes:{...e.fullModes,[r]:n},fullMode:r===(e.activeWorkspaceId??l.AD)?n:e.fullMode}}),setFullMode:(t,r)=>e(e=>{let n="boolean"==typeof t?e.activeWorkspaceId??l.AD:t??e.activeWorkspaceId??l.AD,i="boolean"==typeof t?t:!!r;return{fullModes:{...e.fullModes,[n]:i},fullMode:n===(e.activeWorkspaceId??l.AD)?i:e.fullMode}}),hiddenPaneSessionIds:[],toggleHidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.includes(t)?e.hiddenPaneSessionIds.filter(e=>e!==t):[...e.hiddenPaneSessionIds,t]})),unhidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.filter(e=>e!==t)})),paneWidths:{},setPaneWidth:(t,r)=>e(e=>({paneWidths:{...e.paneWidths,[t]:null==r?null:o(r,s.k9)}})),rightPanelOpen:window.innerWidth>=s.jK,rightPanelTabs:{},rightPanelWidth:s.Ds.default,toggleRightPanel:()=>e(e=>({rightPanelOpen:!e.rightPanelOpen,rightPanelWasOpen:null})),closeRightPanel:()=>e({rightPanelOpen:!1,rightPanelWasOpen:null}),openRightPanel:()=>e({rightPanelOpen:!0,rightPanelWasOpen:null}),setRightPanelTab:(t,r)=>e(e=>({rightPanelOpen:!0,rightPanelWasOpen:null,...null!=r?{rightPanelTabs:{...e.rightPanelTabs,[r]:t}}:{}})),rightPanelRoots:{},setRightPanelRoot:(t,r)=>e(e=>{if(null==t)return e;let n=e.rightPanelRoots[t],i=r&&r!==t?r:void 0;if(n===i)return e;let s={...e.rightPanelRoots};return i?s[t]=i:delete s[t],{rightPanelRoots:s}}),setRightPanelWidth:t=>e({rightPanelWidth:o(t,s.Ds)}),editorFilePath:null,editorPanelWidth:s.Ao.default,setEditorPanelWidth:t=>e({editorPanelWidth:o(t,s.Ao)}),editorPreviewSeq:0,artifactTitle:null,rightPanelWasOpen:null,artifactSessionId:null,editorJump:null,openEditorFile:function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e(e=>({editorFilePath:t,editorPreviewSeq:r.preview?e.editorPreviewSeq+1:0,artifactTitle:r.artifactTitle||null,artifactSessionId:r.artifactSessionId||null,editorJump:r.line?{line:r.line,column:r.column,seq:(e.editorJump?.seq||0)+1}:null,...r.artifactTitle?{rightPanelWasOpen:e.rightPanelWasOpen??e.rightPanelOpen,rightPanelOpen:!1}:{}}))},closeEditorFile:()=>e(e=>({editorFilePath:null,editorPreviewSeq:0,artifactTitle:null,artifactSessionId:null,rightPanelWasOpen:null,...e.rightPanelWasOpen?{rightPanelOpen:!0}:{},...e.artifactSessionId&&e.editorFilePath?{artifactsBySession:((e,t,r)=>{let n=e[t];if(!n)return e;let i=n.filter(e=>e.path!==r);if(i.length===n.length)return e;let{[t]:s,...a}=e;return i.length?{...a,[t]:i}:a})(e.artifactsBySession,e.artifactSessionId,e.editorFilePath)}:{}})),hiddenHeaderButtons:["mobile"],hiddenHeaderButtonsMigrated:!1,toggleHeaderButton:t=>e(e=>({hiddenHeaderButtons:e.hiddenHeaderButtons.includes(t)?e.hiddenHeaderButtons.filter(e=>e!==t):[...e.hiddenHeaderButtons,t]})),mobileLowPower:!1,setMobileLowPower:t=>e({mobileLowPower:!!t}),mobileOpen:!1,mobileMode:"float",mobilePanelWidth:s.b5.default,mobileFloatRect:null,setMobileOpen:t=>e({mobileOpen:!!t}),setMobileMode:t=>e({mobileMode:t,mobileOpen:!0}),setMobilePanelWidth:t=>e({mobilePanelWidth:o(t,s.b5)}),setMobileFloatRect:t=>e({mobileFloatRect:t}),mobileSession:null,setMobileSession:t=>e(e=>({mobileSession:"function"==typeof t?t(e.mobileSession):t}))},...{webglEnabled:!1,setWebglEnabled:t=>e({webglEnabled:!!t}),fontSize:null,setFontSize:t=>e({fontSize:t?Math.max(10,Math.min(18,Math.round(t))):null}),terminalTheme:"default",setTerminalTheme:t=>e({terminalTheme:t||"default"}),terminalBackgrounds:["art8"],setTerminalBackgrounds:t=>e({terminalBackgrounds:Array.isArray(t)?t.filter(Boolean):[]}),terminalBackgroundOpacity:null,setTerminalBackgroundOpacity:t=>e({terminalBackgroundOpacity:null==t?s._z:Number(Math.max(s.DW.min,Math.min(s.DW.max,Math.round(t/s.DW.step)*s.DW.step)).toFixed(2))}),customBackgrounds:[],setCustomBackgrounds:t=>e({customBackgrounds:Array.isArray(t)?t.filter(e=>e?.id&&e?.dataUrl):[]}),backgroundBySession:{},setSessionBackground:(t,r)=>e(e=>{let n={...e.backgroundBySession};return r?n[t]=r:delete n[t],{backgroundBySession:n}}),showFolderButton:!0,showNoteButton:!1,setShowFolderButton:t=>e({showFolderButton:!!t}),setShowNoteButton:t=>e({showNoteButton:!!t}),noteChips:[],addNoteChip:t=>e(e=>({noteChips:[...e.noteChips,t]})),removeNoteChip:t=>e(e=>({noteChips:e.noteChips.filter(e=>e!==t)})),pinnedNotes:{},setNotePinned:(t,r)=>e(e=>{let n={...e.pinnedNotes};return r?n[t]=!0:delete n[t],{pinnedNotes:n}})},...{agentCaps:{},setAgentCaps:t=>e({agentCaps:t||{}}),artifactEnabled:!1,setArtifactEnabled:t=>e({artifactEnabled:!!t}),mcpClients:[],setMcpClients:t=>e({mcpClients:Array.isArray(t)?t:[]}),agentClisBy:{},setAgentClis:(t,r)=>e(e=>({agentClisBy:{...e.agentClisBy,[t]:{list:Array.isArray(r)?r:[],at:Date.now()}}})),agentHistory:{},setAgentHistory:(t,r)=>e(e=>({agentHistory:{...e.agentHistory,[t]:{at:Date.now(),sessions:Array.isArray(r)?r:[]}}})),invalidateAgentHistory:()=>e(e=>({agentHistory:((e,t)=>{let r={};for(let[n,i]of Object.entries(e))r[n]={at:0,sessions:t?i.sessions.map(t):i.sessions};return r})(e.agentHistory)})),agentBySession:{},setSessionAgent:(t,r)=>e(e=>e.agentBySession[t]===r?e:{agentBySession:{...e.agentBySession,[t]:r}}),pendingStartup:{},queueStartup:(t,r)=>e(e=>({pendingStartup:{...e.pendingStartup,[t]:r}})),consumeStartup:r=>{let n=t().pendingStartup[r];return void 0===n?null:(e(e=>{let{[r]:t,...n}=e.pendingStartup;return{pendingStartup:n}}),n)},artifactsBySession:{},pushArtifact:(t,r)=>e(e=>{if(!t||!r?.path)return{};let n=(e.artifactsBySession[t]||[]).filter(e=>e.path!==r.path);return{artifactsBySession:{...e.artifactsBySession,[t]:[r,...n].slice(0,s.zv)}}}),removeArtifact:(t,r)=>e(e=>({artifactsBySession:((e,t,r)=>{let n=e[t];if(!n)return e;let i=n.filter(e=>e.path!==r);if(i.length===n.length)return e;let{[t]:s,...a}=e;return i.length?{...a,[t]:i}:a})(e.artifactsBySession,t,r)}))}}),{name:"terminal-ui-state",partialize:e=>({viewStack:e.viewStack,openedSessions:e.openedSessions,agentBySession:e.agentBySession,activeWorkspaceId:e.activeWorkspaceId,collapsedWorkspaces:e.collapsedWorkspaces,webglEnabled:e.webglEnabled,fontSize:e.fontSize,terminalTheme:e.terminalTheme,terminalBackgrounds:e.terminalBackgrounds,terminalBackgroundOpacity:e.terminalBackgroundOpacity,backgroundBySession:e.backgroundBySession,showFolderButton:e.showFolderButton,showNoteButton:e.showNoteButton,noteChips:e.noteChips,pinnedNotes:e.pinnedNotes,sidebarCollapsed:e.sidebarCollapsed,sidebarWidth:e.sidebarWidth,fullModes:e.fullModes||{},fullMode:e.fullMode,hiddenPaneSessionIds:e.hiddenPaneSessionIds||[],paneWidths:e.paneWidths,rightPanelOpen:e.rightPanelOpen,rightPanelTabs:e.rightPanelTabs,rightPanelWidth:e.rightPanelWidth,editorPanelWidth:e.editorPanelWidth,hiddenHeaderButtons:e.hiddenHeaderButtons,hiddenHeaderButtonsMigrated:e.hiddenHeaderButtonsMigrated,mobileLowPower:e.mobileLowPower,mobileMode:e.mobileMode,mobilePanelWidth:e.mobilePanelWidth,mobileFloatRect:e.mobileFloatRect,artifactsBySession:e.artifactsBySession}),storage:{getItem:e=>{try{let t=localStorage.getItem(e);if(!t)return null;let r=JSON.parse(t);return r&&!Array.isArray(r.viewStack)&&(r.viewStack=[{type:"list"}]),r}catch{return null}},setItem:(e,t)=>{d.name=e,d.value=t,u||(u=setTimeout(h,s.eu))},removeItem:e=>{d.name===e&&(d.name=null,d.value=null),localStorage.removeItem(e)}},onRehydrateStorage:()=>e=>{e&&(Array.isArray(e.viewStack)&&0!==e.viewStack.length||(e.viewStack=[{type:"list"}]),window.location.pathname.replace(/\/+$/,"")===a.U2&&(e.viewStack=[{type:"list"}]),e.viewStack=e.viewStack.filter(e=>e?.type==="browser"||!a.yP.includes(e?.type)&&e?.type!=="site"),0===e.viewStack.length&&(e.viewStack=[{type:"list"}]),Array.isArray(e.terminalBackgrounds)||(e.terminalBackgrounds=[]),e.terminalBackground&&"none"!==e.terminalBackground&&0===e.terminalBackgrounds.length&&(e.terminalBackgrounds=[e.terminalBackground]),e.agentBySession&&"object"==typeof e.agentBySession||(e.agentBySession={}),window.innerWidth<s.jK&&(e.rightPanelOpen=!1),!e.hiddenHeaderButtonsMigrated&&(e.hiddenHeaderButtonsMigrated=!0,Array.isArray(e.hiddenHeaderButtons)?e.hiddenHeaderButtons.includes("mobile")||(e.hiddenHeaderButtons=[...e.hiddenHeaderButtons,"mobile"]):e.hiddenHeaderButtons=["mobile"]))}}))},30068:(e,t,r)=>{r.d(t,{D5:()=>a,FO:()=>c,I9:()=>o,Ic:()=>l,eR:()=>n,ij:()=>s,tC:()=>i});let n={namespace:"/remote",enableWebRTC:!0,enableTurn:!1,debug:{transport:!1,remote:!1,panel:!1,showButton:!1},dcChunkSize:8,dcReliable:!1,dcOrdered:!1,hashRequestInterval:1500,lastDataThreshold:500,restreamDelay:200,mouseThrottle:8,keyThrottle:25,scrollInterval:100,tileLoadTimeout:600,batchSize:16,batchDelay:3,decodeQueueCap:48,resizeDebounceMs:100,resizeStableFrames:3,resizeMaxFrames:30,focusDebounce:50,longPressDelay:1e3,doubleClickDelay:300,moveThreshold:10,edgeScrollThreshold:15,edgeScrollMultiplier:1.5,momentumFriction:.94,momentumMinVelocity:.3,pointerMode:"trackpad",trackpadSensitivity:1.3,trackpadAcceleration:1.5,trackpadTapMaxMove:8,trackpadTapMaxDuration:220,trackpadCursorSize:20,trackpadEdgeMarginRatio:.25,clipboardBadgeTimeout:1e4,gestureLockDelay:80,gestureDistanceThreshold:15,gestureCentroidThreshold:10,gestureDominanceRatio:2,wheelScrollMultiplier:2.5,wheelLineHeight:40,wheelPageHeight:400,wheelZoomStep:.1,wheelBoostInterval:250,mouseButtonMap:{0:"left",1:"middle",2:"right"},pcModeControls:{rectangleSelect:!1,pointerModeToggle:!1,handMode:!1,keyboardToggle:!1,textPanel:!0,modifierRow:!0,help:!0}},i={ctrl:"control",cmd:"command",alt:"alt",shift:"shift"},s=[{id:"ctrl",label:"Ctrl",modifier:"ctrl",type:"modifier"},{id:"alt",label:"Alt",modifier:"alt",type:"modifier"},{id:"shift",label:"Shift",modifier:"shift",type:"modifier"},{id:"cmd",label:"⌘",modifier:"cmd",type:"modifier"},{id:"esc",label:"Esc",key:"escape",type:"key"},{id:"tab",label:"Tab",key:"tab",type:"key"},{id:"enter",label:"↵",key:"enter",type:"key",primary:!0},{id:"backspace",label:"⌫",key:"backspace",type:"key"},{id:"undo",label:"Undo",key:"z",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"redo",label:"Redo",key:"z",modifiers:["control","shift"],type:"combo",osAdaptive:!0},{id:"up",label:"↑",key:"up",type:"arrow"},{id:"down",label:"↓",key:"down",type:"arrow"},{id:"left",label:"←",key:"left",type:"arrow"},{id:"right",label:"→",key:"right",type:"arrow"},{id:"home",label:"Home",key:"home",type:"key"},{id:"end",label:"End",key:"end",type:"key"},{id:"pgup",label:"PgUp",key:"pageup",type:"key"},{id:"pgdn",label:"PgDn",key:"pagedown",type:"key"},{id:"del",label:"Del",key:"delete",type:"key"},{id:"ins",label:"Ins",key:"insert",type:"key"},{id:"f1",label:"F1",key:"f1",type:"key"},{id:"f2",label:"F2",key:"f2",type:"key"},{id:"f3",label:"F3",key:"f3",type:"key"},{id:"f4",label:"F4",key:"f4",type:"key"},{id:"f5",label:"F5",key:"f5",type:"key"},{id:"f6",label:"F6",key:"f6",type:"key"},{id:"f7",label:"F7",key:"f7",type:"key"},{id:"f8",label:"F8",key:"f8",type:"key"},{id:"f9",label:"F9",key:"f9",type:"key"},{id:"f10",label:"F10",key:"f10",type:"key"},{id:"f11",label:"F11",key:"f11",type:"key"},{id:"f12",label:"F12",key:"f12",type:"key"},{id:"ctrlAltDel",label:"Ctl+Alt+Del",key:"delete",modifiers:["control","alt"],type:"combo"},{id:"ctrlShiftEsc",label:"Task Mgr",key:"escape",modifiers:["control","shift"],type:"combo"},{id:"altTab",label:"Alt+Tab",key:"tab",modifiers:["alt"],type:"combo"},{id:"altF4",label:"Alt+F4",key:"f4",modifiers:["alt"],type:"combo"},{id:"winKey",label:"Win",key:"command",type:"key"},{id:"printScreen",label:"PrtSc",key:"printscreen",type:"key"},{id:"paste",label:"Paste",key:"v",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"cut",label:"Cut",key:"x",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"selectAll",label:"All",key:"a",modifiers:["control"],type:"combo",osAdaptive:!0},{id:"desktopPrev",label:"◀ Desk",type:"desktop",direction:"prev"},{id:"desktopNext",label:"Desk ▶",type:"desktop",direction:"next"},{id:"desktopNew",label:"+ Desk",type:"desktop",direction:"new"}],a=["esc","undo","up","down","tab","ctrl","alt","shift","cmd","backspace"],l="enter",o=[["left","right","home","end","pgup","pgdn","del"],["f1","f2","f3","f4","f5","f6","f7","altTab"],["f9","f10","f11","f12","ctrlAltDel",,"desktopPrev","desktopNext","desktopNew"]],c={enter:"enter",return:"enter",space:" ",backspace:"backspace",tab:"tab",escape:"escape",Enter:"enter"," ":"space",Backspace:"backspace",Tab:"tab",Escape:"escape",ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Home:"home",End:"end",PageUp:"pageup",PageDown:"pagedown",Delete:"delete",Insert:"insert",F1:"f1",F2:"f2",F3:"f3",F4:"f4",F5:"f5",F6:"f6",F7:"f7",F8:"f8",F9:"f9",F10:"f10",F11:"f11",F12:"f12",CapsLock:"capslock",NumLock:"numlock",ScrollLock:"scrolllock",PrintScreen:"printscreen",ContextMenu:"menu"}},30368:(e,t,r)=>{r.d(t,{O5:()=>u,U2:()=>n,XG:()=>a,dX:()=>h,mn:()=>d,x0:()=>s,yP:()=>l});let n="/workspace",i={list:()=>n,terminal:e=>`${n}/terminal/${encodeURIComponent(e.sessionId||"")}`,files:e=>c(`${n}/files`,{ws:e.workspace,p:e.currentPath}),editor:e=>c(`${n}/editor`,{path:e.path,line:e.line,col:e.column}),git:e=>c(`${n}/git`,{ws:e.workspace}),remote:()=>`${n}/remote`,mobile:()=>`${n}/mobile`,workspaces:()=>`${n}/workspaces`,browse:e=>c(`${n}/browse`,{path:e.path}),pair:()=>`${n}/pair`,settings:()=>`${n}/settings`,welcome:()=>`${n}/welcome`},s=["list","remote","settings"],a=s,l=["browser"],o={"":"list",terminal:"terminal",files:"files",editor:"editor",git:"git",remote:"remote",mobile:"mobile",workspaces:"workspaces",browse:"browse",pair:"pair",settings:"settings",welcome:"welcome"};function c(e,t){let r=Object.entries(t).filter(e=>{let[,t]=e;return null!=t&&""!==t}).map(e=>{let[t,r]=e;return`${t}=${encodeURIComponent(r)}`}).join("&");return r?`${e}?${r}`:e}function d(e,t){if(!e?.startsWith(n))return null;let[r,i]=e.slice(n.length).replace(/^\//,"").split("/"),s=o[r||""];if(!s)return null;let a=e=>t?.get(e)||void 0;switch(s){case"terminal":return{type:s,sessionId:i?decodeURIComponent(i):void 0};case"files":return{type:s,workspace:a("ws"),currentPath:a("p")};case"editor":return{type:s,path:a("path"),line:p(a("line")),column:p(a("col"))};case"git":return{type:s,workspace:a("ws")};case"browse":return{type:s,path:a("path")};default:return{type:s}}}function u(e){return(i[e?.type]||i.list)(e)}function h(e,t){let r=u(t);if(s.includes(t.type))return[t];let n=e.findIndex(e=>u(e)===r);if(-1!==n)return e.slice(0,n+1);if("terminal"===t.type&&e[e.length-1]?.type==="terminal"){let r=[...e];return r[r.length-1]=t,r}return null}function p(e){let t=Number(e);return Number.isFinite(t)?t:void 0}},30562:(e,t,r)=>{r.d(t,{O:()=>n,Sn:()=>c,TR:()=>o,_8:()=>s,cC:()=>p,dM:()=>u,fm:()=>i,jP:()=>d,lE:()=>l,qn:()=>h,w:()=>a});let n="https://9remote.cc",i="https://9remote.cc/",s=2208,a=`http://127.0.0.1:${s}`,l=a,o=`${a}/api/ui/state`,c={connect:`${n}/api/connect`,tempKeyCreate:`${n}/api/temp-key/create`,tempKeyVerify:`${n}/api/temp-key/verify`,tempKeyRemove:`${n}/api/temp-key/remove`,turnCredentials:`${n}/api/webrtc/turn-credentials`},d=5,u=2e3,h=5e3,p=1e4},31856:(e,t,r)=>{r.d(t,{U:()=>p,x$:()=>h,zm:()=>f});var n=r(30562),i=r(70658),s=r(67841),a=r(189),l=r(69469),o=r(81353),c=r(99022),d=r(81851);let u=0;async function h(e){let{currentKey:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=++u,c=o.rh.getState(),d=t||c.hosts[c.currentKey]?.full||c.currentKey;d&&((0,s.d6)(d,window.location.pathname+window.location.search),o.rh.getState().setAutoConnect((0,l.Uo)(d),!0));let h=await fetch(n.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!h.ok)throw Error("connect failed");let p=await h.json(),f=!1;for(let t=0;t<n.jP&&!f;t++)(f=await (0,i.zg)(p.tunnelUrl,e))||!(t<n.jP-1)||await new Promise(e=>setTimeout(e,n.dM));if(!f)throw Error("unreachable");r===u&&(0,a.vd)({apiKey:e,tunnelUrl:p.tunnelUrl,mode:"remote",localIp:p.localIp||null})}function p(e){try{e?sessionStorage.setItem(d.aS,"1"):sessionStorage.removeItem(d.aS)}catch{}}function f(e){let{remember:t=!0,leavingHead:r=null,navigate:n=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e?.tail&&e.tempKey&&(0,c.LG)(e.tempKey,{tail:e.tail}),p(t),r&&((0,s.d6)(r,window.location.pathname+window.location.search),o.rh.getState().setAutoConnect((0,l.Uo)(r),!0)),n&&(window.location.href="/workspace/")}},32763:(e,t,r)=>{r.d(t,{A:()=>o});var n=r(54568),i=r(7620),s=r(96605),a=r(56156),l=r(9121);function o(e){let{isOpen:t,onClose:o,onScan:c}=e,{t:d}=(0,l.s)(),u=(0,i.useRef)(null),h=(0,i.useRef)(null),p=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null),[g,y]=(0,i.useState)(""),[_,b]=(0,i.useState)(""),w=(0,i.useCallback)(async e=>{if(h.current)try{await h.current.stop()}catch(e){}b("detected"),await new Promise(e=>setTimeout(e,300)),b("authenticating"),await c(e)||(b(""),m.current?.())},[c]),k=(0,i.useCallback)(async()=>{if(!p.current){let e=await Promise.all([r.e(2732),r.e(9700)]).then(r.bind(r,89700)).catch(()=>null);if(!e)return void y(d("login.qrLibFail"));p.current=e.Html5Qrcode}let e=document.getElementById("qr-reader");if(!e)return void y(d("login.qrInitFail"));try{e.innerHTML="";let t=new p.current("qr-reader");h.current=t,await t.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},e=>{f.current?.(e)},()=>{})}catch(t){let e=t.toString();e.includes("NotAllowedError")?y(d("login.qrCamDenied")):e.includes("NotFoundError")?y(d("login.qrNoCamera")):e.includes("NotReadableError")?y(d("login.qrCamBusy")):y(d("login.qrCamError"))}},[d]),v=(0,i.useCallback)(async()=>{if(h.current){try{await h.current.stop()}catch(e){}h.current=null}y(""),b(""),o()},[o]);return((0,i.useEffect)(()=>{f.current=w},[w]),(0,i.useEffect)(()=>{if(!t)return;let e=!1;m.current=async()=>{h.current=null,await new Promise(e=>setTimeout(e,400)),e||k()};let r=setTimeout(()=>{e||k()},200);return()=>{if(e=!0,clearTimeout(r),m.current=null,h.current){try{h.current.stop()}catch(e){}h.current=null}}},[t,k]),t)?(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm fade-in",children:(0,n.jsxs)("div",{className:"relative card-elev max-w-md w-full mx-4 overflow-hidden pop-in",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[(0,n.jsx)("h2",{className:"text-xl font-bold text-text",children:d("login.qrScanTitle")}),(0,n.jsx)("button",{onClick:v,className:"text-text-muted hover:text-text transition-colors p-1",children:(0,n.jsx)(s.X,{size:24})})]}),(0,n.jsx)("div",{className:"relative bg-black",children:(0,n.jsx)("div",{id:"qr-reader",ref:u,className:"w-full",style:{minHeight:"300px"}})}),(0,n.jsxs)("div",{className:"p-4",children:[g?(0,n.jsxs)("div",{className:"flex items-start gap-2 p-3 bg-red-500/10 rounded-brand text-red-400",children:[(0,n.jsx)(s.RI,{size:20,className:"flex-shrink-0 mt-0.5"}),(0,n.jsx)("p",{className:"text-sm",children:g})]}):"detected"===_?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 p-3 bg-green-500/10 rounded-brand text-green-400",children:[(0,n.jsx)(s.vW,{size:22}),(0,n.jsx)("p",{className:"text-sm font-medium",children:d("login.qrDetected")})]}):"authenticating"===_?(0,n.jsx)("div",{className:"flex items-center justify-center gap-2 p-3 bg-brand-500/10 rounded-brand text-brand-400",children:(0,n.jsx)("p",{className:"text-sm font-medium",children:d("login.qrAuthenticating")})}):(0,n.jsx)("p",{className:"text-sm text-text-muted text-center",children:d("login.qrHint")}),(0,n.jsx)(a.A,{variant:"secondary",onClick:v,disabled:"authenticating"===_,className:"w-full mt-4",children:"authenticating"===_?d("login.qrPleaseWait"):d("common.cancel")})]})]})}):null}},36487:(e,t,r)=>{r.d(t,{$Z:()=>ee,A_:()=>c,Ao:()=>p,B$:()=>K,BM:()=>es,DW:()=>H,Ds:()=>h,EE:()=>I,FC:()=>e_,Fz:()=>f,G:()=>w,Gp:()=>et,IJ:()=>Y,Il:()=>ey,Jv:()=>l,KA:()=>_,KN:()=>$,Lo:()=>X,M8:()=>er,Mg:()=>ex,Nz:()=>ev,OM:()=>ep,Pj:()=>E,Pz:()=>Z,Qe:()=>d,RF:()=>eb,RS:()=>V,TM:()=>D,Tb:()=>v,Tk:()=>b,Uc:()=>ea,VE:()=>ec,W$:()=>U,YA:()=>eg,YS:()=>x,ZU:()=>q,_C:()=>eC,_O:()=>Q,_z:()=>N,aD:()=>M,am:()=>T,ar:()=>B,b5:()=>m,b9:()=>ek,bl:()=>ew,bs:()=>C,c:()=>F,cK:()=>eS,dU:()=>ei,de:()=>eP,dt:()=>n,eE:()=>eh,eu:()=>P,fw:()=>ef,g$:()=>eT,gH:()=>u,hp:()=>R,i5:()=>em,iW:()=>k,j4:()=>en,jK:()=>i,k9:()=>s,kn:()=>o,ll:()=>S,ok:()=>eI,pS:()=>a,pZ:()=>W,pl:()=>eu,pt:()=>J,qQ:()=>A,qj:()=>g,qw:()=>el,sB:()=>ed,t:()=>j,vP:()=>L,vk:()=>z,wu:()=>O,y:()=>eA,zm:()=>eo,zv:()=>y});let n=["git status","git add .",'git commit -m ""',"git push","git pull","git fetch","git diff","git log --oneline","git branch","git checkout","git checkout -b","git switch","git stash","git stash pop","git merge","git rebase","git clone","git remote -v","git restore","npm install","npm ci","npm run dev","npm run build","npm run test","npm run lint","npm outdated","pnpm install","pnpm dev","yarn dev","bun install","cd ..","cd ~","cd -","ls -la","ll","mkdir -p","cp -r","find . -name","du -sh","chmod +x","ln -s","grep -rn","grep -i","wc -l","tail -f","ps aux","df -h","free -h","lsof -i","netstat -tlnp","docker ps","docker ps -a","docker images","docker logs -f","docker exec -it","docker compose up -d","docker compose down","docker build -t","code .","claude","claude --continue","claude --resume","claude --dangerously-skip-permissions","claude mcp","codex","codex --full-auto"],i=760,s={min:400,max:1/0},a=2,l=0,o=12,c=250,d=8,u={default:190,min:180,max:1/0},h={default:190,min:190,max:1/0},p={default:420,min:280,max:1/0},f=[{id:"remote",labelKey:"menu.remoteDesktop",descKey:"menu.remoteDesktopHint",group:"header",section:"remote"},{id:"sites",labelKey:"menu.sites",descKey:"menu.sitesHint",group:"header",section:"remote"},{id:"mobile",labelKey:"mobile.androidDevice",descKey:"mobile.androidDeviceHint",group:"header",section:"remote"},{id:"notifications",labelKey:"menu.bellButton",descKey:"menu.bellButtonHint",group:"header",section:"plugins"},{id:"folder",labelKey:"menu.showFolder",group:"pane",section:"terminal",storeKey:"showFolderButton",setterKey:"setShowFolderButton"},{id:"note",labelKey:"menu.showNote",group:"pane",section:"terminal",storeKey:"showNoteButton",setterKey:"setShowNoteButton"}],m={default:300,min:240,max:1/0},g={width:{default:300,min:240,max:900},height:{default:620,min:320},margin:12,defaultOffset:24},y=20,_=1e4,b={maxDepth:1,deepMaxDepth:3,cacheTtlMs:3e4,retryBaseMs:1e3,retryMaxMs:16e3},w=["main","master"],k={topThresholdLines:5,guardMs:600,minFetchBytes:256,chainMax:3,chainDebounceMs:300,disabled:!1},v=5242880,A=5,S=3e3,T=150,x=100,C=101,R=200,I={Escape:{data:"\x1b"},c:{ctrl:!0,data:"\x03",requireNoSelection:!0},d:{ctrl:!0,data:"\x04"},z:{ctrl:!0,data:"\x1a"},l:{ctrl:!0,data:"\f"}},P=250,$=999,D=["check again","continue","summarize"],M="terminal:noteSync",L="terminal:openSession",O=5e3,q=250,U=90,E={cursorBlink:!0,fontSize:12,fontSizeMobile:12,fontFamily:'ui-monospace, "SF Mono", "Cascadia Code", "Roboto Mono", "Noto Sans Mono", Menlo, Monaco, "Courier New", monospace',scrollback:15e3,convertEol:!0,allowProposedApi:!0,scrollOnUserInput:!0,fastScrollModifier:"none",smoothScrollDuration:0,rescaleOverlappingGlyphs:!0,minimumContrastRatio:4.5,macOptionIsMeta:!0};function B(e){return null!=e?e:window.innerWidth<768?E.fontSizeMobile:E.fontSize}let N=.8,j=.25,F="16,16,20",W="116,120,136",K=.28,H={min:.3,max:.95,step:.01},z={none:{label:"None"},art1:{label:"Anime 1",src:"/backgrounds/bg9.jpg"},art2:{label:"Anime 2",src:"/backgrounds/bg2.jpg"},art3:{label:"Anime 3",src:"/backgrounds/bg3.jpg"},art4:{label:"Anime 4",src:"/backgrounds/bg4.jpg"},art5:{label:"Anime 5",src:"/backgrounds/bg5.jpg"},art7:{label:"Anime 7",src:"/backgrounds/bg7.jpg"},art8:{label:"Anime 8",src:"/backgrounds/bg8.jpg"},art9:{label:"Anime 9",src:"/backgrounds/bg10.jpg"},art10:{label:"Anime 10",src:"/backgrounds/bg11.jpg"},art11:{label:"Anime 11",src:"/backgrounds/bg12.jpg"},art12:{label:"Anime 12",src:"/backgrounds/bg13.jpg"}};function J(e,t){return e&&t&&"none"!==t&&(z[t]||String(t).startsWith("custom"))?{...e,background:"#10101400"}:e}function G(e){return"custom"===e?"custom":"string"==typeof e&&e.startsWith("custom:")?e.slice(7):null}function V(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=G(e);return r?t.find(e=>e?.id===r)?.dataUrl||null:z[e]?.src||null}function Z(e){return z[e]?.label||(G(e)?"Custom":z.none.label)}let Q=4e3,X=2e4;function Y(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Array.isArray(e)?e.filter(e=>{let r=G(e);return r?t.some(e=>e?.id===r):"none"===e||!!z[e]}):[]}function ee(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return Y([e],n)[0]||(r=Y(t,n),Array.isArray(r)&&0!==r.length&&r[i%r.length]||"none")}let et={gpuAcceleration:"auto",smoothScrollDuration:125},er={clipboard:!0,search:!0,image:!0},en=30,ei=2,es=100,ea=600,el=150,eo=4e3,ec=3e3,ed=5e3,eu=2e3,eh=8e3,ep=6e4,ef=3e4,em="28%",eg=400,ey={lineHeight:18,sensitivity:1,friction:.95,minVelocity:.3,maxVelocity:55,wheelStepLines:1,tuiThrottleMs:50,momentumRenderCadenceMs:33,tuiBackpressureTimeoutMs:120,sgrUp:(e,t)=>`\x1b[<64;${e};${t}M`,sgrDown:(e,t)=>`\x1b[<65;${e};${t}M`},e_={longPressMs:450,moveTolerance:10,wordChars:/[A-Za-z0-9._\-/~:@]/},eb={verbs:["cd","ls","ll","cat","less","more","head","tail","vim","nvim","nano","bat","code","code-insiders","rm","cp","mv","mkdir","touch","chmod","open","grep"],ttlMs:1e4,debounceMs:120,maxDirs:20,maxResults:8},ew={minDistance:60,ratio:1.5,maxDuration:500},ek=e=>!!e&&27!==e.charCodeAt(0),ev=e=>"string"==typeof e&&(/^\x1b\[[?>=][0-9;]*c$/.test(e)||/^\x1b\[[0-9]+;[0-9]+R$/.test(e)||/^\x1b\[0n$/.test(e)||/^\x1b\]\d+;/.test(e)),eA=[{id:"ctrl",label:"Ctrl",key:"Ctrl",type:"modifier"},{id:"opt",label:"Opt",key:"Alt",type:"modifier"},{id:"shift",label:"Shift",key:"Shift",type:"modifier"},{id:"meta",label:"⌘",key:"Meta",type:"modifier"},{id:"esc",label:"Esc",key:"Escape",type:"key"},{id:"tab",label:"Tab",key:"Tab",type:"key"},{id:"enter",label:"↵",key:"Enter",type:"key"},{id:"backspace",label:"⌫",key:"Backspace",type:"key"},{id:"up",label:"↑",key:"ArrowUp",type:"arrow"},{id:"down",label:"↓",key:"ArrowDown",type:"arrow"},{id:"left",label:"←",key:"ArrowLeft",type:"arrow"},{id:"right",label:"→",key:"ArrowRight",type:"arrow"},{id:"home",label:"Home",key:"Home",type:"key"},{id:"end",label:"End",key:"End",type:"key"},{id:"pgup",label:"PgUp",key:"PageUp",type:"key"},{id:"pgdn",label:"PgDn",key:"PageDown",type:"key"},{id:"del",label:"Del",key:"Delete",type:"key"},{id:"ins",label:"Ins",key:"Insert",type:"key"},{id:"ctrlA",label:"^A",key:"a",type:"ctrl"},{id:"ctrlC",label:"^C",key:"c",type:"ctrl"},{id:"ctrlD",label:"^D",key:"d",type:"ctrl"},{id:"ctrlE",label:"^E",key:"e",type:"ctrl"},{id:"ctrlK",label:"^K",key:"k",type:"ctrl"},{id:"ctrlL",label:"^L",key:"l",type:"ctrl"},{id:"ctrlN",label:"^N",key:"n",type:"ctrl"},{id:"ctrlP",label:"^P",key:"p",type:"ctrl"},{id:"ctrlR",label:"^R",key:"r",type:"ctrl"},{id:"ctrlT",label:"^T",key:"t",type:"ctrl"},{id:"ctrlU",label:"^U",key:"u",type:"ctrl"},{id:"ctrlW",label:"^W",key:"w",type:"ctrl"},{id:"ctrlX",label:"^X",key:"x",type:"ctrl"},{id:"ctrlY",label:"^Y",key:"y",type:"ctrl"},{id:"ctrlZ",label:"^Z",key:"z",type:"ctrl"},{id:"f1",label:"F1",key:"F1",type:"key"},{id:"f2",label:"F2",key:"F2",type:"key"},{id:"f3",label:"F3",key:"F3",type:"key"},{id:"f4",label:"F4",key:"F4",type:"key"},{id:"f5",label:"F5",key:"F5",type:"key"},{id:"f6",label:"F6",key:"F6",type:"key"},{id:"f7",label:"F7",key:"F7",type:"key"},{id:"f8",label:"F8",key:"F8",type:"key"},{id:"f9",label:"F9",key:"F9",type:"key"},{id:"f10",label:"F10",key:"F10",type:"key"},{id:"f11",label:"F11",key:"F11",type:"key"},{id:"f12",label:"F12",key:"F12",type:"key"},{id:"pipe",label:"|",key:"|",type:"key"},{id:"tilde",label:"~",key:"~",type:"key"},{id:"slash",label:"/",key:"/",type:"key"},{id:"backslash",label:"\\",key:"\\",type:"key"},{id:"dash",label:"-",key:"-",type:"key"},{id:"underscore",label:"_",key:"_",type:"key"}],eS=["esc","up","down","ctrlC","ctrl","opt","shift","tab","slash"],eT="enter",ex=[["left","right","home","end","pgup","pgdn","del"],["ctrlZ","ctrlR","ctrlL","ctrlA","ctrlE","ctrlW","ctrlD"],["f1","f2","f3","f4","f5","f10","f11"]],eC={base:"flex items-center justify-center rounded-brand font-semibold transition-all duration-150 ease-out active:scale-[0.94]",textNormal:"text-xs",textSmall:"text-[11px]",normal:"bg-surface-2 hover:bg-surface-3 text-text",arrow:"bg-surface-2 hover:bg-surface-3 text-text text-sm",modifierActive:"bg-brand-500 text-white shadow-sm",pinned:"bg-brand-500/15 hover:bg-brand-500/25 text-brand-400",size:{minWidth:"34px",height:"32px",paddingLeft:"6px",paddingRight:"6px"},sizeLarge:{minWidth:"38px",height:"32px",paddingLeft:"8px",paddingRight:"8px"},sizeSmall:{width:"28px",height:"28px"}},eR=["main","master"],eI=e=>eR.includes(e),eP={DELAY_MS:400,GAP_PX:6,EDGE_PX:8,MAX_WIDTH_PX:320,EST_HEIGHT_PX:48,SLACK_PX:.5}},42126:(e,t,r)=>{r.d(t,{g:()=>ei});var n=r(81851);class i{static #e=this.id="base";static #t=this.capabilities={control:!1,binary:!1,signaling:"none"};static #r=this.priority={control:0,binary:0};constructor(){this._listeners=new Map,this._state=n.Of.idle}get state(){return this._state}get ready(){return this._state===n.Of.open}supports(e){return!!this.constructor.capabilities[e]}getPriority(e){return this.constructor.priority[e]??0}on(e,t){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];let i=this._listeners.get(e);if(i)for(let e of i)e(...r)}_setState(e){this._state!==e&&(this._state=e,this._emit("stateChange",e))}connect(e){throw Error("Not implemented: connect")}disconnect(){throw Error("Not implemented: disconnect")}send(e,t){throw Error("Not implemented: send")}}var s=r(80514),a=r(14511);let l={transports:["websocket"],reconnection:!1,reconnectionDelay:1e3,reconnectionDelayMax:5e3};class o{constructor({tunnelUrl:e,namespace:t="",socketOptions:r={}}){this._tunnelUrl=e,this._namespace=t,this._socketOptions=r}connect(e){let{onSocket:t,onFail:r}=e,n=this._namespace?`${this._tunnelUrl}${this._namespace}`:this._tunnelUrl,i=this._tunnelUrl===window.location.origin?"local":"tunnel",o=(0,s.io)(n,{...l,...this._socketOptions,path:"/socket.io",auth:e=>{(0,a.freshAuth)(this._socketOptions.auth,i).then(e)}}),c=!1;o.once("connect",()=>{c||(c=!0,t(o,i))}),o.once("connect_error",()=>{c||(c=!0,r?.())})}}let c={transports:["websocket"],reconnection:!1};class d{constructor({tunnelUrl:e,localIp:t,namespace:r="",socketOptions:n={}}){this._tunnelUrl=e,this._localIp=t,this._namespace=r,this._socketOptions=n}connect(e){let{onSocket:t,onFail:r}=e,n=!1,i=(e,r)=>{if(n){try{e.disconnect()}catch{}return}n=!0,t(e,r)},l=e=>this._namespace?`${e}${this._namespace}`:e,o=e=>({...c,...this._socketOptions,path:"/socket.io",auth:t=>{(0,a.freshAuth)(this._socketOptions.auth,e).then(t)}}),d=()=>{let e=this._tunnelUrl===window.location.origin?"local":"tunnel",t=(0,s.io)(l(this._tunnelUrl),o(e));t.once("connect",()=>i(t,e)),t.once("connect_error",()=>void(!n&&(n=!0,r?.())))};if(!this._localIp||"https:"===window.location.protocol)return void d();let u=(0,s.io)(l(`http://${this._localIp}`),o("local"));u.once("connect",()=>i(u,"local")),u.once("connect_error",()=>{n||(u.disconnect(),d())})}}var u=r(30562);let h=3;var p=r(55285),f=r(6134);let m=2e3,g=15,y=15,_=15,b=45;class w extends i{static #e=this.id="ws";static #t=this.capabilities={control:!0,binary:!0,file:!0,browser:!0,signaling:"ws"};static #r=this.priority={control:100,binary:10,file:10,browser:10};constructor(){super(),this._socket=null,this._connectionMode="local",this._retryTimer=null,this._retryAttempt=0,this._retryScheduled=!1,this._retryNowTimer=null,this._destroyed=!1,this._blocked=!1,this._updating=!1,this._connecting=!1,this._visibilityHandler=null,this._lastInboundAt=Date.now(),this._lastMsgAt=0,this._zombieWatchdogTimer=null,this._outboundWatchdogTimer=null,this._lastBufferedAmount=0,this._retrySeq=0}get lastInboundAt(){return this._lastInboundAt}get lastMsgAt(){return this._lastMsgAt}get socket(){return this._socket}get connectionMode(){return this._connectionMode}get blocked(){return this._blocked}setUpdating(e){this._updating=e,e&&(this._maxAttempts=b,this._retryAttempt=0,(0,p.c)("transport",`[ws] updating=true maxAttempts=${this._maxAttempts}`))}forceReconnect(){this._destroyed||this._forceReconnect()}retryNow(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";if(this._blocked)return void(0,f.Lq)("switch",`ws retryNow SKIP by=${e} (blocked)`);let t=Date.now(),r=t-(this._lastRetryNowAt||0);if(r<3e3){this._retryNowTimer||(this._retryNowTimer=setTimeout(()=>{this._retryNowTimer=null,this.retryNow(`${e}-deferred`)},3e3-r)),(0,p.c)("transport","[ws] retryNow throttled → deferred"),(0,f.Lq)("switch",`ws retryNow DEFER by=${e} (${3e3-r}ms left)`);return}(0,f.Lq)("switch",`ws retryNow GO by=${e} (drops attempt ${this._retryAttempt})`),this._retrySeq++,this._lastRetryNowAt=t,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,clearTimeout(this._retryTimer),clearTimeout(this._connectingTimer),this._retryTimer=null,this._retryScheduled=!1,this._retryAttempt=0,this._connecting=!1,this._destroyed=!0,this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._destroyed=!1,this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:1,maxAttempts:this._maxAttempts,failed:!1}),this._setState(n.Of.connecting),this._connectInternal()}setBlocked(e){this._blocked=e,(0,p.c)("transport",`[ws] blocked=${e}`),e?(this._cancelRetry(),this._socket?.disconnect()):this._socket?.connected||this._destroyed||this._connectInternal()}connect(e){this._ctx=e,this._auth=e.auth,this._maxAttempts=this._auth.tempKey?g:y,this._reconnectMaxAttempts=_,this._destroyed=!1,this._attachNetworkListeners(),this._setState(n.Of.connecting),this._connectInternal()}disconnect(){this._destroyed=!0,this._retrySeq++,this._cancelRetry(),clearTimeout(this._zombieWatchdogTimer),clearTimeout(this._outboundWatchdogTimer),this._removeNetworkListeners(),this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._setState(n.Of.closed)}send(e,t){if(!this._socket?.connected)return!1;if(e===n.l_.control){let{event:e,args:r=[],cb:n}=t;return n?this._socket.emit(e,...r,n):this._socket.emit(e,...r),!0}return e===n.l_.binary?(this._socket.emit("tiles-bin-v2",t),!0):e===n.l_.browser?(this._socket.emit("browser:tiles-bin",t),!0):e===n.l_.file&&(this._socket.emit("file-bin",t),!0)}_outboundStalled(e){try{let t=e?.io?.engine?.transport?.ws,r="number"==typeof t?.bufferedAmount?t.bufferedAmount:0,n=r>0&&this._lastBufferedAmount>0&&r>=this._lastBufferedAmount;return this._lastBufferedAmount=r,n}catch{return this._lastBufferedAmount=0,!1}}_connectInternal(){if(this._connecting||this._socket?.connected||this._destroyed)return;if(!this._auth.tunnelUrl&&!this._auth.localIp){(0,p.c)("transport","[ws] connect HOLD (no tunnelUrl/localIp yet) → retry"),(0,f.Lq)("switch","ws connect HOLD (no url yet) → fetch on retry"),this._setState(n.Of.degraded),this._scheduleRetry();return}this._connecting=!0,clearTimeout(this._connectingTimer),this._connectingTimer=setTimeout(()=>{this._connecting=!1},m);let e={tunnelUrl:this._auth.tunnelUrl,namespace:this._auth.namespace||"",socketOptions:this._auth.socketOptions||{}};(0,p.c)("transport",`[ws] connect: tunnelUrl=${this._auth.tunnelUrl} localIp=${this._auth.localIp||"none"}`),new o(e).connect({onSocket:(e,t)=>{if(this._connecting=!1,clearTimeout(this._connectingTimer),this._socket?.connected&&this._socket!==e){try{e.disconnect()}catch{}return}this._connectionMode=t,this._socket=e,this._retryAttempt=0,this._updating=!1,this._maxAttempts=this._reconnectMaxAttempts,this._cancelRetry(),this._attachSocketEvents(e),(0,p.c)("transport",`[ws] connect mode=${t}`),(0,f.Lq)("switch",`ws open mode=${t}`),this._setState(n.Of.open)},onFail:()=>{this._connecting=!1,clearTimeout(this._connectingTimer),(0,p.c)("transport","[ws] connect FAIL → schedule retry"),this._scheduleRetry()}})}_attachSocketEvents(e){e.on("disconnect",e=>{(0,p.c)("transport",`[ws] disconnect reason=${e}`),(0,f.Lq)("switch",`ws disconnect reason=${e}`),this._setState(n.Of.degraded),this._destroyed||this._forceReconnect()}),e.on("connect_error",e=>{(0,p.c)("transport",`[ws] connect_error ${e?.message||e}`),this._setState(n.Of.degraded),this._forceReconnect()});let t=()=>{clearTimeout(this._zombieWatchdogTimer),this._zombieWatchdogTimer=setTimeout(()=>{if(!this._destroyed&&this._socket===e){if(Date.now()-this._lastInboundAt<n.Rh)return void t();(0,f.Lq)("switch","ws zombie watchdog → force reconnect"),this.forceReconnect()}},n.Rh)};t(),e.io?.on?.("ping",()=>{this._lastInboundAt=Date.now(),t()}),e.on("connect",()=>{this._lastInboundAt=Date.now(),t()});let r=()=>{clearTimeout(this._outboundWatchdogTimer),this._outboundWatchdogTimer=setTimeout(()=>{if(!this._destroyed&&this._socket===e){if(this._outboundStalled(e)){(0,f.Lq)("switch","ws outbound stall (send buffer frozen) → force reconnect"),this.forceReconnect();return}r()}},n.KP)};r(),e.onAny((e,t)=>{this._lastMsgAt=Date.now(),this._emit("message",{event:e,data:t,source:"ws"})})}_attachNetworkListeners(){this._visibilityHandler||(this._visibilityHandler=()=>{"visible"!==document.visibilityState||this._socket?.connected||this._connecting||this.retryNow("visible")},this._offlineHandler=()=>{(0,f.Lq)("switch","ws offline event → drop socket, degraded"),this._socket?.disconnect(),this._socket=null,this._setState(n.Of.degraded)},this._onlineHandler=()=>{this._socket?.connected||this._connecting?(0,f.Lq)("switch",`ws online event → skip (${this._connecting?"handshaking":"already up"})`):this.retryNow("online")},this._pagehideHandler=()=>{try{this._socket?.disconnect()}catch{}},window.addEventListener("pagehide",this._pagehideHandler),document.addEventListener("visibilitychange",this._visibilityHandler),window.addEventListener("offline",this._offlineHandler),window.addEventListener("online",this._onlineHandler))}_detachSocketEvents(){if(this._socket)try{this._socket.offAny()}catch{}}_removeNetworkListeners(){this._pagehideHandler&&(window.removeEventListener("pagehide",this._pagehideHandler),this._pagehideHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._offlineHandler&&(window.removeEventListener("offline",this._offlineHandler),this._offlineHandler=null),this._onlineHandler&&(window.removeEventListener("online",this._onlineHandler),this._onlineHandler=null)}_forceReconnect(){if(!this._destroyed&&!this._blocked&&!this._retryScheduled&&!this._connecting){if(this._retrySeq++,this._retryAttempt++,this._retryAttempt>h){this._retryAttempt=0,this._scheduleRetry();return}this._socket?.disconnect(),this._socket=null,this._connectInternal()}}_scheduleRetry(){this._retryScheduled||this._destroyed||this._blocked||(this._retryScheduled=!0,this._retryTimer=setTimeout(()=>this._doRetry(),m))}async _doRetry(){if(this._destroyed)return;if("u">typeof document&&"hidden"===document.visibilityState){(0,f.Lq)("switch",`ws retry HOLD (hidden, still at ${this._retryAttempt}/${this._maxAttempts})`),this._retryScheduled=!1,this._scheduleRetry();return}this._retryAttempt++;let e=this._retryAttempt,t=this._retrySeq;if(e>this._maxAttempts){this._retryScheduled=!1,(0,f.Lq)("switch",`ws GAVE UP after ${this._maxAttempts} attempts → closed`),this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:e,maxAttempts:this._maxAttempts,failed:!0}),this._setState(n.Of.closed);return}(0,p.c)("transport",`[ws] retry attempt=${e}/${this._maxAttempts}`),(0,f.Lq)("switch",`ws retry ${e}/${this._maxAttempts}`),this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:e,maxAttempts:this._maxAttempts,failed:!1});try{let e=await fetch(u.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this._auth.apiKey})});if(!e.ok){if(503===e.status){let t=await e.json().catch(()=>({}));t?.error==="agent-offline"&&this._ctx?.onHostOffline?.()}throw Error("Failed")}let{tunnelUrl:r,localIp:n}=await e.json();if(t!==this._retrySeq)return void(0,f.Lq)("switch","ws retry ABORT (superseded mid-fetch)");this._auth.tunnelUrl=r,this._auth.localIp=n||null,this._connectionMode="local",this._ctx?.onUrlUpdate?.({tunnelUrl:r,localIp:n}),this._socket?.disconnect(),this._retryScheduled=!1,this._connectInternal()}catch{if(t!==this._retrySeq)return;this._retryScheduled=!1,this._scheduleRetry()}}_cancelRetry(){clearTimeout(this._retryTimer),this._retryTimer=null,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,this._retrySeq++,this._retryAttempt=0,this._retryScheduled=!1,this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:0,maxAttempts:this._maxAttempts,failed:!1})}}function k(e,t){if(t instanceof Uint8Array){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return{__b:btoa(e)}}return t}function v(e,t){if(t&&"object"==typeof t&&"string"==typeof t.__b){let e=atob(t.__b),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return t}function A(e){return JSON.stringify(e,k)}function S(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=[],n={event:e.event,args:function e(t,r){if(t instanceof ArrayBuffer)return r.push(new Uint8Array(t)),{__B:r.length-1};if(ArrayBuffer.isView(t))return r.push(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),{__B:r.length-1};if(Array.isArray(t))return t.map(t=>e(t,r));if(t&&"object"==typeof t){let n={};for(let i of Object.keys(t))n[i]=e(t[i],r);return n}return t}(e.args||[],r),ackId:e.ackId??null,sq:e.sq??null,ep:e.ep??null,rs:e.rs??null,lens:r.map(e=>e.length)};t&&(n.frag=t.id,n.part=t.part,n.parts=t.parts);let i=new TextEncoder().encode(JSON.stringify(n)),s=new Uint8Array(4+i.length+r.reduce((e,t)=>e+t.length,0));new DataView(s.buffer).setUint32(0,i.length,!0),s.set(i,4);let a=4+i.length;for(let e of r)s.set(e,a),a+=e.length;return s}function T(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<4)throw Error("frame too short");let r=4+new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!0);if(r>t.length)throw Error("frame header truncated");let n=JSON.parse(new TextDecoder().decode(t.subarray(4,r))),i=[],s=r;for(let e of n.lens||[]){if(s+e>t.length)throw Error("frame part truncated");i.push(t.subarray(s,s+e)),s+=e}return{event:n.event,args:function e(t,r){if(Array.isArray(t))return t.map(t=>e(t,r));if(t&&"object"==typeof t){if("number"==typeof t.__B)return r[t.__B]??null;let n={};for(let i of Object.keys(t))n[i]=e(t[i],r);return n}return t}(n.args||[],i),ackId:n.ackId??null,sq:n.sq??null,ep:n.ep??null,rs:n.rs??null,frag:n.frag,part:n.part,parts:n.parts}}function x(){let e=new Map;return{push(t){let{frag:r,part:n,parts:i}=t;if(null==r)return t;if(!Number.isInteger(n)||!Number.isInteger(i)||n<0||i<1||n>=i||i>4096)return null;let s=e.get(r);s||(e.size>=4&&e.delete(e.keys().next().value),s={slices:Array(i),got:0},e.set(r,s));let a=t.args?.[0];if(null==a||(!s.slices[n]&&(s.slices[n]=a,s.got++),s.got<i))return null;e.delete(r);let l=new Uint8Array(s.slices.reduce((e,t)=>e+t.byteLength,0)),o=0;for(let e of s.slices)l.set(e,o),o+=e.byteLength;return T(l)}}}var C=r(99022),R=r(30068);let I=null,P=0,$=new Map,D=0;async function M(e,t){let r=`9remote_turn_cache_${t?.slice(0,12)||"anon"}`;try{let e="u">typeof localStorage?localStorage.getItem(r):null;if(e){let t=JSON.parse(e);if(t?.expiresAt>Date.now()&&Array.isArray(t.iceServers)&&t.iceServers.length)return t.iceServers}}catch{}try{let n=await fetch(e,{headers:{"X-API-Key":t},signal:AbortSignal.timeout(4e3)});if(n.ok){let e=await n.json();if(e?.iceServers?.length){try{"u">typeof localStorage&&localStorage.setItem(r,JSON.stringify({iceServers:e.iceServers,expiresAt:Date.now()+828e5}))}catch{}return e.iceServers}}}catch(e){console.warn("[WebRtcProtocol] TURN fetch failed:",e.message)}return null}class L extends i{static #e=this.id="rtc";static #t=this.capabilities={control:!0,binary:!0,file:!0,browser:!0,signaling:"external"};static #r=this.priority={control:50,binary:100,file:100,browser:100};constructor(){super(),this._pc=null,this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._dcMobile=null,this._typeDetail="dc-stun",this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._pendingEmit=null,this._flushTimer=null,this._latestTileTs=new Map,this._hbTimer=null,this._hbLastPing=0,this._hbFastCadence=!1,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._peerEnv2=!1,this._peerFragCtl=!1,this._v2Announced=!1,this._v2RxSeen=!1,this._fragSeq=0,this._reassemble=x(),this._lastInboundAt=0,this._signalingHandlers={},this._signaling=null,this._useTurn=!1}get lastInboundAt(){return this._lastInboundAt}getPriority(e){return"dc-turn"===this._typeDetail?5:150}async connect(e){this._ctx=e,this._cleanupPeer(),this._peerEpoch=(this._peerEpoch??0)+1,this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._hbFastCadence=!1,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._typeDetail="dc-stun",this._lastMid=null,this._remoteGatheringDone=!1,this._setState(n.Of.connecting),this.connectingSince=Date.now(),this.connectDeadline=this.connectingSince+n.AC,clearTimeout(this._connectTimer),this._connectTimer=setTimeout(()=>{this._state!==n.Of.open&&((0,p.c)("transport",`[rtc] connect timeout (${n.AC}ms, state=${this._state}) → close + retry`),this._closePeer(`connect-timeout (state=${this._state})`))},n.AC);let t=[{urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302","stun:stun3.l.google.com:19302","stun:stun4.l.google.com:19302"]},{urls:"stun:global.stun.twilio.com:3478"},{urls:"stun:stun.cloudflare.com:3478"}];if(this._useTurn=!!(e.useTurn||e.profile?.rtc?.enableTurn),e.iceServers?.length)t=e.iceServers;else if(this._useTurn){let r=await M(u.Sn.turnCredentials,e.auth?.apiKey);r?.length&&(t=r)}let r=new RTCPeerConnection({iceServers:t,iceCandidatePoolSize:4,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});this._pc=r;let i=e.profile?.rtc?.dcControl?.ordered??!0,s=r.createDataChannel("control",{ordered:i}),a=r.createDataChannel("binary",{ordered:!1,maxPacketLifeTime:500}),l=r.createDataChannel("file",{ordered:!0}),o=r.createDataChannel("mobile",{ordered:!0}),c=r.createDataChannel("browser",{ordered:!1,maxPacketLifeTime:500});a.binaryType="arraybuffer",s.binaryType="arraybuffer",l.binaryType="arraybuffer",o.binaryType="arraybuffer",c.binaryType="arraybuffer",this._dcControl=s,this._dcBinary=a,this._dcFile=l,this._dcMobile=o,this._dcBrowser=c;let d=async()=>{if("open"!==s.readyState||"open"!==a.readyState)return;let e="";try{let t=await r.getStats();t.forEach(r=>{if("candidate-pair"===r.type&&"succeeded"===r.state){let n=[...t.values()].find(e=>e.id===r.localCandidateId),i=[...t.values()].find(e=>e.id===r.remoteCandidateId);(n?.candidateType==="relay"||i?.candidateType==="relay")&&(this._typeDetail="dc-turn");let s=n?.address||n?.ip||"",a=i?.address||i?.ip||"";("127.0.0.1"===s||"::1"===s||"127.0.0.1"===a||"::1"===a)&&(this._isLoopback=!0),e=`local=${n?.candidateType}/${n?.protocol} remote=${i?.candidateType}/${i?.protocol}`}})}catch{}this.send(n.l_.control,{event:"rtc:linkType",args:[this._typeDetail]}),(0,p.c)("transport",`[rtc] dc OPEN type=${this._typeDetail} ${e}`),(0,f.Lq)("switch",`rtc dc OPEN (${this._typeDetail} ${e})`),clearTimeout(this._connectTimer),this._connectTimer=null,this._everOpened=!0,this._lastInboundAt=Date.now(),this._setState(n.Of.open)};s.onopen=d,a.onopen=d;let h=()=>{let e=!this._dcControl||"closed"===this._dcControl.readyState,t=!this._dcBinary||"closed"===this._dcBinary.readyState;(0,f.Lq)("switch",`rtc dc-close (ctrl=${this._dcControl?.readyState} bin=${this._dcBinary?.readyState})`),e&&t?this._setState(n.Of.closed):this._setState(n.Of.degraded)};s.onclose=h,a.onclose=h,l.onclose=()=>{this._dcFile=null},o.onclose=()=>{this._dcMobile=null},c.onclose=()=>{this._dcBrowser=null},s.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcControl ERROR:",t)},a.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcBinary ERROR:",t)},l.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcFile ERROR:",t)},s.onmessage=e=>{let t,{data:r}=e;this._lastInboundAt=Date.now();try{let e;if("string"==typeof r)e=JSON.parse("string"==typeof r?r:new TextDecoder().decode(r),v);else e=T(r),this._v2RxSeen||(this._v2RxSeen=!0,(0,f.Lq)("switch","env2: first v2 binary frame DECODED from agent (mutual upgrade confirmed)"));t=this._reassemble.push(e)}catch(e){console.error("[rtc] control parse error:",e.message);return}if(t){if("__ping"===t.event){this._hbTimer||this._startHeartbeatWatch(),(this._hbLastPing?Date.now()-this._hbLastPing:1/0)<=2*n.KF&&(this._hbFastCadence=!0),this._hbLastPing=Date.now();try{s.send(A({event:"__pong",args:t.args||[]}))}catch{}return}this._emit("message",{event:t.event,data:t,source:"rtc"})}},a.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._receiveTile(t,"tiles-data")},c.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._receiveTile(t,"browser:tiles-data")},l.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._emit("binary",{channel:"file",buffer:t,source:"rtc"})},o.onmessage=e=>{let{data:t}=e;this._lastInboundAt=Date.now(),t instanceof ArrayBuffer&&this._emit("binary",{channel:"mobile",buffer:t,source:"rtc"})},r.onicecandidate=e=>{var t;let{candidate:r}=e;if(!r)return void this._sendSignaling({type:"ice",candidate:"",mid:this._lastMid||"0"});this._lastMid=r.sdpMid;let n=/typ (host|srflx|relay|prflx)/.exec(r.candidate||"");n&&this._localCandidateTypes.add(n[1]);let i=(t=r.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;i&&this._emit("netFingerprint",i),this._sendSignaling({type:"ice",candidate:r.candidate,mid:r.sdpMid})},r.oniceconnectionstatechange=()=>{(0,p.c)("transport",`[rtc] iceState=${r.iceConnectionState}`),(0,f.Lq)("switch",`rtc ice=${r.iceConnectionState} types=[${[...this._localCandidateTypes].join(",")}]`),"checking"===r.iceConnectionState&&(this._iceReachedChecking=!0),"disconnected"===r.iceConnectionState?this._setState(n.Of.degraded):"failed"===r.iceConnectionState?this._closePeer("ice-failed"):"connected"===r.iceConnectionState&&this._dcControl?.readyState==="open"&&this._dcBinary?.readyState==="open"&&this._setState(n.Of.open)},this._signaling=e.signaling,this._signaling?.on?.(e=>this._handleSignal(e));try{let e=await r.createOffer();await r.setLocalDescription(e),(0,p.c)("transport","[rtc] offer sent"),(0,f.Lq)("switch","rtc offer sent"),this._sendSignaling({type:"offer",sdp:e.sdp,useTurn:this._useTurn})}catch(e){console.error("[rtc] createOffer error:",e.message),this._closePeer(`create-offer:${e.message}`)}}disconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";this._closePeer(`manual-disconnect by=${e} state=${this._state}`),this._signaling?.off?.(),this._signaling=null}send(e,t){if(e===n.l_.control){if(this._dcControl?.readyState!=="open")return!1;let e={event:t.event,args:t.args||[],ackId:t.ackId||null,sq:t.sq??null,ep:t.ep??null,rs:t.rs??null},r=this._sendControlStallChecked(this._dcControl,e);return r&&this._peerEnv2&&!this._v2Announced&&(this._v2Announced=!0,(0,f.Lq)("switch","env2: client→agent control now SENT as v2 binary frames")),r}if(e===n.l_.binary){if(this._dcBinary?.readyState!=="open")return!1;try{return this._dcBinary.send(t),!0}catch(e){return console.error("[rtc] send binary error:",e.message),!1}}if(e===n.l_.file){if(this._dcFile?.readyState!=="open")return!1;try{if(this._dcFile.bufferedAmount>n.HE.dcBufferThreshold)return!1;return this._dcFile.send(t),!0}catch(e){console.error("[rtc] send file error:",e.message)}}return!1}_sendControlStallChecked(e,t){let r,i=e.bufferedAmount;if(i>0&&i>=this._dcPrevQueued){0===this._dcStallCount&&(this._dcStallSince=Date.now()),this._dcStallCount++;let e=Date.now()-this._dcStallSince;if(this._dcStallCount>=n.fP&&e>=n.b4)return this._closePeer(`dc-drain-stall (${i}B stuck ${e}ms)`),!1}else this._dcStallCount=0;if(this._peerEnv2)r=this._sendFramed(t);else try{e.send(A(t)),r=!0}catch(e){r=!1}return this._dcPrevQueued=e.bufferedAmount,r}get typeDetail(){return this._typeDetail}get isLoopback(){return this._isLoopback}_closePeer(e){(0,f.Lq)("switch",`rtc→closed reason=${e}`),this._cleanupPeer(),this._setState(n.Of.closed)}setPeerCaps(e){this._peerEnv2=!!e?.env2,this._peerFragCtl=!!e?.fragCtl}get maxControlBytes(){return this._pc?.sctp?.maxMessageSize||n.dT}_sendFramed(e){var t;let r,n,i=this._peerFragCtl?this.maxControlBytes:1/0,s=(t=++this._fragSeq,(n=function(e,t){if(e.byteLength<=t)return[e];let r=t-192;if(r<=0)return null;let n=Math.ceil(e.byteLength/r);if(n>4096)return null;let i=[];for(let t=0;t<n;t++)i.push(e.subarray(t*r,Math.min((t+1)*r,e.byteLength)));return i}(r=S(e),i))?1===n.length?[r]:n.map((r,i)=>S({event:e.event,args:[r]},{id:t,part:i,parts:n.length})):null);if(!s)return!1;try{for(let e of s)this._dcControl.send(e);return!0}catch(e){return(0,p.c)("transport",`[rtc] control send refused: ${e.message}`),!1}}_startHeartbeatWatch(){this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),this._hbLastPing=Date.now(),this._hbTimer=setInterval(()=>{if(this._state!==n.Of.open){clearInterval(this._hbTimer),this._hbTimer=null;return}let e=Date.now()-this._hbLastPing;e>(this._hbFastCadence?n.An:n.mk)&&((0,p.c)("transport",`[rtc] heartbeat: no ping for ${e}ms → closing stalled peer`),this._closePeer(`heartbeat-stale (${e}ms)`))},n.KF)}async _addRemoteCandidate(e){let{candidate:t,mid:r}=e;t||(this._remoteGatheringDone=!0),await this._pc.addIceCandidate(new RTCIceCandidate(t?{candidate:t,sdpMid:r}:{candidate:"",sdpMid:r||"0"})).catch(()=>{})}_startDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=setInterval(async()=>{if(this._state===n.Of.open||!this._pc)return this._stopDeadPathWatch();if(!this._remoteGatheringDone||"complete"!==this._pc.iceGatheringState)return;let e=0,t=0;try{(await this._pc.getStats()).forEach(r=>{"candidate-pair"===r.type&&(e++,"failed"===r.state&&t++)})}catch{return}e&&!(t<e)&&(this._stopDeadPathWatch(),this._closePeer(`dead-path (${t} pair(s) failed)`))},n.QS)}_stopDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=null}_sendSignaling(e){this._signaling?.send?.(e)}async _handleSignal(e){if((0,p.c)("transport",`[rtc] signal: ${e.type}`),(0,f.Lq)("switch",`rtc signal recv=${e.type}`),this._pc)try{if("answer"===e.type){if(this._answerApplied||"stable"===this._pc.signalingState){(0,p.c)("transport","[rtc] duplicate answer ignored"),(0,f.Lq)("switch","rtc duplicate answer ignored");return}if(e.pub&&e.sig){let t=await this._verifyHostAnswer(e);if(t){console.error(`[rtc] host key verification FAILED (${t}) — relayed answer rejected`),this._closePeer(`host-key-rejected:${t}`);return}}await this._pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp})),this._answerApplied=!0,(0,p.c)("transport","[rtc] answer set"),(0,f.Lq)("switch","rtc answer applied");let t=this._pendingCandidates;for(let e of(this._pendingCandidates=[],t))await this._addRemoteCandidate(e);clearTimeout(this._connectTimer),this.connectDeadline=Date.now()+n.HJ,this._startDeadPathWatch(),this._connectTimer=setTimeout(async()=>{if(this._state!==n.Of.open){try{let e=await this._pc.getStats();e.forEach(t=>{if("candidate-pair"!==t.type)return;let r=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId),i=(r?.address||r?.ip||"?").split(":")[0].slice(-12),s=n?.address||n?.ip||"?";(0,f.Lq)("switch",`pair ${t.state} ${r?.candidateType}:${i}→${n?.candidateType}:${s}`)})}catch{}this._closePeer(`ice-timeout (state=${this._state})`)}},n.HJ)}else if("ice"===e.type){if(!this._answerApplied)return void this._pendingCandidates.push(e);await this._addRemoteCandidate(e)}else"error"===e.type&&((0,p.c)("transport",`[rtc] server error: ${e.message}`),this._closePeer(`server-error:${e.message}`))}catch(e){console.error("[rtc] signal handle error:",e.message)}}async _verifyHostAnswer(e){let t=this._ctx?.auth?.apiKey;if(!t)return null;let r=(0,C.lz)(t),n=r?.hostPubKey?r:null,i=!!r?.hostSealKey;if((0,p.c)("auth","[seal] verify answer:",{hostSentXpub:!!e.xpub,agentSentXpub:!!e.xpub,pinned:!!n,stalePin:!!(r?.hostPubKey&&!i),pendingFp2:(0,C.e1)()}),n){if(n.hostPubKey!==e.pub){let r=(0,C.e1)();return r&&await (0,C.t8)(e.pub,e.xpub)===r?((0,C.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:r}),(0,p.c)("transport","[rtc] host key re-pinned via fresh pairing fp2"),null):((0,p.c)("auth","[seal] REJECT answer — pinned pub differs (host key rotated?) and no fresh fp2 to re-pin"),"pinned-pub-mismatch")}let r=await (0,C.D5)(e.pub,e.sdp,e.sig);if(!1===r)return(0,p.c)("auth","[seal] REJECT answer — signature invalid (relay tampering?)"),"sig-invalid";if(null===r){if(!i)return(0,p.c)("auth","[seal] REJECT answer — no Ed25519 in browser and pinned fp2 predates sealing"),"no-ed25519-old-pin";let t=await (0,C.t8)(e.pub,e.xpub)===n.fp2;return t||(0,p.c)("auth","[seal] REJECT answer — fp2 fallback mismatch vs pinned",n.fp2),t?null:"fp2-mismatch"}return null}let s=(0,C.e1)();if(s){let r=await (0,C.t8)(e.pub,e.xpub);if(r!==s)return(0,p.c)("auth","[seal] REJECTED — fp2",r,"!= code",s,e.xpub?"":"(agent sent no sealing key — needs the source build)"),(0,C.HY)(),"pairing-fp2-mismatch";(0,C.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:r}),(0,p.c)("auth","[seal] pinned via RTC — fp2",r,"sealing key stored"),(0,p.c)("transport","[rtc] host key pinned via pairing fp2")}return null}natVerdict(){let e=this._localCandidateTypes;return this._everOpened||e.has("relay")?"ok":0===e.size||e.has("srflx")&&(!this._answerApplied||this._iceReachedChecking)?"unknown":"hard"}_cleanupPeer(){for(let e of(clearTimeout(this._connectTimer),this._connectTimer=null,this._stopDeadPathWatch(),this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),[this._dcControl,this._dcBinary,this._dcFile,this._dcMobile]))if(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null;try{e.close()}catch{}}if(this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._dcMobile=null,this._dcStallCount=0,this._dcStallSince=0,this._dcPrevQueued=0,this._isLoopback=!1,this._typeDetail="dc-stun",this._pc){this._pc.onicecandidate=null,this._pc.oniceconnectionstatechange=null;try{this._pc.close()}catch{}this._pc=null}this._pendingEmit=null,this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null),this._latestTileTs.clear(),this._reassemble=x()}_receiveTile(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"tiles-data",n=++P,i=e.byteLength;new Promise(t=>{let i=setTimeout(()=>{$.has(n)&&($.delete(n),t(null))},8e3),s=R.eR.decodeQueueCap;for(;$.size>=s;){let e=$.keys().next().value,t=$.get(e);if(!t)break;clearTimeout(t.timer),$.delete(e),t.resolve(null)}let a=function(){if(!1===I)return null;if(I)return I;try{I=new Worker(r.tu(new URL(r.p+r.u(6153),r.b)))}catch{return I=!1,null}return I.onmessage=e=>{let{data:{tiles:t,timestamp:r,id:n,hasBitmap:i,error:s}}=e;D=0;let a=$.get(n);if(!a){if(t)for(let e of t)e.bitmap?.close?.();return}clearTimeout(a.timer),$.delete(n),a.resolve(s?null:{tiles:t,timestamp:r,hasBitmap:i})},I.onerror=e=>{console.error("[Worker] tileDecoder:",e.message),function(){if(I)try{I.terminate()}catch{}for(let{resolve:e}of(I=null,$.values()))try{e(null)}catch{}$.clear()}(),++D>=3&&(I=!1)},I}();if(!a){clearTimeout(i),$.delete(n),t(null);return}$.set(n,{resolve:t,timer:i}),a.postMessage({buffer:e,id:n,v:2},[e])}).then(e=>{if(!e)return;let{tiles:r,timestamp:n,hasBitmap:s}=e;this._pendingEmits??=new Map,this._latestTsMaps??=new Map;let a=this._pendingEmits.get(t);a||(a={tiles:new Map,timestamp:n,hasBitmap:s,bytes:0},this._pendingEmits.set(t,a));let l=this._latestTsMaps.get(t);for(let e of(l||(l=new Map,this._latestTsMaps.set(t,l)),a.bytes+=i,r))n>=(l.get(e.tileIndex)??0)?(l.set(e.tileIndex,n),a.tiles.get(e.tileIndex)?.bitmap?.close?.(),a.tiles.set(e.tileIndex,e),n>a.timestamp&&(a.timestamp=n)):e.bitmap?.close?.();this._flushTimers??=new Map,this._flushTimers.has(t)&&clearTimeout(this._flushTimers.get(t));let o=setTimeout(()=>{this._flushTimers.delete(t);let e=this._pendingEmits.get(t);if(!e)return;this._pendingEmits.delete(t);let r=[...e.tiles.values()];r.length&&this._emit("message",{event:t,data:{tiles:r,timestamp:e.timestamp,hasBitmap:e.hasBitmap,bytes:e.bytes,transport:this._typeDetail},source:"rtc"})},0);this._flushTimers.set(t,o)})}}let O=new Map;function q(e){if(!e?.id)throw Error("Adapter missing static id");O.set(e.id,e)}function U(){let{urls:e,timeoutMs:t,PeerConnection:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=r||("u">typeof RTCPeerConnection?RTCPeerConnection:null);if(!i)return Promise.resolve(null);let s=[{urls:e||n.cx.urls}];return new Promise(e=>{let r,a,l=!1,o=t=>{if(!l){l=!0,clearTimeout(a);try{r.onicecandidate=null,r.close()}catch{}e(t)}};try{r=new i({iceServers:s,iceCandidatePoolSize:0})}catch{return e(null)}a=setTimeout(()=>o(null),t??n.cx.timeoutMs),r.onicecandidate=e=>{var t;let{candidate:r}=e;if(!r)return o(null);let n=(t=r.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;n&&o(n)};try{r.createDataChannel("probe"),r.createOffer().then(e=>r.setLocalDescription(e)).catch(()=>o(null))}catch{o(null)}})}let E="no-public-ip";function B(e){let t=0,r=!1;for(let n of e.values())"candidate-pair"===n.type&&(n.nominated||n.selected)&&(r=!0,t+=(n.bytesReceived??0)+(n.responsesReceived??0));return r?t:null}function N(e){let{connectingSince:t,connectDeadline:r,connectTimeoutMs:n}=e;return r??(t??0)+n}function j(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"stale",r=e._adapters.get("ws"),i=Math.max(r?.lastInboundAt??0,r?.lastMsgAt??0),s=r?.ready&&function(){let{ready:e=!0,lastInboundAt:t=0,now:r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return!!e&&(!t||r-t>=n.Rh)}({ready:!0,lastInboundAt:i,now:Date.now()});if(r){let e=r.lastInboundAt??0,n=r.lastMsgAt??0,i=Date.now();(0,f.Lq)("switch",`zombie check (${t}): verdict=${!!s} ready=${!!r.ready} lastPong=${e?`${i-e}ms`:"never"} lastMsg=${n?`${i-n}ms`:"never"}`)}if(!s)return!1;(0,p.c)("transport",`[pm] ws zombie (${t}) → force reconnect`);try{r.forceReconnect?.()}catch{}return!0}function F(e,t){let r=e._adapters.get("rtc"),i=r?._pc;if(!i||"failed"===i.connectionState)return void e._forceRestartRtc(`${t}-pc-failed`);if(e._probeLive?.rtc===r)return void(0,f.Lq)("switch",`${t} probe shared (already measuring this peer)`);clearTimeout(e._resumeProbeTimer);let s=++e._probeToken;e._probeLive={rtc:r,token:s},(async()=>{let t=B(await i.getStats());return null==t||(await new Promise(t=>{e._resumeProbeTimer=setTimeout(t,n.UT)}),s!==e._probeToken)?null:B(await i.getStats())-t})().then(i=>{if(s!==e._probeToken)return;let a=r?.lastInboundAt&&Date.now()-r.lastInboundAt<n.mk;null!=i&&i>0||a?(0,f.Lq)("switch",`${t} probe alive (Δ=${i}, recent=${!!a})`):((0,f.Lq)("switch",`${t} probe DEAD (Δ=${i}) → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-dead`))}).catch(()=>{s!==e._probeToken||(r?.lastInboundAt&&Date.now()-r.lastInboundAt<n.mk?(0,f.Lq)("switch",`${t} probe error ignored (rtc recently active)`):((0,f.Lq)("switch",`${t} probe error → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-error`)))}).finally(()=>{e._probeLive?.token===s&&(e._probeLive=null)})}let W="__env",K="__gap",H="__gapmiss";function z(e){let t=e._pickAdapter(n.l_.control);if(t)for(let r of e._outLog.unsentList()){if(!J(e,t,r))return;e._outLog.markSent(r.sq)}}function J(e,t,r){let i={event:r.event,args:r.args||[],ackId:r.ackId??null,sq:r.sq??null,ep:e._seqEpoch,rs:e._intakeSeq.applied};if("ws"===t.constructor.id){if(!e._peerSeqCtl){let i=r.ackId?function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return G(e,r.ackId,n)}:null;return t.send(n.l_.control,i?{event:r.event,args:r.args,cb:i}:{event:r.event,args:r.args})}return t.send(n.l_.control,{event:W,args:[i]})}return t.send(n.l_.control,i)}function G(e,t,r){let i=e._pendingAcks.get(t);if(!i)return;let s=e._ackReqs?.get(t);if(r?.[0]?.error===n.dE&&s&&s.tries<n.mH.admitRetryMax){s.tries++,e._admitQueue.includes(t)||e._admitQueue.push(t),(0,f.Lq)("switch",`not-admitted ${s.event} → hold for re-admission (try ${s.tries})`),Z(e,"ack");return}Number.isInteger(s?.sq)&&e._outLog.markAcked(s.sq),e._ackReqs?.delete(t),e._pendingAcks.delete(t);let a=e._ackTimers.get(t);a&&(clearTimeout(a),e._ackTimers.delete(t)),i(...r||[])}function V(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;e._outLog.append({event:t,args:void 0===r?[]:[r],ackId:n}),z(e)}function Z(e,t){let r=Date.now();if(r-e._admitKickAt<n.mH.admitKickMinMs)return;e._admitKickAt=r;let i=e._adapters.get("ws");if((0,f.Lq)("switch",`admission stale (${t}) → re-dial ${i?"ws":"rtc"}`),i?.forceReconnect){try{i.forceReconnect()}catch{}return}e._forceRestartRtc?.("not-admitted")}let Q=new Set(["getSessions","getWorkspaces","bg:get","bg:list","ai:create","ai:peekSeq","aiSince"]),X=new Set(["ai:prompt"]);function Y(e,t){if(t?.type!=="error")return!1;let r=t.message===n.bg.pending?"pending":t.message===n.bg.rejected?"rejected":null;return!!r&&((0,p.c)("transport",`[pm] device ${r} → approval UI`),e._awaitingApproval=!0,e._wsCallbacks.onApproval?.(r),!0)}function ee(e){if((0,f.Lq)("switch","signaling ready"),er(e),e._awaitingApproval)return;let t=e._adapters.get("rtc");if(!t){(0,f.Lq)("switch","sig-ready → start rtc (was deferred)"),e._startSecondaryAdapters();return}t.state===n.Of.closed&&((0,f.Lq)("switch","sig-ready → restartRtc (rtc was closed)"),e._restartRtc("sig-ready"))}function et(e,t){!(e._sig?.ready&&e._sig.send(t))&&("offer"===t.type&&(e._sigBuffer=e._sigBuffer.filter(e=>"offer"!==e.type&&"ice"!==e.type)),e._sigBuffer.push(t),e._sigBuffer.length>32&&e._sigBuffer.shift())}function er(e){if(!e._sigBuffer.length)return;let t=e._sigBuffer;for(let r of(e._sigBuffer=[],t))et(e,r)}async function en(e){if(e._auth.tunnelUrl!==window.location.origin)try{(0,p.c)("transport",`[pm] refreshTunnelUrl: fetching from ${u.O}/api/connect`);let t=await fetch(`${u.O}/api/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e._auth.apiKey})});if(!t.ok){(0,p.c)("transport",`[pm] refreshTunnelUrl: HTTP ${t.status}`);let r=await t.json().catch(()=>({}));503===t.status&&r?.error==="agent-offline"&&e._wsCallbacks.onHostOffline?.();return}let r=await t.json();(0,p.c)("transport",`[pm] refreshTunnelUrl: got ${r.tunnelUrl} (was ${e._auth.tunnelUrl})`),r.tunnelUrl&&r.tunnelUrl!==e._auth.tunnelUrl&&(e._auth.tunnelUrl=r.tunnelUrl)}catch(e){(0,p.c)("transport",`[pm] refreshTunnelUrl: error ${e.message}`)}}q(w),q(L);class ei{constructor(e,t){const{profile:r,auth:i,wsCallbacks:s,rtcCallbacks:a,peerId:l}=function(e,t){let r=t?.enableWebRTC?"remoteDesktop":"clientApp",i={...n.j3[r]};t?.enableWebRTC||(i.enabled=["ws"]),t?.enableTurn&&(i.rtc={...i.rtc,enableTurn:!0});let s={tunnelUrl:e.tunnelUrl,localIp:e.localIp,apiKey:e.apiKey,tempKey:e.tempKey,deviceId:e.deviceId,namespace:e.namespace,socketOptions:e.socketOptions},a={onConnect:e.onConnect,onDisconnect:e.onDisconnect,onRetryStatus:e.onRetryStatus,onUrlUpdate:e.onUrlUpdate,onApproval:e.onApproval,onHostOffline:e.onHostOffline},l=t?{onUpgrade:t.onUpgrade,onFallback:t.onFallback,onTransportChange:t.onTransportChange}:{},o=`${e.deviceId}:${Math.random().toString(36).slice(2,10)}`;return s.socketOptions?.auth&&(s.socketOptions.auth.peerId=o),{profile:i,auth:s,wsCallbacks:a,rtcCallbacks:l,peerId:o}}(e,t);for(const e of(this._profile=r,this._auth=i,this._wsCallbacks=s,this._rtcCallbacks=a,this._peerId=l,Object.assign(this,{_adapters:new Map,_pendingAcks:new Map,_ackTimers:new Map,_ackSeq:0,_rtcRestartAttempts:0,_rtcRestartTimer:null,_rtcRestartDueAt:0,_probeAttempts:0,_rtcGivenUp:!1,_giveUpIp:null,_lastStunProbeAt:0,_rejoinDebounceTimer:null,_netFingerprint:null,_awaitingApproval:!1,_ackTimeoutMs:n.QZ.ackTimeoutMs,_wsCarryUntil:0,_hiddenAt:null,_resumeProbeTimer:null,_probeToken:0,_probeLive:null,_connected:!1,_type:"ws",_connectionMode:"tunnel",_lastWsState:null,_rawSocket:null,_onConnectFired:!1,_rtcSignalingHandler:null,_sig:null,_sigDestroyed:!1,_sigBuffer:[],_wsFallbackTimer:null,_peerSeqCtl:!1,_ackReqs:new Map,_admitQueue:[],_admitKickAt:0,_seqEpoch:Date.now().toString(36)+Math.random().toString(36).slice(2,8),_outLog:function(e){let{maxBytes:t,maxEntries:r,maxReplayEntries:n=512}=e,i=new Map,s=new Set,a=1,l=1,o=1,c=0,d=0,u=0,h=e=>128+function(e){if(!Array.isArray(e))return 256;let t=64;for(let r of e)null!=r&&("string"==typeof r?t+=r.length:ArrayBuffer.isView(r)||"Buffer"===r.type?t+=r.length||256:"object"==typeof r?t+=512:t+=8);return t}(e.args),p=e=>{let t=[];for(let r=e;r<a;r++){let e=i.get(r);e&&t.push({...e,sq:r})}return t};return{get nextSeq(){return a},get applied(){return c},get droppedUnsent(){return u},append(e){let n=a++,c={event:e.event,args:e.args,ackId:e.ackId??null};for(i.set(n,c),d+=h(c);i.size>1&&(d>t||i.size>r);){let e=i.get(l);if(!e){l++;continue}i.delete(l),s.delete(l),d-=h(e),l>=o&&u++,l++}return{...c,sq:n}},setApplied(e){Number.isInteger(e)&&e>c&&(c=e)},markSent(e){Number.isInteger(e)&&!(e<o)&&(o=e+1)},markAcked(e){Number.isInteger(e)&&e>=l&&s.add(e)},range(e,t){if(!Number.isInteger(e)||!Number.isInteger(t)||e<l||t>=a||t<e)return null;let r=[];for(let n=e;n<=t;n++){let e=i.get(n);if(!e)return null;r.push({...e,sq:n})}return r},unsentList:()=>p(Math.max(o,l)),replayList(){let e=Math.max(c+1,l,a-n);return s.size?p(e).filter(e=>!s.has(e.sq)):p(e)},clear(){i.clear(),s.clear(),a=1,l=1,o=1,c=0,d=0,u=0}}}({maxBytes:n.mH.ringMaxBytes,maxEntries:n.mH.maxEntries}),_intakeSeq:null}),this._intakeSeq=function(e){return function(e){let{holdMax:t,gapDeadlineMs:r,deliver:n,requestGap:i,onLoss:s,onDupe:a,schedule:l=setTimeout,clearFn:o=clearTimeout}=e,c=!1,d=null,u=!1,h=0,p=0,f=new Map,m=null,g=0,y=!1,_=()=>f.size?Math.min(...f.keys()):1/0,b=()=>{for(;f.size;){let e=f.get(h+1);if(!e)break;f.delete(h+1),h++,n(e)}},w=()=>{let e=_()-1;e>h&&(s&&s(h+1,e),h=e),g=0,b(),k()},k=()=>{if(!f.size){m&&(o(m),m=null),g=0;return}let e=h+1,t=_()-1;!(e>t)&&(g!==e&&(g=e,i(e,t)),m||y||(m=l(()=>{m=null,!y&&f.size&&w()},r)))};return{get armed(){return c},get applied(){return h},get maxSeen(){return p},arm(){c=!0,h=p},push(e){(e=>{if(null!=e&&e!==d){if(null===d){d=e;return}d=e,h=0,f.clear(),g=0,m&&(o(m),m=null)}})(e?.ep);let r=e?.sq;if(!c||!Number.isInteger(r)){Number.isInteger(r)&&r>p&&(p=r),n(e);return}if(r>p&&(p=r),!u&&(u=!0,r>h+1&&(h=r-1)),r<=h){a&&a(r);return}if(r===h+1){h++,n(e),b(),k();return}(f.set(r,e),f.size>t)?w():k()},gapMissed(e){c&&e===h+1&&w()},setPaused(e){y=e,e&&m&&(o(m),m=null),!e&&f.size&&(g=0,k())},reset(){c=!1,d=null,u=!1,h=0,p=0,f.clear(),g=0,m&&(o(m),m=null)}}}({holdMax:n.mH.holdMax,gapDeadlineMs:n.mH.gapDeadlineMs,deliver:t=>(function(e,t){switch(t.event){case"__ack":var r;return void G(e,(r=t).ackId,r.args);case K:return function(e){let{from:t,to:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._outLog.range(t,r);if(!i)return void V(e,H,{from:t});let s=e._pickAdapter(n.l_.control);if(s){for(let t of i)if(!J(e,s,t))break}}(e,t.args?.[0]);case H:return e._intakeSeq.gapMissed(t.args?.[0]?.from)}if(t.ackId&&e._pendingAcks.has(t.ackId))return G(e,t.ackId,t.args);!function(e,t){let{event:r}=t,i=Array.isArray(t.args)?t.args:[];if("srvCaps"===r){let r=i[0]??t;(0,p.c)("transport",`[pm] srvCaps from host: ${JSON.stringify(r)}`),e._srvCaps=r||{},r?.seqCtl&&!e._peerSeqCtl&&(e._peerSeqCtl=!0,(0,f.Lq)("switch","host announced seqCtl → sequenced control stream active")),e._adapters.get("rtc")?.setPeerCaps?.(e._srvCaps);return}if("conn:notAdmitted"===r)return Z(e,"notice");if("device:approved"===r){e._awaitingApproval=!1;let t=e._admitQueue.splice(0);if(t.length){for(let r of((0,f.Lq)("switch",`re-admitted → re-send ${t.length} held request(s)`),t)){let t=e._ackReqs.get(r);if(!t||!e._pendingAcks.has(r))continue;let n=e._outLog.append({event:t.event,args:t.args,ackId:r});t.sq=n.sq}z(e)}let r=e._adapters.get("rtc");e._canSignal()&&(!r||r.state===n.Of.closed)&&e._restartRtc("device-approved")}if("rtc:enabled"===r){e._rtcTestDisabled&&(e._rtcTestDisabled=!1,(0,f.Lq)("switch","rtc:enabled by host → clear flag + restart RTC"),e._restartRtc("rtc-enabled"));return}"tunnel:updated"===r?function(e,t){if(!t)return;let{tunnelUrl:r,localIp:n,status:i}=t;if(e._auth.tunnelUrl===window.location?.origin)return(0,f.Lq)("switch",`tunnel:updated ignored (carrier is the page origin; got url=${r||"none"})`);if((0,f.Lq)("switch",`tunnel:updated recv (status=${i} url=${r||"none"})`),"ready"===i&&r){let t=e._auth.tunnelUrl!==r;e._auth.tunnelUrl=r,n&&(e._auth.localIp=n),e._wsCallbacks.onUrlUpdate?.({tunnelUrl:r,localIp:n});let i=e._adapters.get("ws");if(i&&(!i.ready||t)){(0,f.Lq)("switch",`tunnel:updated → ${t?"url changed":"ws not ready"} → retry ws with new URL`);try{i.retryNow("tunnel-updated")}catch{}}}else"down"===i&&(e._auth.tunnelUrl="",e._wsCallbacks.onUrlUpdate?.({tunnelUrl:"",localIp:n}))}(e,i[0]):e._bus?.dispatch(r,i)}(e,t)})(e,t),requestGap:(t,r)=>e._sendStreamEvent(K,{from:t,to:r}),onLoss:(t,r)=>{e._seqLosses=(e._seqLosses||0)+1,(0,f.Lq)("switch",`seq skipped ${t}..${r} (ring evicted)`)},onDupe:()=>{e._seqDupes=(e._seqDupes||0)+1}})}(this),this._bus=function(e){let t=new Map,r=(e,r)=>{t.has(e)||t.set(e,[]),t.get(e).push(r)},n=(e,r)=>{let n=t.get(e);if(!n)return;let i=n.findIndex(e=>e===r||e._original===r);-1!==i&&n.splice(i,1)};return{_listeners:t,get connected(){return e._anyAdapterReady()},get hostCaps(){return e._srvCaps||{}},get id(){return e._rawSocket?.id||null},emit(t){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];e._sendControl(t,n)},on(e,t){r(e,t)},off(e,t){n(e,t)},once(e,t){let i=function(){for(var r=arguments.length,s=Array(r),a=0;a<r;a++)s[a]=arguments[a];n(e,i),t(...s)};i._original=t,r(e,i)},listeners:e=>[...t.get(e)||[]],dispatch(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=t.get(e);if(n?.length){for(let e of[...n])if(n.includes(e))try{e(...r)}catch{}}},clear(){t.clear()},disconnect(){e._rawSocket?.disconnect()},kickWsZombie:t=>e.kickWsZombie(t)}}(this),this.busRef={current:this._bus},C.IU))this._bus.on(e,t=>(0,C.lu)(this,e,t));this._watchers=function(e){let t=()=>{let t;if((0,f.Lq)("switch",`visibility=${document.visibilityState}`),"visible"!==document.visibilityState)return;let r=e._adapters.get("ws"),i=e._adapters.get("rtc");if((0,f.Lq)("switch",`resume check: ws=${r?.ready?"ready":r?.state} rtc=${i?.ready?"ready":i?.state}`),j(e,"resume"),e._awaitingApproval)return;if(e._rtcGivenUp)return void e._maybeRearmRtc();t=e._rtcRestartTimer?Math.max(e._rtcRestartDueAt-Date.now(),0):-1,(0,f.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) reason=resume pendingIn=${t}ms`),e._rtcRestartAttempts=0,e._probeAttempts=0,t<=n.QZ.backoffMs[0]||((0,f.Lq)("switch",`resume: pending rung was ${t}ms out → re-arm fast`),e._disarmRestart(),e._scheduleRtcRestart("resume-rearm"));let s=i?.state;i&&s!==n.Of.closed&&s!==n.Of.degraded?function(e){let t=e._adapters.get("rtc");if(!t?.ready)return e._restartRtc("resume-not-ready");let r=e._hiddenAt?Date.now()-e._hiddenAt:0;if("function"==typeof matchMedia&&matchMedia("(pointer: coarse)").matches&&r>n.Tr){(0,f.Lq)("switch",`resume: hidden ${Math.round(r/1e3)}s on touch → skip probe, force restart`),(0,p.c)("transport",`[pm] resume: hidden ${Math.round(r/1e3)}s → immediate restart`),e._forceRestartRtc("resume-hidden-touch");return}F(e,"resume")}(e):((0,f.Lq)("switch",`visibility → restartRtc (rtc=${s||"absent"})`),e._restartRtc("resume-dead-rtc")),e._canSignal()||e._sig?.retryNow("resume-no-carrier")},r=()=>{if("hidden"===document.visibilityState){e._hiddenAt=Date.now();return}clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=setTimeout(t,150)};document.addEventListener("visibilitychange",r);let i=!1,s=r=>{let n=!!r.detail?.hidden;if(n!==i){if(i=n,n){e._hiddenAt=Date.now();return}clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=setTimeout(t,150)}};document.addEventListener("app-visibility",s);let a=()=>{"visible"===document.visibilityState&&r()},l=()=>{e._hiddenAt=Date.now()};document.addEventListener("resume",a),document.addEventListener("freeze",l);let o=()=>{clearTimeout(e._netDebounceTimer),e._netDebounceTimer=setTimeout(()=>{!1===navigator.onLine?(0,f.Lq)("switch","net-change: still offline → wait"):((0,p.c)("transport","[pm] network change → probe rtc"),(0,f.Lq)("switch",`net-change: online=${navigator.onLine} → kick sig + ws + rtc`),e._sig?.retryNow("net-change"),e.retryNow("net-change"),(0,f.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) givenUp=${e._rtcGivenUp} reason=net-change`),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._shouldRenegotiate()&&e._restartRtc("net-change"))},n.o_.debounceMs)};return window.addEventListener("online",o),navigator.connection?.addEventListener?.("change",o),{visibilityHandler:r,detach(){document.removeEventListener("visibilitychange",r),document.removeEventListener("app-visibility",s),document.removeEventListener("resume",a),document.removeEventListener("freeze",l),window.removeEventListener("online",o),navigator.connection?.removeEventListener?.("change",o),clearTimeout(e._netDebounceTimer),e._netDebounceTimer=null,clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=null}}}(this)}get type(){return this._type}get connected(){return this._connected}get connectionMode(){return this._connectionMode}get wsBlocked(){return this._adapters.get("ws")?.blocked||!1}setWsBlocked(e){this._adapters.get("ws")?.setBlocked(e)}setUpdating(e){this._adapters.get("ws")?.setUpdating(e)}retryNow(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"user",t=this._adapters.get("ws");t?t.retryNow?.(e):((0,f.Lq)("switch",`retryNow by=${e}: no ws adapter → full connect()`),this.connect())}kickWsZombie(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"stale";return j(this,e)}carryControlOnWs(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?",t=this._adapters.get("ws");if(!t?.ready)return!1;let r=this._wsCarryUntil<=Date.now();return(this._wsCarryUntil=Date.now()+n.cO,r)?((0,f.Lq)("switch",`control → WS carry ${n.cO}ms (${e})`),this._flushBuffer(),this._forceRestartRtc(`ws-carry:${e}`)):this._flushBuffer(),!0}emit(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];this._sendControl(e,r)}sendBinary(e,t){let r=this._pickAdapter(e);return!!r&&r.send(e,t)}connect(){this._sigDestroyed=!1;let e=this._profile.enabled.includes("rtc");e&&this._initSignalingClient(),e&&(this._canSignal()?this._startSecondaryAdapters():((0,f.Lq)("switch","rtc deferred — waiting for signaling relay"),clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=setTimeout(()=>{this._sigDestroyed||this._adapters.has("rtc")||((0,f.Lq)("switch","rtc defer expired → start anyway"),this._startSecondaryAdapters())},n.BF))),this._startWsFallback(),(0,p.c)("transport","[pm] connect: RTC + WS parallel (RTC preferred, WS warm standby)."),(0,f.Lq)("switch","connect: RTC + WS parallel")}async _startWsFallback(){if(!(this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)){if((0,f.Lq)("switch","ws-fallback: start (refresh url)"),await this._refreshTunnelUrl(),this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)return void(0,f.Lq)("switch","ws-fallback: aborted (destroyed, loopback or already attached)");(0,f.Lq)("switch","ws-fallback: connecting"),this._instantiate("ws"),this._adapters.get("ws")?.connect(this._buildCtx("ws"))}}async _refreshTunnelUrl(){return en(this)}_initSignalingClient(){!function(e){if(!n.gI.enabled||e._sig||e._sigDestroyed||!e._auth.deviceId||!e._auth.apiKey)return;let t=u.O.replace(/^http/,"ws")+"/signaling";r.e(7489).then(r.bind(r,87489)).then(r=>{let{SignalingClient:i}=r;e._sig||e._sigDestroyed||(e._sig=new i({url:t,role:"client",roomId:e._auth.apiKey,apiKey:e._auth.apiKey,from:e._peerId,onReady:()=>ee(e),pingMs:n.gI.pingMs}),e._sig.on(t=>{if("error"===t.type&&"rtc-disabled"===t.message){e._rtcTestDisabled=!0,(0,f.Lq)("switch","rtc-disabled by host → stop RTC retry (use WS)");return}Y(e,t)||e._rtcSignalingHandler?.(t)}),e._sig.connect())}).catch(e=>(0,p.c)("transport",`[pm] SignalingClient load failed: ${e?.message||e}`))}(this)}_instantiate(e){if(this._adapters.has(e))return;let t=O.get(e);if(!t)return;let r=new t;r.on("stateChange",t=>this._onAdapterStateChange(e,t)),r.on("message",e=>{let{event:t,data:r,source:n}=e;return this._dispatch(t,r,n)}),r.on("binary",e=>this._onBinary(e)),"rtc"===e&&(r.on("netFingerprint",e=>this._onNetFingerprint(e)),this._srvCaps&&r.setPeerCaps?.(this._srvCaps)),this._adapters.set(e,r)}_onNetFingerprint(e){if(!e||e===this._netFingerprint)return;let t=this._netFingerprint;this._netFingerprint=e,t&&(0,p.c)("transport",`[pm] net fingerprint ${t}→${e} (same network — no backoff reset)`)}_maybeRearmRtc(){if(!this._rtcGivenUp)return;let e=Date.now();e-this._lastStunProbeAt<n.cx.minIntervalMs||(this._lastStunProbeAt=e,U().then(e=>{var t;if(this._sigDestroyed||!this._rtcGivenUp)return;let r=e||(this._giveUpIp===E?E:null);(t=this._giveUpIp,r&&(!t||r!==t))?((0,f.Lq)("switch",`rearm check: ip ${this._giveUpIp||"unknown"}→${r} changed → re-arm RTC`),(0,p.c)("transport","[pm] public ip changed → re-arm rtc"),this._rtcGivenUp=!1,this._giveUpIp=null,this._probeAttempts=0,this._rtcRestartAttempts=0,this._netFingerprint=e,this._canSignal())?this._shouldRenegotiate()&&this._restartRtc("stun-rearm"):this._sig?.retryNow("stun-rearm"):(0,f.Lq)("switch",`rearm check: ip=${r||"unknown"} same as give-up → stay WS-only`)}).catch(()=>{}))}_startSecondaryAdapters(){for(let e of((0,p.c)("transport",`[pm] startSecondary enabled=${this._profile.enabled}`),(0,p.c)("transport",`[pm] startSecondary rtcTestDisabled=${!!this._rtcTestDisabled}`),this._profile.enabled))"ws"!==e&&("rtc"!==e||!this._rtcTestDisabled)&&(this._adapters.has(e)||((0,p.c)("transport",`[pm] start adapter ${e}`),this._instantiate(e),this._adapters.get(e)?.connect(this._buildCtx(e))))}_handleApprovalSignal(e){return Y(this,e)}_onSignalingReady(){ee(this)}_canSignal(){return!!this._sig?.ready}_shouldRenegotiate(){return!this._awaitingApproval&&this._canSignal()}_restartRtc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";(0,f.Lq)("switch",`restartRtc CALLED by=${e} attempts=${this._rtcRestartAttempts}`);let t=this._adapters.get("rtc"),r=function(e){let{testDisabled:t,givenUp:r,rtcState:i,hasRtc:s}=e;return t?"skip-test-disabled":r?"skip-given-up":s&&(i===n.Of.connecting||i===n.Of.open)?"skip-in-flight":s?"restart":"start-fresh"}({testDisabled:!!this._rtcTestDisabled,givenUp:this._rtcGivenUp,rtcState:t?.state,hasRtc:!!t});if("skip-test-disabled"===r)return void(0,f.Lq)("switch","restartRtc skipped (rtcTestDisabled)");if("skip-given-up"===r)return void(0,f.Lq)("switch","restartRtc skipped (hard NAT → WS-only)");if("skip-in-flight"===r)return void(0,f.Lq)("switch",`restartRtc skipped (rtc=${t.state})`);if("start-fresh"===r){(0,f.Lq)("switch","restartRtc: no rtc → startSecondary"),this._startSecondaryAdapters();return}(0,f.Lq)("switch","restartRtc: tear down + renegotiate"),(0,p.c)("transport","[pm] ws reconnected → restart rtc");try{t.disconnect(`restart:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null,this._startSecondaryAdapters()}_forceRestartRtc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";(0,f.Lq)("switch",`forceRestartRtc CALLED by=${e}`);let t=this._adapters.get("rtc");if(t){try{t.disconnect(`force:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}this._rtcGivenUp?(0,f.Lq)("switch","forceRestartRtc: torn down, no renegotiate (hard NAT)"):this._startSecondaryAdapters()}disconnect(){this._watchers?.detach(),this._watchers=null,clearTimeout(this._resumeProbeTimer),this._resumeProbeTimer=null,clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=null,this._probeToken++;try{this._sig?.disconnect()}catch{}for(let e of(this._sig=null,this._sigDestroyed=!0,this._sigBuffer=[],clearTimeout(this._wsFallbackTimer),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=null,this._adapters.values()))try{e.disconnect("pm-disconnect")}catch{}for(let[e,t]of(this._adapters.clear(),this._bus.clear(),this._intakeSeq?.reset(),this._outLog?.clear(),this._peerSeqCtl=!1,this._connected=!1,this._rawSocket=null,this._wsCarryUntil=0,this._disarmRestart(),(0,f.Lq)("switch",`RESET attempts (was ${this._rtcRestartAttempts}) reason=pm-disconnect`),this._rtcRestartAttempts=0,this._probeAttempts=0,this._rtcGivenUp=!1,this._giveUpIp=null,this._lastStunProbeAt=0,this._pendingAcks)){try{t({error:"disconnected"})}catch{}let r=this._ackTimers.get(e);r&&clearTimeout(r)}for(let e of(this._pendingAcks.clear(),this._ackReqs?.clear(),this._admitQueue=[],this._ackTimers.values()))clearTimeout(e);this._ackTimers.clear()}_buildCtx(e,t){let r={auth:this._auth,profile:this._profile};return"ws"===e&&(r.onRetryStatus=this._wsCallbacks.onRetryStatus,r.onHostOffline=this._wsCallbacks.onHostOffline,r.onUrlUpdate=e=>{e.tunnelUrl&&(this._auth.tunnelUrl=e.tunnelUrl),void 0!==e.localIp&&(this._auth.localIp=e.localIp),this._wsCallbacks.onUrlUpdate?.(e)}),"rtc"===e&&(r.signaling={send:e=>this._sendSignaling(e),on:e=>{this._rtcSignalingHandler=e},off:()=>{this._rtcSignalingHandler=null}}),r}_onAdapterStateChange(e,t){(0,p.c)("transport",`[pm] ${e} state=${t}`),("rtc"!==e||t!==n.Of.closed)&&(0,f.Lq)("switch",`${e}→${t}`),"ws"===e&&function(e,t){let r=e._adapters.get("ws");if(t===n.Of.open){let t=e._lastWsState===n.Of.degraded;e._connected=!0,e._connectionMode=r?.connectionMode||"tunnel",e._rawSocket=r?.socket||null,t&&e._maybeFireRejoin("ws","ws reconnect while rtc ready"),e._lastWsState!==n.Of.open&&(e._onConnectFired?e._wsCallbacks.onUrlUpdate?.({}):(e._onConnectFired=!0,(0,f.Lq)("switch",`onConnect FIRE (ws, mode=${e._connectionMode})`),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)))}else e._rawSocket=null,e._lastWsState===n.Of.open&&((0,f.Lq)("switch","ws down"),e._anyAdapterReady()&&(0,f.Lq)("switch","ws down but rtc alive → skip onDisconnect"));e._lastWsState=t}(this,t),"rtc"===e&&function(e,t){if(t===n.Of.open){e._wsCarryUntil&&(e._wsCarryUntil=0,(0,f.Lq)("switch","rtc reopened → control back on rtc"));let t=e._onConnectFired;clearTimeout(e._wsFallbackTimer),e._rtcCallbacks.onUpgrade?.(e._adapters.get("rtc")?.typeDetail||"dc-stun"),e._onConnectFired||(e._onConnectFired=!0,e._connected=!0,e._connectionMode="webrtc",(0,f.Lq)("switch","onConnect FIRE (rtc, mode=webrtc)"),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._disarmRestart(),clearTimeout(e._rejoinDebounceTimer),e._rejoinDebounceTimer=null;let r=e._adapters.get("rtc");if(r?.isLoopback){(0,f.Lq)("switch","rtc loopback detected (same machine) → drop ws standby");let t=e._adapters.get("ws");if(t){try{t.disconnect()}catch{}e._adapters.delete("ws")}}t&&e._maybeFireRejoin("rtc","rtc reconnect while ws ready")}t===n.Of.closed&&(e._rtcCallbacks.onFallback?.("ws"),(0,f.Lq)("switch","rtc closed → startWsFallback + scheduleRtcRestart"),e._startWsFallback(),clearTimeout(e._wsFallbackTimer),e._scheduleRtcRestart("rtc-closed"))}(this,t),"rtc"===e&&t===n.Of.open&&((0,p.c)("auth","[seal] rtc OPEN → sending proof"),(0,C.pV)(this)),this._recomputeType();let r=this._anyAdapterReady();r!==this._connected&&(this._connected=r,r||(this._onConnectFired=!1,(0,f.Lq)("switch",`onDisconnect FIRE (last carrier gone: ${e}→${t})`),this._wsCallbacks.onDisconnect?.(`${e}-${t}`))),(t===n.Of.open||t===n.Of.closed)&&this._flushBuffer(),this._intakeSeq?.setPaused(!r)}_maybeFireRejoin(e,t){let r="ws"===e?this._adapters.get("rtc"):this._adapters.get("ws");if(r?.ready){(0,p.c)("transport",`[pm] ${t} → skip rejoin (other ready)`),(0,f.Lq)("switch",`${t} → skip rejoin (other ready)`);return}if("ws"===e&&r&&r.state===n.Of.connecting){(0,p.c)("transport",`[pm] ${t} → debounce rejoin (rtc connecting)`),(0,f.Lq)("switch",`${t} → debounce rejoin ${n.ZN}ms (rtc connecting)`),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=setTimeout(()=>{this._rejoinDebounceTimer=null;let e=this._adapters.get("rtc");e?.ready?(0,f.Lq)("switch","debounce: rtc opened → skip rejoin"):((0,f.Lq)("switch",`debounce expired → FIRE rejoin (rtc=${e?.state||"absent"})`),this._bus.dispatch("connect",[]))},n.ZN);return}(0,f.Lq)("switch",`${t} → FIRE rejoin`),this._bus.dispatch("connect",[])}_recomputeType(){let e=this._pickAdapter(n.l_.binary)||this._pickAdapter(n.l_.control),t=e&&"rtc"===e.constructor.id?e.typeDetail||"dc-stun":"ws";t!==this._type&&(this._type=t,this._rtcCallbacks.onTransportChange?.(t))}_anyAdapterReady(){for(let e of this._adapters.values())if(e.ready)return!0;return!1}_pickAdapter(e){if(e===n.l_.control&&this._wsCarryUntil>Date.now()){let e=this._adapters.get("ws");if(e?.ready)return e}return function(e,t,r){let n=t.channels[r];if(!n)return null;let i=[...e.values()].filter(e=>e.supports(r)&&e.ready);return i.length?(i.sort((e,t)=>{let i=t.getPriority?t.getPriority(r):t.constructor.priority[r]??0,s=e.getPriority?e.getPriority(r):e.constructor.priority[r]??0;if(i!==s)return i-s;if(n.prefer){if(t.constructor.id===n.prefer)return 1;if(e.constructor.id===n.prefer)return -1}return 0}),i[0]||null):null}(this._adapters,this._profile,e)}_seqActive(){return!0===this._peerSeqCtl}_sendStreamEvent(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;V(this,e,t,r)}_sendControl(e,t){!function(e,t,r){var n,i,s,a;let l,o="function"==typeof r[r.length-1]?r.pop():null,c=o?(n=e,i=t,s=r,a=o,l=`c_${++n._ackSeq}`,n._pendingAcks.set(l,a),n._ackReqs?.set(l,{event:i,args:s,tries:0}),n._scheduleAckTimeout(l,{event:i,args:s,ackId:l}),l):null,d=e._outLog.append({event:t,args:r,ackId:c});if(c){let t=e._ackReqs?.get(c);t&&(t.sq=d.sq)}(0,p.c)("transport",`[pm] send control event=${t} sq=${d.sq}`),z(e)}(this,e,t)}_flushBuffer(){!function(e){let t=e._pickAdapter(n.l_.control);if(t)for(let r of(e._intakeSeq.setPaused(!1),e._outLog.replayList())){if(!J(e,t,r))return;e._outLog.markSent(r.sq)}}(this)}_dispatch(e,t,r){let n;n=e===W?t:"rtc"===r?Array.isArray(t?.args)?{...t,event:e}:{event:e,args:[t],ackId:null,sq:null,ep:null}:{event:e,args:[t],ackId:null},n?.event&&(Number.isInteger(n.rs)&&this._outLog.setApplied(n.rs),Number.isInteger(n.sq)&&!this._intakeSeq.armed&&this._peerSeqCtl&&this._intakeSeq.arm(),this._intakeSeq.push(n))}_onBinary(e){e&&("mobile"===e.channel?this._bus?.dispatch("mobile-bin",[e.buffer]):"file"===e.channel&&this._bus?.dispatch("file-bin",[e.buffer]))}_scheduleAckTimeout(e,t){var r;let i;r=this,i=setTimeout(()=>{r._ackTimers.delete(e),(0,p.c)("transport",`[pm] ack timeout ackId=${e} event=${t?.event} → suspect zombie RTC`);let i=r._pendingAcks.get(e),s=r._adapters.get("rtc"),a=r._adapters.get("ws");if(r._admitQueue?.includes(e))return;if(X.has(t?.event)){let l=r._srvCaps?.promptDedupe&&t.args?.[0]?.promptId;if(i&&a?.ready&&l){let s=r._ackReqs?.get(e);Number.isInteger(s?.sq)&&r._outLog.markAcked(s.sq),r._ackReqs?.delete(e),r._pendingAcks.delete(e),(0,f.Lq)("switch",`ack-timeout ${t.event} → retry via ws (slow ack)`),a.send(n.l_.control,{event:t.event,args:t.args,cb:i});return}(s?.ready||s?.state===n.Of.open)&&F(r,`ack-timeout:${t.event}`)}if(r._seqActive()&&i&&!X.has(t?.event)&&a?.ready&&s?.ready)return void r.carryControlOnWs?.(`ack-timeout:${t?.event||"?"}`);if(i&&t&&a?.ready&&Q.has(t.event)){if(r._pendingAcks.delete(e),a.send(n.l_.control,{event:t.event,args:t.args,cb:i}))return void(0,f.Lq)("switch",`ack-timeout ${t.event} → retry via ws (rtc zombie?)`);r._pendingAcks.set(e,i)}if(r._seqActive()&&i)return void(0,f.Lq)("switch",`ack-timeout ${t?.event} → keep pending (sequenced stream owns retry)`);let l=Date.now(),o=s?.lastInboundAt||0;s?.ready&&o&&l-o<n.mk?(0,f.Lq)("switch",`ack-timeout ${t?.event||"?"} ignored (rtc active, lastInbound=${l-o}ms ago)`):s?.state===n.Of.open?F(r,`ack-timeout:${t?.event||"?"}`):r._scheduleRtcRestart("ack-timeout")},r._ackTimeoutMs),r._ackTimers.set(e,i)}_armRestart(e,t){clearTimeout(this._rtcRestartTimer),this._rtcRestartDueAt=Date.now()+t,this._rtcRestartTimer=setTimeout(e,t)}_disarmRestart(){let e=this._rtcRestartTimer?Math.max(this._rtcRestartDueAt-Date.now(),0):-1;return clearTimeout(this._rtcRestartTimer),this._rtcRestartTimer=null,this._rtcRestartDueAt=0,e}_scheduleRtcRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"?";if((0,f.Lq)("switch",`rtcRestart REQ by=${e} attempts=${this._rtcRestartAttempts} probe=${this._probeAttempts} givenUp=${this._rtcGivenUp} pending=${!!this._rtcRestartTimer}`),this._rtcRestartTimer){let t=Math.max(this._rtcRestartDueAt-Date.now(),0);(0,f.Lq)("switch",`rtcRestart SKIP by=${e} (pending rung ${this._rtcRestartAttempts} fires in ${t}ms)`);return}if(this._rtcGivenUp){(0,f.Lq)("switch","scheduleRtcRestart skipped (hard NAT → WS-only)"),(0,p.c)("transport","[pm] rtc probe skipped (given up — hard NAT)");return}let t=function(e){let t,r,{attempts:i,probeAttempts:s,verdict:a}=e,l=i>=n.QZ.maxAttempts,o=s;if(l){if(t=n.QZ.probeBackoffMs[s]??n.QZ.probeBackoffMs.at(-1),(o=s+1)>=n.QZ.classifyAfterProbes){if("hard"===(r=a?.()??"unknown"))return{giveUp:!0,verdict:r,probeAttempts:o};o=0}}else t=n.QZ.backoffMs[i]??n.QZ.backoffMs.at(-1);return{delay:t,isProbe:l,attempts:i+1,probeAttempts:o,verdict:r}}({attempts:this._rtcRestartAttempts,probeAttempts:this._probeAttempts,verdict:()=>this._adapters.get("rtc")?.natVerdict?.()??"unknown"});if(void 0!==t.verdict&&((0,f.Lq)("switch",`scheduleRtcRestart natVerdict=${t.verdict} probeAttempts=${t.probeAttempts}`),(0,p.c)("transport",`[pm] rtc nat verdict=${t.verdict} after ${t.probeAttempts} probes`)),t.giveUp){this._probeAttempts=t.probeAttempts,this._rtcGivenUp=!0,this._giveUpIp=this._netFingerprint,this._giveUpIp||U().then(e=>{this._rtcGivenUp&&!this._giveUpIp&&(this._giveUpIp=e||E,(0,f.Lq)("switch",`give-up baseline from probe: ip=${this._giveUpIp}`))}).catch(()=>{}),(0,f.Lq)("switch",`RTC give-up: hard NAT → WS-only (ip=${this._giveUpIp||"pending"})`);return}let{delay:r,isProbe:i}=t;this._probeAttempts=t.probeAttempts,this._rtcRestartAttempts=t.attempts,(0,f.Lq)("switch",`rtcRestart ARM by=${e} rung=${this._rtcRestartAttempts} delay=${r}ms probe=${i}`),(0,p.c)("transport",`[pm] schedule rtc ${i?"probe":"restart"} #${this._rtcRestartAttempts} in ${r}ms`);let s=()=>{if(this._disarmRestart(),this._awaitingApproval||!this._sig?.ready)return;let e=this._adapters.get("rtc");if(e){let t=function(e){let{state:t,connectingSince:r,connectDeadline:i,now:s,connectTimeoutMs:a}=e;return t!==n.Of.connecting?"restart":s<N({connectingSince:r,connectDeadline:i,connectTimeoutMs:a})?"wait":"teardown"}({state:e.state,connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,now:Date.now(),connectTimeoutMs:n.AC});if("wait"===t){let t=Math.max(N({connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,connectTimeoutMs:n.AC})-Date.now(),r);(0,f.Lq)("switch",`restart tick: peer still young (rung ${this._rtcRestartAttempts}) → re-arm in ${t}ms, no rung spent`),this._armRestart(s,t);return}if("teardown"===t){try{e.disconnect(`rung-${this._rtcRestartAttempts}-teardown`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}}this._restartRtc(`rung-${this._rtcRestartAttempts}`)};this._armRestart(s,r)}_sendSignaling(e){et(this,e)}_flushSigBuffer(){er(this)}}},44964:(e,t,r)=>{r.d(t,{N:()=>i.N0,u:()=>o});var n=r(7620),i=r(81851);let s="9remote_api_keys",a=()=>{window.dispatchEvent(new Event(i.N0))};function l(e){try{return btoa(e)}catch{return e}}function o(){let e=(0,n.useCallback)(()=>{try{let e=localStorage.getItem(s);if(!e)return[];return JSON.parse(e).map(e=>({...e,key:function(e){try{return atob(e)}catch{return e}}(e.key)}))}catch(e){return console.error("Failed to load API keys:",e),[]}},[!0]),t=(0,n.useCallback)(function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(t&&1)try{let n=e(),i=n.findIndex(e=>e.key===t);if(-1!==i){let e=n.map((e,t)=>({...e,key:l(e.key),lastLoginDate:t===i?new Date().toISOString():e.lastLoginDate}));localStorage.setItem(s,JSON.stringify(e));return}let o={id:Date.now().toString(),key:l(t),label:r||`Key ${n.length+1}`,createdAt:new Date().toISOString(),lastLoginDate:new Date().toISOString()},c=[...n.map(e=>({...e,key:l(e.key)})),o];localStorage.setItem(s,JSON.stringify(c)),a()}catch(e){console.error("Failed to save API key:",e)}},[!0,e]),r=(0,n.useCallback)((t,r)=>{try{let n=e(),i=n.findIndex(e=>e.id===t),o=i+r;if(-1===i||o<0||o>=n.length)return;[n[i],n[o]]=[n[o],n[i]],localStorage.setItem(s,JSON.stringify(n.map(e=>({...e,key:l(e.key)})))),a()}catch(e){console.error("Failed to move API key:",e)}},[!0,e]),i=(0,n.useCallback)(t=>{try{let r=e().filter(e=>e.id!==t).map(e=>({...e,key:l(e.key)}));localStorage.setItem(s,JSON.stringify(r)),a()}catch(e){console.error("Failed to remove API key:",e)}},[!0,e]),o=(0,n.useCallback)(()=>{try{localStorage.removeItem(s)}catch(e){console.error("Failed to clear API keys:",e)}},[!0]),c=(0,n.useCallback)(()=>{try{let e=localStorage.getItem(s);if(!e)return!1;return JSON.parse(e).length>0}catch{return!1}},[!0]),d=(0,n.useCallback)((t,r)=>{try{let n=e().map(e=>({...e,key:l(e.key),label:e.id===t?r:e.label||""}));localStorage.setItem(s,JSON.stringify(n)),a()}catch(e){console.error("Failed to rename API key:",e)}},[!0,e]),u=(0,n.useCallback)(t=>{if(t&&1)try{let r=e().map(e=>({...e,key:l(e.key),lastLoginDate:e.key===t?new Date().toISOString():e.lastLoginDate}));localStorage.setItem(s,JSON.stringify(r))}catch(e){console.error("Failed to update last login date:",e)}},[!0,e]);return{saveKey:t,loadKeys:e,moveKey:r,removeKey:i,renameKey:d,clearKeys:o,hasStoredKeys:c,updateLastLogin:u}}},55285:(e,t,r)=>{r.d(t,{c:()=>i});var n=r(30068);function i(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];n.eR.debug?.[e]&&console.log(...r)}},56156:(e,t,r)=>{r.d(t,{A:()=>i});var n=r(54568);function i(e){let{children:t,variant:r="primary",size:i="md",disabled:s=!1,loading:a=!1,onClick:l,className:o="",...c}=e,d=`font-semibold rounded-brand transition-all duration-150 ease-out transform active:scale-[0.97] ${{primary:"bg-brand-500 hover:bg-brand-600 disabled:bg-surface-3 disabled:text-text-muted text-white shadow-sm",secondary:"bg-surface-2 hover:bg-surface-3 disabled:bg-surface disabled:text-text-muted text-text",danger:"bg-red-500 hover:bg-red-600 disabled:bg-surface-3 disabled:text-text-muted text-white",success:"bg-green-600 hover:bg-green-700 disabled:bg-surface-3 disabled:text-text-muted text-white"}[r]} ${{sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-base",lg:"px-6 py-3 text-lg"}[i]} ${s||a?"cursor-not-allowed":""} ${o}`;return(0,n.jsx)("button",{onClick:l,disabled:s||a,className:d,...c,children:a?(0,n.jsxs)("span",{className:"flex items-center justify-center gap-2",children:[(0,n.jsx)("span",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),t]}):t})}},59506:(e,t,r)=>{function n(e,t){if(e===t)return!0;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n of r)if(!(n in t)||e[n]!==t[n])return!1;return!0}function i(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function s(e,t){if(e===t)return!0;if(!e||!t)return!1;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let i of r)if(!(i in t)||!n(e[i],t[i]))return!1;return!0}r.d(t,{dI:()=>n,h3:()=>s,nk:()=>i})},67841:(e,t,r)=>{r.d(t,{H$:()=>a,d6:()=>s});var n=r(7620),i=r(79748);let s=(e,t)=>{if(e&&t)try{localStorage.setItem("9remote_nav:"+e,t)}catch{}};function a(e){let t=(0,i.usePathname)(),r=(0,i.useSearchParams)();(0,n.useEffect)(()=>{if(!e||!t?.startsWith("/workspace"))return;let n=function(e,t){if(!e)return"";let r=t?.toString();return r?`${e}?${r}`:e}(t,r);n&&s(e,n)},[e,t,r])}},68469:(e,t,r)=>{r.d(t,{O:()=>u,Y:()=>c});let n=new Uint8Array([48,42,48,5,6,3,43,101,110,3,33,0]);function i(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function s(e){let t="",r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}function a(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];let n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),i=0;for(let e of t)n.set(e,i),i+=e.length;return n}async function l(e){let t;try{t=i(String(e))}catch{return null}if(32!==t.length)return null;try{return await crypto.subtle.importKey("spki",a(n,t),{name:"X25519"},!0,[])}catch{return null}}async function o(e,t,r,n){let i=await crypto.subtle.deriveBits({name:"X25519",public:t},e,256),s=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a(r,n),info:new TextEncoder().encode("9remote-tail-seal-v1")},s,{name:"AES-GCM",length:256},!1,["encrypt"])}async function c(e,t){if("string"!=typeof e||!e||"string"!=typeof t||!t)return null;let r=await l(t);if(!r)return null;try{let t=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),n=new Uint8Array(await crypto.subtle.exportKey("spki",t.publicKey)).slice(-32),i=new Uint8Array(await crypto.subtle.exportKey("spki",r)).slice(-32),a=await o(t.privateKey,r,n,i),l=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:l},a,new TextEncoder().encode(e));return{epk:s(n),iv:s(l),ct:s(c)}}catch{return null}}let d="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";async function u(e,t){if("u"<typeof crypto||!crypto.subtle)return null;let r=[e,t].map(e=>{let t;try{t=i(String(e||""))}catch{t=new Uint8Array(0)}let r=new Uint8Array(2);return new DataView(r.buffer).setUint16(0,t.length),a(r,t)}),n=new Uint8Array(await crypto.subtle.digest("SHA-256",a(...r)));return d[n[0]%32]+d[n[1]%32]}},69469:(e,t,r)=>{function n(e){return"string"==typeof e&&!!e&&/^sk-[a-z0-9]{8}-[a-z0-9]{4}-[0-9a-f]{6}$/.test(e.trim().toLowerCase())}function i(e){if("string"!=typeof e||!/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(e))return e||null;let t=e.split("-");return`${t[0]}-${t[1]}-${t[2]}`}function s(e){return"string"==typeof e&&/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(e)?e.split("-")[3]:null}r.d(t,{Cj:()=>s,PF:()=>n,Uo:()=>i})},70658:(e,t,r)=>{r.d(t,{As:()=>m,zg:()=>u});var n=r(7620),i=r(79748),s=r(30562),a=r(69469),l=r(99022),o=r(96631),c=r(189);let d="wrong-key-tail";async function u(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.qn;try{let t=new AbortController,n=setTimeout(()=>t.abort(),r),i=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(n),i.ok}catch{return!1}}async function h(e,t){let{tail:r,tempKey:n}=t,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.qn;try{let t=new AbortController,s=setTimeout(()=>t.abort(),i),a=await fetch(`${e}/api/verify-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tail:r||null,tempKey:n||null}),signal:t.signal});if(clearTimeout(s),!a.ok)return null;return(await a.json())?.ok===!0}catch{return null}}async function p(){return(0,o._r)()?(0,o.rh)(await f()):(0,o.Yr)()?window.location.origin:null}async function f(){try{let e=await fetch(s.TR);return e.ok?await e.json():null}catch{return null}}function m(){let[e,t]=(0,n.useState)(!1),[r,o]=(0,n.useState)(""),u=(0,i.useRouter)(),{setAuth:m}=(0,c.Fo)(),g=(0,n.useCallback)(async function(e){let{persistSession:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t(!0),o("");try{let t,n=await p();if(n){let t=e.tail||(0,a.Cj)(e.apiKey||""),i=e.tempKey||(e.token?.length<=8?e.token:null),s=await f(),c=(0,a.Uo)(s?.permanentKey||""),u=(0,a.Uo)(e.apiKey||e.token||""),p=String(s?.oneTimeKey||"").slice(0,6).toUpperCase(),g=i?!!p&&p===i.toUpperCase():!!c&&!!u&&(0,a.Uo)(c)===u;try{let s=g?await h(n,{tail:t,tempKey:i}):null;if(!0===s){let s=e.apiKey||i||"",o=(0,a.Uo)(s)||"direct";return t&&(0,l.LG)(o,{tail:t}),r&&m({apiKey:o,tunnelUrl:n,mode:"local",tempKey:i?i.toUpperCase():null,localIp:null}),{success:!0,shouldAskToSave:!0,apiKey:o}}if(!1===s)return o(d),{success:!1,wrongTail:!0}}catch{}}let i=new AbortController,c=setTimeout(()=>i.abort(),s.cC);try{t=await fetch(s.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:(0,a.Uo)(e.apiKey)}),signal:i.signal})}catch(e){throw Error(e?.name==="AbortError"?"Connection timed out. Please try again.":"Network error. Please try again.")}finally{clearTimeout(c)}if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error||"Authentication failed")}let u=await t.json(),g=(0,a.Uo)(e.apiKey||u.apiKey);u.hostKeys?.x&&(0,l.LG)(g,{hostSealKey:u.hostKeys.x,hostPubKey:u.hostKeys.ed||null});let y=e.tail||(0,a.Cj)(e.apiKey||"");if(u.tunnelUrl&&(y||e.tempKey)){let t=await h(u.tunnelUrl,{tail:y,tempKey:e.tempKey||null});if(!1===t)return o(d),{success:!1,wrongTail:!0}}return r&&m({apiKey:g,tunnelUrl:u.tunnelUrl||null,mode:"remote",tempKey:e.tempKey?e.tempKey.toUpperCase():null,localIp:u.localIp||null}),{success:!0,shouldAskToSave:!0,apiKey:g}}catch(e){return o(e.message),{success:!1,error:e.message}}finally{t(!1)}},[u,m]);return{loading:e,error:r,setError:o,authenticateWithToken:(0,n.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0;return t?g({token:e,tempKey:e,tail:r},n):g({token:e},n)},[g]),authenticateWithApiKey:(0,n.useCallback)((e,t)=>g({apiKey:e},t),[g])}}},72627:(e,t,r)=>{r.d(t,{AD:()=>n,Jc:()=>o,Mt:()=>a,g4:()=>l,gk:()=>s,xs:()=>i});let n="__ungrouped__",i=e=>e?.workspaceId??e?.groupId??null;function s(e){let{sessions:t,openedSessions:r,livePanes:s,mountedWorkspaces:a,activeWorkspaceId:l,isDesktop:o}=e,c=new Set(t.filter(e=>i(e)===(l??null)).map(e=>e.id)),d=r.filter(e=>c.has(e)),u=new Set([...d,...s.filter(e=>r.includes(e))]),h=r.filter(e=>u.has(e)),p=new Map(t.map(e=>[e.id,i(e)])),f=new Set(r.filter(e=>!!c.has(e)||!!o&&!!a[p.get(e)??n])),m=new Map(d.map((e,t)=>[e,t]));return{workspaceSessionIds:c,workspaceOpenedSessions:d,renderedSessions:h,mountedSet:f,workspaceIndex:m}}let a=(e,t,r)=>!t&&r.has(e)?120*r.get(e):0;function l(e){let{container:t,pane:r}=e;if(!t||!r||r.offsetWidth<=0)return null;let n=r.getBoundingClientRect().left-t.getBoundingClientRect().left;return Math.max(0,Math.min(t.scrollLeft+n-(t.clientWidth-r.offsetWidth)/2,t.scrollWidth-t.clientWidth))}function o(e){let{rowWidth:t,paneCount:r,sidebarWidth:n,sidePx:i,gapPx:s,paddingPx:a,minWidth:l}=e;return!(t>0)||r<=0?null:Math.max(l,Math.floor((t-n-a-i-(r-1)*s)/r))}},75677:(e,t,r)=>{r.d(t,{o:()=>n});function n(e){if(!e)return"";if(e.length<=14)return e;let t=e.substring(0,8),r=e.substring(e.length-6),n="•".repeat(12);return`${t}${n}${r}`}},81353:(e,t,r)=>{r.d(t,{Nw:()=>x,eJ:()=>S,d:()=>T,rh:()=>A});var n=r(94245),i=r(23635),s=r(89228),a=r(42126),l=r(30068),o=r(69469),c=r(99022);let d="9remote_fleet_connected";function u(){try{return JSON.parse(localStorage.getItem(d)||"[]")}catch{return[]}}class h{constructor({hostOf:e,patch:t,bindBus:r,ready:n,probeTargets:i,servedBy:s=null,servedBus:a=null}){this._hostOf=e,this._patch=t,this._bindBus=r,this._ready=n,this._probeTargets=i,this._servedBy=s||(()=>!1),this._servedBus=a||(()=>null),this.buses=new Map,this._connectTimers=new Map,this.pending=new Map,this._probeTimer=null,this._probeVisible=null}busOf(e){return e&&this.buses.get(e)?.busRef?.current||null}pmOf(e){return this.buses.get(e)||null}has(e){return this.buses.has(e)}whenReady(e,t){let r=this._hostOf(e);if(!e||!r)return;if(this._servedBy(e)){let r=this._servedBus(e);r&&t(r);return}let n=this.busOf(e);if(n&&"online"===r.status)return void t(n);if(!this._canOpen(r,e))return;this.open(e,r);let i=this.pending.get(e)||[];i.push(t),this.pending.set(e,i)}persistIntent(e,t){if(e)try{let r=new Set(u());t?r.add(e):r.delete(e),localStorage.setItem(d,JSON.stringify([...r]))}catch{}}_canOpen(e,t){return!(!e||this._servedBy(t))&&!!e.full}open(e,t){if(this.has(e))return;let r=function(){try{return localStorage.getItem("9remote_deviceId")}catch{return null}}();if(!this._canOpen(t,e)||!r)return;this.persistIntent(e,!0);let n=(0,o.Cj)(t.full);n&&(0,c.LG)(e,{tail:n});let i=t=>this._patch(e,t),s=!1,d=new a.g({tunnelUrl:null,localIp:null,namespace:"",socketOptions:{auth:{apiKey:e,tempKey:null,deviceId:r}},apiKey:e,deviceId:r,tempKey:null,onConnect:t=>{clearTimeout(this._connectTimers.get(e)),this._connectTimers.delete(e),i({status:"online",lastSeenAt:Date.now(),updating:!1,approval:null});let r=this.pending.get(e);if(r)for(let n of(this.pending.delete(e),r))try{n(t)}catch{}s||(s=!0,this._bindBus(t,e)),this._ready(t,e)},onDisconnect:()=>{this.pending.delete(e),i({status:"offline",lastSeenAt:Date.now()})}},{enableWebRTC:l.eR.enableWebRTC,enableTurn:l.eR.enableTurn,apiKey:e,onTransportChange:e=>i({carrier:e||"ws"})});this.buses.set(e,d),i({status:"connecting"}),this._connectTimers.set(e,setTimeout(()=>this._onConnectTimeout(e),15e3)),d.connect()}_onConnectTimeout(e){this._connectTimers.delete(e),this.buses.has(e)&&this._hostOf(e)?.status==="connecting"&&(this._patch(e,{status:"offline"}),this._hostOf(e)?.approval!=="pending"&&this.persistIntent(e,!1))}drop(e){let t=this.buses.get(e);t&&(t.disconnect(),this.buses.delete(e)),clearTimeout(this._connectTimers.get(e)),this._connectTimers.delete(e),this.pending.delete(e)}retry(e){this.drop(e),this.open(e,this._hostOf(e))}closeAll(){for(let e of this.buses.values())e.disconnect();for(let e of(this.buses.clear(),this._connectTimers.values()))clearTimeout(e);this._connectTimers.clear(),this.pending.clear(),this.disarmProbe()}armProbe(){this._probeTimer||(this._probeTimer=setInterval(()=>{document.hidden||this.probeOnce()},6e4),this._probeVisible=()=>{"visible"===document.visibilityState&&this.probeOnce()},document.addEventListener("visibilitychange",this._probeVisible))}disarmProbe(){this._probeTimer&&(clearInterval(this._probeTimer),this._probeTimer=null,document.removeEventListener("visibilitychange",this._probeVisible),this._probeVisible=null)}probeOnce(){let e=this._probeTargets().filter(e=>!this.has(e));e.length&&fetch("/api/host-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({heads:e})}).then(e=>e.ok?e.json():null).then(t=>{for(let r of e){if(this.has(r))continue;let e=t?.hosts?.[r];e&&this._patch(r,{status:e.online?"online":"offline"})}}).catch(()=>{})}}var p=r(18753),f=r(59506),m=r(6134);let g="9remote_fleet_cache",y=null;function _(e){clearTimeout(y),y=setTimeout(()=>{y=null;let t={};for(let[r,n]of Object.entries(e().hosts))t[r]={label:n.label,platform:n.platform,version:n.version,sessions:n.sessions,workspaces:n.workspaces,statusMap:n.statusMap,lastSeenAt:n.lastSeenAt};try{localStorage.setItem(g,JSON.stringify(t))}catch{}},1e3)}let b=e=>({key:e,full:null,label:"",status:"offline",carrier:"ws",sessions:[],workspaces:[],statusMap:{},tasksBySession:{},platform:null,version:null,lastSeenAt:null,updateAvailable:null,canSelfUpdate:!1,updating:!1,approval:null,remoteAvailable:!1,remoteStatus:null,mobileAvailable:!1,isCodespaces:!1,mobileDeviceCount:0}),w=(e,t)=>A.getState()._patchHost(e,t),k=(e,t)=>{e?.emit("getSessions",e=>{Array.isArray(e)&&w(t,{sessions:e})}),e?.emit("getWorkspaces",e=>{Array.isArray(e)&&w(t,{workspaces:e})}),e?.emit("getStatusState"),e?.emit("getSessionTasks",e=>A.getState().applySessionTasksState(t,e))},v=null,A=(0,n.v)((e,t)=>({hosts:{},currentKey:null,sync(r,n){let i=n||"",s=new Map;for(let e of r){let t=(0,o.Uo)(e.key);t&&!s.has(t)&&s.set(t,{full:e.key,label:e.label||""})}i&&!s.has(i)&&s.set(i,{full:null,label:""});let a=[...s.keys()].filter(e=>e!==i).slice(0,8),l=new Set(a);for(let e of[...v.buses.keys()])l.has(e)||v.drop(e);let c=function(){try{return JSON.parse(localStorage.getItem(g)||"{}")}catch{return{}}}(),d=new Set(u()),h=!1;try{h="1"===sessionStorage.getItem("9remote_manual_disconnect")}catch{}for(let r of(e(e=>{let t={};for(let[r,n]of s){let s=e.hosts[r]||{...b(r),...c[r]||{}};t[r]={...s,key:r,full:n.full,label:n.label||s.label,status:r===i?h?"offline":"full":l.has(r)&&("online"===s.status||"connecting"===s.status)?s.status:"offline"}}return{hosts:t,currentKey:i}}),a))d.has(r)&&v.open(r,t().hosts[r]);v.probeOnce(),v.armProbe()},_patchHost(r,n){e(e=>{let t=e.hosts[r];return t?{hosts:{...e.hosts,[r]:{...t,...n}}}:e}),_(t)},applyStatusState(r,n){let i=n||{};e(e=>{let t=e.hosts[r];return!t||(0,f.h3)(t.statusMap,i)?e:{hosts:{...e.hosts,[r]:{...t,statusMap:i}}}}),_(t)},applyStatusChange(r){let{sessionId:n,state:i,tool:s,since:a,conversationId:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n&&(e(e=>{let t=e.hosts[r];if(!t)return e;let o=t.statusMap[n],c={state:i,tool:void 0!==s?s:o?.tool,since:a,...l||o?.conversationId?{conversationId:l||o?.conversationId}:{}};return(0,f.dI)(o,c)?e:{hosts:{...e.hosts,[r]:{...t,statusMap:{...t.statusMap,[n]:c}}}}}),_(t))},applyStatusCleared(r,n){n&&(e(e=>{let t=e.hosts[r],i=t?.statusMap?.[n];return i?{hosts:{...e.hosts,[r]:{...t,statusMap:{...t.statusMap,[n]:{...i,state:"idle"}}}}}:e}),_(t))},applySessionTasks(t){let{sessionId:r,records:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r&&e(e=>{let i=e.hosts[t];if(!i)return e;let s={...i.tasksBySession||{}};return Array.isArray(n)&&n.length?s[r]=n:delete s[r],{hosts:{...e.hosts,[t]:{...i,tasksBySession:s}}}})},applySessionTasksState(t,r){e(e=>{let n=e.hosts[t];if(!n)return e;let i={};for(let[e,t]of Object.entries(r||{}))Array.isArray(t)&&t.length&&(i[e]=t);return{hosts:{...e.hosts,[t]:{...n,tasksBySession:i}}}})},_closeHost(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};v.drop(e),t()._patchHost(e,{status:"offline",lastSeenAt:Date.now(),approval:null,...r})},ensureHost(e){e===t().currentKey||v.has(e)||v.open(e,t().hosts[e])},connectHost(e){t().retryHost(e)},requestHostUpdate(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"update",n=t().hosts[e];if(!n||n.updating)return;let i={updating:!0,updateAvailable:null};if("full"===n.status){let n=s.d.getState(),a=n.busRef?.current;if(!a?.connected)return void(0,m.Lq)("update",`request ${r} on ACTIVE ${e} dropped: bus not connected`);t()._patchHost(e,i),n.protocolRef?.current?.setUpdating?.(!0),a.emit("restart"===r?"requestRestart":"requestUpdate")}else t()._patchHost(e,i),v.pmOf(e)?.setUpdating?.(!0),v.whenReady(e,t=>{v.pmOf(e)?.setUpdating?.(!0),(0,m.Lq)("update",`request ${r} sent on fleet bus ${e}`),t.emit("restart"===r?"requestRestart":"requestUpdate")});setTimeout(()=>{t().hosts[e]?.updating&&t()._patchHost(e,{updating:!1})},12e4)},setAutoConnect(e,t){v.persistIntent(e,t)},retryHost(e){v.retry(e)},disconnectHost(e){v.persistIntent(e,!1),t()._closeHost(e)},closeAll(){v.closeAll()}}));function S(e){return v?.busOf(e)||null}function T(e){return v?.pmOf(e)||null}function x(e,t){v?.whenReady(e,t)}v=new h({hostOf:e=>A.getState().hosts[e],patch:w,bindBus:(e,t)=>{e.on("connect",()=>{e.emit("device:clientReady"),k(e,t)}),e.on("serverInfo",e=>{let r=!!A.getState().hosts[t]?.updating;w(t,{platform:e?.platform||null,isCodespaces:!!e?.isCodespaces,version:e?.version||null,updateAvailable:!r&&(0,p.U)(e?.updateAvailable?.version,e?.version)?e.updateAvailable:null,canSelfUpdate:!!e?.canSelfUpdate,remoteAvailable:!!e?.remoteAvailable,remoteStatus:e?.remoteStatus||null,mobileAvailable:!!e?.mobileAvailable})}),e.on("statusState",e=>A.getState().applyStatusState(t,e)),e.on("statusChange",e=>A.getState().applyStatusChange(t,e)),e.on("statusCleared",e=>A.getState().applyStatusCleared(t,e)),e.on("sessionTasks",e=>A.getState().applySessionTasks(t,e)),e.on("sessionsChanged",()=>k(e,t)),e.on("workspacesChanged",()=>k(e,t)),e.on("session-renamed",()=>k(e,t)),e.on("sessionClosed",r=>{r&&i.B.getState().closeSession(r),k(e,t)}),e.on("device:pendingApproval",()=>w(t,{approval:"pending"})),e.on("device:approved",()=>w(t,{approval:null})),e.on("device:rejected",()=>A.getState()._closeHost(t,{approval:"rejected"})),e.on("device:tailRejected",()=>A.getState()._closeHost(t))},ready:(e,t)=>{e.emit("device:clientReady"),k(e,t)},probeTargets:()=>{let e=A.getState(),t=new Set(u());return Object.values(e.hosts).filter(r=>r.key!==e.currentKey&&t.has(r.key)).map(e=>e.key)},servedBy:e=>!!e&&e===A.getState().currentKey,servedBus:()=>{let e=s.d.getState();return e.connected?e.busRef?.current||e.bus:null}})},81851:(e,t,r)=>{r.d(t,{AC:()=>f,An:()=>d,BF:()=>y,El:()=>T,HE:()=>q,HJ:()=>m,Ic:()=>I,J2:()=>A,Jd:()=>R,KF:()=>c,KP:()=>D,ML:()=>v,N0:()=>C,Of:()=>U,QS:()=>g,QZ:()=>s,Rh:()=>$,Tr:()=>b,UT:()=>_,ZN:()=>l,aS:()=>x,b4:()=>p,bg:()=>k,cO:()=>M,cx:()=>a,dE:()=>L,dT:()=>i,fP:()=>h,gI:()=>w,j3:()=>E,l_:()=>n,mH:()=>O,mk:()=>u,o_:()=>P,qM:()=>S,si:()=>o});let n={control:"control",binary:"binary",file:"file",mobile:"mobile",browser:"browser"},i=65536,s={ackTimeoutMs:5e3,maxAttempts:3,backoffMs:[500,1500,3e3],probeBackoffMs:[3e4,6e4,12e4,3e5],classifyAfterProbes:3},a={urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302"],timeoutMs:2500,minIntervalMs:15e3},l=500,o=3,c=3e3,d=9e3,u=25e3,h=3,p=1e3,f=4e3,m=15e3,g=1e3,y=12e3,_=2e3,b=1e4,w={enabled:!0,pingMs:25e3},k={pending:"pending-approval",rejected:"device-rejected"},v={mismatch:"mismatch",sealUnreadable:"seal-unreadable",timeout:"proof-timeout"},A={pending:"pending",approved:"approved",rejected:"rejected",reconnect:"reconnect"},S=8,T="9remote_pending_save",x="9remote_wants_save",C="9remote:keys-changed",R="9remote_login_error",I="strict",P={debounceMs:500},$=3e4,D=15e3,M=6e4,L="not-admitted",O={admitRetryMax:2,admitKickMinMs:3e3,ringMaxBytes:4194304,maxEntries:2e3,holdMax:256,gapDeadlineMs:3e3,ackMaxLives:3},q={chunkSize:65528,windowSize:64,dcBufferThreshold:8388608,maxUploadSize:0x3200000,maxDownloadSize:0xc800000,maxStreamMediaSize:524288e3},U={idle:"idle",connecting:"connecting",open:"open",degraded:"degraded",closed:"closed"},E={clientApp:{enabled:["ws","rtc"],parallel:!0,channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"},file:{strategy:"priority",prefer:"rtc"},mobile:{strategy:"priority",prefer:"rtc"},browser:{strategy:"priority",prefer:"rtc"}},rtc:{enableTurn:!0,dcControl:{ordered:!0}}},remoteDesktop:{enabled:["ws","rtc"],parallel:!0,channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"},file:{strategy:"priority",prefer:"rtc"},mobile:{strategy:"priority",prefer:"rtc"},browser:{strategy:"priority",prefer:"rtc"}},rtc:{enableTurn:!0,dcControl:{ordered:!0}}}}},89228:(e,t,r)=>{r.d(t,{d:()=>s});var n=r(94245),i=r(81851);let s=(0,n.v)(e=>({bus:null,busRef:{current:null},protocolRef:{current:null},connected:!1,everConnected:!1,deliberate:!1,connectionMode:"tunnel",carrier:"ws",approvalStatus:null,admitted:!1,authKey:null,endpoint:null,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1},hostOffline:!1,setConnection:t=>e(e=>({...e,...t})),setConnected:t=>e({connected:t}),setCarrier:t=>e({carrier:t}),setConnectionMode:t=>e({connectionMode:t}),setRetryStatus:t=>e({retryStatus:t}),setHostOffline:t=>e({hostOffline:t}),setAuthKey:t=>e({authKey:t}),setAdmitted:t=>e({admitted:t}),applyApproval:t=>e(e=>{let r=e.approvalStatus;return t===i.J2.reconnect?r===i.J2.approved?{approvalStatus:null}:{}:r===i.J2.approved&&t===i.J2.pending?{}:{approvalStatus:t}}),reset:()=>e({bus:null,connected:!1,deliberate:!1,everConnected:!1,connectionMode:"tunnel",carrier:"ws",endpoint:null,approvalStatus:null,admitted:!1,hostOffline:!1,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1}})}))},92571:(e,t,r)=>{r.d(t,{$b:()=>b,A0:()=>Z,AE:()=>g,Ax:()=>P,Dk:()=>R,Ez:()=>M,GW:()=>W,HF:()=>K,Jl:()=>F,Kr:()=>V,L0:()=>et,L8:()=>y,LN:()=>E,Qw:()=>L,RV:()=>function e(t){let r;if(!t||"object"!=typeof t)return t;if(Array.isArray(t)){let r=!1,n=t.map(t=>{let n=e(t);return n!==t&&(r=!0),n});return r?n:t}for(let s of Object.keys(t)){let a=t[s];if(i.has(s)&&"string"==typeof a&&a.includes("\\"))(r||={...t})[s]=n(a);else if(a&&"object"==typeof a){let n=e(a);n!==a&&((r||={...t})[s]=n)}}return r||t},Tf:()=>H,W5:()=>er,YO:()=>k,ZH:()=>_,_C:()=>N,aB:()=>z,bd:()=>ee,cv:()=>j,d5:()=>G,gh:()=>x,hh:()=>O,iB:()=>w,kS:()=>B,kb:()=>n,mv:()=>T,n2:()=>$,pA:()=>I,qu:()=>D,rL:()=>X,so:()=>v,u:()=>m,vb:()=>J,vd:()=>q,vs:()=>A,xW:()=>S,xl:()=>Q,xr:()=>Y,zT:()=>U});let n=e=>"string"==typeof e?e.replace(/\\/g,"/"):e,i=new Set(["path","currentPath","parentPath","dirPath","filePath","repoPath","oldPath","newPath","fullPath","relativePath"]),s=[".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".avif",".apng",".tif",".tiff",".heic",".heif"],a=[".mp4",".m4v",".webm",".ogv",".mov",".mkv",".avi",".3gp"],l=[".mp3",".wav",".ogg",".oga",".flac",".m4a",".aac",".opus"],o=[".pdf"],c=[".docx"],d=[".xlsx",".xls",".csv",".tsv"],u=[".html",".htm",".xhtml"],h=[".mmd",".mermaid"],p=[".md",".markdown",".mdx"];function f(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(e=>r.endsWith(e))}let m=e=>f(e,s),g=e=>f(e,a),y=e=>f(e,l),_=e=>f(e,o),b=e=>f(e,c),w=e=>f(e,d);function k(e){return e?f(e,u)?"html":f(e,p)?"markdown":f(e,h)?"mermaid":null:null}let v={".js":"javascript",".jsx":"javascript",".ts":"javascript",".tsx":"javascript",".mjs":"javascript",".cjs":"javascript",".html":"html",".htm":"html",".xhtml":"html",".css":"css",".scss":"css",".sass":"css",".less":"css",".styl":"css",".json":"json",".json5":"json",".jsonc":"json",".md":"markdown",".markdown":"markdown",".mdx":"markdown",".py":"python",".pyw":"python",".rb":"ruby",".php":"php",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".scala":"scala",".clj":"clojure",".cljs":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".ml":"ocaml",".mli":"ocaml",".jl":"julia",".pl":"perl",".pm":"perl",".tcl":"tcl",".lua":"lua",".r":"r",".dart":"dart",".groovy":"groovy",".gradle":"groovy",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".m":"objectivec",".sh":"shell",".bash":"shell",".zsh":"shell",".fish":"shell",".ps1":"powershell",".bat":"batch",".cmd":"batch",".yml":"yaml",".yaml":"yaml",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini",".properties":"ini",".xml":"xml",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".vue":"vue",".svelte":"svelte",".csv":"csv",".tsv":"csv",".log":"log",".diff":"diff",".patch":"diff",".dockerfile":"dockerfile",".makefile":"makefile",".mk":"makefile",".env":"env",".gitignore":"gitignore"},A={M:"text-git-modified",A:"text-git-added",D:"text-git-deleted","?":"text-git-untracked",U:"text-git-modified"},S={normal:{indentBase:12,indentStep:12,icon:16,chevron:14,text:"text-[15px] sm:text-sm",padY:"py-1 sm:py-0.5"},compact:{indentBase:8,indentStep:8,icon:14,chevron:12,text:"text-[13px] sm:text-[12px]",padY:"py-0.5 sm:py-[1px]"}},T=e=>e?"folder-changed"===e?22:32:4,x=768,C="git-diff:",R=(e,t)=>`${C}${e}:${t}`,I=e=>"string"==typeof e&&e.startsWith(C),P=e=>{let t=e.slice(C.length),r=t.indexOf(":");return{status:t.slice(0,r),absPath:t.slice(r+1)}},$=(e,t,r)=>`${C}${e}:${t}\u0000${r}`,D=e=>{let{status:t,absPath:r}=P(e),n=r.indexOf("\0");return -1===n?{status:t,repoPath:null,filePath:r}:{status:t,repoPath:r.slice(0,n),filePath:r.slice(n+1)}},M=(e,t)=>{let{repoPath:r,filePath:n}=D(e);return r?`${r.replace(/\/$/,"")}/${n}`:n.startsWith("/")?n:`${t?.replace(/\/$/,"")||""}/${n}`},L=18,O=12,q=40,U=48,E=30,B=10,N=70,j=20,F={MAX_DIRS:40,DEBOUNCE_MS:300,PREVIEW_DEBOUNCE_MS:1e3,IDLE_UNWATCH_MS:6e4},W="fileExplorer:gitRefresh",K=300,H=200,z=500,J=["fileExplorer:fileSaved","fileExplorer:fileCreated","fileExplorer:fileDeleted","fileExplorer:fileRenamed",W],G={sidebarWidth:"fileExplorer.sidebarWidth",sidebarVisible:"fileExplorer.sidebarVisible",bottomPanelVisible:"fileExplorer.bottomPanelVisible",bottomPanelHeight:"fileExplorer.bottomPanelHeight",activityPanel:"fileExplorer.activityPanel",recentFiles:"fileExplorer.recentFiles",openTabs:"fileExplorer.openTabs",editorFontSize:"fileExplorer.editorFontSize",wordWrap:"fileExplorer.wordWrap",expandedFolders:"fileExplorer.expandedFolders",showHidden:"fileExplorer.showHidden"},V={explorer:"explorer",search:"search",scm:"scm",settings:"settings"},Z=14,Q=4,X=9,Y=10,ee=28,et=5,er=4194304},92673:(e,t,r)=>{r.d(t,{Gf:()=>c,Gi:()=>p,Hu:()=>o,Nn:()=>u,O8:()=>s,cu:()=>d,el:()=>a,ij:()=>h,l7:()=>l,no:()=>f,pe:()=>n,rl:()=>i,xO:()=>m});let n="https://api.github.com",i="https://github.com/decolua/9remote",s=`${n}/repos/decolua/9remote`,a=`${s}/releases?per_page=100`,l=!1,o=".devcontainer/devcontainer.json",c="NREMOTE_API_KEY",d={name:"9Remote",image:"mcr.microsoft.com/devcontainers/universal:latest",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"nohup 9remote start > /tmp/9remote.log 2>&1 &",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"silent",visibility:"public"}}},u=3e3,h=60,p={available:"Available",starting:"Starting",shutdown:"Shutdown",unknown:"Unknown"},f={user:"/user",codespaces:"/user/codespaces",codespaceByName:e=>`/user/codespaces/${e}`,startCodespace:e=>`/user/codespaces/${e}/start`,userReposList:"/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator",repoContents:(e,t,r)=>`/repos/${e}/${t}/contents/${r}`,createCodespaceForRepo:(e,t)=>`/repos/${e}/${t}/codespaces`,codespaceSecretsPublicKey:"/user/codespaces/secrets/public-key",codespaceSecret:e=>`/user/codespaces/secrets/${e}`,codespaceSecretRepos:(e,t)=>`/user/codespaces/secrets/${e}/repositories/${t}`};function m(e){return`https://${e}-2208.app.github.dev`}},96605:(e,t,r)=>{r.d(t,{$o:()=>eE.A,AX:()=>e_.A,Ay:()=>to,BK:()=>e4.A,BZ:()=>X.A,Bm:()=>F.A,Cp:()=>z.A,Do:()=>l.A,F1:()=>o.A,FE:()=>e1.A,FW:()=>eq.A,Fc:()=>eO.A,GD:()=>O.A,GO:()=>em.A,Gr:()=>P.A,Gv:()=>ew.A,Hx:()=>es.A,Ir:()=>d.A,J4:()=>e0.A,JG:()=>g.A,JU:()=>W.A,Jl:()=>f.A,Kq:()=>ta.A,LM:()=>ec.A,Lt:()=>x.A,M6:()=>eY.A,MA:()=>c.A,Mr:()=>eU.A,P6:()=>et.A,QR:()=>T.A,Qp:()=>a.A,RI:()=>i.A,TB:()=>e6.A,Ud:()=>V.A,VA:()=>ey.A,Vn:()=>ez.A,W1:()=>ef.A,WE:()=>b.A,We:()=>e5.A,Wn:()=>S.A,X:()=>ts.A,X_:()=>D.A,ZH:()=>L.A,ZU:()=>e9.A,Ze:()=>eM.A,Zr:()=>K.A,_O:()=>te.A,_V:()=>ee.A,a4:()=>eb.A,aJ:()=>p.A,ak:()=>Z.A,bE:()=>e7.A,bd:()=>e3.A,cC:()=>u.A,c_:()=>y.A,dJ:()=>N.A,de:()=>ti.A,dx:()=>H.A,e6:()=>eS.A,e9:()=>eN.A,eM:()=>eW.A,ek:()=>eZ.A,es:()=>eA.A,f2:()=>G.A,f5:()=>I.A,gH:()=>eP.A,h1:()=>eh.A,iU:()=>E.A,jG:()=>eL.A,jj:()=>eg.A,jl:()=>w.A,jz:()=>eC.A,kU:()=>$.A,kV:()=>er.A,kr:()=>eo.A,kt:()=>eF.A,lM:()=>e8.A,lP:()=>ev.A,m0:()=>k.A,mN:()=>Q.A,nU:()=>eu.A,qz:()=>J.A,rX:()=>_.A,s3:()=>en.A,sU:()=>eX.A,sv:()=>B.A,ue:()=>eT.A,vR:()=>eI.A,vW:()=>eB.A,vd:()=>j.A,vj:()=>eH.A,vv:()=>ea.A,wB:()=>eG.A,wO:()=>eQ.A,ww:()=>Y.A,xq:()=>ep.A,xv:()=>eR.A,y8:()=>el.A,yQ:()=>m.A,yU:()=>eD.A,yd:()=>s.A,zP:()=>h.A,zW:()=>tt.A});var n=r(54568),i=r(14796),s=r(50683),a=r(30307),l=r(62826),o=r(22061),c=r(46480),d=r(77542),u=r(30824),h=r(8631),p=r(34309),f=r(63322),m=r(34041),g=r(8008),y=r(76265),_=r(17156),b=r(11964),w=r(21411),k=r(1173),v=r(72980),A=r(9901),S=r(3129),T=r(59706),x=r(31381),C=r(40414),R=r(91276),I=r(2099),P=r(26083),$=r(20732),D=r(69724),M=r(93675),L=r(96249),O=r(36293),q=r(16556),U=r(14264),E=r(2939),B=r(74206),N=r(52947),j=r(26463),F=r(45894),W=r(72030),K=r(58588),H=r(10280),z=r(57460),J=r(97380),G=r(80172),V=r(7086),Z=r(83667),Q=r(73012),X=r(19773),Y=r(64529),ee=r(31260),et=r(46396),er=r(86163),en=r(45258),ei=r(81167),es=r(7920),ea=r(68476),el=r(53903),eo=r(58299),ec=r(41956),ed=r(1345),eu=r(76710),eh=r(1778),ep=r(81168),ef=r(17212),em=r(32174),eg=r(6906),ey=r(82099),e_=r(39182),eb=r(23428),ew=r(44073),ek=r(26093),ev=r(15217),eA=r(67310),eS=r(45667),eT=r(63742),ex=r(90466),eC=r(16172),eR=r(63253),eI=r(80367),eP=r(794),e$=r(99348),eD=r(81002),eM=r(21126),eL=r(55769),eO=r(28819),eq=r(67447),eU=r(11344),eE=r(49600),eB=r(14858),eN=r(60527),ej=r(16889),eF=r(19293),eW=r(92534),eK=r(14432),eH=r(23555),ez=r(82797),eJ=r(95740),eG=r(37270),eV=r(4326),eZ=r(35198),eQ=r(41684),eX=r(46548),eY=r(3792),e0=r(87130),e1=r(94411),e2=r(27663),e3=r(87547),e5=r(30774),e4=r(88011),e6=r(44968),e8=r(82791),e9=r(70479),e7=r(96466),te=r(63058),tt=r(96553),tr=r(69458),tn=r(1852),ti=r(39075),ts=r(36645),ta=r(56242);let tl={AlertCircle:i.A,ArrowDown:s.A,ArrowRight:a.A,ArrowUp:l.A,ArrowUpRight:o.A,Ban:c.A,Bell:d.A,Bot:u.A,Bug:h.A,Check:p.A,CheckCircle2:f.A,ChevronDown:m.A,ChevronLeft:g.A,ChevronRight:y.A,ChevronUp:_.A,ChevronsDownUp:b.A,Circle:w.A,ClipboardPaste:k.A,Command:v.A,Compass:A.A,Columns2:S.A,Copy:T.A,CornerDownLeft:x.A,Crown:C.A,Delete:R.A,Download:I.A,ExternalLink:P.A,Eye:$.A,EyeOff:D.A,Facebook:M.A,File:L.A,FileCode:O.A,FileJson:q.A,FilePlus:U.A,FileText:E.A,Files:B.A,Filter:N.A,Folder:j.A,FolderOpen:F.A,FolderPlus:W.A,GitBranch:K.A,GitFork:H.A,Github:z.A,Globe:J.A,GripVertical:G.A,Hand:V.A,HardDrive:Z.A,HelpCircle:Q.A,History:X.A,Home:Y.A,Image:ee.A,ImageOff:et.A,KeyRound:er.A,Keyboard:en.A,Laptop:ei.A,LayoutDashboard:es.A,Link2:ea.A,ListChecks:el.A,Loader2:eo.A,Lock:ec.A,LogIn:ed.A,LogOut:eu.A,Maximize2:eh.A,Minimize2:ep.A,Menu:ef.A,Mic:em.A,MicOff:eg.A,Monitor:ey.A,Moon:e_.A,MoreHorizontal:eb.A,MoreVertical:ew.A,MousePointer2:ek.A,Package:ev.A,Palette:eA.A,PanelLeft:eS.A,PanelLeftClose:eT.A,PanelLeftOpen:ex.A,PanelRight:eC.A,Paperclip:eR.A,Pause:eI.A,Pencil:eP.A,Pi:e$.A,Pin:eD.A,PinOff:eM.A,Play:eL.A,Plug:eO.A,Plus:eq.A,Power:eU.A,PowerOff:eE.A,QrCode:eB.A,RefreshCw:eN.A,Replace:ej.A,RotateCw:eF.A,Save:eW.A,Scissors:eK.A,Search:eH.A,Send:ez.A,SendHorizontal:eJ.A,Settings:eG.A,Share:eV.A,Shield:eZ.A,Smartphone:eQ.A,Sparkles:eX.A,Square:eY.A,SquarePen:e0.A,Star:e1.A,StickyNote:e2.A,Sun:e3.A,Target:e5.A,Terminal:e4.A,Trash2:e6.A,Triangle:e8.A,Type:e9.A,Undo2:e7.A,Upload:te.A,Users:tt.A,Volume2:tr.A,VolumeX:tn.A,Wallpaper:ti.A,X:ts.A,Zap:ta.A};function to(e){let{name:t,size:r=20,className:i="",...s}=e,a=tl[t];return a?(0,n.jsx)(a,{size:r,className:i,strokeWidth:2,...s}):(console.warn(`Icon "${t}" not found in the icon registry`),null)}},96631:(e,t,r)=>{r.d(t,{Yr:()=>o,_r:()=>s,gJ:()=>l,rh:()=>c,sP:()=>a});var n=r(30562);let i=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function s(){let e=window.location.hostname;return"localhost"===e||"::1"===e||"[::1]"===e||e.startsWith("127.")||e.endsWith(".localhost")}function a(){return s()||!!window.__TAURI__}function l(){return!!window.__TAURI__||window.location.port===String(n._8)||!0}function o(){if(s())return!0;let e=i.exec(window.location.hostname);if(!e||e.slice(1).some(e=>Number(e)>255))return!1;let t=Number(e[1]),r=Number(e[2]);return 10===t||192===t&&168===r||172===t&&!!(r>=16)&&!!(r<=31)}function c(e){return s()&&window.location.port!==String(n._8)?e?.loopbackOrigin||n.w||n.lE:null}},99022:(e,t,r)=>{r.d(t,{$4:()=>d,D5:()=>b,HY:()=>p,I8:()=>g,IU:()=>w,LG:()=>u,cH:()=>y,e1:()=>f,lu:()=>k,lz:()=>c,pV:()=>v,t8:()=>h});var n=r(81851);r(55285);var i=r(68469);let s="9remote_device_trust",a="9remote_pending_fp2";function l(){try{return JSON.parse(localStorage.getItem(s)||"{}")}catch{return{}}}function o(e){localStorage.setItem(s,JSON.stringify(e))}function c(e){return l()[e]||null}function d(e){if(!e)return e;let t=c(e)?.tail;return t?`${e}-${t}`:e}function u(e,t){let r=l();r[e]={...r[e]||{},...t},o(r)}async function h(e,t){return e&&t?await (0,i.O)(e,t):null}function p(){let e=sessionStorage.getItem(a);return sessionStorage.removeItem(a),e?JSON.parse(e).fp2??null:null}function f(){try{let e=sessionStorage.getItem(a);if(!e)return null;let{fp2:t,exp:r}=JSON.parse(e);if(!t||Date.now()>r)return sessionStorage.removeItem(a),null;return t}catch{return null}}let m="9remote_api_keys";function g(){try{let e=sessionStorage.getItem(n.El);if(!e)return;sessionStorage.removeItem(n.El);let t=JSON.parse(localStorage.getItem(m)||"[]");if(t.some(t=>{try{return atob(t.key)===e}catch{return!1}}))return;t.push({id:String(Date.now()),key:btoa(e),label:`Key ${t.length+1}`,createdAt:new Date().toISOString(),lastLoginDate:new Date().toISOString()}),localStorage.setItem(m,JSON.stringify(t));try{window.dispatchEvent(new Event(n.N0))}catch{}}catch{}}function y(e){if(e)try{let t=l();delete t[e],o(t)}catch{}}function _(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}async function b(e,t,r){try{let n=await crypto.subtle.importKey("raw",_(e),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",n,_(r),new TextEncoder().encode(t))}catch{return null}}let w=["device:keyIssued","device:tailRejected"];function k(e,t,r){let i=e._auth?.apiKey;if(!i)return!1;if("device:keyIssued"===t){e._auth.tempKey=null,e._auth.socketOptions?.auth&&(e._auth.socketOptions.auth.tempKey=null);try{sessionStorage.removeItem("tempKey")}catch{}let t=r?.tail;return!t||(u(i,{tail:t}),e._tailProofSent=e._adapters.get("rtc")?._peerEpoch??0,sessionStorage.getItem(n.aS)&&(sessionStorage.removeItem(n.aS),sessionStorage.setItem(n.El,`${i}-${t}`),g()),!0)}return"device:tailRejected"===t&&(r?.reason===n.ML.sealUnreadable&&u(i,{hostSealKey:null}),!0)}async function v(e){let t=e._auth?.apiKey;if(!t)return;let i=e._adapters.get("rtc");if(!i?.ready)return;let s=i._peerEpoch??0;if(e._tailProofSent===s)return;let{freshAuth:a}=await Promise.resolve().then(r.bind(r,14511)),l=await a({apiKey:t,tempKey:e._auth?.tempKey||null},"rtc");(l.keyTail||l.keyTailSealed)&&i.send(n.l_.control,{event:"device:tailProof",args:[{keyTail:l.keyTail,keyTailSealed:l.keyTailSealed,tempKey:e._auth?.tempKey||null}]})&&(e._tailProofSent=s)}}}]);