@vantran-se/openchamber-web 1.22.1 → 1.22.2

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 (163) hide show
  1. package/README.md +2 -3
  2. package/bin/cli.js +4 -1
  3. package/bin/cli.test.js +92 -0
  4. package/bin/lib/cli-startup.js +49 -0
  5. package/bin/lib/commands-startup.js +41 -6
  6. package/dist/assets/{CodeMirrorCommentWidgets-C53Q7pbX.js → CodeMirrorCommentWidgets-CV1HNV5l.js} +1 -1
  7. package/dist/assets/{DiffView-Dh1ey2x9.js → DiffView-DkkSa30n.js} +3 -3
  8. package/dist/assets/DirtyBranchSwitchDialog-DW4WaXPc.js +1 -0
  9. package/dist/assets/FilesView-DDu8zDy5.js +17 -0
  10. package/dist/assets/GitView-1Ixo8z-M.js +6 -0
  11. package/dist/assets/{JsonTreeView-Bl0lp9Rs.js → JsonTreeView-DvCLL7dT.js} +1 -1
  12. package/dist/assets/LinearIssuesView-Bs1rZrF2.js +1 -0
  13. package/dist/assets/{MarkdownImageGallery-bA0PS-tn.js → MarkdownImageGallery-DyJUc6h9.js} +1 -1
  14. package/dist/assets/MarkdownRendererImpl-Bdm8vMkS.js +12 -0
  15. package/dist/assets/{OnboardingScreen-D3kYJIb6.js → OnboardingScreen-Dg66B6oB.js} +1 -1
  16. package/dist/assets/{PatchDiff-D6NXAfJk.js → PatchDiff-CAduNjfZ.js} +1 -1
  17. package/dist/assets/{PierreDiffViewer-Ct2A13NO.js → PierreDiffViewer-CTIb1GYD.js} +2 -2
  18. package/dist/assets/PlanView-trDaszfq.js +5 -0
  19. package/dist/assets/SettingsView-DStMfBmy.js +28 -0
  20. package/dist/assets/{SettingsWindow-BiWDBRvb.js → SettingsWindow-DQQFnrSZ.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-BQexMQIm.js → ToolOutputDialog-SjY2XZlA.js} +6 -6
  22. package/dist/assets/ToolPartDiffPreview-DJdzUQPE.js +8 -0
  23. package/dist/assets/{VirtualizedFileDiff-Dpz2ra8h.js → VirtualizedFileDiff-Iehm4iMH.js} +1 -1
  24. package/dist/assets/{WalkthroughView-AX-u2pFg.js → WalkthroughView-BALp2d9O.js} +2 -2
  25. package/dist/assets/{computeVirtualFileMetrics-DtyozJdt.js → computeVirtualFileMetrics-BKZA43vN.js} +2 -2
  26. package/dist/assets/{contextPanelEmbeddedChat-C9EcRSDF.js → contextPanelEmbeddedChat-D2PM_pEv.js} +1 -1
  27. package/dist/assets/{de-DqVn5vme.js → de-DlSNLAcy.js} +6 -5
  28. package/dist/assets/{es-hj43Z53i.js → es-D1GbowZ3.js} +6 -5
  29. package/dist/assets/{fr-BmkZt2mF.js → fr-BPOLXIAY.js} +6 -5
  30. package/dist/assets/{index-DmhujXbT.js → index-Ce0LR32V.js} +1 -1
  31. package/dist/assets/index-D42fPvt4.css +1 -0
  32. package/dist/assets/index-DlFbCkEy.js +39 -0
  33. package/dist/assets/{isDiffPlainText-XyulMHxx.js → isDiffPlainText-DaB2u_Kv.js} +1 -1
  34. package/dist/assets/{isFilePlainText-B19Ddps1.js → isFilePlainText-yJZa2IAC.js} +1 -1
  35. package/dist/assets/{ja-DioMIEGF.js → ja-Dm2-m9io.js} +7 -6
  36. package/dist/assets/{ko-BqPgaQJb.js → ko-CIXlzQ5-.js} +7 -6
  37. package/dist/assets/main-B7qTsd_w.js +930 -0
  38. package/dist/assets/{main-B2a_JfKZ.js → main-CyQrD9dG.js} +2 -2
  39. package/dist/assets/{markdownCore-CWRCqSH2.js → markdownCore-CeEwGgEK.js} +2 -2
  40. package/dist/assets/{miniChat-B3CSU_Ps.js → miniChat-7cPEx4sV.js} +2 -2
  41. package/dist/assets/{mobile-QNcFIVCW.js → mobile-QtzkPTM8.js} +2 -2
  42. package/dist/assets/{patchFileDiff-BpMQZnYu.js → patchFileDiff-No55fDiD.js} +1 -1
  43. package/dist/assets/pl-B2zmkOpw.js +16 -0
  44. package/dist/assets/{pt-BR-BqH8fuCH.js → pt-BR-C-JE5H6y.js} +6 -5
  45. package/dist/assets/{renderElectronMiniChatApp-D77bmLqo.js → renderElectronMiniChatApp-ePTkBJNS.js} +2 -2
  46. package/dist/assets/renderMobileApp-D9RjB9DX.js +25 -0
  47. package/dist/assets/runtimeEndpointReset-DfJIWwwo.js +17 -0
  48. package/dist/assets/{scheduledTasksApi-BSRCtP6T.js → scheduledTasksApi-DuhdyYEa.js} +1 -1
  49. package/dist/assets/{shikiHighlight-DE-OwqGw.js → shikiHighlight-EHEg58-n.js} +1 -1
  50. package/dist/assets/tr-MJmRIzEY.js +7 -0
  51. package/dist/assets/{uk-BkkfxbOs.js → uk-BmD7eM8k.js} +6 -5
  52. package/dist/assets/{useAppFontEffects-COAeIX-D.js → useAppFontEffects-CuJPKtI1.js} +151 -180
  53. package/dist/assets/useInlineCommentController-DD7_7OP_.js +2 -0
  54. package/dist/assets/{useRootScrollLock-C0N9mCwz.js → useRootScrollLock-DRGAe8PN.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-BG3v1Ghq.js → vendor-codemirror-language-data-9ZzoH0o0.js} +2 -2
  56. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  57. package/dist/assets/{web-components-BNMwa0qm.js → web-components-PttKBrhi.js} +1 -1
  58. package/dist/assets/{zh-CN-C6FMdVgv.js → zh-CN-JJHl4ehT.js} +6 -5
  59. package/dist/assets/{zh-TW-CdcMjDxv.js → zh-TW-DPc4DEEW.js} +6 -5
  60. package/dist/index.html +5 -5
  61. package/dist/mini-chat.html +4 -4
  62. package/dist/mobile.html +4 -4
  63. package/package.json +8 -4
  64. package/server/index.js +38 -5
  65. package/server/lib/agent-tool/runtime.js +2 -19
  66. package/server/lib/changelog/update-notes.js +82 -0
  67. package/server/lib/changelog/update-notes.test.js +59 -0
  68. package/server/lib/dev-tunnel/DOCUMENTATION.md +13 -4
  69. package/server/lib/dev-tunnel/runtime.js +4 -4
  70. package/server/lib/dev-tunnel/tunnel.test.js +20 -0
  71. package/server/lib/fs/DOCUMENTATION.md +2 -0
  72. package/server/lib/fs/routes.js +32 -21
  73. package/server/lib/fs/routes.test.js +77 -0
  74. package/server/lib/git/DOCUMENTATION.md +3 -1
  75. package/server/lib/git/routes.js +16 -0
  76. package/server/lib/git/service.js +107 -17
  77. package/server/lib/git/service.test.js +171 -0
  78. package/server/lib/mcp-reconnect/DOCUMENTATION.md +55 -0
  79. package/server/lib/mcp-reconnect/runtime.js +122 -0
  80. package/server/lib/mcp-reconnect/runtime.test.js +140 -0
  81. package/server/lib/message-queue/DOCUMENTATION.md +158 -0
  82. package/server/lib/message-queue/runtime.js +870 -0
  83. package/server/lib/message-queue/runtime.test.js +482 -0
  84. package/server/lib/openchamber-sessions/routes.js +102 -0
  85. package/server/lib/openchamber-sessions/routes.test.js +88 -0
  86. package/server/lib/opencode/DOCUMENTATION.md +13 -5
  87. package/server/lib/opencode/config-paths.test.js +116 -0
  88. package/server/lib/opencode/core-routes.js +1 -0
  89. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  90. package/server/lib/opencode/input-history-scope.js +14 -0
  91. package/server/lib/opencode/managed-plugin-config.js +35 -0
  92. package/server/lib/opencode/openchamber-routes.test.js +2 -2
  93. package/server/lib/opencode/plugins.js +2 -2
  94. package/server/lib/opencode/providers.js +44 -2
  95. package/server/lib/opencode/providers.test.js +131 -4
  96. package/server/lib/opencode/routes.js +4 -4
  97. package/server/lib/opencode/server-startup-runtime.js +1 -1
  98. package/server/lib/opencode/settings-helpers.js +28 -0
  99. package/server/lib/opencode/settings-helpers.test.js +177 -0
  100. package/server/lib/opencode/settings-runtime.js +2 -2
  101. package/server/lib/opencode/settings-runtime.test.js +29 -0
  102. package/server/lib/opencode/shared.js +4 -1
  103. package/server/lib/opencode/shutdown-runtime.js +2 -0
  104. package/server/lib/opencode/skill-routes.js +2 -1
  105. package/server/lib/opencode/snippets.js +1 -2
  106. package/server/lib/package-manager.js +4 -29
  107. package/server/lib/package-manager.test.js +2 -2
  108. package/server/lib/quota/DOCUMENTATION.md +2 -1
  109. package/server/lib/quota/credentials/providers.js +4 -0
  110. package/server/lib/quota/credentials/store.js +1 -1
  111. package/server/lib/quota/credentials/store.test.js +4 -4
  112. package/server/lib/quota/providers/exe-dev.js +75 -0
  113. package/server/lib/quota/providers/exe-dev.test.js +47 -0
  114. package/server/lib/quota/providers/index.js +7 -0
  115. package/server/lib/quota/providers/opencode-go.js +1 -0
  116. package/server/lib/quota/providers/opencode-go.test.js +5 -1
  117. package/server/lib/quota/routes.js +2 -0
  118. package/server/lib/quota/utils/auth.js +1 -1
  119. package/server/lib/relay/DOCUMENTATION.md +1 -1
  120. package/server/lib/relay/host-client.test.js +9 -1
  121. package/server/lib/relay/tunnel-host.js +3 -1
  122. package/server/lib/relay/tunnel-host.test.js +9 -1
  123. package/server/lib/security/request-security.js +21 -6
  124. package/server/lib/security/request-security.test.js +42 -8
  125. package/server/lib/session-assist/runtime.js +1 -0
  126. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  127. package/server/lib/session-goal/create.js +3 -1
  128. package/server/lib/session-goal/runtime.js +77 -11
  129. package/server/lib/session-goal/runtime.test.js +426 -0
  130. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  131. package/server/lib/skills-catalog/install.js +3 -2
  132. package/server/lib/small-model/DOCUMENTATION.md +4 -0
  133. package/server/lib/small-model/call.js +8 -2
  134. package/server/lib/small-model/call.test.js +23 -0
  135. package/server/lib/small-model/index.js +2 -1
  136. package/server/lib/small-model/routes.js +2 -1
  137. package/server/lib/system-prompt/runtime.js +2 -21
  138. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  139. package/server/lib/terminal/runtime.js +180 -26
  140. package/server/lib/terminal/runtime.test.js +553 -26
  141. package/server/lib/terminal/shells.js +17 -0
  142. package/server/lib/terminal/shells.test.js +32 -1
  143. package/server/lib/ui-auth/ui-auth.js +4 -1
  144. package/server/lib/ui-auth/ui-auth.test.js +16 -0
  145. package/server/lib/walkthrough/index.js +1 -0
  146. package/server/lib/walkthrough/routes.test.js +26 -5
  147. package/dist/assets/CommitSection-X-f2RgYr.js +0 -1
  148. package/dist/assets/FilesView-3ZYP72ki.js +0 -17
  149. package/dist/assets/GitView-CMuN7z2Z.js +0 -6
  150. package/dist/assets/LinearIssuesView-CQiUDU8b.js +0 -1
  151. package/dist/assets/MarkdownRendererImpl-BGQi2PLq.js +0 -12
  152. package/dist/assets/PlanView-6AUjzNQn.js +0 -5
  153. package/dist/assets/SettingsView-CHI8fFaK.js +0 -28
  154. package/dist/assets/ToolPartDiffPreview-DPAATNn6.js +0 -8
  155. package/dist/assets/index-L_ncV-6H.css +0 -1
  156. package/dist/assets/index-qES19dlJ.js +0 -7
  157. package/dist/assets/main-CYgSu6dx.js +0 -928
  158. package/dist/assets/pl-slULBF4R.js +0 -15
  159. package/dist/assets/renderMobileApp-BQ3Kdm-d.js +0 -25
  160. package/dist/assets/runtimeEndpointReset-CRGn1gVj.js +0 -16
  161. package/dist/assets/tr-CjEbw1Aw.js +0 -6
  162. package/dist/assets/useInlineCommentController-JsBboQwt.js +0 -2
  163. package/dist/assets/vendor-zod-BLfBSgBh.js +0 -39
@@ -0,0 +1,39 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CEam9pDc.js","assets/vendor-react-BUCujlKS.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
+ import{_ as cs}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ze,d as an,p as Nn,a as Al}from"./vendor-zustand-BAGL70zf.js";import{o as P,n as R,s as w,l as F,r as Pl,u as Ea,a as Xe,b as ls,t as Vs,d as Nr,_ as mt,c as Ml}from"./vendor-zod-CK21ihK-.js";import{c as Il}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as ka,R as wr}from"./vendor-react-BUCujlKS.js";const En=1,Cl="openchamber-relay-v1",Aa=1,Pa=12,kn=1+Pa,xn=64*1024,Rn=5,Dn=128,Ma=0,Ia=1,tn=4,xl=1+tn,Ao=xn-Rn-xl,L={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Rl=new Set(Object.values(L)),Dl=e=>Rl.has(e),It={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},Ye=globalThis.crypto.subtle,Ca={name:"ECDH",namedCurve:"P-256"},xa=16,Qr=32,Ol=16,Po=4,Ra=8;class ft extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Ll=()=>Ye.generateKey(Ca,!0,["deriveBits"]),_l=async e=>{const t=await Ye.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Fl=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new ft("invalid ECDH public key JWK");try{return await Ye.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ca,!0,[])}catch{throw new ft("invalid ECDH public key JWK")}},jl=()=>{const e=new Uint8Array(xa);return globalThis.crypto.getRandomValues(e),e},Nl=async(e,t,n)=>{if(n.length!==xa)throw new ft("invalid handshake nonce length");const r=await Ye.deriveBits({name:"ECDH",public:t},e,256),o=await Ye.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await Ye.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Cl)},o,Qr*2*8)),i=(a,c)=>Ye.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,Qr),["encrypt","decrypt"]),hostToClient:await i(s.slice(Qr),["encrypt","decrypt"])}},Ul=(e,t,n)=>{for(let r=Ra-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Bl=(e,t)=>{let n=0n;for(let r=0;r<Ra;r+=1)n=n<<8n|BigInt(e[t+r]);return n},Hl=e=>{const t=new Uint8Array(Po);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>xn)throw new ft("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(Pa);o.set(t,0),Ul(o,Po,n);const s=new Uint8Array(await Ye.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(kn+s.length);return i[0]=Aa,i.set(o,1),i.set(s,kn),i}}},zl=e=>{let t=0n;return{async decrypt(n){if(n.length<kn+Ol)throw new ft("encrypted frame too short");if(n[0]!==Aa)throw new ft("unsupported encrypted frame version");const r=n.slice(1,kn),o=Bl(r,Po);if(o<=t)throw new ft("frame counter regression");let s;try{s=await Ye.decrypt({name:"AES-GCM",iv:r},e,n.slice(kn))}catch{throw new ft("frame decryption failed")}return t=o,new Uint8Array(s)}}},qn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",$l=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],o=n+1<e.length?e[n+1]:void 0,s=n+2<e.length?e[n+2]:void 0;t+=qn[r>>2],t+=qn[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=qn[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=qn[s&63])}return t},Js=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const n=t;if(n.v!==En)return null;const r=n.batch===!0;return n.t==="ready"?{t:"ready",v:En,batch:r}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:En,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r}:null},Gl=e=>({type:"fail",closeCode:It.ChannelFailure,reason:e}),Wl=async(e,t={})=>{const n=t.batch!==!1,r=await Fl(e),o=await Ll(),s=jl(),i={t:"hello",v:En,clientPubJwk:await _l(o.publicKey),nonce:$l(s),...n?{batch:!0}:{}};let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Js(c)?.t==="ready"?{type:"ignore"}:Gl("plaintext frame on established channel");const l=Js(c);if(l?.t!=="ready")return{type:"ignore"};const d=await Nl(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,channel:{encryptor:Hl(d.clientToHost),decryptor:zl(d.hostToClient)}}}}},Da=4294967295;class ie extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Oe=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Da)throw new ie("invalid stream id");if(n.length>Ao)throw new ie("tunnel payload exceeds maximum size");const o=new Uint8Array(Rn+n.length);return o[0]=r?e|Dn:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,Rn),o},ql=e=>{if(e.length<Rn)throw new ie("tunnel frame too short");const t=e[0],n=(t&Dn)!==0,r=t&~Dn;if(!Dl(r))throw new ie(`unknown tunnel frame type ${r}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:o,payload:e.slice(Rn),hasMoreFragments:n}},Kl=new TextEncoder,Vl=new TextDecoder,Kn=e=>Kl.encode(JSON.stringify(e)),Vn=(e,t)=>{let n;try{n=JSON.parse(Vl.decode(e))}catch{throw new ie("malformed JSON tunnel payload")}if(!t(n))throw new ie("unexpected JSON tunnel payload shape");return n},Oa=(e,t=Ao)=>{if(t<=0||t>Ao)throw new ie("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},Ys=(e,t,n)=>{const r=Oa(n);return r.map((o,s)=>Oe(e,t,o,s<r.length-1))},Jl=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,o=t.get(r);if(!n.hasMoreFragments&&!o)return n.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ie("fragmented message exceeds maximum size");if(s.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:s,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},Yl=e=>{if(e.length===0)throw new ie("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=Ma,s.set(o,1),s.length>xn)throw new ie("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=tn+o.length;if(t>xn)throw new ie("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Ia;let r=1;for(const o of e)n[r]=o.length>>>24&255,n[r+1]=o.length>>>16&255,n[r+2]=o.length>>>8&255,n[r+3]=o.length&255,r+=tn,n.set(o,r),r+=o.length;return n},Ql=e=>{if(e.length<1)throw new ie("empty batch plaintext");const t=e[0];if(t===Ma)return[e.slice(1)];if(t!==Ia)throw new ie(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+tn>e.length)throw new ie("truncated batch frame length");const o=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=tn,r+o>e.length)throw new ie("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ie("empty frame batch");return n},Xl=new Set([L.HttpBody,L.WsText,L.WsBinary]),La=150,Zl=24*1024,ed=32,td=e=>{const t=e.windowMs??La,n=e.maxBatchBytes??Zl,r=e.maxBatchFrames??ed,o=e.now??(()=>Date.now()),s=e.setTimer??((g,y)=>setTimeout(g,y)),i=e.clearTimer??(g=>clearTimeout(g));let a=[],c=0,l=null,d=0,u=!1;const f=()=>{l!==null&&(i(l),l=null)},p=()=>{if(f(),a.length===0)return;const g=a;a=[],c=0,d=o(),e.sendBatch(Yl(g))};return{enqueue:g=>{if(u)return;const y=g[0]&~Dn;if(!Xl.has(y)){a.push(g),p();return}const b=o();if(a.length===0&&b-d>=t){a.push(g),p();return}const S=tn+g.length;if(a.length>0&&1+c+S>xn&&p(),a.push(g),c+=S,c>=n||a.length>=r){p();return}l===null&&(l=s(p,t))},flush:p,dispose(){u=!0,f(),a=[],c=0}}},nd=()=>{let e=1;return{next(){if(e>Da)throw new ie("stream id space exhausted");const t=e;return e+=2,t}}},Ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rd=e=>Ur(e)&&Object.values(e).every(t=>typeof t=="string"),od=e=>Ur(e)&&typeof e.status=="number"&&rd(e.headers),Qs=e=>Ur(e)&&typeof e.reason=="string",sd=e=>Ur(e)&&typeof e.code=="number"&&typeof e.reason=="string",_a=/^[a-z][a-z\d+.-]*:\/\//i,ds="http://tunnel.invalid",id=e=>{try{const t=_a.test(e)?new URL(e):new URL(e,ds);return`${t.pathname}${t.search}`}catch{return e}},Jn=e=>({async*[Symbol.asyncIterator](){yield e}}),ad=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)return;r&&(yield r)}}finally{t.releaseLock()}}}),cd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},ld=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:ad(e)};if(typeof e=="string")return{body:Jn(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Jn(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Jn(cd(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Jn(r),contentType:n}},dd=async(e,t)=>{let n;const r=new Headers;let o="GET",s=null,i;e instanceof Request?(n=e.url,o=e.method,e.headers.forEach((u,f)=>r.set(f,u)),i=e.signal,s=e.body):n=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((u,f)=>r.set(f,u)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=_a.test(n)?new URL(n):new URL(n,ds),{body:c,contentType:l}=await ld(s);l&&!r.has("content-type")&&r.set("content-type",l);const d={};return r.forEach((u,f)=>{d[f]=u}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:d,body:c,signal:i}},Fa="__openchamberAmbiguousTransport",ja=e=>(Object.defineProperty(e,Fa,{value:!0,enumerable:!1,configurable:!0}),e),ud=e=>!e||typeof e!="object"?!1:e[Fa]===!0,Yn=new Uint8Array(0),fd=new TextEncoder,pd=new TextDecoder,ke=e=>e instanceof Error?e:new Error(String(e)),Qn=()=>new DOMException("The operation was aborted.","AbortError"),hd=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(n){e.send(n)},close(n,r){e.close(n,r)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>t.onmessage?.({data:n.data}),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),e.onerror=()=>t.onerror?.(),t},md=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(n){n&&(e.binaryType=n)},onopen:null,onmessage:null,onerror:null,onclose:null,send(n){e.send(n)},close(n,r){e.close(n,r)}};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>{const r=n.data;(typeof r=="string"||r instanceof ArrayBuffer)&&t.onmessage?.({data:r})},e.onerror=()=>t.onerror?.(),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),t},Xs=0,Xr=1,Zs=2,ei=3,yd=new Set([It.AuthFailed,It.DuplicateClient,It.LimitExceeded]),gd={[It.AuthFailed]:"relay authentication failed",[It.DuplicateClient]:"relay connection replaced by another client",[It.LimitExceeded]:"relay connection limit reached"},ti=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},us=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??La,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(E=>hd(new WebSocket(E)));let u=!1,f={state:"idle"};const p=new Set;let h=null,g=null,y=null,b=0,S=0,k=null,I=[],$=!1;const A=E=>{if(!(f.state===E.state&&f.lastError===E.lastError)){f=E;for(const _ of p)try{_(f)}catch{}}},fe=E=>{const _=I;I=[];for(const M of _)M.reject(E)},Q=E=>{const _=I;I=[];for(const M of _)M.resolve(E)},zn=(E,_)=>{E.dead=!0;const M=Array.from(E.streams.values());E.streams.clear();for(const x of M)try{x.fail(_)}catch{}},pe=()=>{k!==null&&(clearTimeout(k),k=null)},fn=()=>{u||k===null||ti()||(pe(),C(),Ut())},$n=()=>{typeof document<"u"&&document.visibilityState==="visible"&&fn()},Nt=()=>{$||typeof window>"u"||($=!0,window.addEventListener("online",fn),typeof document<"u"&&document.addEventListener("visibilitychange",$n))},C=()=>{!$||typeof window>"u"||($=!1,window.removeEventListener("online",fn),typeof document<"u"&&document.removeEventListener("visibilitychange",$n))},He=()=>{if(u||k!==null)return;const E=Math.max(0,S-1),_=a*2**Math.min(E,10),M=ti()?l:c,x=Math.min(M,_);Nt(),k=setTimeout(()=>{k=null,C(),Ut()},x)},pn=()=>{const E=new URL(e.relayUrl);return E.searchParams.set("v",String(En)),E.searchParams.set("role","client"),E.searchParams.set("serverId",e.serverId),e.grant&&E.searchParams.set("grant",e.grant),E.toString()},Ut=async()=>{if(u)return;pe(),b+=1;const E=b;A({state:S>0?"reconnecting":"connecting",lastError:f.lastError});let _;try{_=await Wl(e.hostEncPubJwk,{batch:i})}catch(U){if(E!==b||u)return;he(E,ke(U),!0);return}if(E!==b||u)return;let M;try{M=d(pn())}catch(U){he(E,ke(U));return}g=M;let x=!1,D=null,j=null,ge=null,oe=null,O=Promise.resolve(),N=null,V=null,ze=!1,X=null,se=Date.now();const ae=()=>{D!==null&&(clearInterval(D),D=null),j!==null&&(clearTimeout(j),j=null),ge!==null&&(clearInterval(ge),ge=null),oe!==null&&(clearTimeout(oe),oe=null),X!==null&&(X.dispose(),X=null)};y=ae;function K(U,G=!1,H=!1){if(!(x||E!==b)){x=!0,ae(),N&&(h=null,zn(N,new Error(`relay tunnel reset: ${U.message}`))),fe(U);try{M.close()}catch{}if(g===M&&(g=null),!u){if(S+=1,H){A({state:"error",lastError:U.message});return}A({state:G?"error":"reconnecting",lastError:U.message}),He()}}}const wt=()=>{try{M.send(_.helloText)}catch{}},J=(U,G)=>{V=U,ze=G,D!==null&&(clearInterval(D),D=null),j!==null&&(clearTimeout(j),j=null);const H=new Map,Z=nd(),bt=Jl();let ve=Promise.resolve();const $e=Ht=>{ve=ve.then(async()=>{if(Bt.dead)return;const Wn=await U.encryptor.encrypt(Ht);M.send(Wn)}).catch(()=>{})},St=G?td({windowMs:s,sendBatch:$e}):null;X=St;const Bt={streams:H,assembler:bt,nextStreamId:()=>Z.next(),dead:!1,send(Ht){if(Bt.dead)return;const Wn=Ht[0]&~Dn;Wn!==L.Ping&&Wn!==L.Pong&&(se=Date.now()),St?St.enqueue(Ht):$e(Ht)}};N=Bt,h=Bt,S=0,se=Date.now(),A({state:"connected"}),Q(Bt),ge=setInterval(()=>{Date.now()-se<r||(Bt.send(Oe(L.Ping,0,Yn)),oe===null&&(oe=setTimeout(()=>{oe=null,K(new Error("relay keepalive timeout"))},o)))},r)},tt=(U,G)=>{let H;try{H=ql(G)}catch(ve){K(ke(ve));return}if(oe!==null&&(clearTimeout(oe),oe=null),H.frameType===L.Ping){U.send(Oe(L.Pong,H.streamId,Yn));return}if(H.frameType===L.Pong)return;se=Date.now();let Z=H.payload;if(H.frameType===L.WsText||H.frameType===L.WsBinary){let ve;try{ve=U.assembler.push(H)}catch($e){K(ke($e));return}if(ve===null)return;Z=ve}else if(H.hasMoreFragments){K(new Error("unexpected fragmented tunnel frame"));return}const bt=U.streams.get(H.streamId);bt&&bt.handleFrame(H.frameType,Z)};M.onopen=()=>{x||E!==b||(wt(),D=setInterval(wt,t))},M.onmessage=U=>{if(x||E!==b)return;const G=U.data;if(typeof G=="string"){O=O.then(async()=>{if(x||E!==b)return;const Z=await _.handleText(G);if(Z.type==="established"){if(V)return;J(Z.channel,Z.batch)}else Z.type==="fail"&&K(new Error(`relay handshake failed: ${Z.reason}`))}).catch(Z=>{K(ke(Z))});return}const H=G instanceof ArrayBuffer?new Uint8Array(G):G instanceof Uint8Array?G:null;H&&(O=O.then(async()=>{if(x||E!==b)return;const Z=N,bt=V;if(!Z||!bt){K(new Error("encrypted frame before handshake completed"));return}let ve;try{ve=await bt.decryptor.decrypt(H)}catch($e){K(ke($e));return}if(ze){let $e;try{$e=Ql(ve)}catch(St){K(ke(St));return}for(const St of $e){if(x||E!==b||Z.dead)return;tt(Z,St)}return}tt(Z,ve)}).catch(Z=>{K(ke(Z))}))},M.onclose=U=>{const G=yd.has(U.code);K(new Error(gd[U.code]??`relay socket closed (code ${U.code})`),G,G)},M.onerror=()=>{},j=setTimeout(()=>{j=null,K(new Error("relay handshake timeout"),!0)},n);function he(U,G,H=!1){U!==b||u||(fe(G),S+=1,A({state:H?"error":"reconnecting",lastError:G.message}),He())}},Gn=E=>u?Promise.reject(new Error("relay tunnel closed")):E?.aborted?Promise.reject(Qn()):h&&!h.dead?Promise.resolve(h):new Promise((_,M)=>{let x=null;const D={resolve(j){x&&E&&E.removeEventListener("abort",x),_(j)},reject(j){x&&E&&E.removeEventListener("abort",x),M(j)}};E&&(x=()=>{I=I.filter(j=>j!==D),M(Qn())},E.addEventListener("abort",x,{once:!0})),I.push(D)}),Jr=async(E,_)=>{const M=await dd(E,_),x=M.signal;if(x?.aborted)throw Qn();const D=await Gn(x),j=D.nextStreamId();return await new Promise((ge,oe)=>{let O=!1,N=!1,V=null,ze=null;const X=()=>{D.streams.delete(j),D.assembler.dropStream(j),ze&&x&&x.removeEventListener("abort",ze)},se=J=>{if(!N){if(N=!0,X(),!O){oe(J);return}try{V?.error(J)}catch{}}},ae=J=>{D.dead||D.send(Oe(L.StreamAbort,j,Kn({reason:J})))},K=J=>ja(new Error(J));ze=()=>{ae("aborted"),se(Qn())},D.streams.set(j,{handleFrame(J,tt){if(J===L.HttpResponse){if(O||N)return;let he;try{he=Vn(tt,od)}catch(H){ae("malformed response head"),se(K(ke(H).message));return}const U=he.status===204||he.status===205||he.status===304;let G=null;U||(G=new ReadableStream({start(H){V=H},cancel(){N||(N=!0,X(),ae("response body cancelled"))}})),O=!0,ge(new Response(G,{status:he.status,headers:he.headers})),U&&(N=!0,X());return}if(J===L.HttpBody){if(!O||N)return;try{V?.enqueue(tt)}catch{}return}if(J===L.StreamEnd){if(N)return;if(!O){se(K("tunnel stream ended before response head"));return}N=!0,X();try{V?.close()}catch{}return}if(J===L.StreamAbort){let he="stream aborted by host";try{he=Vn(tt,Qs).reason}catch{}se(K(he))}},fail(J){se(K(J.message))}}),x&&x.addEventListener("abort",ze,{once:!0});const wt={method:M.method,path:M.path,query:M.query,headers:M.headers,hasBody:M.body!==null};D.send(Oe(L.HttpRequest,j,Kn(wt))),(async()=>{try{let J=!1;if(M.body)for await(const tt of M.body){if(N||D.dead)return;for(const he of Oa(tt))D.send(Oe(L.HttpBody,j,he)),J=!0}!N&&!D.dead&&(M.body&&!J&&D.send(Oe(L.HttpBody,j,Yn)),D.send(Oe(L.StreamEnd,j,Yn)))}catch(J){ae("request body failed"),se(K(ke(J).message))}})()})},et=E=>{const _=E.indexOf("?");return _===-1?{path:E,query:""}:{path:E.slice(0,_),query:E.slice(_+1)}},Yr=(E,_)=>{let M=Xs,x=null,D=0,j=!1;const ge={get readyState(){return M},onopen:null,onmessage:null,onerror:null,onclose:null,send(O){if(M!==Xr||!x||x.dead)throw new Error("relay tunnel socket is not open");if(typeof O=="string"){for(const V of Ys(L.WsText,D,fd.encode(O)))x.send(V);return}const N=O instanceof ArrayBuffer?new Uint8Array(O.slice(0)):(()=>{const V=new Uint8Array(O.byteLength);return V.set(new Uint8Array(O.buffer,O.byteOffset,O.byteLength)),V})();for(const V of Ys(L.WsBinary,D,N))x.send(V)},close(O=1e3,N=""){M===ei||M===Zs||(M===Xr&&x&&!x.dead&&(M=Zs,x.send(Oe(L.WsClose,D,Kn({code:O,reason:N})))),oe(O,N))}},oe=(O,N,V=!1)=>{if(!j){if(j=!0,x&&(x.streams.delete(D),x.assembler.dropStream(D)),M=ei,V)try{ge.onerror?.()}catch{}try{ge.onclose?.({code:O,reason:N})}catch{}}};return(async()=>{let O;try{O=await Gn()}catch(X){oe(1006,ke(X).message,!0);return}if(j)return;x=O,D=O.nextStreamId(),O.streams.set(D,{handleFrame(X,se){if(X===L.WsOpened){if(M===Xs){M=Xr;try{ge.onopen?.()}catch{}}return}if(X===L.WsText){try{ge.onmessage?.({data:pd.decode(se)})}catch{}return}if(X===L.WsBinary){const ae=new ArrayBuffer(se.byteLength);new Uint8Array(ae).set(se);try{ge.onmessage?.({data:ae})}catch{}return}if(X===L.WsClose){let ae=1e3,K="";try{const wt=Vn(se,sd);ae=wt.code,K=wt.reason}catch{}oe(ae,K);return}if(X===L.StreamAbort){let ae="stream aborted";try{ae=Vn(se,Qs).reason}catch{}oe(1006,ae,!0)}},fail(X){oe(1012,X.message,!0)}});const{path:N,query:V}=et(E),ze=_&&_.length>0?{path:N,query:V,protocols:_}:{path:N,query:V};O.send(Oe(L.WsOpen,D,Kn(ze)))})(),ge},kl=()=>{if(u)return;u=!0,b+=1,pe(),C(),y?.(),y=null;const E=h;h=null;const _=new Error("relay tunnel closed");E&&zn(E,_),fe(_);try{g?.close()}catch{}g=null,A({state:"idle"})};return Ut(),{fetch:Jr,openWebSocket:Yr,getStatus:()=>f,subscribeStatus(E){return p.add(E),()=>{p.delete(E)}},close:kl}};let Te=null,Qe=null;const wd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Br=()=>Te,Og=()=>!Te||!Qe?null:{relayUrl:Qe.relayUrl,serverId:Qe.serverId,hostEncPubJwk:{...Qe.hostEncPubJwk}},Lg=()=>Te!==null,bd=e=>(Te&&Qe&&wd(Qe,e)||(Te?.close(),Qe=e,Te=us(e)),Te),_g=(e,t)=>{Te!==t&&(Te?.close(),Qe=e,Te=t)},Sd=()=>{Te?.close(),Te=null,Qe=null};let Na=()=>null,Ua="",br={},Rt="",On=0,kt=null,Zt="",Ln=0,Dt="",At=null,dt="",ur=0,fr=0;const fs=1e4,Td=e=>e.toLowerCase()==="authorization",Ba=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!Td(o)&&(t[o]=s)}return t},vd=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},Hr=e=>typeof e!="string"?"":e.trim(),Ed=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return Hr(e)},kd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Ha=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():kd();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},ps=e=>{try{return new URL(e).origin}catch{return""}},za=()=>{Zt="",Ln=0,Dt="",At=null,dt="",ur+=1},Un=()=>{Rt="",On=0,za()},$a=()=>{fr+=1,kt=null,Un(),hs()},Ga=e=>{const t=Hr(e);Ua=t,$a(),Na=()=>t?{type:"bearer",token:t}:null},Wa=e=>{const t=Ba(e);vd(br,t)||(br=t,$a())},zr=()=>{if(Object.keys(br).length>0)return br;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Ba(e):{}},qa=()=>Ua||Ed(),Ad=(e,t)=>{const n=Hr(e);if(!n||typeof t!="number"||!Number.isFinite(t)){Un();return}const r=Rt;Rt=n,On=t,r&&r!==n&&xd()},Ka=()=>!Rt||On<=Date.now()+fs?(Un(),""):Rt,Va=e=>{const t=ps(e);return!t||Dt!==t?"":!Zt||Ln<=Date.now()+fs?(Zt="",Ln=0,Dt="",""):Zt},Pd=()=>{const e=Ka();return!e&&(qa()||typeof window<"u")&&$r().catch(()=>{}),e},Md=e=>{const t=e?Va(e):"";return!t&&e&&typeof window<"u"&&Qa(e).catch(()=>{}),t},Ja=async()=>{const e=await Na(),t=e?.type==="bearer"?Hr(e.token):qa();return t?{type:"bearer",token:t}:null},Ya=e=>{if(kt)return kt;const t=fr,r=(async()=>{const o=await Ja(),s=new Headers;for(const[u,f]of Object.entries(zr()))s.set(u,f);o?.type==="bearer"&&s.set("Authorization",`Bearer ${o.token}`);const i=Br(),a=i?await i.fetch("/auth/url-token",{method:"POST",headers:s}):await fetch(Ha(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===fr&&Un(),new Error(`Failed to mint runtime URL auth token (${a.status})`);const c=await a.json().catch(()=>null),l=typeof c?.token=="string"?c.token.trim():"",d=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==fr)throw new Error("Runtime URL auth token response is stale");if(Ad(l,d),!Rt)throw new Error("Runtime URL auth token response was invalid");return Rt})().finally(()=>{kt===r&&(kt=null)});return kt=r,kt},Id=e=>{const t=ps(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(At&&dt===t)return At;const n=ur,o=(async()=>{const s=await fetch(Ha(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===ur&&t===dt&&(Zt="",Ln=0,Dt=""),new Error(`Failed to mint local runtime URL auth token (${s.status})`);const i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!a||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(n!==ur||t!==dt)throw new Error("Local runtime URL auth token response is stale");return Zt=a,Ln=c,Dt=t,a})().finally(()=>{At===o&&(At=null,dt="")});return At=o,dt=t,At},$r=async e=>{const t=Ka();return t||Ya(e)},Qa=async e=>{const t=ps(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Va(t);return n||((Dt&&Dt!==t||dt&&dt!==t)&&za(),Id(t))};let Jt=0,An=null,Xa=null;const Mo=new Set,Cd=5e3,xd=()=>{for(const e of Mo)try{e()}catch{}},Za=()=>{An!==null&&(clearTimeout(An),An=null)},hs=()=>{if(Za(),Jt<=0||typeof window>"u")return;const e=On-fs-Cd,t=On>0?Math.max(0,e-Date.now()):0;An=setTimeout(()=>{An=null,!(Jt<=0)&&Ya(Xa).catch(()=>{}).finally(()=>{hs()})},t)},Fg=e=>{typeof e=="string"&&e.trim()&&(Xa=e.trim()),Jt+=1,hs();let t=!1;return()=>{t||(t=!0,Jt=Math.max(0,Jt-1),Jt===0&&Za())}},jg=e=>(Mo.add(e),()=>{Mo.delete(e)}),Rd=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(zr()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await Ja();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},Sr=Ze(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),Dd=15e3,Od=5*6e4;let Io=0,Zr=!1;const Ld=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),_d=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Ld(t)},ec=async()=>{if(!Zr){Zr=!0;try{const{runtimeFetch:e}=await cs(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>eu);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Sr.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=Sr.getState();n==="expired"&&r()}}catch{}finally{Zr=!1}}},Fd=(e,t)=>{if(t!==401||Sr.getState().state==="expired"||!_d(e))return;const n=Date.now();n-Io<Dd||(Io=n,ec())};let ni=!1;const Ng=()=>{if(ni)return;ni=!0;let e=Date.now();const t=()=>{if(Sr.getState().state!=="ok")return;const n=Date.now();n-e<Od||(e=n,Io=n,ec())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},Tr=/^[a-z][a-z\d+.-]*:\/\//i,jd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},vr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Nd=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return vr(e)},Ud=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return vr(e)},Bd=()=>Object.keys(zr()).length>0,Hd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Co=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},zd=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Co({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},ri=(e,t,n)=>{if(Tr.test(t)){const s=new URL(t);return Co(s,n),s.toString()}const r=jd(t);if(!e)return zd(r,n);const o=new URL(r,`${e}/`);return Co(o,n),o.toString()},eo=e=>{const t=Pd();if(!t)return e;const n=Tr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),Tr.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},tc=(e,t)=>{const n=Tr.test(e)?new URL(e):new URL(e,Hd(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},oi=(e,t,n)=>{if(!Bd())return null;const r=Ud();if(!r)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);o.searchParams.set("url",t);const s=Md(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",tc(o.toString(),n)):o.toString()}catch{return null}},ms=(e={})=>{const t=vr(e.apiBaseUrl),n=vr(e.realtimeBaseUrl),r=()=>t||Nd(),o=()=>n||r(),s=(a,c)=>ri(r(),a,c),i=(a,c)=>ri(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>eo(s(a,c)),auth:s,health:a=>s("/health",a),rawFile:(a,c)=>s("/api/fs/raw",{path:a,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(a,c)=>{const l=eo(i(a,c));return oi("sse",l,e)||l},websocket:(a,c)=>{const l=tc(eo(i(a,c)),e);return oi("ws",l,e)||l}}};let Er=ms();const ye=()=>Er,$d=e=>{Er=e},nc=e=>(Er=ms(e),Er),Ot=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Gd=()=>typeof window>"u"?"":window.location.origin||"",ys=e=>{if(typeof window>"u")return!1;const t=Gd();if(t&&e.origin===t)return!0;try{const n=new URL(window.location.href||t);return e.protocol===n.protocol&&e.host===n.host}catch{return!1}},gs=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Wd=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),at=(e,t)=>{try{Wd(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},ws=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},pr=e=>{try{const t=ye().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:Ot(e.pathname)}catch{return!1}},to=e=>{if(Ot(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return ys(t)&&Ot(t.pathname)}catch{return!1}},qd=(e,t)=>{try{const n=new URL(e);if(!ys(n))return e;const r=ht(`${n.pathname}${n.search}`,t);return!gs(r)&&(n.protocol==="http:"||n.protocol==="https:")?(ws(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},ht=(e,t)=>e==="/health"?ye().health(t):e.startsWith("/auth/")||e==="/auth"?ye().auth(e,t):Ot(e)?ye().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?qd(e,t):e,Kd=e=>{const t=e instanceof Request?e.url:e.toString();if(!gs(t))return Ot(t);try{return pr(new URL(t))}catch{return!1}},rc=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Vd=(e,t)=>!rc(t),xo=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const n=[];let r=!1,o=!1;for(const[s,i]of t)Vd(s,i)?(n.push([s,encodeURIComponent(i)]),r=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):n.push([s,i]);return o&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},Ge=async(e,t,n=!0)=>{const r=new Headers(xo(e)??e);return t&&new Headers(xo(t)??t).forEach((o,s)=>r.set(s,o)),n?Rd(r):r},Jd=(e,t)=>{if(!t)return e;const n=new URL(e,ds);return ws(n,t),`${n.pathname}${n.search}`},oc=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!gs(n))return Ot(n)?Jd(n,t):null;try{const r=new URL(n);return!ys(r)||!Ot(r.pathname)?null:(ws(r,t),`${r.pathname}${r.search}`)}catch{return null}},Yd=async(e,t,n)=>{const r=Br();if(!r)return null;const o=oc(e,n);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await Ge(s,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(o,{...t,headers:i})},Qd=(e,t)=>{if(typeof e=="string")return ht(e,t);if(e instanceof URL)return ht(e.toString(),t);const n=ht(e.url,t);return n===e.url?e:new Request(n,e)},Xd=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Xn=new Map,Zd=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!Xd.test(t)?null:`GET ${t}`,m=async(e,t={})=>{const{query:n,...r}=t,o=Br(),s=o?oc(e,n):null;let i,a,c;if(o&&s!==null){const h=e instanceof Request?e.headers:void 0,g=await Ge(h,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:g}):()=>o.fetch(s,{...r,headers:g}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const h=Qd(e,n),g=h instanceof Request?h.headers:void 0,y=await Ge(g,r.headers,Kd(h)),b=h instanceof Request?h.url:h instanceof URL?h.toString():String(h);at(b,y),i=h instanceof Request?()=>fetch(new Request(h,{...r,headers:y})):()=>fetch(h,{...r,headers:y}),a=b,c=String(r.method??(h instanceof Request?h.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(h=>(Fd(a,h.status),h));const d=r.signal!=null||e instanceof Request,u=Zd(c,a,d);if(!u)return i();const f=Xn.get(u);if(f)return f.then(h=>h.clone());const p=i();return Xn.set(u,p),p.then(()=>Xn.delete(u),()=>Xn.delete(u)),p.then(h=>h.clone())};let si=!1;const sc=()=>{if(si||typeof window>"u")return;si=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await Yd(t,n??{});if(r)return r;if(typeof t=="string"){if(!to(t)){try{const i=new URL(t);if(pr(i)){const a=await Ge(void 0,n?.headers);return at(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await Ge(void 0,n?.headers),s=ht(t);return at(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!to(o)){if(pr(t)){const a=await Ge(void 0,n?.headers);return at(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await Ge(void 0,n?.headers),i=ht(o);return at(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!to(t.url)){try{const a=new URL(t.url);if(pr(a)){const c=await Ge(t.headers,n?.headers);return at(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await Ge(t.headers,n?.headers),s=ht(t.url);at(s,o);const i=s===t.url?t:new Request(s,t);return e(new Request(i,{...n,headers:o}))}return e(t,n)}},eu=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:at,buildRuntimeFetchUrl:ht,installRuntimeFetchBridge:sc,isLatin1Safe:rc,runtimeFetch:m,sanitizeHeadersForBrowser:xo},Symbol.toStringTag,{value:"Module"})),Ro="openchamber:runtime-endpoint-changed",Do="openchamber:runtime-endpoint-will-change";let nn="",_n="";const no=(e,t,n)=>{try{e[t]=n}catch{}},bs=e=>{try{const t=new URL(e);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,"")||"/",`url:${t.toString().replace(/\/+$/,"")}`}catch{return`url:${e.trim().replace(/\/+$/,"")||"default"}`}},tu="mobile-disconnected",nu="url:default",ic=e=>e===""||e===nu||e===tu,ac=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},cc=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},lc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Gr=()=>nn||ac();let ro="",ii=null,ai,ci;const li=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},B=()=>{if(_n)return _n;const e=li("__OPENCHAMBER_API_BASE_URL__"),t=li("__OPENCHAMBER_LOCAL_ORIGIN__");if(ii===nn&&ai===e&&ci===t)return ro;const n=Gr();return ro=lc(n,cc())?"local":bs(n),ii=nn,ai=e,ci=t,ro},ru=(e={})=>{if(nn||_n)return;const t=e.apiBaseUrl?.trim()||ac();t&&(nn=t,_n=e.runtimeKey?.trim()||(lc(t,cc())?"local":bs(t)))},kr=e=>{const t=e.apiBaseUrl.trim(),n=Gr(),r=B(),o=e.runtimeKey?.trim()||bs(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Do,{detail:s})),nn=t,_n=o,typeof window<"u"){const i=window;no(i,"__OPENCHAMBER_API_BASE_URL__",t),no(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),no(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}nc({apiBaseUrl:t,realtimeBaseUrl:t}),Wa(e.requestHeaders||null),Ga(e.clientToken||null),e.relay?bd(e.relay):Sd(),$r(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ro,{detail:s}))},ou=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Do,t),()=>window.removeEventListener(Do,t)},dc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Ro,t),()=>window.removeEventListener(Ro,t)},su=["local","remote",null],iu=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function uc(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,o=t.status;if(r!==null&&(typeof r!="string"||!su.includes(r)))return{valid:!1};if(typeof o!="string"||!iu.includes(o))return{valid:!1};if(r==="remote"||r==="local"){if(o==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(o==="ok"&&r==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...n}};if(o==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...n}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...n}};if(o==="incompatible"||o==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...n}};if(o==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...n}}}if(r===null){if(o==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(o==="missing")return{valid:!1}}return{valid:!1}}function Ug(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const n=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...n};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...n}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...n};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...n};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...n};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...n};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...n};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...n}}return null}function Bg(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function Hg(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function fc(){if(au()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=uc(t);return n.valid?n.outcome:null}function au(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":uc(e).valid?"valid":"malformed"}let Oo=null;const zg=e=>{Oo=e},Wr=()=>Oo||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),pc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,cu=(e=pc())=>!!e,lu=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,cn=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,_t=()=>lu()?.runtime==="electron",du=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},uu="right",$g=()=>{if(!_t())return!1;const e=du();return e==="win32"||e==="linux"},Gg=e=>e==="left"?"left":uu,Wg=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],de=()=>typeof cn()?.invoke=="function",ln=()=>_t()&&de(),Y=async(e,t)=>{const n=cn();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},qg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},Kg=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},Vg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},Jg=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},Yg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},Qg=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},di=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},oo=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},fu=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),hn=e=>{const t=fu(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ue=()=>{if(typeof window>"u"||!gt())return!1;if(B()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=oo(e),n=oo(Gr());if(!n&&t&&fc()?.target==="local")return!0;if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&hn(t.hostname)&&hn(n.hostname)}const r=oo(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&hn(t.hostname)&&hn(r.hostname)}const o=di(e),s=di(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&hn(r.hostname))},gt=()=>typeof window>"u"?!1:_t(),Xg=async()=>{if(!gt())return!1;try{return!!await Y("desktop_focus_window")}catch{return!1}},pu=()=>gt()&&de()&&ue(),Zg=async()=>{if(!gt())return!1;try{return await Y("desktop_start_window_drag"),!0}catch{return!1}},Be=()=>cu()?!0:Wr()?.runtime?.isVSCode===!0,ew=()=>{const t=Wr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Be()},tw=(e,t=gt())=>e==="web"&&!t,hc=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},nw=async e=>{if(pu())try{const t=await cn()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},hu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mu=P({path:w().min(1),outsideFileGrant:w().min(1),expiresAt:R().finite()}),rw=async e=>{if(de()&&ue())try{const t=await cn()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!hu(t))return{success:!1,error:"File selection cancelled"};const n=typeof t.path=="string"?t.path:"";return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},ow=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!de()||!ue())return{success:!1,error:"Native file access not available"};try{const n=await cn()?.grantFileAccess?.(t),r=mu.safeParse(n);return r.success?{success:!0,...r.data}:{success:!1,error:"File access was not granted"}}catch(n){return console.warn("Failed to request existing file access",n),{success:!1,error:n instanceof Error?n.message:String(n)}}},sw=async e=>({success:!0}),iw=async e=>({success:!0}),aw=async()=>de()?await Y("desktop_check_for_updates"):null,cw=async e=>{if(!de())return!1;const t=cn();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:o});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(r=d),typeof u=="number"&&(o=u),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await Y("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(n)try{const s=n();s instanceof Promise&&await s}catch{}}},lw=async()=>de()?(await Y("desktop_restart"),!0):!1,dw=async()=>{if(!de())return!1;try{return await Y("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},uw=async()=>{if(!de()||!ue())return null;try{const e=await Y("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},yu=async(e,t)=>{if(!de()||!ue())return!1;const n=e?.trim();if(!n)return!1;try{return await Y("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},fw=async e=>{if(!de()||!ue())return!1;const t=e?.trim();if(!t)return!1;try{return await Y("desktop_reveal_path",{path:t}),!0}catch{return yu(t)}},pw=async(e,t)=>{if(!de()||!ue())return null;const n=e?.trim();if(!n)return null;try{const r=await Y("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},hw=async(e,t,n)=>{if(!de()||!ue())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await Y("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},mw=async(e,t,n)=>{if(!de()||!ue())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await Y("desktop_open_file_in_app",{filePath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},yw=async(e,t)=>{if(!de()||!ue())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await Y("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=r;return o.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(o.apps)?{apps:o.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},en=16384,Ar=globalThis,gu=e=>{if(Ar.Buffer)return Ar.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.slice(r,r+32768));return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},mc=e=>{try{if(Ar.Buffer)return Ar.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}},wu=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:(n.hash="",n.toString().replace(/\/+$/g,""))}catch{return null}},bu=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"?null:(n.hash="",n.toString())}catch{return null}},ui=e=>typeof e=="string"&&e.length>0,Su=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ui(t.x)||!ui(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Tu=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,vu=e=>{if(!e||typeof e!="object")return null;const t=e,n=Tu(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=wu(t.url);return r?n===void 0?{type:t.type,url:r}:{type:t.type,url:r,priority:n}:null}if(t.type==="relay"){const r=bu(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=Su(t.hostEncPubJwk);if(!s)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:o,hostEncPubJwk:s,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},Ss=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const n=typeof t.pairingId=="string"?t.pairingId.trim():"",r=typeof t.secret=="string"?t.secret.trim():"";if(!n||!r)return null;const o=Array.isArray(t.candidates)?t.candidates.map(vu).filter(c=>!!c):[];if(o.length===0)return null;const s=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(s){const c=Date.parse(s);if(!Number.isFinite(c)||c<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,a=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:n,secret:r,...i?{label:i}:{},...a?{fingerprint:a}:{},...s?{expiresAt:s}:{},candidates:o}},gw=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),ww=e=>{const t=Ss(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",gu(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},Eu=e=>{const t=e.trim();if(!t||t.length>en)return null;try{const n=new URL(t);if(n.protocol!=="openchamber:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>en)return null;const o=mc(r);return!o||o.length>en?null:Ss(JSON.parse(o))}catch{return null}},bw=e=>{const t=e.trim();if(!t||t.length>en)return null;const n=t.indexOf("?");if(n===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,n)))return null;let r=null,o=null;for(const i of t.slice(n+1).split("&")){const a=i.indexOf("=");if(a===-1)continue;const c=i.slice(0,a),l=i.slice(a+1);c==="v"?r=l:c==="p"&&(o=l)}if(r!=="2"||!o||o.length>en)return null;const s=mc(o);if(!s||s.length>en)return null;try{return Ss(JSON.parse(s))}catch{return null}},rn=e=>typeof e=="object"&&e!==null,ku=e=>e.trim().toLowerCase()==="authorization",Au=e=>{if(!rn(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=typeof r=="string"?r.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||ku(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},Pu=e=>`relay://${e}`,Mu=e=>{if(!rn(e))return null;const t=ce(e,"relayUrl")||ce(e,"relay_url"),n=ce(e,"serverId")||ce(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!rn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Iu=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},Sw=async(e,t)=>{const n=Eu(e);if(!n)throw new Error("invalid-connect-link");const r=await Ou().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Iu(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=async y=>{if(!y.ok)return null;const b=await y.json().catch(()=>null);return(typeof b?.clientToken=="string"?b.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((y,b)=>(y.type==="relay"?1:0)-(b.type==="relay"?1:0));for(const y of a){if(y.type==="relay"){const S=us({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const k=await s(await S.fetch("/api/client-auth/pairing/redeem",o));if(k){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:k};break}}catch{}finally{S.close()}continue}const b=le(y.url);if(b)try{const S=await s(await fetch(`${b}/api/client-auth/pairing/redeem`,o));if(S){i={directUrl:b,token:S};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(y=>y.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=n.candidates.filter(y=>y.type!=="relay").map(y=>le(y.url)).find(y=>!!y),u=i.directUrl||d,f=u||(l?Pu(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&le(y.apiUrl||y.url)===f),h=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),g={...p||{},id:h,label:n.label||p?.label||yc(f),url:f,apiUrl:u,clientToken:i.token,...l?{relay:l}:{}};return{hostId:h,hosts:p?t.map(y=>y.id===h?g:y):[g,...t]}},Cu=/^(t|.*(?:token|auth|secret|api).*)$/i,le=e=>{const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Tw=e=>{const t=le(e);if(!t)return null;try{const n=new URL(t);if((n.pathname.replace(/\/+$/,"")||"/")==="/connect"&&n.searchParams.has("t"))return{persistedUrl:n.origin,redeemUrl:n.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},yc=e=>{const t=le(e);if(!t)return e;try{const n=new URL(t);(n.username||n.password)&&(n.username="",n.password="");const r=Array.from(new Set(Array.from(n.searchParams.keys())));for(const o of r)Cu.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},Zn=(e,t)=>{const n=le(e),r=le(t);if(!n||!r)return!1;try{const o=new URL(n),s=new URL(r);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},ce=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},fi=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},xu=e=>{if(!rn(e))return null;const t=ce(e,"id"),n=ce(e,"label"),r=ce(e,"url"),o=ce(e,"apiUrl")||ce(e,"api_url"),s=ce(e,"clientToken")||ce(e,"client_token"),i=Au(e.requestHeaders),a=Mu(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Pn=e=>le(e.apiUrl||e.url)||e.apiUrl||e.url,Ft=()=>de()?(e,t)=>Y(e,t):null,Ts=async()=>{const e=Ft();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!rn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(xu).filter(a=>!!a):[],o=ce(t,"defaultHostId")||ce(t,"default_host_id")||ce(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ce(t,"localOrigin")||ce(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},Ru=async e=>{const t=Ft();if(!t)return;const n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:n})},Du=async()=>{const e=Ft();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ou=async()=>{const e=Ft();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Lu=8e3,_u=15e3,Fu=400,ju=async(e,t,n,r)=>{const o=new AbortController,s=window.setTimeout(()=>o.abort(),n);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(s)}},pi=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await ju(e,t,Math.min(Lu,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,Fu))}}},Nu=async(e,t)=>{const n=us({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+_u;let s=!1;try{if(!(await pi(n,"/health",o)).ok)return{status:"unreachable",latencyMs:0};const a=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&a.set(d,u);const c=t?.clientToken?.trim();c&&a.set("Authorization",`Bearer ${c}`);const l=await pi(n,"/auth/session",o,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(s=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...s?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{s||n.close()}},vs=async(e,t)=>{const n=Ft();if(!n)return{status:"unreachable",latencyMs:0};const r=await n("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!rn(r))return{status:"unreachable",latencyMs:0};const o=r.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=fi(r,"latencyMs")??fi(r,"latency_ms")??0;return{status:s,latencyMs:i}},vw=async(e,t)=>{const n=Ft();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Ew=async e=>{const t=Ft();t&&await t("desktop_new_window_for_host",{hostId:e})},pt="local",Uu=e=>({id:pt,label:"Local",url:e||gc()}),gc=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Bu=e=>e.id===pt?"local":`host:${e.id}`,kw=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(d=>d.id===pt)?.url||gc(),r=Gr(),o=le(n)||n,s=le(t)||t,i=B(),a=e.find(d=>d.relay&&Bu(d)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Zn(r,n))return{id:pt,label:"Local",url:o};const c=e.find(d=>r?Zn(r,Pn(d)):!1);if(c)return{id:c.id,label:c.label,url:le(Pn(c))||Pn(c)};if(t&&Zn(t,n))return{id:pt,label:"Local",url:o};const l=e.find(d=>t?Zn(t,d.url):!1);return l?{id:l.id,label:l.label,url:le(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:pt,label:"Local",url:o}:{id:"custom",label:yc(s||"Instance"),url:s}},Pr=new Map;let wc=0;const Mr=new Map;let Lo=0,bc={byHostId:{},isProbing:!1};const _o=new Set,Ir=()=>{bc={byHostId:Object.fromEntries(Pr),isProbing:Lo>0};for(const e of _o)try{e()}catch{}},Aw=e=>(_o.add(e),()=>{_o.delete(e)}),Pw=()=>bc,Sc=(e,t)=>{Pr.set(e,t),Ir()},Mw=(e,t)=>{Mr.set(e,++wc),Sc(e,t)},Hu=e=>{const t=new Set([pt,...e]);let n=!1;for(const r of Array.from(Pr.keys()))t.has(r)||(Pr.delete(r),Mr.delete(r),n=!0);n&&Ir()},zu=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",$u=async()=>_t()?Du().catch(()=>""):"",Gu=async(e,t)=>{const n=e.id===pt?t:e.clientToken||"",r=async()=>{const i=await Nu(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const o=le(_t()?Pn(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await vs(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(zu(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},Wu=async e=>{if(!gt())return;const t=++wc;for(const n of e)Mr.set(n.id,t);Lo+=1,Ir();try{const n=await $u();await Promise.all(e.map(async r=>{const o=await Gu(r,n);Mr.get(r.id)===t&&Sc(r.id,o)}))}finally{Lo-=1,Ir()}};let hi=!1;const qu=async()=>{if(hi||!gt())return;hi=!0;const e=await Ts().catch(()=>null);e&&(Hu(e.hosts.map(t=>t.id)),await Wu([Uu(e.localOrigin),...e.hosts]))},Ku=5e3,Vu=1500;let so=!1;const Ju=async e=>{if(!_t()||so)return;const t=`host:${e}`;if(B()===t){so=!0;try{const n=await Ts().catch(()=>null),r=n?.hosts.find(u=>u.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?le(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await m("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const u of a){if(!u||typeof u!="object")continue;const f=u;if(f.type!=="lan"||typeof f.url!="string")continue;const p=le(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await Ru({hosts:n.hosts.map(u=>u.id===e?{...u,apiUrl:l}:u),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const d=await vs(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(d.status==="unreachable"||d.status==="wrong-service"||d.status==="incompatible"||B()!==t)return;kr({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{so=!1}}},Yu=e=>{typeof window>"u"||window.setTimeout(()=>{Ju(e).catch(()=>{})},Ku)},Qu=async e=>{if(!_t())return;const t=await Ts().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(u=>u.id===n);if(!r?.relay)return;const o=`host:${r.id}`;if(B()===o)return;const s=u=>{kr({apiBaseUrl:u,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{kr({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),Yu(r.id)},a=r.apiUrl?le(Pn(r)):null;if(!a){i();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",l=vs(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),d=await Promise.race([l,new Promise(u=>setTimeout(()=>u(null),Vu))]);if(d){if(c(d)){s(a);return}i();return}i(),l.then(u=>{c(u)&&B()===o&&s(a)})};class Ct extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const Iw=e=>e instanceof Ct||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Cr=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},mi=500,Tc=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},Cw=()=>Tc(),Me=(e,t)=>{if(!Tc())return;const n=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>mi&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-mi)},Xu=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("loadAgents")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory")||r.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=Xu);const xw=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Me(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return Me(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw Me(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},Zu=3,ef=3e4,tf=32e3,nf=3600*1e3,rf=600*1e3,of=200,sf=new Set([429,502,503,504]),Ve=new Map,Es=e=>JSON.stringify([B(),e]);function af(){const e=Date.now();for(const[t,n]of Ve){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>nf&&Ve.delete(t)}}typeof setInterval<"u"&&setInterval(af,rf).unref?.();function cf(e){const t=Es(e);let n=Ve.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:ef},Ve.set(t,n);Ve.size>of;){const r=Ve.keys().next().value;if(!r)break;Ve.delete(r)}return n}function lf(e){e&&Ve.delete(Es(e))}function yi(e,t){if(!e)return;const n=cf(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),df(t)&&n.consecutiveErrors>=Zu&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function df(e){return e!==void 0&&sf.has(e)}function uf(e){const t=Ve.get(Es(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,tf*4),!1):!0:!1}function ff(e){if(!(!e||!uf(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const gi="/api",pf=1e4,hf=4e3;function Yt(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}const mf=P({reason:w().optional()});function Ae(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${Yt(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function zt(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${Yt(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const yf=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,wi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gf=14;let bi=0,io=0;const wf=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let r=0;r<e;r+=1)t[r]=Math.floor(Math.random()*256);let n="";for(let r=0;r<e;r+=1)n+=wi[t[r]%wi.length];return n},Si=e=>{const t=Date.now();t!==bi&&(bi=t,io=0),io+=1;const n=BigInt(t)*BigInt(4096)+BigInt(io),r=new Uint8Array(6);for(let s=0;s<6;s+=1)r[s]=Number(n>>BigInt(40-8*s)&BigInt(255));const o=Array.from(r,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${wf(gf)}`},Ti=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(yf.test(t)||typeof window>"u")return t;const n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),t}},vi=()=>{try{return ye().api("/api")}catch{return null}},vc=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},bf=3e4,Sf=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),ao=e=>{const t=e.requestTimeoutMs??bf;return Il({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(Sf(n)||o==="POST")return m(n,r);const s=vc(t),i=r?.signal,a=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let c,l=null;if(i&&a)c=AbortSignal.any([i,s.signal]);else if(i){const d=new AbortController,u=()=>d.abort(i.reason),f=()=>d.abort(s.signal.reason);i.aborted?u():s.signal.aborted?f():(i.addEventListener("abort",u,{once:!0}),s.signal.addEventListener("abort",f,{once:!0}),l=()=>{i.removeEventListener("abort",u),s.signal.removeEventListener("abort",f)}),c=d.signal}else c=s.signal;try{return await m(n,{...r,signal:c})}catch(d){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):d}finally{l?.(),s.cleanup()}}})},$t=e=>e.replace(/\\/g,"/"),Ei=400,ki=()=>{const e=Wr();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Ai=w().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),Tf=P({home:Ai,chatsRoot:Ai.optional()});class vf{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;constructor(t=gi){const r=vi()||t;this.baseUrl=Ti(r),this.client=ao({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==B())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=vi(),n=Ti(t||gi);n!==this.baseUrl&&(this.baseUrl=n,this.client=ao({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear())}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",o=this.scopedClients.get(r);if(o)return o;const s=ao({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,s),s}normalizeCandidatePath(t){if(typeof t!="string")return null;const n=t.trim();if(!n)return null;const r=n.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(r.length>1?r.replace(/\/+$/,""):r)||null}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const s=n[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:s,username:void 0}}const r=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&Me("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:n??null}),this.currentDirectory=n}getDirectory(){return this.currentDirectory}async withDirectory(t,n){const r=async()=>{if(t==null)return n();const s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,n=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(n(s.directory),n(s.worktree),n(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>n(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(t);return this.deriveHomeDirectory(r)}async probeDirectory(t){return await this.getDirectoryAvailability(t)==="available"}async getDirectoryAvailability(t){const n=this.normalizeCandidatePath(t);if(!n)return"unknown";try{const r=await m("/api/fs/list",{query:{path:n}});if(r.ok)return"available";const o=mf.safeParse(await r.json().catch(()=>null)).data,s=Cr(o?.reason);return s==="not-found"||s==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.create({...r?{directory:r}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Ae(o,"session.create")}async getSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...r?{directory:r}:{}});return Ae(o,"session.get")}async deleteSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...r?{directory:r}:{}});return zt(o,"session.delete")===!0}async updateSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s={...n.title!==void 0?{title:n.title}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},...n.time?.archived!==void 0&&n.time.archived!==null?{time:{archived:n.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Ae(i,"session.update")}async getSessionMessages(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.messages({sessionID:t,...o?{directory:o}:{},...typeof n=="number"?{limit:n}:{}});return Ae(s,"session.messages")}async getSessionTodos(t){try{const n=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(n.error)return[];const r=n.data;return!r||!Array.isArray(r)?[]:r}catch{return[]}}shouldNormalizeToTextPlain(t){if(!t)return!1;const n=t.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(t){if(!t)return!1;const n=t.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(t){try{const n=(await cs(async()=>{const{default:u}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:u}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const o=t.url.substring(r+1),s=atob(o),i=new Uint8Array(s.length);for(let u=0;u<s.length;u++)i[u]=s.charCodeAt(u);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((u,f)=>{const p=new FileReader;p.onload=()=>u(p.result),p.onerror=f,p.readAsDataURL(c)});let d=t.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const o=t.url.substring(5,r),s=t.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toNormalizedFilePartInput(t){const n=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??Si("msg"),r=[];if(t.prefaceText&&t.prefaceText.trim()&&r.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};r.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const d=await this.toNormalizedFilePartInput(l);r.push(d)}if(t.additionalParts&&t.additionalParts.length>0)for(const l of t.additionalParts){if(l.text&&l.text.trim()){const d={type:"text",text:l.text};l.synthetic&&(d.synthetic=!0),l.metadata&&(d.metadata=l.metadata),r.push(d)}if(l.files&&l.files.length>0)for(const d of l.files){const u=await this.toNormalizedFilePartInput(d);r.push(u)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&r.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(r.length===0)throw new Error("Message must have at least one part (text or file)");const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;t.format&&console.info("[git-generation][browser] send structured message",{sessionId:t.id,providerID:t.providerID,modelID:t.modelID,agent:t.agent,variant:t.variant,directory:o,baseUrl:this.baseUrl,formatType:t.format.type}),ff(t.providerID),this.assertRuntimeUnchanged(t.runtimeKey);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:n,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:r});if(l.response instanceof Response)s=l.response;else if(l.error){const d=l.response?.status;if(!d){const u=new Error(`Message send transport failure: ${Yt(l.error)}`);throw ud(l.error)?ja(u):u}s=new Response(JSON.stringify(l.error),{status:d})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw yi(t.providerID),l}if(s.ok)return lf(t.providerID),n;let i="";try{i=await s.text()}catch{}const a=i&&i.trim().length>0?`: ${i.trim()}`:"",c=new Error(`Failed to send message (${s.status})${a}`);throw c.status=s.status,yi(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??Si("msg"),r=[];if(t.files&&t.files.length>0)for(const i of t.files)r.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;this.assertRuntimeUnchanged(t.runtimeKey);const s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...r.length>0?{parts:r}:{},messageID:n});return zt(s,"session.command"),n}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,r=await this.client.session.shell({sessionID:t.sessionId,...n?{directory:n}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Ae(r,"session.shell")}async revertSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:n,partID:r});return Ae(i,"session.revert")}async summarizeSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:n,modelID:r});return zt(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Ae(n,"session.unrevert")}async forkSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:n});return Ae(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const n=typeof t=="string"?t.trim():"",r=await this.client.session.status(n?{directory:n}:void 0);return r.error||!r.data||typeof r.data!="object"?null:r.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const t=await m("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async listToolIds(t){try{const n=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,n,r){const o=this.normalizeCandidatePath(r?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:n,...r?.message?{message:r.message}:{}});return zt(s,"permission.reply")===!0}async createPermission(t,n,r,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:n,resources:r,...o?.id?{id:o.id}:{},...o?.save?{save:o.save}:{},...o?.metadata?{metadata:o.metadata}:{},...o?.source?{source:o.source}:{},...o?.agent?{agent:o.agent}:{}});if(s.error!==void 0)return null;const i=s.data?.data;return i===void 0?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(t,n,r){try{const s=await(r?this.getScopedSdkClient(r):this.client).v2.session.permission.get({sessionID:t,requestID:n});if(s.error===void 0){const i=s.data?.data;if(i!==void 0)return{state:"ok",permission:i}}return s.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${Yt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}async replyToQuestion(t,n,r){const o=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n],s=this.normalizeCandidatePath(r)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return zt(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return zt(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${Yt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configCache.get(r);if(o&&o.expiresAt>Date.now())return Me("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return Me("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{Me("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),d=await(n?this.getScopedApiClient(n):this.client).config.get();if(!d.data)throw new Error("Failed to get config");const u=typeof performance<"u"?performance.now():Date.now();return Me("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(u-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:d.data,expiresAt:Date.now()+pf}),d.data})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async updateConfig(t){const n=await this.client.config.update({config:t}),r=Ae(n,"global.config.update");return this.clearConfigCache(),r}async updateConfigPartial(t){const n=await this.getConfig(),r=t(n);return await this.updateConfig(r)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configProvidersInFlight.get(r);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(n?{directory:n}:void 0);return Ae(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.delete(r)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.listAgentsInFlight.get(r);if(o)return o;const s=(async()=>{const i=n?{directory:n}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await m("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${Yt(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(r,s);try{return await s}finally{this.listAgentsInFlight.delete(r)}}async listCommandsWithDetails(t){const n=this.normalizeCandidatePath(t??null)??this.currentDirectory,r=await this.client.command.list(n?{directory:n}:void 0);return(Ae(r,"command.list")||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,source:s.source,template:s.template}))}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;Me("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=vc(hf),o=await m(n,{signal:r.signal}).finally(r.cleanup);if(Me("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return Me("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=ki();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await m(`${this.baseUrl}/opencode/directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,create:!0})});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create project directory"}));throw new Error(l.error||"Failed to create project directory")}return{success:!0,path:(await a.json()).path}}const o={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await m(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const n=await m(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(r.error||"Failed to clone repository")}return await n.json()}async listLocalDirectory(t,n){const o=`${typeof t=="string"?$t(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const d=ki();try{if(d){const y=await d.listDirectory(t||"",n);if(!y||!Array.isArray(y.entries))throw new Ct("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries.map(S=>({name:S.name,path:$t(S.path),isDirectory:!!S.isDirectory,isFile:!S.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+Ei}),b}const u=new URLSearchParams;t&&t.trim().length>0&&u.set("path",t),n?.respectGitignore&&u.set("respectGitignore","true");const f=u.toString(),p=await m(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!p.ok){const y=await p.json().catch(()=>({})),b=typeof y.error=="string"?y.error:"Failed to list directory";throw new Ct(b,{reason:Cr(y.reason),status:p.status})}const h=await p.json();if(!h||!Array.isArray(h.entries))throw new Ct("Directory listing returned an invalid response",{reason:"invalid-response"});const g=h.entries;return this.listDirectoryCache.set(o,{entries:g,expiresAt:Date.now()+Ei}),g}catch(u){throw console.error("Failed to list directory contents:",u),u}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?$t(r):null,s=r?this.getScopedApiClient(r):this.client;try{const i=await s.find.files({query:t,limit:typeof n?.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0,dirs:n?.dirs===!1||n?.type==="file"?"false":"true",type:n?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=$t(c),d=l.split("/").filter(Boolean).pop()||l,u=$t(o?`${o}/${l}`:l);return{name:d,path:u,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=B();if(!t||t==="local"){const n=await hc();if(n)return n}try{const n=await m(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async getFilesystemHomeInfo(){const t=await m(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to resolve the chats root (${t.status})`);return Tf.parse(await t.json())}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const n=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",n,"with path:",t);try{const r=await m(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await r.json().catch(()=>null);if(!r.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const Ne=new vf,Ec=["session","repository","usage","subagents","tasks","mcp","pinned","contextSources"],Rw={session:"chat.workStatus.section.session",repository:"chat.workStatus.section.project",usage:"chat.workStatus.section.usage",subagents:"chat.workStatus.section.subagents",tasks:"chat.workStatus.section.tasks",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},Ef=new Set(Ec),kf=e=>typeof e=="string"&&Ef.has(e),Dw=(e,t)=>!e?.includes(t),Ow=e=>e!=null&&Ec.every(t=>e.includes(t)),Lw=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),kc=e=>{if(!Array.isArray(e))return[];const t=new Set;for(const n of e)kf(n)&&t.add(n);return[...t]},Af=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const s of n)r+=String.fromCharCode(s);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let co=null,lo=null,uo=null;const Pi=new Set;let Mi=!1;const Ac=e=>{if(Pi.add(e),Mi||typeof window>"u")return;Mi=!0;const t=()=>{for(const n of Pi)n()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t()}),document.addEventListener("freeze",t))}catch{}},Pf=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,o=new Set;let s;const i=()=>{if(s=void 0,r.size===0&&o.size===0)return;const c=Array.from(r.entries()),l=Array.from(o);r.clear(),o.clear();for(const[d,u]of c)try{n.setItem(d,JSON.stringify(u,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(d)&&!o.has(d)&&r.set(d,u)}for(const d of l)try{n.removeItem(d)}catch(u){console.error("Failed to remove deferred storage value",u),r.has(d)||o.add(d)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return Ac(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(o.has(c))return null;const l=u=>{if(u===null)return null;try{return JSON.parse(u,t?.reviver)}catch{try{n.removeItem(c)}catch{}return null}},d=n.getItem(c);return d instanceof Promise?d.then(l):l(d)},setItem:(c,l)=>{r.set(c,l),o.delete(c),a()},removeItem:c=>{r.delete(c),o.add(c),a()}}},ks=e=>Pf(()=>Ic(),e),Mf=e=>{const t=new Map,n=new Set;let r;const o=()=>{if(r=void 0,t.size===0&&n.size===0)return;const i=Array.from(t.entries()),a=Array.from(n);t.clear(),n.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(d){console.error("Failed to persist deferred storage value",d),!t.has(c)&&!n.has(c)&&t.set(c,l)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l),t.has(c)||n.add(c)}},s=()=>{r===void 0&&(r=setTimeout(o,0))};return Ac(o),{getItem:i=>t.has(i)?t.get(i)??null:n.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),n.delete(i),s()},removeItem:i=>{t.delete(i),n.add(i),s()},clear:()=>{t.clear(),n.clear(),r!==void 0&&(clearTimeout(r),r=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},Pc=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},As=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},Mc=e=>{const t=As(),n=new Set,r=new Set,o=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},s=(l,d)=>{try{e.setItem(l,d),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,d),n.add(l),r.delete(l)},i=l=>{try{e.removeItem(l),r.delete(l)}catch{r.add(l)}t.removeItem(l),n.delete(l)},a=()=>{const l=[];try{for(let d=0;d<e.length;d+=1){const u=e.key(d);u&&l.push(u)}}catch{}try{e.clear(),r.clear()}catch{for(const d of l)r.add(d)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let d=0;d<e.length;d+=1){const u=e.key(d);u&&!r.has(u)&&!n.has(u)&&l.add(u)}}catch{}for(const d of n)l.add(d);return[...l]};return{getItem:o,setItem:s,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},If=()=>{const e=Pc("localStorage");return e?Mc(e):As()},Ic=()=>(co||(co=If()),co),Bn=()=>(uo||(uo=Mf(Ic())),uo),Cf=()=>{const e=Pc("sessionStorage");return e?Mc(e):As()},xf=()=>(lo||(lo=Cf()),lo),Rf={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem",settingsPageTitle:"1.125rem"},_w={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem",settingsPageTitle:"1.0625rem"};function Ii(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const er={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},fo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...er.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...er.tool.inline})},Df=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"fixel",label:"Fixel Text",description:"Humanist geometric sans-serif with full Ukrainian support.",stack:'"Fixel Text", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Fixel Text",weights:[400,500,600],urls:{400:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Regular.woff2",500:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Medium.woff2",600:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-SemiBold.woff2"}}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'"SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],Of=[{id:"jetbrains-mono",label:"JetBrains Mono",description:"Developer-focused monospace with strong punctuation clarity.",stack:'"JetBrains Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"JetBrains Mono",packageName:"@fontsource/jetbrains-mono",filePrefix:"jetbrains-mono",weights:[400,500,600]}},{id:"fira-code",label:"Fira Code",description:"Readable coding font with ligature support.",stack:'"Fira Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Fira Code",packageName:"@fontsource/fira-code",filePrefix:"fira-code",weights:[400,500,600]}},{id:"geist-mono",label:"Geist Mono",description:"Sharp monospace pair for Geist Sans.",stack:'"Geist Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Geist Mono",packageName:"@fontsource/geist-mono",filePrefix:"geist-mono",weights:[400,500,600]}},{id:"commit-mono",label:"Commit Mono",description:"Code-oriented monospace with polished editor ergonomics.",stack:'"Commit Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Commit Mono",packageName:"@fontsource/commit-mono",filePrefix:"commit-mono",weights:[400,500,600]}},{id:"source-code-pro",label:"Source Code Pro",description:"Adobe monospace designed for source code readability.",stack:'"Source Code Pro", "SFMono-Regular", "Menlo", monospace',source:{family:"Source Code Pro",packageName:"@fontsource/source-code-pro",filePrefix:"source-code-pro",weights:[400,500,600]}},{id:"cascadia-code",label:"Cascadia Code",description:"Microsoft coding font popular in terminals and editors.",stack:'"Cascadia Code", "SFMono-Regular", "Menlo", monospace',source:{family:"Cascadia Code",packageName:"@fontsource/cascadia-code",filePrefix:"cascadia-code",weights:[400,500,600]}},{id:"roboto-mono",label:"Roboto Mono",description:"Neutral monospace companion to Roboto.",stack:'"Roboto Mono", "SFMono-Regular", "Menlo", monospace',source:{family:"Roboto Mono",packageName:"@fontsource/roboto-mono",filePrefix:"roboto-mono",weights:[400,500,600]}},{id:"iosevka",label:"Iosevka",description:"Compact monospace for dense code and terminal layouts.",stack:'"Iosevka", "SFMono-Regular", "Menlo", monospace',source:{family:"Iosevka",packageName:"@fontsource/iosevka",filePrefix:"iosevka",weights:[400,500,600]}},{id:"system-mono",label:"System Mono",description:"Native operating system monospace font.",stack:'ui-monospace, "SFMono-Regular", "Menlo", "Cascadia Mono", "Segoe UI Mono", monospace'}],Cc=e=>Object.fromEntries(e.map(t=>[t.id,t])),Lf=Cc(Df),_f=Cc(Of),Ff="system",jf="system-mono",xc=e=>typeof e=="string"&&e in Lf,Rc=e=>typeof e=="string"&&e in _f,Fo="openchamber.mobileKeyboardMode",Nf='meta[name="viewport"]',Ci="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Fw=()=>!0;function qr(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Uf=e=>qr(e)==="resize-content"?`${Ci}, interactive-widget=resizes-content`:Ci,Bf=()=>{if(typeof window>"u")return"resize-content";try{return qr(localStorage.getItem(Fo))}catch{return"resize-content"}},Dc=e=>{const t=qr(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Fo):localStorage.setItem(Fo,t)}catch{}return t},jw=e=>{const t=Dc(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Nf);if(n instanceof HTMLMetaElement){const r=Uf(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},dn=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(o,s)=>s.toUpperCase()+":");return n==="/"?"/":(n.length>1?n.replace(/\/+$/,""):n)||null},Hf=e=>dn(e)??"",po=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),zf=new Set(["starting","running","stopping"]),$f=e=>!!e?.tabs.some(t=>Qt(t.purpose)&&t.lifecycle!=="exited"),jo=512*1024,Gf=new TextEncoder,Wf=new TextDecoder,ho=e=>{const t=Gf.encode(e);if(t.byteLength<=jo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-jo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Wf.decode(r),byteLength:r.byteLength}},De=(e,t)=>`${e}\0${t}`,Gt=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},qf="terminal-store";let xi=!1,Ri=0;const Kf=P({type:F("project-action"),actionId:w()}),bn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Ri+=1,`tab-${Date.now().toString(36)}-${Ri.toString(36)}`),mo=e=>typeof e=="object"&&e!==null,Qt=e=>e.type==="project-action",tr=(e,t)=>Qt(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Vf=()=>bn().replace(/^tab-/,"exec-"),Di=e=>e==="running"?"running":"exited",Jf=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Yf=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const o=t.get(r.purpose.actionId);(!o||r.status==="running"&&o.status!=="running"||r.status===o.status&&((r.createdAt??0)>(o.createdAt??0)||r.createdAt===o.createdAt&&r.sessionId>o.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},yo={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},Qf=e=>e.trim()||"Action",Xf=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},W=Hf,xr=(e,t)=>`${e}\0${t}`,mn=(e,t,n,r)=>{e.set(xr(t,n),r)},Oi=(e,t,n,r)=>{if(!r)return!1;const o=xr(t,n),s=e.actionMutationRevisions.get(o)??0,i=r.get(o)??0;return s>i},Zf=/^Terminal(?: (\d+))?$/,Li=e=>{let t=0;for(const n of e){const r=Zf.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},Nw=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&zf.has(e.lifecycle),ep=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),nr=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",purpose:{type:"terminal"},label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),go=e=>({tabs:[e],activeTabId:e.id}),me=(e,t)=>e.tabs.findIndex(n=>n.id===t);let wo=null,bo=null;const tp=e=>{if(bo&&wo?.sessions===e.sessions&&wo.nextTabId===e.nextTabId)return bo;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt,purpose:o.purpose.type==="project-action"?{type:"project-action",actionId:o.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return wo={sessions:e.sessions,nextTabId:e.nextTabId},bo=t,t},np=()=>{const e=Al(()=>xf());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},hr=Ze()(an(Nn((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=W(n);r&&e(o=>{if(o.sessions.has(r))return o;const s=new Map(o.sessions),i=bn(),a=nr(i,"Terminal");return s.set(r,go(a)),{sessions:s,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=W(n);return t().sessions.get(r)},getActiveTab:n=>{const r=W(n),o=t().sessions.get(r);if(!o)return;const s=o.activeTabId;return s?o.tabs.find(i=>i.id===s)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(De(W(n),r))??po,matchesActionExecution:(n,r,o)=>{const s=t().sessions.get(W(n))?.tabs.find(i=>i.id===r);return!!(s&&Qt(s.purpose)&&s.purpose.executionId===o)},captureStartedActionMutationRevisions:n=>{const r=W(n),o=xr(r,""),s=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(o)&&s.set(i,a);return s},createTab:n=>{const r=W(n);if(!r)return"tab-invalid";const o=bn();return e(s=>{const i=new Map(s.sessions),a=i.get(r),c=s.nextTabId+1,l=Li(a?.tabs??[]),d=nr(o,l);return a?i.set(r,{...a,tabs:[...a.tabs,d]}):i.set(r,go(d)),{sessions:i,nextTabId:c}}),o},reconcileServerSessions:(n,r,o)=>{const s=W(n);s&&e(i=>{const a=i.sessions.get(s);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,d=!1,u=null;const f=new Set,p=new Set,h=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(De(s,c[0].id))?c[0]:null;h&&r.length>0&&(c.length=0);for(const A of Yf(r)){let fe=c.findIndex(C=>C.terminalSessionId===A.sessionId||C.id===A.sessionId);const Q=A.purpose,zn=Q?.type==="project-action"&&Oi(i,s,Q.actionId,o?.startedActionMutationRevisions);if(Q?.type==="project-action"){f.add(Q.actionId);const C=c.findIndex(He=>Qt(He.purpose)&&He.purpose.actionId===Q.actionId);if(zn){C>=0&&p.add(c[C].id);continue}fe<0&&(fe=C)}const pe=Q?.type==="project-action"?Jf(Q,A.status):{type:"terminal"};if(fe>=0){const C=c[fe];let He=C.purpose.type==="project-action"||Q?.type==="project-action"?Di(A.status):A.status;C.lifecycle==="stopping"&&A.status==="running"&&C.purpose.type==="project-action"&&pe.type==="project-action"&&C.purpose.executionId===pe.executionId&&(He="stopping");const pn=A.createdAt??C.createdAt,Ut=Q?.type==="project-action"&&(C.terminalSessionId!==A.sessionId||pe.type==="project-action"&&pe.executionId!==null&&(C.purpose.type!=="project-action"||C.purpose.executionId!==pe.executionId));if(Ut){const et=De(s,C.id);l=Gt(l,Yr=>Yr===et)??l}const Gn=Q?.type==="project-action"&&A.status==="running"&&(C.terminalSessionId!==A.sessionId||C.lifecycle!=="running"),Jr=C.purpose.type!==pe.type||C.purpose.type==="project-action"&&pe.type==="project-action"&&(C.purpose.actionId!==pe.actionId||C.purpose.executionId!==pe.executionId);if((C.terminalSessionId!==A.sessionId||C.lifecycle!==He||C.isConnecting!==!1||C.createdAt!==pn||Jr)&&(c[fe]={...C,terminalSessionId:A.sessionId,lifecycle:He,purpose:pe,isConnecting:!1,createdAt:pn},Ut&&Object.assign(c[fe],yo),d=!0),Gn){const et={tabId:C.id,createdAt:pn,index:fe};(!u||et.createdAt>u.createdAt||et.createdAt===u.createdAt&&et.index>u.index)&&(u=et)}p.add(C.id);continue}const fn=Q?.type==="project-action"?Qf(Q.actionId):h&&c.length===0?h.label:Li(c),$n=Q?.type==="project-action"?"play":null,Nt={...nr(A.sessionId,fn),terminalSessionId:A.sessionId,lifecycle:Q?.type==="project-action"?Di(A.status):A.status,purpose:pe,iconKey:$n,createdAt:A.createdAt??Date.now()};if(c.push(Nt),d=!0,Q?.type==="project-action"&&A.status==="running"){const C={tabId:Nt.id,createdAt:Nt.createdAt,index:c.length-1};(!u||C.createdAt>u.createdAt||C.createdAt===u.createdAt&&C.index>u.index)&&(u=C)}p.add(Nt.id)}let g=d||!!(h&&r.length>0);const y=c.map(A=>!Qt(A.purpose)||f.has(A.purpose.actionId)||p.has(A.id)||A.lifecycle==="starting"||Oi(i,s,A.purpose.actionId,o?.startedActionMutationRevisions)||A.lifecycle==="exited"&&!A.isConnecting?A:(g=!0,{...A,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:A.purpose.actionId,executionId:null}})),b=a?.activeTabId??null,S=b&&y.some(A=>A.id===b)?b:y[0]?.id??null,k=S?y.find(A=>A.id===S):y[0],I=u&&!ep(k)?u.tabId:S;if(!g&&a&&I===a.activeTabId&&y.length===a.tabs.length&&y.every((A,fe)=>A===a.tabs[fe]))return i;const $=new Map(i.sessions);return $.set(s,{tabs:y,activeTabId:I}),{sessions:$,buffers:l}})},setActiveTab:(n,r)=>{const o=W(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);return!a||a.activeTabId===r||me(a,r)<0?s:(i.set(o,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,o)=>{const s=W(n),i=o.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(s);if(!l)return a;const d=me(l,r);if(d<0||l.tabs[d]?.label===i)return a;const u=[...l.tabs];return u[d]={...u[d],label:i},c.set(s,{...l,tabs:u}),{sessions:c}})},setTabIconKey:(n,r,o)=>{const s=W(n);e(i=>{const a=new Map(i.sessions),c=a.get(s);if(!c)return i;const l=me(c,r);if(l<0)return i;const d=o?.trim()||null;if(c.tabs[l]?.iconKey===d)return i;const u=[...c.tabs];return u[l]={...u[l],iconKey:d},a.set(s,{...c,tabs:u}),{sessions:a}})},closeTab:(n,r)=>{const o=W(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=me(a,r);if(c<0)return s;const l=a.tabs[c].purpose;let d=s.actionMutationRevisions,u=s.nextActionMutationRevision;l.type==="project-action"&&(d=new Map(d),mn(d,o,l.actionId,u),u+=1);const f={actionMutationRevisions:d,nextActionMutationRevision:u},p=a.tabs.filter(S=>S.id!==r),h=De(o,r),g=s.buffers.has(h)?Gt(s.buffers,S=>S===h):null;if(p.length===0){const S=bn(),k=nr(S,"Terminal");i.set(o,go(k));const I={sessions:i,nextTabId:s.nextTabId+1};return g&&(I.buffers=g),{...I,...f}}let y=a.activeTabId;a.activeTabId===r&&(y=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(o,{...a,tabs:p,activeTabId:y});const b={sessions:i};return g&&(b.buffers=g),{...b,...f}})},setTabPurpose:(n,r,o)=>{const s=W(n);e(i=>{const a=i.sessions.get(s);if(!a)return i;const c=me(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(o))return i;const d=[...a.tabs],u=o.type==="project-action"&&o.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==o.executionId);d[c]={...l,purpose:o},u&&Object.assign(d[c],yo);const f=De(s,r),p=u?Gt(i.buffers,y=>y===f)??i.buffers:i.buffers,h=new Map(i.sessions);if(h.set(s,{...a,tabs:d}),o.type!=="project-action")return{sessions:h};const g=new Map(i.actionMutationRevisions);return mn(g,s,o.actionId,i.nextActionMutationRevision),{sessions:h,buffers:p,actionMutationRevisions:g,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,o)=>{const s=W(n),i=t().sessions.get(s);if(!i||me(i,r)<0)return null;const a=Vf();return e(c=>{const l=c.sessions.get(s);if(!l)return c;const d=me(l,r);if(d<0)return c;const u=[...l.tabs];u[d]={...u[d],purpose:{type:"project-action",actionId:o,executionId:a},lifecycle:"starting",terminalSessionId:null,...yo,isConnecting:!1};const f=new Map(c.sessions);f.set(s,{...l,tabs:u});const p=new Map(c.actionMutationRevisions);mn(p,s,o,c.nextActionMutationRevision);const h=De(s,r),g=Gt(c.buffers,y=>y===h)??c.buffers;return{sessions:f,buffers:g,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,o,s)=>{const i=W(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0)return a;const u=l.tabs[d];if(!tr(u,s?.expectedExecutionId))return a;const f=o!==null&&u.terminalSessionId!==o,p=o?"running":u.terminalSessionId?"exited":u.lifecycle,h={...u,terminalSessionId:o,lifecycle:p,isConnecting:!1},g=De(i,r),y=f&&a.buffers.has(g)?Gt(a.buffers,k=>k===g):null,b=[...l.tabs];b[d]=h,c.set(i,{...l,tabs:b});const S={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(Qt(u.purpose)){const k=new Map(a.actionMutationRevisions);mn(k,i,u.purpose.actionId,a.nextActionMutationRevision),S.actionMutationRevisions=k,S.nextActionMutationRevision=a.nextActionMutationRevision+1}return y&&(S.buffers=y),S})},setTabLifecycle:(n,r,o,s)=>{const i=W(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0||!tr(l.tabs[d],s?.expectedExecutionId))return a;const u=l.tabs[d];if(u.lifecycle===o&&!u.isConnecting)return a;const f=[...l.tabs];if(f[d]={...u,lifecycle:o,isConnecting:!1},c.set(i,{...l,tabs:f}),u.purpose.type!=="project-action"||u.lifecycle===o)return{sessions:c};const p=new Map(a.actionMutationRevisions);return mn(p,i,u.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,o,s)=>{const i=W(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0||!tr(l.tabs[d],s?.expectedExecutionId))return a;const u=[...l.tabs];return u[d]={...u[d],isConnecting:o},c.set(i,{...l,tabs:u}),{sessions:c}})},replaceBuffer:(n,r,o,s)=>{const i=W(n);e(a=>{const c=a.sessions.get(i);if(!c||me(c,r)<0)return a;const l=De(i,r),d=a.buffers.get(l)??po;if(d.lastSequence>s)return a;const u=ho(o);if(d.lastSequence===s&&d.byteLength===u.byteLength&&d.chunks.map(h=>h.data).join("")===u.text)return a;const f=a.nextChunkId,p=new Map(a.buffers);return p.set(l,{chunks:u.text?[{id:f,data:u.text,byteLength:u.byteLength}]:[],byteLength:u.byteLength,lastSequence:s}),{buffers:p,nextChunkId:u.text?f+1:f}})},appendToBuffer:(n,r,o,s,i)=>{if(!o)return;const a=W(n);e(c=>{const l=c.sessions.get(a);if(!l||me(l,r)<0)return c;const d=De(a,r),u=c.buffers.get(d)??po;if(s!==void 0&&s<=u.lastSequence)return c;const f=c.nextChunkId,p=ho(o),h=i!==void 0&&i!==o?ho(i).text:void 0,g={id:f,data:p.text,...h!==void 0?{replayData:h}:{},byteLength:p.byteLength},y=[...u.chunks,g];let b=u.byteLength+g.byteLength;for(;b>jo&&y.length>1;){const k=y.shift();if(!k)break;b-=k.byteLength}const S=new Map(c.buffers);return S.set(d,{chunks:y,byteLength:b,lastSequence:s??u.lastSequence}),{buffers:S,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,s={})=>{const i=W(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0)return a;const u=l.tabs[d];if(!tr(u,s.expectedExecutionId))return a;const f=s.autoOpened??u.previewAutoOpened,p=s.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===f&&u.previewUrlLocked===p)return a;const h=[...l.tabs];return h[d]={...u,previewUrl:o,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:h}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const o=W(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=me(a,r);if(c<0)return s;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return s;const d=[...a.tabs];return d[c]={...l,previewAutoOpened:!0},i.set(o,{...a,tabs:d}),{sessions:i}})},removeDirectory:n=>{const r=W(n);e(o=>{const s=new Map(o.sessions);s.delete(r);const i=De(r,""),a=Gt(o.buffers,u=>u.startsWith(i)),c=xr(r,"");let l;for(const u of o.actionMutationRevisions.keys())u.startsWith(c)&&(l??=new Map(o.actionMutationRevisions),l.delete(u));const d={sessions:s};return a&&(d.buffers=a),l&&(d.actionMutationRevisions=l),d})},clearAll:()=>{e({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1})}}),{name:qf,storage:np(),partialize:tp,merge:(e,t)=>{if(!mo(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!mo(l))continue;const d=Array.isArray(l.tabs)?l.tabs:[],u=[],f=new Map;for(const y of d){if(!mo(y))continue;const b=typeof y.id=="string"?y.id:null;if(!b)continue;const S=Xf(b);S!==null&&(o=Math.max(o,S));const k=S===null?b:bn();f.set(b,k);const I=Kf.safeParse(y.purpose).data,$=I?{type:"project-action",actionId:I.actionId,executionId:null}:{type:"terminal"};u.push({id:k,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:$,createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const p=typeof l.activeTabId=="string"?l.activeTabId:null,h=p?f.get(p)??p:null,g=h?u.some(y=>y.id===h):!1;r.set(c,{tabs:u,activeTabId:g?h:u[0].id})}const s=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,s,o+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!xi){xi=!0;const e=hr.persist,t=()=>{hr.getState().hasHydrated||hr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Le=20,rp=8,_i=4096,op=2160*60*6e4,z=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",s=/^[A-Za-z]:\/$/.test(r);return!o&&!s&&(r=r.replace(/\/+$/,"")),r},ct=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,ut=(e,t)=>{const n=z(t),r=z(e);if(!n||!r)return!1;const o=ct(n),s=ct(r);return s===o||s.startsWith(`${o}/`)},yn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=z(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>z(p)).filter(p=>p.length<=_i&&ut(p,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>z(p)).filter(p=>p.length<=_i&&ut(p,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?z(i.selectedPath):null,d=l&&ut(l,s)?l:a[0]??null,u=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-u>op)continue;const f=n[s];if(f){const p=Array.from(new Set([...f.openPaths,...a])),h=Array.from(new Set([...f.expandedPaths,...c])),g=f.selectedPath??d??p[0]??null;n[s]={openPaths:p,selectedPath:g,expandedPaths:h,touchedAt:Math.max(f.touchedAt,u)};continue}n[s]={openPaths:a,selectedPath:d,expandedPaths:c,touchedAt:u}}return _e(n,Le)},_e=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},Wt=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},sp=Ze()(an(Nn((e,t)=>({byRoot:{},activeRuntimeKey:B(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:yn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:yn(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=z((n||"").trim()),i=z((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!ut(i,s)||e(a=>{const c=a.byRoot[s],l=Wt(c),d=l.openPaths.includes(i),u=d?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&d&&c.selectedPath===f)return a;const p={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:f}};return{byRoot:_e(p,Le)}})},removeOpenPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=h=>ct(h)===c,d=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!d)return i;const u=a.openPaths.filter(h=>!l(h)),f=d?u[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:_e(p,Le)}})},removeOpenPathsByPrefix:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=c.endsWith("/")?c:`${c}/`,d=h=>{const g=ct(h);return g===c||g.startsWith(l)},u=a.openPaths.filter(h=>!d(h));if(u.length===a.openPaths.length)return i;const f=a.selectedPath&&d(a.selectedPath)?u[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:_e(p,Le)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=c.endsWith("/")?c:`${c}/`,d=a.expandedPaths.filter(f=>{const p=ct(f);return p!==c&&!p.startsWith(l)});if(d.length===a.expandedPaths.length)return i;const u={...i.byRoot,[o]:{...a,expandedPaths:d,touchedAt:Date.now()}};return{byRoot:_e(u,Le)}})},setSelectedPath:(n,r,o)=>{const s=z((n||"").trim()),i=r?z(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!ut(i,s)||e(a=>{const c=a.byRoot[s],l=Wt(c),d=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&d===c.openPaths)return a;const u={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:i}};return{byRoot:_e(u,Le)}})},ensureSelectedPath:n=>{const r=z((n||"").trim());if(!r)return;const o=t().byRoot[r];if(!o||o.selectedPath)return;const s=o.openPaths[0]??null;s&&t().setSelectedPath(r,s)},toggleExpandedPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||!ut(s,o)||e(i=>{const a=i.byRoot[o],c=Wt(a),d=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===d&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:d}};return{byRoot:_e(u,Le)}})},collapseAllExpandedPaths:n=>{const r=z((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...Wt(s),expandedPaths:[]}};return{byRoot:_e(i,Le)}})},expandPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||!ut(s,o)||e(i=>{const a=i.byRoot[o],c=Wt(a);if(c.expandedPaths.includes(s)&&a)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:_e(d,Le)}})},expandPaths:(n,r)=>{const o=z((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>z((i||"").trim())).filter(i=>i&&ut(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=Wt(a),l=new Set(c.expandedPaths),d=s.filter(f=>!l.has(f));if(d.length===0)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...d]}};return{byRoot:_e(u,Le)}})}}),{name:"files-view-tabs-store",version:3,storage:ks(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:B(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:yn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,rp).map(([r,o])=>[r,{byRoot:yn(o.byRoot),updatedAt:o.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:n}},merge:(e,t)=>{const n=e&&typeof e=="object"?e:{},r=n.runtimeSnapshots&&typeof n.runtimeSnapshots=="object"?n.runtimeSnapshots:{},o=B();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:yn(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),Oc=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",ip=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},Uw=()=>{if(typeof window>"u"||!Oc()||ap()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},ap=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Be()?"vscode":gt()?"desktop":"web"},Lc="ask",Fi=e=>e==="attach"||e==="inline"||e==="ask"?e:Lc;function ji(e){return e==="vim"?"vim":"default"}const Je="all";function Ni(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Ui(e){return e==="me"||e==="any"?e:"any"}function _c(e){return typeof e!="string"?Je:e.trim()||Je}function Bi(e,t){const n=B();if(ic(n))return e;const r={...e};return t===Je?delete r[n]:r[n]=t,r}function cp(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e)){if(!n.trim()||typeof r!="string")continue;const o=_c(r);o!==Je&&(t[n]=o)}return t}function Hi(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const rr={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},nt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},or=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,lp=e=>{if(!e||typeof e!="object")return!1;const t=e;return or(t.completion,rr.completion)&&or(t.error,rr.error)&&or(t.question,rr.question)&&or(t.subtask,rr.subtask)},dp=380,up=380,fp=1400,Fc=12,zi=120,gn=280;let $i=0;const pp=e=>ne(e),ne=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},jc=e=>Number.isFinite(e)?Math.min(fp,Math.max(up,Math.round(e))):dp,Fn=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Rr=e=>{const t=Fn(e);return t&&pp(t)||null},Dr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>zi?t.slice(0,zi):t:null},Ps=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Nc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.id=="string"?t.id.trim():"",r=typeof t.path=="string"?t.path.trim():"";return n&&r?{id:n,path:r}:null},hp=(e,t)=>(e==="file"||e==="browser")&&t||e,Uc=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return hp(e,t)},Bc=(e,t)=>t===e?e:`${e}:${t}`,Hc=e=>{const t=Fn(e.targetPath),n=e.mode==="terminal"?Rr(e.targetDirectory):null,r=Uc(e.mode,t,e.dedupeKey);return{id:Bc(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Nc(e.projectPlanRef),dedupeKey:r,label:Dr(e.label),sessionTitleFallback:Dr(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Ps(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},zc=(e,t,n)=>{const r=new Map;for(const i of e)r.set(i.mode,(r.get(i.mode)??0)+1);const o=[...r.entries()].filter(([,i])=>i>t);if(o.length===0)return e;const s=new Set;for(const[i,a]of o){const l=[...e.filter(d=>d.mode===i)].sort((d,u)=>d.touchedAt-u.touchedAt).filter(d=>d.id!==n);for(const d of l.slice(0,a-t))s.add(d.id)}return s.size===0?e:e.filter(i=>!s.has(i.id))},$c=e=>{if(!Array.isArray(e))return[];const t=Be(),n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o;if(s.mode!=="diff"&&s.mode!=="walkthrough"&&s.mode!=="file"&&s.mode!=="context"&&s.mode!=="plan"&&s.mode!=="chat"&&s.mode!=="browser"&&s.mode!=="git"&&s.mode!=="pr"&&s.mode!=="linear"&&s.mode!=="notes"&&s.mode!=="terminal"||t&&s.mode==="browser")continue;const i=Fn(typeof s.targetPath=="string"?s.targetPath:null),a=s.mode==="terminal"?Rr(s.targetDirectory):null,c=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,l=Nc(s.projectPlanRef);if(s.mode==="plan"&&c!==null!=(l!==null))continue;const d=Uc(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),u=Bc(s.mode,d);!u||r.has(u)||(r.add(u),n.push({id:u,mode:s.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:d,label:Dr(typeof s.label=="string"?s.label:null),sessionTitleFallback:Dr(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:Ps(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},on=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Tt=e=>{if(e){const t=$c(e.tabs),n=on(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},touchedAt:Date.now()}},mp=(e,t,n)=>{const r=n?.reveal!==!1,o=Hc(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(d=>!(d.mode==="file"&&!d.targetPath)):e.tabs,i=s.findIndex(d=>d.id===o.id),a=i===-1?[...s,o]:s.map((d,u)=>u===i?{...d,mode:o.mode,targetPath:o.targetPath||d.targetPath,targetDirectory:o.targetDirectory,projectPlanId:o.projectPlanId??d.projectPlanId,projectPlanRef:o.projectPlanRef??d.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||d.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:d),c=r?o.id:e.activeTabId??o.id,l=zc(a,Fc,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:on(l,c),touchedAt:Date.now()}},yp=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),o=e.tabs.filter(l=>!n.has(l.id));if(o.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:o,activeTabId:on(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?o.filter(l=>l.mode===i):[],c=a.length>0?a.reduce((l,d)=>d.touchedAt>=l.touchedAt?d:l):null;return{...e,tabs:o,activeTabId:c?.id??on(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},gp=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===n);if(r===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(r,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},wp=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),So=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=ne(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=$c(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat"||i.mode==="terminal")&&(a=[Hc({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,targetDirectory:i.targetDirectory,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=on(a,c),d=zc(a,Fc,l),u={};if(i.widthByMode&&typeof i.widthByMode=="object")for(const[f,p]of Object.entries(i.widthByMode))(f==="diff"||f==="file"||f==="context"||f==="plan"||f==="chat"||f==="browser"||f==="git"||f==="pr"||f==="linear"||f==="notes"||f==="terminal")&&typeof p=="number"&&Number.isFinite(p)&&(u[f]=jc(p));n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:on(d,l),widthByMode:u,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},vt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},Se=Ze()(an(Nn((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:gn,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,showOpenCodeRestartConfirm:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:Ff,monoFont:jf,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Bf(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Je,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...nt.completion},error:{...nt.error},question:{...nt.question},subtask:{...nt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!ip(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Lc,enterToSend:!1,enterToSendConfigured:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>{const r=!n.isSidebarOpen;return r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:gn}:{isSidebarOpen:r}})},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==gn?{isSidebarOpen:n,sidebarWidth:gn}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:gn}:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((o,s)=>typeof o=="string"&&o.trim()!==""&&n.indexOf(o)===s):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>({contextEditorTreeVisible:!n.contextEditorTreeVisible}))},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(n)))})},openContextSurface:(n,r)=>{const o=ne((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],a=i?.tabs??[],c=a.find(u=>u.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const f=(a.find(p=>p.mode==="terminal")??null)?.targetDirectory??null;if(f){const p=hr.getState().getDirectoryState(f);if($f(p))return}s.openContextPanelTab(o,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),s.closeContextPanel(o);return}const d=a.filter(u=>u.mode===r);if(d.length>0){l();const u=d.reduce((f,p)=>p.touchedAt>=f.touchedAt?p:f);s.setActiveContextPanelTab(o,u.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=ne((n||"").trim());if(!s)return;const i=r.mode==="terminal"?{...r,targetDirectory:Rr(r.targetDirectory)===s?null:Rr(r.targetDirectory)}:r;e(a=>{const c=a.contextPanelByDirectory[s],l=Tt(c),d={...a.contextPanelByDirectory,[s]:mp(l,i,o)};return{contextPanelByDirectory:vt(d,20)}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=ne((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Ps(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=ne((n||"").trim()),s=Fn(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=ne((n||"").trim()),a=Fn(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=ne((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=ne((n||"").trim()),s=(r||"").trim();!o||!s||Be()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=ne((n||"").trim());!r||Be()||($i+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${$i}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=ne((n||"").trim());if(!s||Be())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(s,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},o)},setContextPanelTabTargetPath:(n,r,o)=>{const s=ne((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:wp(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=ne((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Tt(a);if(!c.tabs.some(d=>d.id===s)||c.activeTabId===s&&c.isOpen)return i;const l={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===s?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:vt(l,20)}})},reorderContextPanelTabs:(n,r,o)=>{const s=ne((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],d=Tt(l);if(!d.tabs.some(p=>p.id===i)||!d.tabs.some(p=>p.id===a))return c;const u=gp(d,i,a);if(u.tabs===d.tabs)return c;const f={...c.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:vt(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=ne((n||"").trim()),s=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!o||s.length===0)return;const i=s.map(a=>t().contextPanelByDirectory[o]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[o],l=Tt(c);if(!l.tabs.some(u=>s.includes(u.id)))return a;const d={...a.contextPanelByDirectory,[o]:yp(l,s)};return{contextPanelByDirectory:vt(d,20)}});for(const a of i)a.mode==="file"&&a.targetPath&&sp.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=ne((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Tt(s),isOpen:!1}};return{contextPanelByDirectory:vt(i,20)}})},toggleContextPanelExpanded:n=>{const r=ne((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=Tt(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:vt(a,20)}})},setContextPanelWidth:(n,r,o)=>{const s=ne((n||"").trim());s&&e(i=>{const a=i.contextPanelByDirectory[s],c=Tt(a),l={...i.contextPanelByDirectory,[s]:{...c,widthByMode:{...c.widthByMode,[r]:jc(o)}}};return{contextPanelByDirectory:vt(l,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(o=>o.workStatusExpandedSections[n]===r?o:{workStatusExpandedSections:{...o.workStatusExpandedSections,[n]:r}})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(o=>{const s=o.workStatusHiddenSections,i=s.includes(n);return r===!i?o:{workStatusHiddenSections:r?s.filter(a=>a!==n):[...s,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)]})},setContextRailSurfaceVisible:(n,r)=>{e(o=>{const s=o.contextRailHiddenSurfaces,i=s.includes(n);return r===!i?o:{contextRailHiddenSurfaces:r?s.filter(a=>a!==n):[...s,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?o:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:o})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{isArchivePageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isMultiRunLauncherOpen:!1}:{worktreesPageProjectId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:""})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},setSessionGoalDefaultBudgetEnabled:n=>{e({sessionGoalDefaultBudgetEnabled:n})},setSessionGoalDefaultBudget:n=>{e({sessionGoalDefaultBudget:n})},setCollapsibleThinkingBlocks:n=>{e({collapsibleThinkingBlocks:n})},setChatRenderMode:n=>{e({chatRenderMode:n})},setActivityRenderMode:n=>{e({activityRenderMode:n})},setShowDeletionDialog:n=>{e({showDeletionDialog:n})},setShowOpenCodeRestartConfirm:n=>{e({showOpenCodeRestartConfirm:n})},setAutoDeleteEnabled:n=>{e({autoDeleteEnabled:n})},setAutoSaveEnabled:n=>{e({autoSaveEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));e({autoDeleteAfterDays:r})},setSessionRetentionAction:n=>{e({sessionRetentionAction:n})},setAutoDeleteLastRunAt:n=>{e({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));e({messageLimit:r})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:n=>{e({globalDraftStarters:n})},setDraftStartersVisible:n=>{e({draftStartersVisible:n})},setTerminalFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(52,r));e({terminalFontSize:o})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(32,r));e({editorFontSize:o})},setUiFont:n=>{e({uiFont:n})},setMonoFont:n=>{e({monoFont:n})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));e({padding:r}),t().applyPadding()},setCornerRadius:n=>{e({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=t(),r=document.documentElement,o=n/100,s=Object.entries(Rf);if(o===1){for(const[i]of s)r.style.removeProperty(Ii(i));return}for(const[i,a]of s){const c=parseFloat(a);Number.isFinite(c)&&r.style.setProperty(Ii(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,o=n/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);r.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{e({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{e(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{e({diffWrapLines:n})},setWalkthroughTocWidth:n=>{e({walkthroughTocWidth:Math.round(n)})},setGitChangesViewMode:n=>{e({gitChangesViewMode:n})},setToolJsonViewMode:n=>{e({toolJsonViewMode:n})},setLinearIssueListStatus:n=>{e({linearIssueListStatus:Ni(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Ui(n)})},setLinearIssueListTeamId:n=>{const r=_c(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Bi(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=B();e(r=>({linearIssueListTeamId:ic(n)?Je:r.linearIssueListTeamIdByRuntime[n]??Je}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Hi(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Je,linearIssueListTeamIdByRuntime:Bi(n.linearIssueListTeamIdByRuntime,Je),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},reorderFavoriteModel:(n,r,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===r),c=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const o=n.filter(i=>typeof i=="string"&&i.length>0),s=r.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?r:{providerOrder:o}})},toggleHiddenModel:(n,r)=>{e(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},hideAllModels:(n,r)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...s]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const o=Array.from(new Set(n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...o]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},addRecentModel:(n,r)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...s].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>{if(o.recentAgents.includes(r))return o;const s=o.recentAgents;return{recentAgents:[r,...s].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const s=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";e(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const u=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null}:{}}))},openMultiRunLauncher:()=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(o=>({agentMemoryViewedAt:r>(o.agentMemoryViewedAt[n]??0)?{...o.agentMemoryViewedAt,[n]:r}:o.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:Fi(n)})},setEnterToSend:n=>{e({enterToSend:n})},setEnterToSendConfigured:n=>{e({enterToSendConfigured:n})},setWideChatLayoutEnabled:n=>{e({wideChatLayoutEnabled:n})},setCodeBlockLineWrap:n=>{e({codeBlockLineWrap:n})},setShowToolFileIcons:n=>{e({showToolFileIcons:n})},setShowTurnChangedFiles:n=>{e({showTurnChangedFiles:n})},setShowExpandedBashTools:n=>{e({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{e({showExpandedEditTools:n})},setTimeFormatPreference:n=>{e({timeFormatPreference:n})},setWeekStartPreference:n=>{e({weekStartPreference:n})},setDesktopWindowControlsPosition:n=>{e({desktopWindowControlsPosition:n==="left"?"left":"right"})},setDesktopWindowControlsStyle:n=>{e({desktopWindowControlsStyle:n==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:n=>{e({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{e({userMessageRenderingMode:n})},setCollapsibleUserMessages:n=>{e({collapsibleUserMessages:n})},setStickyUserHeader:n=>{e({stickyUserHeader:n})},setPromptNavigatorEnabled:n=>{e({promptNavigatorEnabled:n})},setShowSplitAssistantMessageActions:n=>{e({showSplitAssistantMessageActions:n})},setAllowPromptingSubagentSessions:n=>{e({allowPromptingSubagentSessions:n})},setReportUsage:n=>{e({reportUsage:n})},viewPagerPage:"center",setViewPagerPage:n=>{e({viewPagerPage:n}),e({isSessionSwitcherOpen:n==="left"})},setShortcutOverride:(n,r)=>{e(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:ji(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:ks(),version:19,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const o of Object.values(r)){if(!o||typeof o!="object")continue;const s=o,i=s.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(s.tabs))continue;const a=new Set,c=[];for(const l of s.tabs){if(!l||typeof l!="object")continue;const d=l;if(d.mode!=="preview"){typeof d.id=="string"&&a.add(d.id),c.push(d);continue}const u=typeof d.targetPath=="string"?d.targetPath:"",f=typeof d.dedupeKey=="string"&&d.dedupeKey.trim()?d.dedupeKey.trim():u||"browser",p=f==="browser"?"browser":`browser:${f}`;a.has(p)||(a.add(p),c.push({...d,mode:"browser",id:p,dedupeKey:f}))}if(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(d=>typeof d.id=="string");s.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const o=localStorage.getItem("openchamber:files:auto-save-enabled");o!==null&&(r=o!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&lp(n.notificationTemplates)&&(n.notificationTemplates={completion:{...nt.completion},error:{...nt.error},question:{...nt.question},subtask:{...nt.subtask}}),t<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,s=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof s=="number"&&!r.has(s)&&(n.messageLimit=s),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=So(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[s,i]of Object.entries(r))typeof s=="string"&&typeof i=="string"&&(o[s]=i);n.shortcutOverrides=o}return t<6&&(n.contextPanelByDirectory=So(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=So(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ni(n.linearIssueListStatus),n.linearIssueListAssignee=Ui(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=cp(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Hi(n.linearIssueListPriority),n.fileEditorKeymap=ji(n.fileEditorKeymap),n.largeTextPasteBehavior=Fi(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,showOpenCodeRestartConfirm:e.showOpenCodeRestartConfirm,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,toolJsonViewMode:e.toolJsonViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,enterToSend:e.enterToSend,enterToSendConfigured:e.enterToSendConfigured,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Ms="session",Is=40,bp=1,Sp=100,Cs=e=>e==="global"||e==="session",Kr=e=>e!=null&&Number.isInteger(e)&&e>=bp&&e<=Sp,Xt="openchamber-input-history.v1",Tp=8,vp=50,Ep=[40,25,10,5,1],To=Object.freeze([]);let We=null,Gi=0;const Mn=(e=Ms,t=Is)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Gc=()=>(Gi+=1,Date.now()*1e3+Gi),Wc=e=>JSON.stringify([e]),No=(e,t,n)=>JSON.stringify([e,t,n]),xs=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},kp=()=>{const e=xs(),t=Ie?JSON.stringify(yr(Ie.base)):We;if(!e)return t;try{return e.getItem(Xt)??(Ie?null:We)}catch{return t}},Wi=Pl(w(),ls()),Ap=P({key:w().min(1),source:Ea([F("file-url"),F("vscode-file")]),filename:w().min(1),mimeType:w().min(1),size:R().finite().nonnegative(),reference:w().min(1)}),Pp=P({text:w(),attachmentKeys:Xe(w()),restorableAttachments:Xe(Ap),submittedAt:R().finite().nonnegative()}),Mp=P({touchedAt:R().finite().nonnegative(),entries:Xe(ls())}),Ip=(e,t)=>{try{const n=JSON.parse(e),o=(t===1?Vs([w().trim().min(1)]):Vs([w().trim().min(1),w().trim().min(1),w().trim().min(1)])).safeParse(n);if(!o.success)return null;if(t===3){const s=dn(o.data[1]);if(!s||s!==o.data[1])return null}return o.data}catch{return null}},qi=(e,t)=>{const n=[];for(const[r,o]of Object.entries(e)){if(!Ip(r,t))continue;const s=Mp.safeParse(o);if(!s.success)continue;const i=s.data.entries.map(a=>Pp.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:s.data.touchedAt,entries:i}])}return Object.fromEntries(n)},Cp=()=>{const e=kp();if(e===null)return Mn();try{const t=JSON.parse(e),n=P({version:F(1),entryLimit:R().int().optional(),scope:Ea([F("global"),F("session")]).optional(),global:Wi.default({}),session:Wi.default({})}).safeParse(t);return n.success?{entryLimit:Kr(n.data.entryLimit)?n.data.entryLimit:Is,scope:n.data.scope??Ms,globalBuckets:qi(n.data.global,1),sessionBuckets:qi(n.data.session,3)}:Mn()}catch{const t=xs();if(t)try{t.removeItem(Xt)}catch{}return We=null,Mn()}};let Ie=null,mr=Mn();const Ki=(e,t,n)=>{const r={...e};for(const o of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[o])===JSON.stringify(n[o]))continue;const s=n[o];if(!s){delete r[o];continue}const i=new Set((t[o]?.entries??[]).map(d=>JSON.stringify(d))),a=new Set(s.entries.map(d=>JSON.stringify(d))),c=(e[o]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!i.has(u)||a.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of s.entries){const u=JSON.stringify(d);!i.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),r[o]={touchedAt:Math.max(s.touchedAt,e[o]?.touchedAt??0),entries:c}}return r},Sn=()=>{const e=Cp();if(mr=e,!Ie)return e;const{base:t,value:n}=Ie;return Uo({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Ki(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Ki(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},qc=(e,t)=>e.slice(Math.max(0,e.length-t)),Vi=(e,t,n)=>{const r=Object.entries(e).map(([o,s])=>[o,{touchedAt:s.touchedAt,entries:qc(s.entries,n)}]).sort((o,s)=>s[1].touchedAt-o[1].touchedAt).slice(0,t);return Object.fromEntries(r)},Uo=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Vi(e.globalBuckets,Tp,t),sessionBuckets:Vi(e.sessionBuckets,vp,t)}),yr=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Ji=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Tn=e=>{const t=Uo(e),n=JSON.stringify(yr(t));Ie={base:mr,value:t};const r=xs();if(!r)return We=n,t;try{return r.setItem(Xt,n),Ie=null,We=n,t}catch(i){if(!(i instanceof Error)||!Ji(i))return We=n,t}try{r.removeItem(Xt)}catch{}for(const i of Ep){const a=Uo(t,i),c=JSON.stringify(yr(a));try{return r.setItem(Xt,c),Ie=null,We=c,a}catch(l){if(!(l instanceof Error)||!Ji(l))return Ie={base:mr,value:a},We=c,a}}const o=Mn(t.scope,t.entryLimit),s=JSON.stringify(yr(o));try{r.setItem(Xt,s),Ie=null}catch{Ie={base:mr,value:o}}return We=s,o},xp=(e,t,n)=>{const r=e.trim(),o=dn(t),s=n.trim();return!r||!o||!s?null:{runtimeKey:r,directory:o,sessionId:s}},Kc=e=>e.source==="vscode"&&e.vscodeSource==="file"?dn(e.vscodePath??null):e.dataUrl.trim()||null,Rp=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Bo=e=>{const t=Kc(e),n=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),n].join("|")},Dp=e=>{const t=Kc(e);return!t||!Rp(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Bo(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Bo(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},Op=(e,t)=>({text:e,attachmentKeys:t.map(Bo),restorableAttachments:t.map(Dp).filter(n=>n!==null)}),Lp=(e,t)=>e.length===t.length&&e.every((n,r)=>{const o=t[r];return o!==void 0&&n.key===o.key&&n.source===o.source&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.size===o.size&&n.reference===o.reference}),_p=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&Lp(e.restorableAttachments,t.restorableAttachments),Yi=(e,t,n,r)=>{const o=e?[...e.entries]:[];for(const s of t){const i=o.at(-1);_p(i,s)||o.push({text:s.text,attachmentKeys:[...s.attachmentKeys],restorableAttachments:s.restorableAttachments.map(a=>({...a})),submittedAt:Gc()})}return{touchedAt:n,entries:qc(o,r)}},Fp=Tn(Sn()),Vc=Ze(e=>({...Fp,applyEntryLimit:t=>{Kr(t)&&e(n=>{const r=Sn();if(r.entryLimit===t)return{...n,...r};const o=Tn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},applyScope:t=>{Cs(t)&&e(n=>{const r=Sn();if(r.scope===t)return{...n,...r};const o=Tn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const o=Sn(),s=Gc(),i=Wc(t.runtimeKey),a=No(t.runtimeKey,t.directory,t.sessionId),c=Tn({entryLimit:o.entryLimit,scope:o.scope,globalBuckets:{...o.globalBuckets,[i]:Yi(o.globalBuckets[i],n,s,o.entryLimit)},sessionBuckets:{...o.sessionBuckets,[a]:Yi(o.sessionBuckets[a],n,s,o.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Sn(),o=No(t.runtimeKey,t.directory,t.sessionId);if(!(o in r.sessionBuckets))return{...n,...r};const s={...r.sessionBuckets};delete s[o];const i=Tn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:s});return{...n,...i}})}})),Bw=(e,t)=>t?e.scope==="session"?e.sessionBuckets[No(t.runtimeKey,t.directory,t.sessionId)]?.entries??To:e.globalBuckets[Wc(t.runtimeKey)]?.entries??To:To,jp=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Np=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
3
+ `).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const o=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:o,endLine:Math.max(o,Math.floor(e.endLine)),text:r}},Up=(e,t)=>{const n=t.map(Np).filter(s=>s!==null);if(n.length===0)return e;const o=["<terminal_context>",...n.flatMap((s,i)=>[`- ${s.terminalLabel} lines ${s.startLine}-${s.endLine}:`,...s.text.split(`
4
+ `).map((a,c)=>` ${s.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
5
+ `);return e.trim()?`${e.trim()}
6
+
7
+ ${o}`:o},Hw=e=>{const t=jp.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const o of(t[1]??"").split(`
8
+ `)){const s=/^- (.+) lines (\d+)-(\d+):$/.exec(o);if(s){r&&n.push(r),r={terminalLabel:s[1],startLine:Number(s[2]),endLine:Number(s[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(o);r&&i&&(r.text+=`${r.text?`
9
+ `:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},Rs="openchamberContext",Ds="opencodeComment";function Bp(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
10
+ \`\`\`${e.language}
11
+ ${e.code}
12
+ \`\`\`
13
+
14
+ ${e.text}`}case"terminal":return Up("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
15
+
16
+ ${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
17
+
18
+ ${e.body}${e.text?`
19
+
20
+ ${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
21
+ `).map(r=>`> ${r}`).join(`
22
+ `);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
23
+ ${n}${e.text?`
24
+
25
+ ${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
26
+ ${e.quote.split(`
27
+ `).map(n=>`> ${n}`).join(`
28
+ `)}${e.text?`
29
+
30
+ ${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
31
+ \`\`\`
32
+ ${e.output}
33
+ \`\`\`${e.text?`
34
+
35
+ ${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":return""}}function zw(e,t){const n=t??Bp(e),r={[Rs]:e};return e.kind==="code-comment"&&(r[Ds]={path:e.fileLabel,selection:{startLine:e.startLine,endLine:e.endLine,startChar:0,endChar:0},comment:e.text,preview:e.code,origin:e.source==="diff"?"review":"file"}),{text:n,synthetic:!0,metadata:r}}function $w(e){switch(e.source){case"terminal":return{kind:"terminal",terminalId:e.terminalId??"",terminalLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,output:e.code};case"preview-annotation":return{kind:"browser-annotation",pageUrl:e.fileLabel,prompt:e.code,text:e.text};case"pr-comment":return{kind:"pr-comment",label:e.fileLabel,body:e.code,text:e.text};case"pr-check":return{kind:"pr-check",label:e.fileLabel,output:e.code,text:e.text};case"file-quote":{const t={kind:"file-quote",fileLabel:e.fileLabel,quote:e.code,text:e.text};return e.startLine>0&&e.endLine>0&&(t.startLine=e.startLine,t.endLine=e.endLine),t}case"chat-quote":{const t={kind:"chat-quote",quote:e.code,text:e.text};return e.fileLabel&&(t.messageId=e.fileLabel),t}case"diff":case"file":case"plan":{const t={kind:"code-comment",source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,language:e.language,code:e.code,text:e.text};return e.source==="diff"&&e.side&&(t.side=e.side),t}}}const Jc=Nr("kind",[P({kind:F("code-comment"),source:mt(["diff","file","plan"]),fileLabel:w(),startLine:R(),endLine:R(),side:mt(["original","modified"]).optional(),language:w(),code:w(),text:w()}),P({kind:F("terminal"),terminalId:w(),terminalLabel:w(),startLine:R(),endLine:R(),output:w()}),P({kind:F("browser-annotation"),pageUrl:w(),prompt:w(),text:w()}),P({kind:F("pr-comment"),label:w(),body:w(),text:w()}),P({kind:F("pr-check"),label:w(),output:w(),text:w()}),P({kind:F("file-quote"),fileLabel:w(),startLine:R().optional(),endLine:R().optional(),quote:w(),text:w()}),P({kind:F("chat-quote"),messageId:w().optional(),quote:w(),text:w()}),P({kind:F("github-issue"),number:R().int().positive(),title:w(),url:w()}),P({kind:F("github-pr"),number:R().int().positive(),title:w(),url:w()}),P({kind:F("linear-issue"),identifier:w().min(1),title:w(),url:w()})]),Yc=P({path:w(),selection:P({startLine:R().finite(),endLine:R().finite(),startChar:R().finite().optional(),endChar:R().finite().optional()}).optional(),comment:w(),preview:w().optional(),origin:mt(["file","review"]).optional()}),Hp=P({[Rs]:Jc,[Ds]:Yc.optional()});function zp(e){if(e.type!=="text")return null;const t=Jc.safeParse(e.metadata?.[Rs]);if(t.success)return t.data;const n=Yc.safeParse(e.metadata?.[Ds]);if(n.success){const r=n.data;return r.selection?{kind:"code-comment",source:r.origin==="review"?"diff":"file",fileLabel:r.path,startLine:r.selection.startLine,endLine:r.selection.endLine,language:"",code:r.preview??"",text:r.comment}:{kind:"file-quote",fileLabel:r.path,quote:r.preview??"",text:r.comment}}return null}function Gw(e){return e.some(t=>zp(t)!==null)}function Ww(e){switch(e.kind){case"code-comment":{const t={source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,code:e.code,language:e.language,text:e.text};return e.side&&(t.side=e.side),t}case"terminal":return{source:"terminal",fileLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,code:e.output,language:"",text:"",terminalId:e.terminalId};case"browser-annotation":return{source:"preview-annotation",fileLabel:e.pageUrl,startLine:0,endLine:0,code:e.prompt,language:"",text:e.text};case"pr-comment":return{source:"pr-comment",fileLabel:e.label,startLine:0,endLine:0,code:e.body,language:"",text:e.text};case"pr-check":return{source:"pr-check",fileLabel:e.label,startLine:0,endLine:0,code:e.output,language:"",text:e.text};case"file-quote":return{source:"file-quote",fileLabel:e.fileLabel,startLine:e.startLine??0,endLine:e.endLine??0,code:e.quote,language:"",text:e.text};case"chat-quote":return{source:"chat-quote",fileLabel:e.messageId??"",startLine:0,endLine:0,code:e.quote,language:"",text:e.text};case"github-issue":case"github-pr":case"linear-issue":return null}}const Os="queue",Ls=e=>e==="steer"||e==="queue",_s=(e,t)=>e==="immediate"?"steer":Ls(e)?e:t===!1?"steer":t===!0?"queue":Os,it=()=>!Be(),Qi=50,Ho=(e,t,n=B())=>{const r=dn(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},Ee=e=>`${e.runtimeKey}
36
+ ${e.directory}
37
+ ${e.sessionId}`,Pt=e=>{const[t,n,...r]=e.split(`
38
+ `);return Ho(r.join(`
39
+ `),n,t)},$p=P({providerID:w().min(1),modelID:w().min(1),agent:w().optional(),variant:w().optional()}),Gp=P({id:w(),filename:w(),mimeType:w(),size:R(),source:mt(["local","server","vscode"]),serverPath:w().optional(),dataUrl:w().optional()}),Wp=Nr("kind",[P({kind:F("context"),text:w(),metadata:Hp,instructions:w().optional()}),P({kind:F("instruction"),text:w()}),P({kind:F("synthetic"),text:w()})]),Fs=P({id:w().min(1),createdAt:R(),content:w(),text:w(),agentMention:w().optional(),attachments:Xe(Gp),context:Xe(Wp).optional(),sendConfig:$p}),js=P({sessionId:w().min(1),directory:w(),items:Xe(Fs),sendingId:w().nullable()}),Xi=P({revision:R(),sessions:Xe(js)}),In=P({revision:R(),session:js}),qp=In.extend({item:Fs}),Kp=In.extend({items:Xe(Fs)}),Vp=e=>{const t=e.indexOf(",");if(!e.startsWith("data:")||t===-1)return null;const n=e.slice(5,t),r=e.slice(t+1);try{if(n.endsWith(";base64")){const i=atob(r),a=new ArrayBuffer(i.length),c=new Uint8Array(a);for(let l=0;l<i.length;l+=1)c[l]=i.charCodeAt(l);return a}const o=new TextEncoder().encode(decodeURIComponent(r)),s=new ArrayBuffer(o.byteLength);return new Uint8Array(s).set(o),s}catch{return null}},Jp=e=>{const t=e.dataUrl??"",n=t?Vp(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},sr=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(Jp)),e.context&&(t.context=e.context),t},Yp=e=>{const t={id:e.id,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source,dataUrl:e.dataUrl};return e.serverPath&&(t.serverPath=e.serverPath),t},Zi=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(r=>!!r.dataUrl).map(Yp),context:e.context??[],sendConfig:t};return e.agentMention&&(n.agentMention=e.agentMention),n},Et=async(e,t,n)=>{const r=await m(t,n);if(!r.ok){const s=new Error(`Message queue request failed (${r.status})`);throw s.status=r.status,s}const o=e.safeParse(await r.json());if(!o.success)throw new Error("Invalid message queue response");return o.data},rt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},ot=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,ir=new Set,lt=new Map;let vo=0;const ea=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),Qp=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:ea(n.queuedMessages??{}),quarantinedLegacyMessages:ea({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:_s(n.followUpBehavior,n.queueModeEnabled??null)}},Fe=(e,t)=>{const{[t]:n,...r}=e;return r},ar=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(o=>o.id!==n);return r.length===0?{queuedMessages:Fe(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},Xp=(e,t,n,r)=>{let o=e.queuedMessages,s=e.sendingIds;for(const i of new Set([...Object.keys(o),...Object.keys(s)])){const a=Pt(i);a?.runtimeKey!==t||a.sessionId!==n||(lt.get(i)??-1)>r||(lt.set(i,r),o=Fe(o,i),s=Fe(s,i))}return{queuedMessages:o,sendingIds:s}},Qc=Ze()(an(Nn((e,t)=>{const n=(s,i,a)=>{if(a!==B())return;const c=Ho(s.sessionId,s.directory,a);if(!c){if(s.items.length>0)return;e(d=>Xp(d,a,s.sessionId,i));return}const l=Ee(c);(lt.get(l)??-1)>i||(lt.set(l,i),e(d=>{const u=s.items.map(sr),f=u.length>0?{...d.queuedMessages,[l]:u}:Fe(d.queuedMessages,l),p=s.sendingId?{...d.sendingIds,[l]:[s.sendingId]}:Fe(d.sendingIds,l);return{queuedMessages:f,sendingIds:p}}))},r=async s=>{try{const i=await Et(Xi,"/api/message-queue"),a=i.sessions.find(c=>c.sessionId===s.sessionId)??{sessionId:s.sessionId,directory:s.directory,items:[],sendingId:null};n(a,i.revision,s.runtimeKey)}catch{}},o=async(s,i,a)=>{try{const c=await Et(In,i,a);n(c.session,c.revision,s.runtimeKey)}catch(c){console.warn("[queue] server update failed:",c),await r(s)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:Os,sendingIds:{},addToQueue:async(s,i)=>{const a=Ee(s),c=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,l={id:c,content:i.content,text:i.text??i.content,createdAt:Date.now(),sendConfig:i.sendConfig};if(i.agentMention&&(l.agentMention=i.agentMention),i.attachments&&i.attachments.length>0&&(l.attachments=i.attachments),i.context&&i.context.length>0&&(l.context=i.context),e(f=>{const p=f.queuedMessages[a]??[],h={...f.queuedMessages,[a]:[...p,l].slice(-20)},g=Object.keys(h);if(g.length>Qi){g.sort((y,b)=>(h[y]?.[0]?.createdAt??0)-(h[b]?.[0]?.createdAt??0));for(const y of g.slice(0,g.length-Qi))delete h[y]}return{queuedMessages:h}}),!it())return;if(!i.sendConfig)throw e(f=>ar(f,a,c)),new Error("A queued message needs a provider and model to be delivered later.");const d=xp(s.runtimeKey,s.directory,s.sessionId),u=Op(i.content,i.attachments??[]);try{const f=await Et(In,`${ot(s.sessionId)}/items`,rt("POST",{directory:s.directory,item:Zi(i,i.sendConfig)}));e(p=>ar(p,a,c)),n(f.session,f.revision,s.runtimeKey),d&&Vc.getState().appendSubmissions(d,[u])}catch(f){throw e(p=>ar(p,a,c)),f}},removeFromQueue:(s,i)=>{const a=Ee(s);e(c=>ar(c,a,i)),it()&&o(s,`${ot(s.sessionId)}/items/${encodeURIComponent(i)}`,rt("DELETE"))},reorderQueue:(s,i,a)=>{if(i===a)return;const c=Ee(s),l=t().queuedMessages[c];if(!l)return;const d=l.findIndex(h=>h.id===i),u=l.findIndex(h=>h.id===a);if(d===-1||u===-1)return;const f=l.slice(),[p]=f.splice(d,1);if(f.splice(u,0,p),e(h=>({queuedMessages:{...h.queuedMessages,[c]:f}})),it()){const h=f.map(g=>g.id);o(s,`${ot(s.sessionId)}/order`,rt("PUT",{itemIds:h}))}},popToInput:async(s,i)=>{const[a]=await t().takeForSend(s,i);return a??null},takeForSend:async(s,i)=>{const a=Ee(s);if(it()){if(i){const p=await Et(qp,`${ot(s.sessionId)}/items/${encodeURIComponent(i)}/take`,rt("POST"));return n(p.session,p.revision,s.runtimeKey),[sr(p.item)]}const f=await Et(Kp,`${ot(s.sessionId)}/take`,rt("POST"));return n(f.session,f.revision,s.runtimeKey),f.items.map(sr)}const c=t(),l=c.sendingIds[a]??[],d=(c.queuedMessages[a]??[]).filter(f=>(i?f.id===i:!0)&&!l.includes(f.id));if(d.length===0)return[];const u=new Set(d.map(f=>f.id));return e(f=>{const p=(f.queuedMessages[a]??[]).filter(h=>!u.has(h.id));return p.length===0?{queuedMessages:Fe(f.queuedMessages,a)}:{queuedMessages:{...f.queuedMessages,[a]:p}}}),d},clearQueue:s=>{const i=Ee(s);e(a=>{const c=a.sendingIds[i]??[],l=(a.queuedMessages[i]??[]).filter(d=>c.includes(d.id));return l.length>0?{queuedMessages:{...a.queuedMessages,[i]:l}}:{queuedMessages:Fe(a.queuedMessages,i)}}),it()&&o(s,ot(s.sessionId),rt("DELETE"))},forgetQueue:s=>{const i=Ee(s);lt.delete(i),e(a=>({queuedMessages:Fe(a.queuedMessages,i),sendingIds:Fe(a.sendingIds,i)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(s,i)=>{const a=Ee(s);e(c=>{const l=c.sendingIds[a]??[];return l.includes(i)?c:{sendingIds:{...c.sendingIds,[a]:[...l,i]}}})},clearSending:(s,i)=>{const a=Ee(s);e(c=>{const l=c.sendingIds[a];if(!l||!l.includes(i))return c;const d=l.filter(u=>u!==i);return d.length===0?{sendingIds:Fe(c.sendingIds,a)}:{sendingIds:{...c.sendingIds,[a]:d}}})},getSendableQueue:s=>{const i=Ee(s),a=t(),c=a.queuedMessages[i]??[],l=a.sendingIds[i];return!l||l.length===0?c:c.filter(d=>!l.includes(d.id))},setFollowUpBehavior:s=>{e({followUpBehavior:s}),je({followUpBehavior:s})},getQueueForTarget:s=>t().queuedMessages[Ee(s)]??[],hydrate:async()=>{if(!it())return;const s=B(),i=++vo,a=()=>i===vo&&s===B(),c=Object.entries(t().queuedMessages).map(([d,u])=>({target:Pt(d),queue:u})).filter(d=>d.target!==null&&d.target.runtimeKey===s&&!ir.has(s));for(const{target:d,queue:u}of c)for(const f of u)if(f.sendConfig){try{await Et(In,`${ot(d.sessionId)}/items`,rt("POST",{directory:d.directory,item:Zi(f,f.sendConfig)}))}catch(p){console.warn("[queue] failed to migrate a locally queued message to the server:",p)}if(!a())return}const l=await Et(Xi,"/api/message-queue");a()&&(ir.add(s),e(d=>{const u={},f={};for(const[p,h]of Object.entries(d.queuedMessages))Pt(p)?.runtimeKey!==s&&(u[p]=h);for(const[p,h]of Object.entries(d.sendingIds))Pt(p)?.runtimeKey!==s&&(f[p]=h);for(const p of l.sessions){const h=Ho(p.sessionId,p.directory,s);if(!h)continue;const g=Ee(h);if((lt.get(g)??-1)>l.revision){d.queuedMessages[g]&&(u[g]=d.queuedMessages[g]),d.sendingIds[g]&&(f[g]=d.sendingIds[g]);continue}lt.set(g,l.revision),p.items.length>0&&(u[g]=p.items.map(sr)),p.sendingId&&(f[g]=[p.sendingId])}return{queuedMessages:u,sendingIds:f}}))},applyServerSession:n,setServerHold:async(s,i)=>{if(!it())return;const a=await m(`${ot(s)}/hold`,rt("PUT",{held:i}));if(!a.ok)throw new Error(`Message queue hold request failed (${a.status})`)},resetForRuntimeSwitch:s=>{vo+=1,!(!s||!ir.has(s))&&e(i=>{const a={},c={};for(const[l,d]of Object.entries(i.queuedMessages))Pt(l)?.runtimeKey===s?lt.delete(l):a[l]=d;for(const[l,d]of Object.entries(i.sendingIds))Pt(l)?.runtimeKey!==s&&(c[l]=d);return{queuedMessages:a,sendingIds:c}})}}},{name:"message-queue-store",version:3,storage:ks(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Pt(t)?.runtimeKey;return!n||!ir.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:Qp}),{name:"message-queue-store"})),Zp=P({properties:P({revision:R(),session:js})}),qw=(e,t)=>{if(!it())return;const n=Zp.safeParse(e);if(!n.success)return;const{session:r,revision:o}=n.data.properties;Qc.getState().applyServerSession(r,o,t)},Xc="directoryTreeShowHidden",zo="directory-show-hidden-change",ta=()=>{if(typeof window>"u")return!0;try{const e=Bn().getItem(Xc);return e===null?!0:e==="true"}catch{return!0}},eh=()=>{typeof window>"u"||window.dispatchEvent(new Event(zo))},th=(e,t={})=>{if(!(typeof window>"u")){try{Bn().setItem(Xc,e?"true":"false"),eh()}catch{}t.persist!==!1&&je({directoryShowHidden:e})}},Kw=()=>{const e=ka.c(2),[t,n]=wr.useState(ta);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(ta())};return window.addEventListener("storage",s),window.addEventListener(zo,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(zo,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),wr.useEffect(r,o),t},Zc="filesViewShowGitignored",$o="files-view-show-gitignored-change",na=()=>{if(typeof window>"u")return!1;try{return Bn().getItem(Zc)==="true"}catch{return!1}},nh=()=>{typeof window>"u"||window.dispatchEvent(new Event($o))},rh=(e,t={})=>{if(!(typeof window>"u")){try{Bn().setItem(Zc,e?"true":"false"),nh()}catch{}t.persist!==!1&&je({filesViewShowGitignored:e})}},Vw=()=>{const e=ka.c(2),[t,n]=wr.useState(na);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(na())};return window.addEventListener("storage",s),window.addEventListener($o,s),()=>{window.removeEventListener("storage",s),window.removeEventListener($o,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),wr.useEffect(r,o),t},oh=e=>{if(!e||typeof e!="object")return null;const t={};return typeof e.showReasoningTraces=="boolean"&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),Object.keys(t).length>0?t:null},sh=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},ih=e=>{const t=Se.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},ah=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=sh(t);return oh(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},el=[{name:"explore",icon:"compass-3",labelKey:"chat.draftPresets.explore.label",command:"/explore"},{name:"catch-up",icon:"history",labelKey:"chat.draftPresets.catchup.label",command:"/catch-up"},{name:"weigh",icon:"scales-3",labelKey:"chat.draftPresets.weigh.label",command:"/weigh"},{name:"plan-feature",icon:"survey",labelKey:"chat.draftPresets.plan.label",command:"/plan-feature"},{name:"craft-goal",icon:"target",labelKey:"chat.draftPresets.craftGoal.label",command:"/craft-goal"},{name:"schedule-task",icon:"calendar-schedule",labelKey:"chat.draftPresets.scheduleTask.label",command:"/schedule-task"},{name:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],ch=new Map(el.map(e=>[e.name,e])),Jw=e=>ch.get(e),Yw=el.map(e=>({type:"command",name:e.name})),Qw="terminal-box",Xw="book-open",Zw=e=>`${e.type}:${e.name}`,eb=(e,t)=>e.type===t.type&&e.name===t.name,tb=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},tl=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=o.type==="command"||o.type==="skill"?o.type:null,i=typeof o.name=="string"?o.name.trim():"";if(!s||!i)continue;const a=`${s}:${i}`;n.has(a)||(n.add(a),t.push({type:s,name:i}))}return t},lh=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Or=e=>e==="auto"||typeof e=="string"&&lh.includes(e),dh=[{id:"finder",label:"Finder",appName:"Finder"},{id:"terminal",label:"Terminal",appName:"Terminal"},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"vscode-insiders",label:"VS Code Insiders",appName:"Visual Studio Code - Insiders"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"kiro",label:"Kiro",appName:"Kiro"},{id:"antigravity",label:"Antigravity",appName:"Antigravity"},{id:"trae",label:"Trae",appName:"Trae"}],uh="finder",nb=new Set(["finder","terminal"]),fh=e=>{if(typeof window>"u")return e;const t=window.__OPENCHAMBER_PLATFORM__;if(e.id==="finder"){if(t==="win32")return{...e,label:"Explorer",appName:"File Explorer"};if(t==="linux")return{...e,label:"File Manager"}}return e},rb=e=>{if(!e)return null;const t=dh.find(n=>n.id===e)??null;return t?fh(t):null},ph=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,n},Go=Ze()(Nn(e=>({projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sessionGroupingMode:"by-worktree",setSessionGroupingMode:t=>e({sessionGroupingMode:t}),stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,projectSortOrder:"manual",setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions})),setProjectSortOrder:t=>e({projectSortOrder:t})}),{name:"session-display-mode",version:5,migrate:ph})),hh=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},ra="openchamber.settingsMirror.v2.index",mh="openchamber.settingsMirror.v2:",yh=5,oa=e=>`${mh}${encodeURIComponent(e)}`,qt=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},gh=(e,t)=>{const n={themeId:e.themeId,themeVariant:e.themeVariant,lightThemeId:e.lightThemeId,darkThemeId:e.darkThemeId,useSystemTheme:e.useSystemTheme,lastDirectory:e.lastDirectory,homeDirectory:e.homeDirectory,projects:e.projects,activeProjectId:e.activeProjectId,sidebarProjectDisplayMode:e.sidebarProjectDisplayMode,sidebarSessionGroupingMode:e.sidebarSessionGroupingMode,sidebarProjectSortOrder:e.sidebarProjectSortOrder,sidebarShowRecentSection:e.sidebarShowRecentSection,pinnedDirectories:e.pinnedDirectories,gitmojiEnabled:e.gitmojiEnabled,directoryShowHidden:e.directoryShowHidden,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode,openCodeUpdateToastDismissedVersion:e.openCodeUpdateToastDismissedVersion,inputHistoryScope:e.inputHistoryScope,inputHistoryLimit:e.inputHistoryLimit,dictationEnabled:e.dictationEnabled,sttProvider:e.sttProvider,sttServerUrl:e.sttServerUrl,sttModel:e.sttModel,sttLocalModel:e.sttLocalModel,sttLanguage:e.sttLanguage};localStorage.setItem(oa(t),JSON.stringify(n));let r=[];try{const s=JSON.parse(localStorage.getItem(ra)??"[]");Array.isArray(s)&&(r=s.filter(i=>typeof i=="string"))}catch{r=[]}const o=[t,...r.filter(s=>s!==t)].slice(0,yh);for(const s of r)o.includes(s)||localStorage.removeItem(oa(s));localStorage.setItem(ra,JSON.stringify(o))},wh=e=>{if(!(typeof window>"u")){if(gh(e,B()),qt("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),hh(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),qt("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(Dc(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),qt("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),qt("sttModel",typeof e.sttModel=="string"?e.sttModel:null),qt("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),qt("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},Wo=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let qo="idle",cr=null;const Ko=new Set,ob=()=>qo,sb=e=>(Ko.add(e),()=>Ko.delete(e)),ib=e=>{qe(e)},qe=e=>{cr&&(clearTimeout(cr),cr=null);const t=e==="saved"?"idle":e;t!==qo&&(qo=t,Ko.forEach(n=>n())),t==="error"&&(cr=setTimeout(()=>qe("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},bh=e=>{if(!Array.isArray(e))return;const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",a=typeof o.source=="string"?o.source.trim():"",c=typeof o.subpath=="string"?o.subpath.trim():"",l=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";if(!s||!i||!a||n.has(s))continue;n.add(s);const d={id:s,label:i,source:a};c&&(d.subpath=c),l&&(d.gitIdentityId=l),t.push(d)}return t},Sh=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=typeof n=="string"?n.trim():"",s=typeof r=="string"?r.trim():"";!o||!s||(t[o]=s)}return t},Th=(e,t)=>{const n=Object.entries(e),r=Object.entries(t);return n.length!==r.length?!1:n.every(([o,s])=>t[o]===s)},Eo=(e,t)=>e.length===t.length&&e.every((n,r)=>n.providerID===t[r]?.providerID&&n.modelID===t[r]?.modelID),Vo=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Jo=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.length>0)))},vh=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!n||!Array.isArray(r))continue;const o=Jo(r);o&&o.length>0&&(t[n]=o.slice(0,5))}return Object.keys(t).length>0?t:void 0},Eh=(e,t)=>{const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>Array.isArray(t[r])&&Vo(e[r],t[r]))},kh=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Ah=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&kh.test(t)?t.toLowerCase():null},Ph=e=>{if(!Array.isArray(e))return;const t=[],n=new Set,r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.path=="string"?s.path.trim():"";if(!i)continue;const a=i==="/"?i:i.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=Af(a);if(!c||n.has(c)||r.has(a))continue;n.add(c),r.add(a);const l={id:c,path:a};if(typeof s.label=="string"&&s.label.trim().length>0&&(l.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(l.icon=s.icon.trim()),s.iconImage===null)l.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,u=typeof d.mime=="string"?d.mime.trim():"",f=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,p=d.source==="custom"||d.source==="auto"?d.source:null;u&&f>0&&p&&(l.iconImage={mime:u,updatedAt:f,source:p})}if(typeof s.color=="string"&&s.color.trim().length>0&&(l.color=s.color.trim()),s.iconBackground===null)l.iconBackground=null;else{const d=Ah(s.iconBackground);d&&(l.iconBackground=d)}typeof s.addedAt=="number"&&Number.isFinite(s.addedAt)&&s.addedAt>=0&&(l.addedAt=s.addedAt),typeof s.lastOpenedAt=="number"&&Number.isFinite(s.lastOpenedAt)&&s.lastOpenedAt>=0&&(l.lastOpenedAt=s.lastOpenedAt),typeof s.sidebarCollapsed=="boolean"&&(l.sidebarCollapsed=s.sidebarCollapsed),t.push(l)}return t.length>0?t:void 0},Mh=e=>{if(!Array.isArray(e))return;const t=[],n=new Set,r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.name=="string"?s.name.trim():"",c=typeof s.hostname=="string"?s.hostname.trim().toLowerCase():"";!i||!a||!c||n.has(i)||r.has(c)||(n.add(i),r.add(c),t.push({id:i,name:a,hostname:c}))}return t},Ih=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n={};for(const[r,o]of Object.entries(t)){const s=r.trim(),i=typeof o=="string"?o.trim():"";!s||!i||(n[s]=i)}return Object.keys(n).length>0?n:void 0},ko=(e,t)=>{if(!Array.isArray(e))return;const n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.providerID=="string"?s.providerID.trim():"",a=typeof s.modelID=="string"?s.modelID.trim():"";if(!i||!a)continue;const c=`${i}/${a}`;if(!r.has(c)&&(r.add(c),n.push({providerID:i,modelID:a}),n.length>=t))break}return n},nl=()=>{const e=Se.persist;if(e&&typeof e=="object")return e},rl=()=>Wr()?.settings??null,Ch=e=>{const t=Se.getInitialState();return{openInAppId:uh,showReasoningTraces:t.showReasoningTraces,streamingAutoFollowEnabled:t.streamingAutoFollowEnabled,workStatusPanelEnabled:t.workStatusPanelEnabled,workStatusHiddenSections:t.workStatusHiddenSections,sessionRecapEnabled:t.sessionRecapEnabled,sessionSuggestionEnabled:t.sessionSuggestionEnabled,sessionGoalEnabled:t.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:t.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:t.sessionGoalDefaultBudget,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,autoDeleteEnabled:t.autoDeleteEnabled,autoSaveEnabled:t.autoSaveEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,followUpBehavior:Os,showDeletionDialog:t.showDeletionDialog,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,inputSpellcheckEnabled:t.inputSpellcheckEnabled,enterToSend:t.enterToSend,enterToSendConfigured:t.enterToSendConfigured,showOpenCodeUpdateNotifications:t.showOpenCodeUpdateNotifications,agentControlToolEnabled:t.agentControlToolEnabled,agentWebToolEnabled:t.agentWebToolEnabled,agentMemoryToolEnabled:t.agentMemoryToolEnabled,showToolFileIcons:t.showToolFileIcons,codeBlockLineWrap:t.codeBlockLineWrap,showTurnChangedFiles:t.showTurnChangedFiles,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,timeFormatPreference:t.timeFormatPreference,weekStartPreference:t.weekStartPreference,desktopWindowControlsPosition:t.desktopWindowControlsPosition,desktopWindowControlsStyle:t.desktopWindowControlsStyle,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,collapsibleUserMessages:t.collapsibleUserMessages,messageStreamTransport:"auto",inputHistoryScope:Ms,inputHistoryLimit:Is,stickyUserHeader:t.stickyUserHeader,promptNavigatorEnabled:t.promptNavigatorEnabled,wideChatLayoutEnabled:t.wideChatLayoutEnabled,showSplitAssistantMessageActions:t.showSplitAssistantMessageActions,draftStartersVisible:t.draftStartersVisible,reportUsage:t.reportUsage,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,terminalShell:t.terminalShell,terminalLoginShells:t.terminalLoginShells,editorFontSize:t.editorFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,inputBarOffset:t.inputBarOffset,shortcutOverrides:t.shortcutOverrides,mobileKeyboardMode:"resize-content",favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,gitChangesViewMode:t.gitChangesViewMode,toolJsonViewMode:t.toolJsonViewMode,directoryShowHidden:!0,filesViewShowGitignored:!1,dictationEnabled:!0,sttProvider:"local",sttServerUrl:"http://localhost:8001/v1",sttModel:"deepdml/faster-whisper-large-v3-turbo-ct2",sttLocalModel:"parakeet-tdt-0.6b-v2-int8",sttLanguage:"",...e}},Yo=e=>{const t=Se.getState(),n=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,r=typeof window<"u"?window.__zustand_config_store__??null:null,o=Qc.getState(),s=Vc.getState();if(typeof e.workStatusPanelEnabled=="boolean"&&e.workStatusPanelEnabled!==t.workStatusPanelEnabled&&t.setWorkStatusPanelEnabled(e.workStatusPanelEnabled),Array.isArray(e.workStatusHiddenSections)){const c=kc(e.workStatusHiddenSections);c.join("\0")!==t.workStatusHiddenSections.join("\0")&&t.setWorkStatusHiddenSections(c)}if(typeof e.showReasoningTraces=="boolean"&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.streamingAutoFollowEnabled=="boolean"&&e.streamingAutoFollowEnabled!==t.streamingAutoFollowEnabled&&t.setStreamingAutoFollowEnabled(e.streamingAutoFollowEnabled),typeof e.sessionRecapEnabled=="boolean"&&e.sessionRecapEnabled!==t.sessionRecapEnabled&&t.setSessionRecapEnabled(e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&e.sessionSuggestionEnabled!==t.sessionSuggestionEnabled&&t.setSessionSuggestionEnabled(e.sessionSuggestionEnabled),typeof e.sessionGoalEnabled=="boolean"&&e.sessionGoalEnabled!==t.sessionGoalEnabled&&t.setSessionGoalEnabled(e.sessionGoalEnabled),typeof e.sessionGoalDefaultBudgetEnabled=="boolean"&&e.sessionGoalDefaultBudgetEnabled!==t.sessionGoalDefaultBudgetEnabled&&t.setSessionGoalDefaultBudgetEnabled(e.sessionGoalDefaultBudgetEnabled),typeof e.sessionGoalDefaultBudget=="number"&&Number.isFinite(e.sessionGoalDefaultBudget)&&e.sessionGoalDefaultBudget!==t.sessionGoalDefaultBudget&&t.setSessionGoalDefaultBudget(e.sessionGoalDefaultBudget),typeof e.collapsibleThinkingBlocks=="boolean"&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoSaveEnabled=="boolean"&&e.autoSaveEnabled!==t.autoSaveEnabled&&t.setAutoSaveEnabled(e.autoSaveEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)){const c=Math.max(1,Math.min(365,e.autoDeleteAfterDays));c!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(c)}(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let i=null;if(Ls(e.followUpBehavior)?i=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(i=_s(void 0,e.queueModeEnabled)),i&&i!==o.followUpBehavior&&o.setFollowUpBehavior(i),typeof e.showDeletionDialog=="boolean"&&e.showDeletionDialog!==t.showDeletionDialog&&t.setShowDeletionDialog(e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&e.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&t.setNativeNotificationsEnabled(e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&e.notificationMode!==t.notificationMode&&t.setNotificationMode(e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&e.notifyOnSubtasks!==t.notifyOnSubtasks&&t.setNotifyOnSubtasks(e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&e.notifyOnCompletion!==t.notifyOnCompletion&&t.setNotifyOnCompletion(e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&e.notifyOnError!==t.notifyOnError&&t.setNotifyOnError(e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&e.notifyOnQuestion!==t.notifyOnQuestion&&t.setNotifyOnQuestion(e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"&&t.setNotificationTemplates(e.notificationTemplates),typeof e.summarizeLastMessage=="boolean"&&e.summarizeLastMessage!==t.summarizeLastMessage&&t.setSummarizeLastMessage(e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&t.setSummaryThreshold(e.summaryThreshold),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&t.setSummaryLength(e.summaryLength),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&t.setMaxLastMessageLength(e.maxLastMessageLength),typeof e.inputSpellcheckEnabled=="boolean"&&e.inputSpellcheckEnabled!==t.inputSpellcheckEnabled&&t.setInputSpellcheckEnabled(e.inputSpellcheckEnabled),(e.enterToSend===!0||e.enterToSend===!1)&&e.enterToSend!==t.enterToSend&&t.setEnterToSend(e.enterToSend),(e.enterToSendConfigured===!0||e.enterToSendConfigured===!1)&&e.enterToSendConfigured!==t.enterToSendConfigured&&t.setEnterToSendConfigured(e.enterToSendConfigured),typeof e.showOpenCodeUpdateNotifications=="boolean"&&e.showOpenCodeUpdateNotifications!==t.showOpenCodeUpdateNotifications&&t.setShowOpenCodeUpdateNotifications(e.showOpenCodeUpdateNotifications),typeof e.agentControlToolEnabled=="boolean"&&e.agentControlToolEnabled!==t.agentControlToolEnabled&&t.setAgentControlToolEnabled(e.agentControlToolEnabled),typeof e.agentWebToolEnabled=="boolean"&&e.agentWebToolEnabled!==t.agentWebToolEnabled&&t.setAgentWebToolEnabled(e.agentWebToolEnabled),typeof e.agentMemoryToolEnabled=="boolean"&&e.agentMemoryToolEnabled!==t.agentMemoryToolEnabled&&t.setAgentMemoryToolEnabled(e.agentMemoryToolEnabled),typeof e.agentMemoryFeatureAvailable=="boolean"&&e.agentMemoryFeatureAvailable!==t.agentMemoryFeatureAvailable&&t.setAgentMemoryFeatureAvailable(e.agentMemoryFeatureAvailable),typeof e.showToolFileIcons=="boolean"&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap=="boolean"&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles=="boolean"&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&e.showExpandedEditTools!==t.showExpandedEditTools&&t.setShowExpandedEditTools(e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.desktopWindowControlsPosition=="string"){const c=e.desktopWindowControlsPosition==="left"?"left":e.desktopWindowControlsPosition==="right"||e.desktopWindowControlsPosition==="auto"?"right":null;c&&c!==t.desktopWindowControlsPosition&&t.setDesktopWindowControlsPosition(c)}if(typeof e.desktopWindowControlsStyle=="string"){const c=e.desktopWindowControlsStyle==="traffic-lights"?"traffic-lights":e.desktopWindowControlsStyle==="classic"?"classic":null;c&&c!==t.desktopWindowControlsStyle&&t.setDesktopWindowControlsStyle(c)}if(typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&n&&e.messageStreamTransport!==n.settingsMessageStreamTransport&&n.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.inputHistoryScope=="string"&&Cs(e.inputHistoryScope)&&e.inputHistoryScope!==s.scope&&s.applyScope(e.inputHistoryScope),Kr(e.inputHistoryLimit)&&e.inputHistoryLimit!==s.entryLimit&&s.applyEntryLimit(e.inputHistoryLimit),typeof e.stickyUserHeader=="boolean"&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.promptNavigatorEnabled=="boolean"&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.wideChatLayoutEnabled=="boolean"&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.reportUsage=="boolean"&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){let c=tl(e.draftStarters);if(e.draftStartersCraftGoalAdded!==!0&&!c.some(l=>l.type==="command"&&l.name==="craft-goal")){const l=c.findIndex(u=>u.type==="command"&&u.name==="plan-feature"),d=l>=0?l+1:c.length;c=[...c.slice(0,d),{type:"command",name:"craft-goal"},...c.slice(d)]}if(e.draftStartersScheduleTaskAdded!==!0&&!c.some(l=>l.type==="command"&&l.name==="schedule-task")){const l=c.findIndex(u=>u.type==="command"&&u.name==="craft-goal"),d=l>=0?l+1:c.length;c=[...c.slice(0,d),{type:"command",name:"schedule-task"},...c.slice(d)]}JSON.stringify(t.globalDraftStarters)!==JSON.stringify(c)&&t.setGlobalDraftStarters(c),(e.draftStartersCraftGoalAdded!==!0||e.draftStartersScheduleTaskAdded!==!0)&&(e.draftStarters=c,e.draftStartersCraftGoalAdded=!0,e.draftStartersScheduleTaskAdded=!0)}else e.draftStartersCraftGoalAdded!==!0&&(e.draftStartersCraftGoalAdded=!0),e.draftStartersScheduleTaskAdded!==!0&&(e.draftStartersScheduleTaskAdded=!0);if(typeof e.draftStartersVisible=="boolean"&&e.draftStartersVisible!==t.draftStartersVisible&&t.setDraftStartersVisible(e.draftStartersVisible),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),Or(e.terminalShell)&&e.terminalShell!==t.terminalShell&&t.setTerminalShell(e.terminalShell),Array.isArray(e.terminalLoginShells)&&(e.terminalLoginShells.length!==t.terminalLoginShells.length||e.terminalLoginShells.some((c,l)=>c!==t.terminalLoginShells[l]))&&t.setTerminalLoginShells(e.terminalLoginShells),typeof e.editorFontSize=="number"&&Number.isFinite(e.editorFontSize)&&e.editorFontSize!==t.editorFontSize&&t.setEditorFontSize(e.editorFontSize),xc(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),Rc(e.monoFont)&&e.monoFont!==t.monoFont&&t.setMonoFont(e.monoFont),typeof e.padding=="number"&&Number.isFinite(e.padding)&&e.padding!==t.padding&&t.setPadding(e.padding),typeof e.cornerRadius=="number"&&Number.isFinite(e.cornerRadius)&&e.cornerRadius!==t.cornerRadius&&t.setCornerRadius(e.cornerRadius),typeof e.inputBarOffset=="number"&&Number.isFinite(e.inputBarOffset)&&e.inputBarOffset!==t.inputBarOffset&&t.setInputBarOffset(e.inputBarOffset),e.shortcutOverrides&&!Th(e.shortcutOverrides,t.shortcutOverrides)&&Se.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode=="string"){const c=qr(e.mobileKeyboardMode,t.mobileKeyboardMode);c!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(c)}if(r&&n){const c={};typeof e.dictationEnabled=="boolean"&&e.dictationEnabled!==n.dictationEnabled&&(c.dictationEnabled=e.dictationEnabled),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&e.sttProvider!==n.sttProvider&&(c.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&e.sttServerUrl!==n.sttServerUrl&&(c.sttServerUrl=e.sttServerUrl),typeof e.sttModel=="string"&&e.sttModel!==n.sttModel&&(c.sttModel=e.sttModel),typeof e.sttLocalModel=="string"&&e.sttLocalModel!==n.sttLocalModel&&(c.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage=="string"&&e.sttLanguage!==n.sttLanguage&&(c.sttLanguage=e.sttLanguage),Object.keys(c).length>0&&r.setState(c)}if(Array.isArray(e.favoriteModels)){const c=t.favoriteModels,l=e.favoriteModels;Eo(c,l)||Se.setState({favoriteModels:l})}if(Array.isArray(e.hiddenModels)){const c=t.hiddenModels,l=e.hiddenModels;Eo(c,l)||Se.setState({hiddenModels:l})}if(Array.isArray(e.collapsedModelProviders)){const c=t.collapsedModelProviders,l=e.collapsedModelProviders;Vo(c,l)||Se.setState({collapsedModelProviders:l})}if(Array.isArray(e.recentModels)){const c=t.recentModels,l=e.recentModels;Eo(c,l)||Se.setState({recentModels:l})}if(Array.isArray(e.recentAgents)){const c=t.recentAgents,l=e.recentAgents;Vo(c,l)||Se.setState({recentAgents:l})}if(e.recentEfforts&&typeof e.recentEfforts=="object"){const c=t.recentEfforts,l=e.recentEfforts;Eh(c,l)||Se.setState({recentEfforts:l})}typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&e.diffLayoutPreference!==t.diffLayoutPreference&&t.setDiffLayoutPreference(e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&e.gitChangesViewMode!==t.gitChangesViewMode&&t.setGitChangesViewMode(e.gitChangesViewMode),typeof e.toolJsonViewMode=="string"&&(e.toolJsonViewMode==="summary"||e.toolJsonViewMode==="formatted"||e.toolJsonViewMode==="raw")&&e.toolJsonViewMode!==t.toolJsonViewMode&&t.setToolJsonViewMode(e.toolJsonViewMode),typeof e.directoryShowHidden=="boolean"&&th(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored=="boolean"&&rh(e.filesViewShowGitignored,{persist:!1});const a={};(e.sidebarProjectDisplayMode==="all"||e.sidebarProjectDisplayMode==="single")&&(a.projectDisplayMode=e.sidebarProjectDisplayMode),(e.sidebarSessionGroupingMode==="by-worktree"||e.sidebarSessionGroupingMode==="flat")&&(a.sessionGroupingMode=e.sidebarSessionGroupingMode),(e.sidebarProjectSortOrder==="manual"||e.sidebarProjectSortOrder==="a-z"||e.sidebarProjectSortOrder==="z-a"||e.sidebarProjectSortOrder==="date-added"||e.sidebarProjectSortOrder==="recent")&&(a.projectSortOrder=e.sidebarProjectSortOrder),typeof e.sidebarShowRecentSection=="boolean"&&(a.showRecentSection=e.sidebarShowRecentSection),Object.keys(a).length>0&&Go.setState(a)},Qo=e=>{if(!e||typeof e!="object")return null;const t=e,n={};if(typeof t.themeId=="string"&&t.themeId.length>0&&(n.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(n.useSystemTheme=t.useSystemTheme),typeof t.themeVariant=="string"&&(t.themeVariant==="light"||t.themeVariant==="dark")&&(n.themeVariant=t.themeVariant),typeof t.lightThemeId=="string"&&t.lightThemeId.length>0&&(n.lightThemeId=t.lightThemeId),typeof t.darkThemeId=="string"&&t.darkThemeId.length>0&&(n.darkThemeId=t.darkThemeId),typeof t.lastDirectory=="string"&&t.lastDirectory.length>0&&(n.lastDirectory=t.lastDirectory),typeof t.homeDirectory=="string"&&t.homeDirectory.length>0&&(n.homeDirectory=t.homeDirectory),typeof t.opencodeBinary=="string"){const h=t.opencodeBinary.trim();n.opencodeBinary=h.length>0?h:void 0}typeof t.desktopLanAccessEnabled=="boolean"&&(n.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled=="boolean"&&(n.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled=="boolean"&&(n.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled),typeof t.desktopMacMenuBarEnabled=="boolean"&&(n.desktopMacMenuBarEnabled=t.desktopMacMenuBarEnabled);const r=Ph(t.projects);if(r&&(n.projects=r),typeof t.activeProjectId=="string"&&t.activeProjectId.length>0&&(n.activeProjectId=t.activeProjectId),(t.sidebarProjectDisplayMode==="all"||t.sidebarProjectDisplayMode==="single")&&(n.sidebarProjectDisplayMode=t.sidebarProjectDisplayMode),(t.sidebarSessionGroupingMode==="by-worktree"||t.sidebarSessionGroupingMode==="flat")&&(n.sidebarSessionGroupingMode=t.sidebarSessionGroupingMode),(t.sidebarProjectSortOrder==="manual"||t.sidebarProjectSortOrder==="a-z"||t.sidebarProjectSortOrder==="z-a"||t.sidebarProjectSortOrder==="date-added"||t.sidebarProjectSortOrder==="recent")&&(n.sidebarProjectSortOrder=t.sidebarProjectSortOrder),typeof t.sidebarShowRecentSection=="boolean"&&(n.sidebarShowRecentSection=t.sidebarShowRecentSection),Array.isArray(t.securityScopedBookmarks)&&(n.securityScopedBookmarks=t.securityScopedBookmarks.filter(h=>typeof h=="string"&&h.length>0)),Array.isArray(t.pinnedDirectories)&&(n.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(h=>typeof h=="string"&&h.length>0)))),Array.isArray(t.draftStarters)&&(n.draftStarters=tl(t.draftStarters)),typeof t.draftStartersVisible=="boolean"&&(n.draftStartersVisible=t.draftStartersVisible),typeof t.draftStartersCraftGoalAdded=="boolean"&&(n.draftStartersCraftGoalAdded=t.draftStartersCraftGoalAdded),typeof t.draftStartersScheduleTaskAdded=="boolean"&&(n.draftStartersScheduleTaskAdded=t.draftStartersScheduleTaskAdded),typeof t.workStatusPanelEnabled=="boolean"&&(n.workStatusPanelEnabled=t.workStatusPanelEnabled),Array.isArray(t.workStatusHiddenSections)&&(n.workStatusHiddenSections=kc(t.workStatusHiddenSections)),typeof t.showReasoningTraces=="boolean"&&(n.showReasoningTraces=t.showReasoningTraces),typeof t.streamingAutoFollowEnabled=="boolean"&&(n.streamingAutoFollowEnabled=t.streamingAutoFollowEnabled),typeof t.inputHistoryScope=="string"&&Cs(t.inputHistoryScope)&&(n.inputHistoryScope=t.inputHistoryScope),typeof t.inputHistoryLimit=="number"&&Kr(t.inputHistoryLimit)&&(n.inputHistoryLimit=t.inputHistoryLimit),typeof t.sessionRecapEnabled=="boolean"&&(n.sessionRecapEnabled=t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&(n.sessionSuggestionEnabled=t.sessionSuggestionEnabled),typeof t.sessionGoalEnabled=="boolean"&&(n.sessionGoalEnabled=t.sessionGoalEnabled),typeof t.sessionGoalDefaultBudgetEnabled=="boolean"&&(n.sessionGoalDefaultBudgetEnabled=t.sessionGoalDefaultBudgetEnabled),typeof t.sessionGoalDefaultBudget=="number"&&Number.isFinite(t.sessionGoalDefaultBudget)&&t.sessionGoalDefaultBudget>0&&(n.sessionGoalDefaultBudget=Math.floor(t.sessionGoalDefaultBudget)),typeof t.collapsibleThinkingBlocks=="boolean"&&(n.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&(n.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoSaveEnabled=="boolean"&&(n.autoSaveEnabled=t.autoSaveEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)&&(n.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&(n.sessionRetentionAction=t.sessionRetentionAction),typeof t.tunnelProvider=="string"){const h=t.tunnelProvider.trim().toLowerCase();h.length>0&&(n.tunnelProvider=h)}if(typeof t.tunnelMode=="string"){const h=t.tunnelMode.trim().toLowerCase();(h==="quick"||h==="managed-remote"||h==="managed-local")&&(n.tunnelMode=h)}if(t.tunnelBootstrapTtlMs===null?n.tunnelBootstrapTtlMs=null:typeof t.tunnelBootstrapTtlMs=="number"&&Number.isFinite(t.tunnelBootstrapTtlMs)&&(n.tunnelBootstrapTtlMs=t.tunnelBootstrapTtlMs),typeof t.tunnelSessionTtlMs=="number"&&Number.isFinite(t.tunnelSessionTtlMs)&&(n.tunnelSessionTtlMs=t.tunnelSessionTtlMs),t.managedLocalTunnelConfigPath===null)n.managedLocalTunnelConfigPath=null;else if(typeof t.managedLocalTunnelConfigPath=="string"){const h=t.managedLocalTunnelConfigPath.trim();n.managedLocalTunnelConfigPath=h.length>0?h:null}typeof t.managedRemoteTunnelHostname=="string"&&(n.managedRemoteTunnelHostname=t.managedRemoteTunnelHostname.trim()),t.managedRemoteTunnelToken===null?n.managedRemoteTunnelToken=null:typeof t.managedRemoteTunnelToken=="string"&&(n.managedRemoteTunnelToken=t.managedRemoteTunnelToken.trim());const o=Mh(t.managedRemoteTunnelPresets);if(o&&(n.managedRemoteTunnelPresets=o),typeof t.managedRemoteTunnelSelectedPresetId=="string"){const h=t.managedRemoteTunnelSelectedPresetId.trim();n.managedRemoteTunnelSelectedPresetId=h.length>0?h:void 0}const s=Ih(t.managedRemoteTunnelPresetTokens);if(s&&(n.managedRemoteTunnelPresetTokens=s),typeof t.defaultModel=="string"&&t.defaultModel.length>0&&(n.defaultModel=t.defaultModel),typeof t.defaultVariant=="string"&&t.defaultVariant.length>0&&(n.defaultVariant=t.defaultVariant),typeof t.defaultAgent=="string"&&t.defaultAgent.length>0&&(n.defaultAgent=t.defaultAgent),typeof t.smallModelUseDefault=="boolean"&&(n.smallModelUseDefault=t.smallModelUseDefault),typeof t.smallModelOverride=="string"&&t.smallModelOverride.length>0&&(n.smallModelOverride=t.smallModelOverride),typeof t.walkthroughModelOverride=="string"&&t.walkthroughModelOverride.length>0&&(n.walkthroughModelOverride=t.walkthroughModelOverride),typeof t.autoCreateWorktree=="boolean"&&(n.autoCreateWorktree=t.autoCreateWorktree),typeof t.gitmojiEnabled=="boolean"&&(n.gitmojiEnabled=t.gitmojiEnabled),Ls(t.followUpBehavior)?n.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(n.followUpBehavior=_s(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog=="boolean"&&(n.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&(n.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&(n.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&(n.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&(n.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&(n.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&(n.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"){const h=t.notificationTemplates,g=I=>{const $=h[I];if(!$||typeof $!="object")return;const A=$,fe=typeof A.title=="string"?A.title:"",Q=typeof A.message=="string"?A.message:"";return{title:fe,message:Q}},y=g("completion"),b=g("error"),S=g("question"),k=g("subtask");(y||b||S||k)&&(n.notificationTemplates={completion:y??{title:"Task Complete",message:"Your task has finished."},error:b??{title:"Error Occurred",message:"An error occurred while processing your task."},question:S??{title:"Input Needed",message:"Please provide input to continue."},subtask:k??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof t.summarizeLastMessage=="boolean"&&(n.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&(n.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&(n.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&(n.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),(t.usageDisplayMode==="usage"||t.usageDisplayMode==="remaining")&&(n.usageDisplayMode=t.usageDisplayMode),Array.isArray(t.usageDropdownProviders)&&(n.usageDropdownProviders=t.usageDropdownProviders.filter(h=>typeof h=="string"&&h.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels=="object"){const h={};for(const[g,y]of Object.entries(t.usageSelectedModels))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageSelectedModels=h)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies=="object"){const h={};for(const[g,y]of Object.entries(t.usageCollapsedFamilies))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageCollapsedFamilies=h)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies=="object"){const h={};for(const[g,y]of Object.entries(t.usageExpandedFamilies))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageExpandedFamilies=h)}if(t.usageModelGroups&&typeof t.usageModelGroups=="object"){const h={};for(const[g,y]of Object.entries(t.usageModelGroups))if(y&&typeof y=="object"){const b=y,S={};Array.isArray(b.customGroups)&&(S.customGroups=b.customGroups.filter(k=>k&&typeof k=="object").map(k=>({id:String(k.id??""),label:String(k.label??""),models:Array.isArray(k.models)?k.models.filter(I=>typeof I=="string"):[],order:typeof k.order=="number"?k.order:0}))),b.modelAssignments&&typeof b.modelAssignments=="object"&&(S.modelAssignments=Object.fromEntries(Object.entries(b.modelAssignments).filter(([,k])=>typeof k=="string").map(([k,I])=>[k,String(I)]))),b.renamedGroups&&typeof b.renamedGroups=="object"&&(S.renamedGroups=Object.fromEntries(Object.entries(b.renamedGroups).filter(([,k])=>typeof k=="string").map(([k,I])=>[k,String(I)]))),Object.keys(S).length>0&&(h[g]=S)}Object.keys(h).length>0&&(n.usageModelGroups=h)}typeof t.inputSpellcheckEnabled=="boolean"&&(n.inputSpellcheckEnabled=t.inputSpellcheckEnabled),(t.enterToSend===!0||t.enterToSend===!1)&&(n.enterToSend=t.enterToSend),(t.enterToSendConfigured===!0||t.enterToSendConfigured===!1)&&(n.enterToSendConfigured=t.enterToSendConfigured),typeof t.showOpenCodeUpdateNotifications=="boolean"&&(n.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.agentControlToolEnabled=="boolean"&&(n.agentControlToolEnabled=t.agentControlToolEnabled),typeof t.agentWebToolEnabled=="boolean"&&(n.agentWebToolEnabled=t.agentWebToolEnabled),typeof t.agentMemoryToolEnabled=="boolean"&&(n.agentMemoryToolEnabled=t.agentMemoryToolEnabled),typeof t.openCodeUpdateToastDismissedVersion=="string"&&(n.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons=="boolean"&&(n.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap=="boolean"&&(n.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles=="boolean"&&(n.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&(n.showExpandedBashTools=t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&(n.showExpandedEditTools=t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&(n.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&(n.weekStartPreference=t.weekStartPreference),typeof t.desktopWindowControlsPosition=="string"&&(t.desktopWindowControlsPosition==="left"?n.desktopWindowControlsPosition="left":(t.desktopWindowControlsPosition==="right"||t.desktopWindowControlsPosition==="auto")&&(n.desktopWindowControlsPosition="right")),typeof t.desktopWindowControlsStyle=="string"&&(t.desktopWindowControlsStyle==="classic"||t.desktopWindowControlsStyle==="traffic-lights")&&(n.desktopWindowControlsStyle=t.desktopWindowControlsStyle),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&(n.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&(n.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&(n.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&(n.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&(n.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&(n.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader=="boolean"&&(n.stickyUserHeader=t.stickyUserHeader),typeof t.promptNavigatorEnabled=="boolean"&&(n.promptNavigatorEnabled=t.promptNavigatorEnabled),typeof t.wideChatLayoutEnabled=="boolean"&&(n.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&(n.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&(n.fontSize=t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&(n.terminalFontSize=t.terminalFontSize),Or(t.terminalShell)&&(n.terminalShell=t.terminalShell),Array.isArray(t.terminalLoginShells)&&(n.terminalLoginShells=[...new Set(t.terminalLoginShells.filter(Or))]),typeof t.editorFontSize=="number"&&Number.isFinite(t.editorFontSize)&&(n.editorFontSize=t.editorFontSize),xc(t.uiFont)&&(n.uiFont=t.uiFont),Rc(t.monoFont)&&(n.monoFont=t.monoFont),typeof t.padding=="number"&&Number.isFinite(t.padding)&&(n.padding=t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&(n.cornerRadius=t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&(n.inputBarOffset=t.inputBarOffset);const i=Sh(t.shortcutOverrides);i&&(n.shortcutOverrides=i),typeof t.mobileKeyboardMode=="string"&&(t.mobileKeyboardMode==="native"||t.mobileKeyboardMode==="resize-content")&&(n.mobileKeyboardMode=t.mobileKeyboardMode);const a=ko(t.favoriteModels,64);a&&(n.favoriteModels=a);const c=ko(t.hiddenModels,1024);c&&(n.hiddenModels=c);const l=Jo(t.collapsedModelProviders);l&&(n.collapsedModelProviders=l);const d=ko(t.recentModels,16);d&&(n.recentModels=d);const u=Jo(t.recentAgents);u&&(n.recentAgents=u);const f=vh(t.recentEfforts);if(f&&(n.recentEfforts=f),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&(n.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&(n.gitChangesViewMode=t.gitChangesViewMode),typeof t.toolJsonViewMode=="string"&&(t.toolJsonViewMode==="summary"||t.toolJsonViewMode==="formatted"||t.toolJsonViewMode==="raw")&&(n.toolJsonViewMode=t.toolJsonViewMode),typeof t.directoryShowHidden=="boolean"&&(n.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored=="boolean"&&(n.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&(n.openInAppId=t.openInAppId),typeof t.pwaAppName=="string"){const h=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);n.pwaAppName=h.length>0?h:""}const p=bh(t.skillCatalogs);return p&&(n.skillCatalogs=p),typeof t.reportUsage=="boolean"&&(n.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt=="string"&&(n.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled=="boolean"&&(n.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset=="string"&&(t.responseStylePreset==="concise"||t.responseStylePreset==="detailed"||t.responseStylePreset==="mentor"||t.responseStylePreset==="pushback"||t.responseStylePreset==="noFiller"||t.responseStylePreset==="matchEnergy"||t.responseStylePreset==="warmPeer"||t.responseStylePreset==="custom")&&(n.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions=="string"&&(n.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled=="boolean"&&(n.dictationEnabled=t.dictationEnabled),t.sttProvider==="local"||t.sttProvider==="openai-compatible"?n.sttProvider=t.sttProvider:t.sttProvider==="server"?n.sttProvider="openai-compatible":(t.sttProvider==="browser"||t.sttProvider==="wasm")&&(n.sttProvider="local"),typeof t.sttServerUrl=="string"&&(n.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel=="string"&&(n.sttModel=t.sttModel.trim()),typeof t.sttLocalModel=="string"&&(n.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage=="string"&&(n.sttLanguage=t.sttLanguage.trim()),n};class xh{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(o=>o.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const o of this.mutations)o.revision<=n.revision||(r={...r,...o.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let Ns=0,Ke=null,Mt=null,yt=null,xt=null,xe=null,Xo=[],sa=!1,Lr=0;const Ue=new xh,Rh=2e3,Dh=200,Us=()=>({runtimeKey:B(),generation:Ns}),Zo=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,re=e=>e.generation===Ns&&e.runtimeKey===B(),wn=()=>{yt&&(xe&&(clearTimeout(xe),xe=null),_r({keepalive:!0}))},Bs=()=>{if(!(sa||typeof window>"u")){sa=!0,ou(e=>{e.runtimeKey!==e.previousRuntimeKey&&(xe&&clearTimeout(xe),yt&&_r())}),dc(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Ns+=1,Ue.reset(),Lr=0,Ke=null,Mt=null)});try{window.addEventListener("pagehide",wn,{capture:!0}),window.addEventListener("beforeunload",wn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&wn()}),document.addEventListener("freeze",wn)),Oc()&&cs(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||wn()})).catch(()=>{})}catch{}}},Oh=async(e=Us())=>{if(Bs(),Ke&&Zo(Ke.context,e)&&Date.now()-Ke.at<Rh)return Ke.value;if(Mt&&Zo(Mt.context,e))return Mt.promise;const t={context:e,promise:(async()=>{const n=rl();if(n)try{const r=await n.load();if(!re(e))return null;const o=Qo(r.settings);return Ke={value:o,at:Date.now(),context:e},o}catch(r){if(!re(e))return null;console.warn("Failed to load shared settings from runtime settings API:",r)}if(!re(e))return null;try{const r=await m("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!re(e)||!r.ok)return null;const o=await r.json().catch(()=>null);if(!re(e))return null;const s=Qo(o);return Ke={value:s,at:Date.now(),context:e},s}catch(r){return re(e)&&console.warn("Failed to load shared settings from server:",r),null}})()};return Mt=t,t.promise.finally(()=>{Mt===t&&(Mt=null)}),t.promise},ab=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Bs();const r=Us(),o=Ue.begin(),s=[nl(),Go.persist],i=d=>!d?.hasHydrated||d.hasHydrated()||!d.onFinishHydration?Promise.resolve():new Promise(u=>{let f=!1;const p=()=>{f||(f=!0,u())},h=d.onFinishHydration(()=>{h?.(),p()});d.hasHydrated?.()&&p()}),a=()=>Promise.all(s.map(i)).then(()=>{}),c=d=>!yt||!xt||!re(xt)?d:{...d,...yt},l=async d=>{if(!re(r))return;let u=c(Ue.reconcile(d,o));if(await a(),!re(r))return;u=c(Ue.reconcile(d,o));const f=u.draftStartersCraftGoalAdded!==!0||u.draftStartersScheduleTaskAdded!==!0,p=typeof u.autoSaveEnabled!="boolean",h=u.sidebarProjectDisplayMode===void 0,g=u.sidebarSessionGroupingMode===void 0,y=u.sidebarProjectSortOrder===void 0,b=u.sidebarShowRecentSection===void 0,S=Ch(u);try{wh(u)}catch($){console.warn("persistToLocalStorage failed:",$)}p&&(S.autoSaveEnabled=Se.getState().autoSaveEnabled);const k=Go.getState();h&&(S.sidebarProjectDisplayMode=k.projectDisplayMode),g&&(S.sidebarSessionGroupingMode=k.sessionGroupingMode),y&&(S.sidebarProjectSortOrder=k.projectSortOrder),b&&(S.sidebarShowRecentSection=k.showRecentSection),u.draftStarters===void 0&&Se.setState({globalDraftStarters:null});try{Yo(S)}catch($){console.warn("applyDesktopUiPreferences failed:",$)}const I={};f&&(S.draftStarters&&(I.draftStarters=S.draftStarters),I.draftStartersCraftGoalAdded=!0,I.draftStartersScheduleTaskAdded=!0),p&&(I.autoSaveEnabled=S.autoSaveEnabled),h&&(I.sidebarProjectDisplayMode=S.sidebarProjectDisplayMode),g&&(I.sidebarSessionGroupingMode=S.sidebarSessionGroupingMode),y&&(I.sidebarProjectSortOrder=S.sidebarProjectSortOrder),b&&(I.sidebarShowRecentSection=S.sidebarShowRecentSection),!(Object.keys(I).length>0&&(await je(I),!re(r)))&&Wo(S,t,n)};try{const d=await Oh(r);d&&re(r)&&await l(d)}catch(d){console.warn("Failed to synchronise settings:",d)}finally{Ue.finish(o)}};async function _r({keepalive:e=!1}={}){const t=yt,n=xt,r=Lr,o=Xo;yt=null,xt=null,Lr=0,xe=null,Xo=[];try{if(!t||!n||Object.keys(t).length===0||!re(n)){qe("saved");return}const s=Ue.begin(r);try{const i=rl();if(i)try{const a=await i.save(t);if(!re(n))return;if(a){const c=Ue.reconcile(a,s);Yo(c),Wo(c,!1),Ke=null}qe(a?"saved":"error");return}catch(a){if(!re(n))return;console.warn("Failed to update settings via runtime settings API:",a)}if(!re(n))return;try{const a=await m("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t),keepalive:e});if(!re(n))return;if(!a.ok){console.warn("Failed to update shared settings via API:",a.status,a.statusText),qe("error");return}const c=Qo(await a.json().catch(()=>null));if(!re(n))return;if(c){const l=Ue.reconcile(c,s);Yo(l),Wo(l,!1),qe("saved"),Ke=null}else qe("error")}catch(a){re(n)&&(console.warn("Failed to update shared settings via API:",a),qe("error"))}}finally{Ue.finish(s)}}finally{o.forEach(s=>s())}}const je=async e=>{if(typeof window>"u")return;Bs();const t=Us();xt&&!Zo(xt,t)&&(xe&&clearTimeout(xe),_r()),yt={...yt??{},...e},xt=t,Lr=Ue.record(e),qe("saving"),xe&&clearTimeout(xe);const n=new Promise(r=>{Xo.push(r)});return xe=setTimeout(()=>{_r()},Dh),n},cb=async()=>{if(typeof window>"u")return;const e=nl();try{const t=await ah();if(!t)return;const n=()=>ih(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){const r=e.onFinishHydration(()=>{r?.(),n()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},Lh=3e4,_h=40,Fh=60,jh=(e,t,n,r,o,s,i)=>{const a=t.trim(),c=n.trim().toLowerCase();return JSON.stringify([e,a,c,r,o,s,i])},ia=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},Nh=Ze()(an((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,o=Fh,s){if(!n||n.trim().length===0)return[];const i=n.trim(),a=B(),c=typeof r=="string"?r.trim():"",l=!!s?.includeHidden,d=s?.respectGitignore??!0,u=s?.type==="directory"?"directory":"file",f=jh(a,i,c,o,l,d,u),p=Date.now(),h=t().cache[f];if(h&&p-h.timestamp<Lh)return h.files;const g=t().inFlight[f];if(g)return g;const y=Ne.searchFiles(c,{directory:i,limit:o,includeHidden:l,respectGitignore:d,dirs:u!=="file",type:u}).then(b=>(e(S=>{if(S.inFlight[f]!==y)return S;const k={...S.cache,[f]:{files:b,timestamp:Date.now()}},I=S.cacheKeys.filter($=>$!==f);for(I.push(f);I.length>_h;){const $=I.shift();$&&delete k[$]}return{cache:k,cacheKeys:I}}),b)).finally(()=>{e(b=>{if(b.inFlight[f]!==y)return b;const S={...b.inFlight};return delete S[f],{inFlight:S}})});return e(b=>({inFlight:{...b.inFlight,[f]:y}})),y},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(o=>{const s={...o.cache},i=o.cacheKeys.filter(l=>ia(l,r)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!ia(l,r)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),Uh=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},es="openchamber_stream_perf",Bh=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(es)==="1"}catch{return!1}};let jt=Bh();const aa=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Hh=()=>{if(!jt||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},ol=e=>Array.from(e.entries()).map(([t,n])=>({metric:t,count:n.count,avg:n.count>0?Number((n.total/n.count).toFixed(3)):0,max:Number(n.max.toFixed(3)),total:Number(n.total.toFixed(3)),last:Number(n.last.toFixed(3))})).sort((t,n)=>n.total-t.total||n.count-t.count),Hs=(e,t)=>{const n=Hh();if(!n)return;const r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},zh=e=>{if(jt=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(es,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(es),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},$h=()=>{typeof window>"u"||(jt&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Gh=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!jt||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:ol(e.counters)}},lb=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!jt||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:ol(e.counters)}},db=(e,t=1)=>{Hs(e,t)},ub=(e,t)=>{Hs(e,t)},fb=e=>{!jt||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},pb=(e,t)=>{if(!jt)return t();const n=aa();try{return t()}finally{Hs(e,aa()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:zh,reset:$h,getSnapshot:Gh});var Wh={};let Re=null,ca=0;const Ce=Bn(),la=Ce.getItem("lastDirectory"),qh=typeof la=="string"&&la.length>0,lr=e=>{try{Nh.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},sn=e=>{const t=e.trim();if(!t)return t;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(r,o)=>o.toUpperCase()+":");return n.length>1?n.replace(/\/+$/,""):n},Kh=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},gr=(e,t)=>{const n=Kh(e,t);return sn(n)},Vh=()=>{const e=Ce.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},Jh=()=>{const e=Ce.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},Yh=()=>{if(typeof process>"u")return null;const e=Wh,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=sn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=sn(n);return r.length>0?r:null}return null},Fr=()=>{if(typeof window<"u"){if(Re)return Re;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return Re=t,Ce.setItem("homeDirectory",t),t;const n=Vh();if(n&&!Be())return Re=n,n}const e=Yh();return e||"/"},Qh=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/");if(n.length>1){const r=n.replace(/\/+$/,"");if(r&&r.length>0)return r==="/"?null:r}return n==="/"||n.length===0?null:n},Xh=e=>(Re=e,typeof window<"u"&&Ce.setItem("homeDirectory",e),je({homeDirectory:e}),e),ts=async()=>{const e=r=>{const o=Qh(r);return o?Xh(o):null};try{const r=await Ne.getFilesystemHome(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await Ne.getSystemInfo(),o=e(r?.homeDirectory);if(o)return o}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await hc(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=Fr(),n=e(t);return n||t},Zh=()=>{if(!Be())return null;const e=pc()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},jn=Zh()||Fr(),jr=(()=>{const e=Jh();return e&&!Be()?gr(e,jn):jn})();jr&&Ne.setDirectory(jr);const em=!!(jn&&jn!=="/"),ns=Ze()(an((e,t)=>({currentDirectory:jr,directoryHistory:[jr],historyIndex:0,homeDirectory:jn,hasPersistedDirectory:qh,isHomeReady:em,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const o=Re||t().homeDirectory||Ce.getItem("homeDirectory"),s=gr(n,o);Uh()&&console.log("[DirectoryStore] setDirectory called with path:",s),Ne.setDirectory(s),lr(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return Ce.setItem("lastDirectory",s),je({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,o=n.directoryHistory[r];Ne.setDirectory(o),lr(),Ce.setItem("lastDirectory",o),je({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,o=n.directoryHistory[r];Ne.setDirectory(o),lr(),Ce.setItem("lastDirectory",o),je({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),o=Re||t().homeDirectory||Fr();if(n===o||n==="/")return;const s=n.endsWith("/")?n.slice(0,-1):n,i=s.lastIndexOf("/");if(i===-1){const a=Re||Fr();r(a)}else r(i===0?"/":s.substring(0,i))},goHome:async()=>{const n=Re||t().homeDirectory||await ts();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),o=n;Re=o;const s=r.homeDirectory!==o,i=Ce.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!s&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof o=="string"&&o!==""&&o!=="/",d=r.currentDirectory?gr(r.currentDirectory,o):r.currentDirectory,u=r.directoryHistory.map(g=>gr(g,o)),f=u.some((g,y)=>g!==r.directoryHistory[y]),p=!!(d&&d!==r.currentDirectory),h={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(h.currentDirectory=o,h.directoryHistory=[o],h.historyIndex=0,h.isSwitchingDirectory=!1):(p||f)&&(h.currentDirectory=d,h.directoryHistory=u,h.historyIndex=Math.min(r.historyIndex,u.length-1),h.isSwitchingDirectory=!1),e(()=>h),(c||p)&&l){const g=c?o:d;Ne.setDirectory(g),lr(),Ce.setItem("lastDirectory",g),je({lastDirectory:g})}je({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(ts().then(e=>{ns.getState().synchronizeHomeDirectory(e)}),dc(()=>{Re=null;const e=++ca;ts().then(t=>{e===ca&&ns.getState().synchronizeHomeDirectory(t)})}));const tm=(e,t)=>{const n=Br();return n?n.openWebSocket(id(e),t):md(new WebSocket(e))},sl=1,da=512*1024,nm=0,Kt=1,rm=15e3,zs=new TextEncoder,il=new TextDecoder,$s=mt(["interactive","command"]),al=mt(["running","exited","error"]),om=mt(["node","bun"]),Gs=Nr("type",[P({type:F("terminal")}),P({type:F("project-action"),actionId:w(),executionId:w()})]),sm=P({sessionId:w(),cols:R(),rows:R(),status:al,mode:$s.optional(),purpose:Gs.optional()}),im=P({sessionId:w(),cwd:w(),status:mt(["running","exited"]),createdAt:R().nullable().optional().transform(e=>e??null),mode:$s.optional(),purpose:Gs.optional()}),ua={mode:$s.optional(),purpose:Gs.optional()},am=Nr("t",[P({t:F("hello")}),P({t:F("pong")}),P({t:F("error"),s:w().optional(),message:w().optional(),code:w().optional(),fatal:Ml().optional()}),P({t:F("snapshot"),s:w(),q:R().int().nonnegative().default(0),history:w().default(""),status:al,exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional(),runtime:om.optional(),ptyBackend:w().optional(),...ua}),P({t:F("output"),s:w(),q:R().int().nonnegative(),d:w(),r:w().optional()}),P({t:F("exit"),s:w(),q:R().int().nonnegative(),exitCode:R().nullish().transform(e=>e??void 0),signal:R().nullable().optional()}),P({t:F("restarted"),s:w(),q:R().int().nonnegative(),history:w().default(""),...ua})]),cm=e=>{const t=zs.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=sl,n.set(t,1),n},lm=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):zs.encode(e);t[0]===sl&&(t=t.subarray(1));try{return am.safeParse(JSON.parse(il.decode(t))).data??null}catch{return null}},dm="TERMINAL_CWD_MISSING";class cl extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const hb=e=>e instanceof cl&&e.code===dm,um=P({error:w().optional(),code:w().optional()}),Vr=async(e,t)=>{const n=um.safeParse(await e.json().catch(()=>null)).data;return new cl(n?.error??t,n?.code??null)},fm=e=>{const t=zs.encode(e);if(t.byteLength<=da)return e;let n=t.byteLength-da;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return il.decode(t.subarray(n))},pm=P({sessions:Xe(ls())});class ll{constructor(t={refreshAuth:$r,openSocket:()=>tm(ye().websocket("/api/terminal/ws")),clearUrlAuthToken:Un}){this.dependencies=t}socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},o=this.subscribers.get(t)??new Set,s=o.size===0;o.add(r),this.subscribers.set(t,o);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data:i.history,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend}));const a=this.socket?.readyState===Kt;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);s&&a&&c===o&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{o.has(r)&&(n.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(r),c?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Kt){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,n){if(n&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=!0,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Kt)return;if(this.opening)return await this.opening,this.socket?.readyState===Kt?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,o)=>{let s=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,d=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},u=p=>{s||(s=!0,clearTimeout(f),p?o(p):r())},f=setTimeout(()=>{d(),c?.close(),u(new Error("Terminal connection timed out"))},1e4);try{const p=this.dependencies.openSocket();c=p,p.binaryType="arraybuffer",this.socket=p,p.onopen=()=>{if(!l()){p.close(),u(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const h of this.subscribers.keys())this.send({t:"attach",v:3,s:h});this.startKeepalive(),u()},p.onmessage=h=>{this.handleMessage(h.data)},p.onerror=()=>{const h=l();h&&d(),u(new Error("Terminal WebSocket failed")),h&&this.subscribers.size>0&&this.scheduleReconnect()},p.onclose=()=>{const h=l();h&&(this.stopKeepalive(),d()),this.socket===p&&(this.socket=null),u(new Error("Terminal WebSocket closed")),h&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(p){u(p instanceof Error?p:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}handleMessage(t){const n=lm(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const s=new Error(n.message??"Terminal error");s.code=n.code;const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(s,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const s={sequence:n.q??0,history:n.history??"",status:n.status,mode:n.mode,purpose:n.purpose,exitCode:n.exitCode,signal:n.signal??null,runtime:n.runtime,ptyBackend:n.ptyBackend};this.projections.set(n.s,s);for(const i of r)i.lastSequence=s.sequence,i.handlers.onEvent({type:"snapshot",sequence:s.sequence,data:s.history,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal,runtime:s.runtime,ptyBackend:s.ptyBackend});return}const o=this.projections.get(n.s);o&&n.q>o.sequence&&(n.t==="output"?this.projections.set(n.s,{...o,sequence:n.q,history:fm(o.history+(n.r??n.d))}):n.t==="exit"?this.projections.set(n.s,{...o,sequence:n.q,status:"exited",exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&this.projections.set(n.s,{...o,sequence:n.q,history:n.history??"",status:"running",mode:n.mode??o.mode,purpose:n.purpose??o.purpose,exitCode:void 0,signal:null}));for(const s of r)n.q<=s.lastSequence||(s.lastSequence=n.q,n.t==="output"?s.handlers.onEvent({type:"data",sequence:n.q,data:n.d,replayData:n.r}):n.t==="exit"?s.handlers.onEvent({type:"exit",sequence:n.q,exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&s.handlers.onEvent({type:"snapshot",sequence:n.q,data:n.history??"",status:"running",mode:n.mode??o?.mode,purpose:n.purpose??o?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==Kt)return!1;try{return this.socket.send(cm(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const n=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const o of this.subscribers.values())for(const s of o)s.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const r=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",r),typeof document<"u"&&document.addEventListener("visibilitychange",r),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",r),typeof document<"u"&&document.removeEventListener("visibilitychange",r)},this.reconnectTimer=setTimeout(r,n)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},rm))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===nm||t.readyState===Kt)&&t.close()}}let Lt=new ll;async function hm(e){const t=await m("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Vr(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=sm.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function mm(e){const t=await m(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await Vr(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=pm.safeParse(n).data?.sessions;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const o=[];for(const s of r){const i=im.safeParse(s).data;i&&o.push(i)}return o}async function ym(e){e.length!==0&&await un("/api/terminal/touch","POST",{sessionIds:e})}async function gm(){const e=await m("/api/terminal/shells");if(!e.ok)throw await Vr(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Or(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function wm(e,t,n){return Lt.subscribe(e,{onEvent:t,onError:n})}async function bm(e,t){await Lt.write(e,t)}async function un(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const o=await m(e,r);if(!o.ok)throw await Vr(o,"Terminal command failed");return o}async function Sm(e,t,n){await un(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n})}async function Tm(e,t){await un(`/api/terminal/${e}/appearance`,"POST",t)}async function vm(e){await un(`/api/terminal/${e}`,"DELETE"),Lt.forget(e)}async function Em(e,t){return(await un(`/api/terminal/${e}/restart`,"POST",t)).json()}async function km(e){const n=await(await un("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&Lt.forget(r);else e.sessionId&&Lt.forget(e.sessionId)}function mb(){Lt.dispose(),Lt=new ll}const Am=()=>({async listShells(){return gm()},async listSessions(e){return mm(e)},async touchSessions(e){await ym(e)},async createSession(e){return hm(e)},connect(e,t){const n=wm(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await bm(e,t)},async resize(e){await Sm(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await Tm(e,t)},async close(e){await vm(e)},async restartSession(e,t){return Em(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await km(e)}}),rs=new Set,Pm=e=>(rs.add(e),()=>{rs.delete(e)}),Mm=e=>{for(const t of rs)t(e)},T="/api/git",Im=1200,Cm=5e3,os=new Map,vn=new Map,dl=new Map,fa=new Map,dr=new Map,ul=e=>e.trim(),Ws=(e,t)=>JSON.stringify([e,ul(t)]),fl=(e,t,n)=>JSON.stringify([e,ul(t),n??"full"]),ss=(e,t)=>dl.get(Ws(e,t))??0,pl=(e,t)=>{const n=Ws(e,t);dl.set(n,ss(e,t)+1);for(const r of[void 0,"light"]){const o=fl(e,t,r);os.delete(o),vn.delete(o)}};Pm(e=>{pl(B(),e)});const Hn=e=>{Mm(e)},q=async(e,t)=>{const n=await t.json();return Hn(e),n};function v(e,t,n){const r={...n};return t&&(r.directory=t),ye().api(e,r)}async function xm(e){const t=Ws(B(),e),n=Date.now(),r=fa.get(t);if(r&&r.expiresAt>n)return r.value;const o=dr.get(t);if(o)return o;const s=(async()=>{const i=await m(v(`${T}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return fa.set(t,{value:c,expiresAt:Date.now()+Cm}),c})();dr.set(t,s);try{return await s}finally{dr.get(t)===s&&dr.delete(t)}}class Rm extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function yb(e){const t=await m("/api/fs/git-dirs",{query:{path:e}});if(t.status===501)throw new Rm;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>dn(r?.path??null)).filter(r=>r!==null)}async function Dm(e,t){const n=t?.mode,r=B();t?.fresh&&pl(r,e);const o=fl(r,e,n),s=Date.now(),i=os.get(o);if(i&&i.expiresAt>s)return i.value;const a=vn.get(o);if(a)return a;const c=(async()=>{const l=ss(r,e),d=await m(v(`${T}/status`,e,n?{mode:n}:void 0));if(!d.ok)throw new Error(`Failed to get git status: ${d.statusText}`);const u=await d.json();return ss(r,e)===l&&os.set(o,{value:u,expiresAt:Date.now()+Im}),u})();vn.set(o,c);try{return await c}finally{vn.get(o)===c&&vn.delete(o)}}async function gb(e){const t=await m(v(`${T}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function wb(e){const t=await m(v(`${T}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function bb(e,t){const n=await m(v(`${T}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function Om(e,t){const{path:n,staged:r,contextLines:o}=t;if(!n)throw new Error("path is required to fetch git diff");const s=await m(v(`${T}/diff`,e,{path:n,staged:r?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function Lm(e,t){const{base:n,head:r,path:o,contextLines:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const i=await m(v(`${T}/range-diff`,e,{base:n,head:r,path:o||void 0,context:s}));if(!i.ok)throw new Error(`Failed to get git range diff: ${i.statusText}`);return i.json()}async function _m(e,t){const{base:n,head:r}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await m(v(`${T}/range-files`,e,{base:n,head:r}));if(!o.ok)throw new Error(`Failed to get git range files: ${o.statusText}`);const s=await o.json();return Array.isArray(s.files)?s.files.filter(i=>{if(!i||typeof i!="object")return!1;const a=i;return typeof a.path=="string"&&typeof a.status=="string"}):[]}async function Fm(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await m(v(`${T}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function jm(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const o=await m(v(`${T}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function Nm(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await m(v(`${T}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert git changes")}Hn(e)}async function Um(e,t){await hl(e,[t])}async function hl(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await m(v(`${T}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stage git changes")}Hn(e)}async function Bm(e,t){await ml(e,[t])}async function ml(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await m(v(`${T}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to unstage git changes")}Hn(e)}async function Hm(e,t,n){await qs(e,t,n,"stage")}async function zm(e,t,n){await qs(e,t,n,"unstage")}async function $m(e,t,n){await qs(e,t,n,"discard")}async function qs(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const o=await m(v(`${T}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to apply git hunk")}Hn(e)}async function Gm(e){if(!e)return!1;const t=await m(v(`${T}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Wm(e){const t=await m(v(`${T}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function qm(e,t){const n=await m(v(`${T}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function Km(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await m(v(`${T}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return q(e,n)}async function Vm(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await m(v(`${T}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return q(e,n)}async function Jm(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await m(v(`${T}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to remove remote")}return q(e,r)}async function Ym(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const o=await m(v(`${T}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const s=await o.json();if(!s?.message||typeof s.message!="object")throw new Error("Malformed commit generation response");const i=typeof s.message.subject=="string"&&s.message.subject.trim().length>0?s.message.subject.trim():"",a=Array.isArray(s.message.highlights)?s.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function Qm(e,t){const{base:n,head:r,context:o,zenModel:s,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};o?.trim()&&(c.context=o.trim()),s&&(c.zenModel=s),i&&(c.providerId=i),a&&(c.modelId=a);const l=await m(v(`${T}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",f=typeof d?.body=="string"?d.body:"";if(!u&&!f)throw new Error("Malformed PR description response");return{title:u,body:f}}async function pa(e){const t=await m(v(`${T}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function ha(e,t){const n=await m(v(`${T}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function Xm(e){const t=await m(v(`${T}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function Zm(e,t){const n=await m(v(`${T}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function ma(e,t){const n=await m(v(`${T}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function ya(e,t){const n=await m(v(`${T}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}async function ey(e,t,n={}){const r=await m(v(`${T}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create commit")}return q(e,r)}async function ty(e,t={}){const n=await m(v(`${T}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to push")}return q(e,n)}async function ny(e,t={}){const n=await m(v(`${T}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return q(e,n)}async function ry(e,t={}){const n=await m(v(`${T}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return q(e,n)}async function oy(e){const t=await m(v(`${T}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function sy(e,t){const n=await m(v(`${T}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function yl(e,t={}){const n=await m(v(`${T}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return q(e,n)}const Ks=async(e,t,n)=>{const r=await m(v(`${T}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||`Failed to ${t}`)}return q(e,r)},iy=(e,t)=>Ks(e,"stash/apply",t),gl=(e,t)=>Ks(e,"stash/pop",t),ay=(e,t)=>Ks(e,"stash/drop",t);async function cy(e,t){const n=await m(v(`${T}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return q(e,n)}async function ly(e,t,n){const r=await m(v(`${T}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create branch")}return q(e,r)}async function dy(e,t,n){const r=await m(v(`${T}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename branch")}return q(e,r)}async function uy(e,t={}){const n=await m(v(`${T}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return n.json()}async function fy(e,t){const n=await m(v(`${T}/commit-files`,e,{hash:t}));if(!n.ok)throw new Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Sb(e,t,n,r){const o=await m(v(`${T}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function py(){const e=await m(v(`${T}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function hy(e){const t=await m(v(`${T}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to create git identity")}return t.json()}async function my(e,t){const n=await m(v(`${T}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function yy(e){const t=await m(v(`${T}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function gy(e){if(!e)return null;const t=await m(v(`${T}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function wy(e){if(!e)return!1;const t=await m(v(`${T}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function Tb(){const e=await m(v(`${T}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function by(e,t){const n=await m(v(`${T}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function vb(){const e=await m(v(`${T}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Eb(e,t){if(!e)return null;const n=await m(v(`${T}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function Sy(e){const t=await m(v(`${T}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Ty(e,t){const n=await m(v(`${T}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return q(e,n)}async function vy(e){const t=await m(v(`${T}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return q(e,t)}async function Ey(e,t){const n=await m(v(`${T}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return q(e,n)}async function ky(e,t){const n=await m(v(`${T}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return q(e,n)}async function Ay(e,t){const n=await m(v(`${T}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return q(e,n)}async function Py(e,t){const n=await m(v(`${T}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return q(e,n)}async function My(e,t,n,r){const o=await m(v(`${T}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to reset")}return q(e,o)}async function Iy(e){const t=await m(v(`${T}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return q(e,t)}async function Cy(e){const t=await m(v(`${T}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return q(e,t)}async function xy(e){const t=await m(v(`${T}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return q(e,t)}async function Ry(e,t){return await yl(e,{message:t?.message}),{success:!0}}async function Dy(e){return await gl(e,{ref:"stash@{0}"}),{success:!0}}async function Oy(e){const t=await m(v(`${T}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Ly(e,t){const n=await m(`${T}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function _y(e){const t=await m(`${T}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const Fy=()=>({checkIsGitRepository:xm,getGitStatus:Dm,getGitDiff:Om,getGitFileDiff:jm,getGitRangeDiff:Lm,getGitRangeFiles:_m,getBranchBase:Fm,revertGitFile:Nm,stageGitFile:Um,stageGitFiles:hl,unstageGitFile:Bm,unstageGitFiles:ml,stageGitHunk:Hm,unstageGitHunk:zm,revertGitHunk:$m,isLinkedWorktree:Gm,getGitBranches:Wm,getGitUnpushedBranchCounts:qm,deleteGitBranch:Km,deleteRemoteBranch:Vm,removeRemote:Jm,generateCommitMessage:Ym,generatePullRequestDescription:Qm,listGitWorktrees:pa,validateGitWorktree:ha,createGitWorktree:ma,deleteGitWorktree:ya,validateWorktreeDirectory:Ly,canonicalizeWorktreeState:_y,createGitCommit(e,t,n){return ey(e,t,n)},gitPush:ty,gitPull:ny,gitFetch:ry,listGitStashes:oy,countGitStashFiles:sy,stashGitChanges:yl,applyGitStash:iy,popGitStash:gl,dropGitStash:ay,checkoutBranch:cy,createBranch:ly,renameBranch:dy,getGitLog(e,t){return uy(e,t)},getCommitFiles:fy,getCurrentGitIdentity:gy,hasLocalIdentity:wy,setGitIdentity:by,getGitIdentities:py,createGitIdentity:hy,updateGitIdentity:my,deleteGitIdentity:yy,getRemotes:Sy,rebase:Ty,abortRebase:vy,continueRebase:Cy,merge:Ey,abortMerge:Iy,continueMerge:xy,checkoutCommit:ky,cherryPick:Ay,revertCommit:Py,resetToCommit:My,stash:Ry,stashPop:Dy,getConflictDetails:Oy,worktree:{list:pa,validate:ha,bootstrapStatus:Xm,preview:Zm,create:ma,remove:ya}}),te=e=>e.replace(/\\/g,"/"),jy=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Ct("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:te(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:te(r.path),isDirectory:!!r.isDirectory}))}},Pe=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},Ny=({getDirectory:e})=>({async listDirectory(t,n){const r=te(t),o=new URLSearchParams;r&&o.set("path",r),n?.respectGitignore&&o.set("respectGitignore","true");const s=await m("/api/fs/list",{query:o,headers:Pe(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Ct(a.error||"Failed to list directory",{reason:Cr(a.reason),status:s.status})}const i=await s.json();return jy(r,i)},async search(t){const n=new URLSearchParams,r=te(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const o=await m("/api/find/file",{query:n,headers:Pe(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to search files")}const s=await o.json();return(Array.isArray(s)?s:[]).map(a=>({path:te(`${r}/${a}`),preview:[te(a)]}))},async createDirectory(t){const n=te(t),r=await m("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create directory")}const o=await r.json();return{success:!!o?.success,path:typeof o?.path=="string"?te(o.path):n}},async statFile(t,n){const r=te(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant);const s=await m("/api/fs/stat",{query:o,headers:Pe(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await s.json().catch(()=>({}));return{path:typeof i.path=="string"?te(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=te(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&o.set("optional","true");const s=await m("/api/fs/read",{query:o,cache:n?.optional||n?.fresh?"no-store":"default",headers:Pe(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await s.text(),path:r}},async writeFile(t,n){const r=te(t),o=await m("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:r,content:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to write file")}const s=await o.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?te(s.path):r}},async uploadFile(t,n,r){const o=te(t),s=await m("/api/fs/upload",{method:"POST",query:{path:o,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Pe(e,r?.directory)},body:n});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Ct(a.error||"Failed to upload file",{reason:Cr(a.reason),status:s.status})}const i=await s.json().catch(()=>({}));return{success:!!i.success,path:i.path?te(i.path):o}},async delete(t){const n=te(t),r=await m("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await m("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename file")}const o=await r.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?te(o.path):n}},async revealPath(t){const n=await m("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:te(t)})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=te(t),r=await m("/api/fs/raw",{query:{path:n,download:!0},headers:Pe(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const o=await r.blob(),s=n.split("/").pop()||"file",i=window.Capacitor,a=new File([o],s,{type:o.type||"application/octet-stream"});if(i?.isNativePlatform?.()===!0&&navigator.canShare?.({files:[a]})){await navigator.share({files:[a]});return}const c=URL.createObjectURL(o),l=document.createElement("a");l.href=c,l.download=s,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),100)}}),ga="/api/config/settings",Uy="/api/config/reload",wa=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},By=()=>({async load(){const e=await m(ga,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:wa(await e.json()),source:"web"}},async save(e){const t=await m(ga,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to save settings")}return wa(await t.json())},async restartOpenCode(){const e=await m(Uy,{method:"POST"});if(!e.ok){const t=await e.json().catch(()=>({error:e.statusText}));throw new Error(t.error||"Failed to restart OpenCode")}return{restarted:!0}}}),Hy=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),zy=1500,is=5e3,$y="openchamber-notification-claim:",Cn=new Map,Gy=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Wy=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim()).join("|")},qy=e=>{for(const[t,n]of Cn)e-n>is&&Cn.delete(t)},Ky=e=>{const t=Wy(e);if(!t)return!0;const n=Date.now();qy(n);const r=Cn.get(t)??0;if(n-r<is)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${$y}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<is)return Cn.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return Cn.set(t,n),!0},wl=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{setTimeout(()=>n(null),zy)})])??e}catch{return e}},Vy=async e=>{const t=await wl();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},Jy=async()=>{const e=await wl();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},Yy=async e=>{if(e?.requireHidden&&typeof document<"u"&&document.hasFocus())return!0;if(typeof Notification>"u")return console.info("Notifications not supported in this environment",e),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;if(!Gy()&&await Jy()||!Ky(e))return!0;try{return await Vy(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},Qy=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},Xy=()=>({async notifyAgentCompletion(e){return await Qy(e)||await Yy(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Zy=()=>({async getAvailableTools(){const e=await m("/api/experimental/tool/ids");if(!e.ok)throw new Error(`Tools API returned ${e.status} ${e.statusText}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Tools API returned invalid data format");return t.filter(n=>typeof n=="string"&&n!=="invalid").sort()}}),Vt=async(e,t)=>{try{const n=await m(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},eg=()=>({async getVapidPublicKey(){return Vt("/api/push/vapid-public-key")},async subscribe(e){return Vt("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Vt("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Vt("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return Vt("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Vt("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),ee=async e=>await e.json().catch(()=>null),tg=({urls:e})=>({async authStatus(){const t=await m("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await m("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await ee(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await m("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await m("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await m("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await m("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await m("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,o){const s=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...o?.force?{force:"true"}:{}}),i=await m(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await ee(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const n=await m("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await m("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await m("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await m("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await m(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await m(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await ee(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to fetch repo branches");return o.branches??[]},async prsList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await m(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&o.set("diff","1"),r?.includeCheckDetails&&o.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await m(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}});async function we(e){try{return await e.json()}catch{return null}}function be(e,t){return e?.error?.trim()||t}function bl(e){return Number.isFinite(e)?e??null:null}function Sl(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function Tl(e){const t=e?.id?.trim();return t?{id:t,name:e?.name?.trim()||null,displayName:e?.displayName?.trim()||null,email:e?.email?.trim()||null,avatarUrl:e?.avatarUrl?.trim()||null}:null}function ng(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function rg(e){const t=e?.id?.trim();if(!t)return null;const n=e?.authorizedAt;return{id:t,name:e?.name?.trim()||null,urlKey:e?.urlKey?.trim()||null,current:e?.current===!0,user:Tl(e?.user),authorizedAt:bl(n)}}function ba(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(rg).filter(n=>n!=null):[];return{connected:e.connected,user:Tl(e.user),organization:ng(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function og(e){const t=e?.authorizationUrl?.trim(),n=e?.expiresIn,r=e?.scope?.trim();return!t||!Number.isFinite(n)||n==null||!r?null:{authorizationUrl:t,expiresIn:n,scope:r}}function sg(e){const t=e?.id?.trim()||null,n=e?.name?.trim()||null,r=e?.type?.trim()||null;return!t&&!n&&!r?null:{id:t,name:n,type:r}}function ig(e){const t=e?.id?.trim(),n=e?.name?.trim();if(!t||!n)return null;const r=e?.position;return{id:t,name:n,type:e?.type?.trim()||null,position:bl(r)??0}}function ag(e){const t=e?.name?.trim()||null,n=e?.displayName?.trim()||null,r=e?.avatarUrl?.trim()||null;return!t&&!n&&!r?null:{name:t,displayName:n,avatarUrl:r}}function cg(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();return!t||!n||!r?null:{id:t,key:n,name:r}}function lg(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function dg(e){const t=e?.trim();if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9A-Fa-f]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function ug(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:dg(e.color)}}function fg(e){return Array.isArray(e)?e.map(ug).filter(t=>t!=null):[]}function vl(e){if(!e)return null;const t=e?.id?.trim(),n=e?.identifier?.trim(),r=e?.title?.trim(),o=e?.url?.trim();return!t||!n||!r||!o?null:{id:t,identifier:n,title:r,url:o,state:sg(e.state),assignee:ag(e.assignee),team:cg(e.team),priority:lg(e.priority),labels:fg(e.labels)}}function pg(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:Sl(n)??"",createdAt:e?.createdAt?.trim()||null,user:e?.user?{name:e.user.name?.trim()||null,displayName:e.user.displayName?.trim()||null,avatarUrl:e.user.avatarUrl?.trim()||null}:null}}function El(e){const t=vl(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(pg).filter(o=>o!=null):[],r=e?.description;return{...t,description:Sl(r),comments:n}}function hg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(vl).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function mg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:El(e.issue)}}function yg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(ig).filter(n=>n!=null):[]}}function gg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:El(e.issue)}}function wg(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();if(!t||!n||!r)return null;const o=e?.projectPath?.trim()||null;return{id:t,key:n,name:r,projectPath:o}}function Sa(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};const t=Array.isArray(e.teams)?e.teams.map(wg).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const bg=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function Sg(e){return bg.find(t=>t===e)??null}function Ta(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function Tg(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};if(e.posted===!0)return{connected:!0,posted:!0,commentId:e.commentId?.trim()||null};const t=Sg(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const vg=()=>({async authStatus(){const e=await m("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=ba(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await m("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await we(t),r=og(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await m("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await we(e);if(!e.ok)throw new Error(be(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await m("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await we(t),r=ba(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),o=e?.status?.trim(),s=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),o&&t.set("status",o),s&&t.set("assignee",s),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",d=await m(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),u=await we(d),f=hg(u);if(!d.ok||!f)throw new Error(be(u,d.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await m(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await we(n),o=mg(r);if(!n.ok||!o)throw new Error(be(r,n.statusText||"Failed to load Linear issue"));return o},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await m(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await we(n),o=yg(r);if(!n.ok||!o)throw new Error(be(r,n.statusText||"Failed to load Linear workflow states"));return o},async issueUpdate(e){const t=await m("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await we(t),r=gg(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await m("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=Sa(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await m("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await we(t),r=Sa(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await m("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await we(t),r=Tg(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await m("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=Ta(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await m("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await we(t),r=Ta(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to save Linear preferences"));return r}}),st=async e=>await e.json().catch(()=>null),Eg=()=>({async listClients(){const e=await m("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await m("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await st(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await m("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),n=await st(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await m("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await m("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==!1}},async cancelPairing(e){const t=await m(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await st(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await m(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await st(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await m("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),kg=()=>({api:(...e)=>ye().api(...e),authenticatedAsset:(...e)=>ye().authenticatedAsset(...e),auth:(...e)=>ye().auth(...e),health:(...e)=>ye().health(...e),rawFile:(...e)=>ye().rawFile(...e),sse:(...e)=>ye().sse(...e),websocket:(...e)=>ye().websocket(...e)}),Ag=(e={})=>{const t=e.urls??ms();$d(t);const n=kg();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Am(),git:Fy(),files:Ny({getDirectory:()=>ns.getState().currentDirectory}),settings:By(),permissions:Hy(),notifications:Xy(),github:tg({urls:n}),linear:vg(),push:eg(),clientAuth:Eg(),tools:Zy()}},Pg=3e3,va=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Mg=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__)}};let as=Promise.resolve();const kb=()=>as,Ab=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:o,relayHostId:s,relay:i}=e??Mg(),a=e?null:fc(),c=s||(a?.target==="remote"?a.hostId:""),l=nc({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return ru({apiBaseUrl:t,runtimeKey:va(t,r)?"local":c?`host:${c}`:null}),Ga(n||null),Wa(o||null),i&&kr({apiBaseUrl:t,clientToken:n||null,requestHeaders:o||null,runtimeKey:s?`host:${s}`:null,relay:i}),Ne.reconnectToRuntimeBaseUrl(),$r(t||void 0).catch(()=>{}),r&&!va(t,r)&&Object.keys(zr()).length>0&&Qa(r).catch(()=>{}),sc(),as=i?Promise.resolve():Promise.race([Qu(s||void 0).catch(()=>{}),new Promise(d=>{window.setTimeout(d,1e4)})]).then(()=>{Ne.reconnectToRuntimeBaseUrl()}),as.then(()=>{window.setTimeout(()=>{qu().catch(()=>{})},Pg)}),Ag({urls:l})};export{ye as $,ue as A,hw as B,yu as C,uh as D,hr as E,pw as F,Be as G,fw as H,dn as I,db as J,ln as K,Ts as L,tu as M,gc as N,dh as O,kw as P,Uu as Q,pt as R,yc as S,Y as T,qa as U,Zg as V,tw as W,Kw as X,Vw as Y,Nh as Z,Iw as _,B as a,Ww as a$,ks as a0,Br as a1,$r as a2,tm as a3,zr as a4,Og as a5,pp as a6,ew as a7,je as a8,Go as a9,sw as aA,iw as aB,rw as aC,zf as aD,po as aE,hb as aF,_f as aG,jf as aH,mb as aI,Qc as aJ,$g as aK,Gg as aL,Wg as aM,cu as aN,pc as aO,Af as aP,Uh as aQ,xw as aR,Ic as aS,zp as aT,Mm as aU,Ho as aV,it as aW,xp as aX,Vc as aY,ou as aZ,ud as a_,Nw as aa,Hf as ab,fb as ac,pu as ad,nw as ae,Gh as af,lb as ag,$h as ah,Zn as ai,Pn as aj,xf as ak,Me as al,Cw as am,au as an,fc as ao,Ug as ap,zh as aq,jw as ar,Bg as as,Hg as at,dw as au,lw as av,aw,cw as ax,_t as ay,ib as az,ap as b,Nm as b$,ja as b0,Xm as b1,tl as b2,hc as b3,Un as b4,qw as b5,Iy as b6,vy as b7,iy as b8,_y as b9,py as bA,uy as bB,Lm as bC,_m as bD,Dm as bE,qm as bF,Tb as bG,Eb as bH,Sy as bI,ha as bJ,pa as bK,ry as bL,ny as bM,ty as bN,wy as bO,Gm as bP,oy as bQ,Ey as bR,gl as bS,Zm as bT,Ty as bU,Jm as bV,dy as bW,My as bX,gb as bY,wb as bZ,Py as b_,xm as ba,cy as bb,ky as bc,Ay as bd,xy as be,Cy as bf,sy as bg,ly as bh,ey as bi,hy as bj,ma as bk,Km as bl,yy as bm,ya as bn,Vm as bo,vb as bp,ay as bq,Fm as br,Sb as bs,fy as bt,Oy as bu,gy as bv,Wm as bw,bb as bx,Om as by,jm as bz,Ab as c,Gw as c$,$m as c0,by as c1,Um as c2,hl as c3,Hm as c4,Ry as c5,yl as c6,Dy as c7,Bm as c8,ml as c9,fo as cA,ub as cB,yb as cC,Rm as cD,Pm as cE,ow as cF,Ee as cG,Jw as cH,Qw as cI,tb as cJ,Xw as cK,Yw as cL,Zw as cM,el as cN,eb as cO,zw as cP,$w as cQ,Op as cR,Bw as cS,Rs as cT,pb as cU,Xg as cV,Ow as cW,Ec as cX,Rw as cY,Dw as cZ,Lw as c_,zm as ca,my as cb,Ly as cc,de as cd,_w as ce,Rf as cf,ic as cg,Uw as ch,Aw as ci,Pw as cj,le as ck,Ru as cl,Hu as cm,Wu as cn,Bu as co,vs as cp,Nu as cq,Mw as cr,Tw as cs,Ew as ct,vw as cu,Du as cv,Yu as cw,Ng as cx,Hw as cy,er as cz,Bn as d,Pt as d0,Lf as d1,Ff as d2,sb as d3,ob as d4,Ou as d5,Pu as d6,gw as d7,ww as d8,uw as d9,Je as dA,rh as da,Kr as db,Fw as dc,Df as dd,Of as de,Or as df,Sp as dg,bp as dh,th as di,qr as dj,ip as dk,qg as dl,Vg as dm,Yg as dn,Kg as dp,Jg as dq,Qg as dr,rb as ds,yw as dt,nb as du,fh as dv,Fg as dw,jg as dx,mw as dy,Sw as dz,Gr as e,Lg as f,kb as g,_g as h,Oc as i,us as j,at as k,bw as l,ns as m,sp as n,Wr as o,Eu as p,Sr as q,m as r,kr as s,zg as t,Se as u,dc as v,Ne as w,cb as x,ab as y,gt as z};