@aiworker/web 1.23.0 → 1.23.1

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 (152) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-B1Gizi3a.js → CodeMirrorCommentWidgets-teB3HmBT.js} +1 -1
  2. package/dist/assets/DiffView-DC9RX3MF.js +4 -0
  3. package/dist/assets/{DirtyBranchSwitchDialog-aig6zJjg.js → DirtyBranchSwitchDialog-DwPkzXsS.js} +1 -1
  4. package/dist/assets/FilesView-BFZkuu4O.js +13 -0
  5. package/dist/assets/{GitView-BXsS3jG6.js → GitView-B_x52MHY.js} +4 -4
  6. package/dist/assets/{JsonTreeView-D_hpXBnF.js → JsonTreeView-cmAzUTiw.js} +1 -1
  7. package/dist/assets/{LinearIssuesView-BoUiLQG1.js → LinearIssuesView-Dehh5afm.js} +1 -1
  8. package/dist/assets/{MarkdownImageGallery-B_B_a9KS.js → MarkdownImageGallery-DgNOqqhE.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-xgyyLiBM.js → MarkdownRendererImpl-DusmMZ_p.js} +2 -2
  10. package/dist/assets/{OnboardingScreen-DIp84OWt.js → OnboardingScreen-B8fm1H4m.js} +1 -1
  11. package/dist/assets/{PatchDiff-8p6nLJaU.js → PatchDiff-BVr7gJU0.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-DjC8nTk9.js → PierreDiffViewer-DzLt-nel.js} +1 -1
  13. package/dist/assets/PlanView-BmQUYT_z.js +5 -0
  14. package/dist/assets/SettingsView-ChWmAcZT.js +28 -0
  15. package/dist/assets/{SettingsWindow-Cpb4hM6q.js → SettingsWindow-Dy3M6ZB9.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-DfaKZXNU.js → ToolOutputDialog-cTl_eLIH.js} +6 -6
  17. package/dist/assets/{ToolPartDiffPreview-DtZLzrSK.js → ToolPartDiffPreview-C_3iYNJQ.js} +2 -2
  18. package/dist/assets/{VirtualizedFileDiff-C8i9HpTB.js → VirtualizedFileDiff-CAWthkoy.js} +4 -4
  19. package/dist/assets/WalkthroughView-C7AHOpCA.js +4 -0
  20. package/dist/assets/{computeVirtualFileMetrics-BBI7ZwrC.js → computeVirtualFileMetrics-BkiDSlTW.js} +2 -2
  21. package/dist/assets/de-DJsQr-p7.js +10 -0
  22. package/dist/assets/es-BuYMlA9g.js +16 -0
  23. package/dist/assets/fr-ePDay33C.js +14 -0
  24. package/dist/assets/index-BD8ILbxF.js +40 -0
  25. package/dist/assets/{index-jXSK5RrB.js → index-n6O3hklM.js} +1 -1
  26. package/dist/assets/index-zhgg-SDz.css +1 -0
  27. package/dist/assets/{isDiffPlainText-B_x_rVon.js → isDiffPlainText-GMdPz-71.js} +1 -1
  28. package/dist/assets/{isFilePlainText-DW_xMer1.js → isFilePlainText-BVuH1zH9.js} +1 -1
  29. package/dist/assets/ja-BzR9xOY_.js +16 -0
  30. package/dist/assets/{ko-idhXGF8j.js → ko-BEjHAm14.js} +3 -3
  31. package/dist/assets/main-BydQ1tr_.js +930 -0
  32. package/dist/assets/{main-CzdPuL0s.js → main-D3ZDQglc.js} +2 -2
  33. package/dist/assets/{markdownCore-Cn4Tyejo.js → markdownCore-Cb2MdZnV.js} +3 -3
  34. package/dist/assets/{miniChat-CCkqKOLp.js → miniChat-d01k801U.js} +2 -2
  35. package/dist/assets/{mobile-mvxTo055.js → mobile-D7VV-Ufz.js} +2 -2
  36. package/dist/assets/patchFileDiff-CdztVMz0.js +13 -0
  37. package/dist/assets/{pl-CGZWUqZJ.js → pl-rQmpxNIF.js} +3 -3
  38. package/dist/assets/pt-BR-CorbsSW-.js +16 -0
  39. package/dist/assets/renderElectronMiniChatApp-BGG9UIlh.js +2 -0
  40. package/dist/assets/renderMobileApp-BRP3J1iv.js +25 -0
  41. package/dist/assets/runtimeEndpointReset-BhT_-c52.js +41 -0
  42. package/dist/assets/scheduledTasksApi-BEuUF_cj.js +1 -0
  43. package/dist/assets/{shikiHighlight-CRl0SUC9.js → shikiHighlight-BzXUjlby.js} +1 -1
  44. package/dist/assets/surface-COKb77Ua.js +1 -0
  45. package/dist/assets/tr-CoAMXPtI.js +7 -0
  46. package/dist/assets/uk-YlAX0rRU.js +16 -0
  47. package/dist/assets/{useAppFontEffects-CPKeOpUo.js → useAppFontEffects-Cwyhjfl5.js} +153 -155
  48. package/dist/assets/useGitComparison-BCZVefdE.js +1 -0
  49. package/dist/assets/{useInlineCommentController-BiWz4AVb.js → useInlineCommentController-DDkpBEU8.js} +2 -2
  50. package/dist/assets/{useRootScrollLock-BS4-kr7P.js → useRootScrollLock-CwjoWuC4.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-DdV8vhHn.js → vendor-base-ui-BY_5qla_.js} +1 -1
  52. package/dist/assets/{vendor-codemirror-language-data-Bg4AEeCr.js → vendor-codemirror-language-data-Cb1YnICj.js} +2 -2
  53. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  54. package/dist/assets/{vendor-zod-BPAANqvH.js → vendor-zod-B6551dwG.js} +2 -2
  55. package/dist/assets/{web-components-z7hfnS8n.js → web-components-LV3vjTxy.js} +1 -1
  56. package/dist/assets/zh-CN-DDYg0Jl7.js +16 -0
  57. package/dist/assets/zh-TW-CQKaCayr.js +16 -0
  58. package/dist/index.html +4 -4
  59. package/dist/mini-chat.html +4 -4
  60. package/dist/mobile.html +4 -4
  61. package/package.json +1 -1
  62. package/server/index.js +3 -13
  63. package/server/lib/agent-memory/runtime.js +7 -2
  64. package/server/lib/agent-memory/runtime.test.js +22 -0
  65. package/server/lib/event-stream/DOCUMENTATION.md +3 -0
  66. package/server/lib/event-stream/global-hub.js +29 -4
  67. package/server/lib/event-stream/global-hub.test.js +22 -0
  68. package/server/lib/event-stream/global-ws-bridge.js +15 -18
  69. package/server/lib/event-stream/protocol.js +21 -7
  70. package/server/lib/event-stream/runtime.js +9 -6
  71. package/server/lib/event-stream/runtime.test.js +60 -0
  72. package/server/lib/git/DOCUMENTATION.md +10 -1
  73. package/server/lib/git/routes.js +21 -8
  74. package/server/lib/git/routes.test.js +78 -0
  75. package/server/lib/git/service.js +159 -4
  76. package/server/lib/git/service.test.js +74 -0
  77. package/server/lib/github/DOCUMENTATION.md +5 -0
  78. package/server/lib/github/routes.js +2 -2
  79. package/server/lib/message-queue/DOCUMENTATION.md +7 -0
  80. package/server/lib/message-queue/runtime.js +13 -0
  81. package/server/lib/message-queue/runtime.test.js +31 -1
  82. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  83. package/server/lib/notifications/emitter-runtime.js +4 -3
  84. package/server/lib/opencode/DOCUMENTATION.md +18 -4
  85. package/server/lib/opencode/env-runtime.js +5 -1
  86. package/server/lib/opencode/env-runtime.test.js +72 -0
  87. package/server/lib/opencode/feature-routes-runtime.js +15 -1
  88. package/server/lib/opencode/lifecycle.js +4 -3
  89. package/server/lib/opencode/lifecycle.test.js +29 -0
  90. package/server/lib/opencode/managed-plugin-config.js +1 -1
  91. package/server/lib/opencode/proxy.js +33 -0
  92. package/server/lib/opencode/settings-helpers.js +3 -0
  93. package/server/lib/opencode/settings-helpers.test.js +11 -1
  94. package/server/lib/opencode/settings-registry.json +3 -0
  95. package/server/lib/opencode/settings-runtime.js +36 -9
  96. package/server/lib/opencode/settings-runtime.test.js +158 -2
  97. package/server/lib/project-context/DOCUMENTATION.md +13 -3
  98. package/server/lib/project-context/runtime.js +8 -2
  99. package/server/lib/project-context/runtime.test.js +54 -0
  100. package/server/lib/projects/DOCUMENTATION.md +2 -1
  101. package/server/lib/projects/project-config.js +38 -9
  102. package/server/lib/projects/project-config.test.js +97 -0
  103. package/server/lib/projects/project-id.js +26 -0
  104. package/server/lib/relay/DOCUMENTATION.md +20 -0
  105. package/server/lib/relay/host-client.js +7 -0
  106. package/server/lib/relay/host-client.test.js +14 -0
  107. package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
  108. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
  109. package/server/lib/scheduled-tasks/runtime.js +12 -2
  110. package/server/lib/scheduled-tasks/runtime.test.js +53 -0
  111. package/server/lib/session-assist/DOCUMENTATION.md +131 -66
  112. package/server/lib/session-assist/context.js +127 -0
  113. package/server/lib/session-assist/context.test.js +132 -0
  114. package/server/lib/session-assist/prompt.js +54 -0
  115. package/server/lib/session-assist/runtime.js +111 -257
  116. package/server/lib/session-assist/runtime.test.js +203 -0
  117. package/server/lib/walkthrough/DOCUMENTATION.md +15 -5
  118. package/server/lib/walkthrough/pr-source.test.js +21 -0
  119. package/server/lib/walkthrough/pull-request.js +7 -4
  120. package/server/lib/walkthrough/pull-request.test.js +16 -0
  121. package/server/lib/walkthrough/routes.js +19 -0
  122. package/server/lib/walkthrough/routes.test.js +26 -0
  123. package/server/lib/walkthrough/sources.js +13 -2
  124. package/server/opencode-worktree-readiness.test.js +130 -0
  125. package/dist/assets/DiffView-DXjVsEOw.js +0 -4
  126. package/dist/assets/FilesView-CJdG0-wk.js +0 -17
  127. package/dist/assets/PlanView-CJTmOF6I.js +0 -5
  128. package/dist/assets/SettingsView-DD-JqIJx.js +0 -28
  129. package/dist/assets/WalkthroughView-DeKMvZlL.js +0 -4
  130. package/dist/assets/de-DCrsQ5zS.js +0 -10
  131. package/dist/assets/es-Dwv4YfH6.js +0 -16
  132. package/dist/assets/fr-BCWg4Cnx.js +0 -14
  133. package/dist/assets/index-B68h5S5B.css +0 -1
  134. package/dist/assets/index-DVwMarHI.js +0 -39
  135. package/dist/assets/ja-Bruw3RYC.js +0 -16
  136. package/dist/assets/main-BkyaQhJX.js +0 -930
  137. package/dist/assets/patchFileDiff-Csk4iNUi.js +0 -13
  138. package/dist/assets/pt-BR-B8V7u7tA.js +0 -16
  139. package/dist/assets/renderElectronMiniChatApp-BxoyujA5.js +0 -2
  140. package/dist/assets/renderMobileApp-B48CsP4r.js +0 -25
  141. package/dist/assets/runtimeEndpointReset-Bg5gx18H.js +0 -17
  142. package/dist/assets/scheduledTasksApi-BW0Etzwz.js +0 -1
  143. package/dist/assets/surface-oMvhsog3.js +0 -1
  144. package/dist/assets/tr-BK_KiO2V.js +0 -7
  145. package/dist/assets/uk-CG74xV8N.js +0 -16
  146. package/dist/assets/useGitComparison-DH220WmO.js +0 -1
  147. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  148. package/dist/assets/zh-CN-T4AXofZI.js +0 -16
  149. package/dist/assets/zh-TW-Dte40sxp.js +0 -16
  150. package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
  151. package/server/lib/mcp-reconnect/runtime.js +0 -122
  152. package/server/lib/mcp-reconnect/runtime.test.js +0 -140
@@ -0,0 +1,40 @@
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{o as I,n as C,s as w,b as Xt,l as H,_ as ke,r as qt,u as fe,a as Jt,c as G,t as _i,d as bo,e as tr,f as hc}from"./vendor-zod-B6551dwG.js";import{_ as Ys}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as ft,d as In,p as ur,a as Ru}from"./vendor-zustand-BAGL70zf.js";import{c as Cu}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as mc,R as Xr}from"./vendor-react-BUCujlKS.js";const qn=1,Du="openchamber-relay-v1",gc=1,yc=12,Jn=1+yc,nr=64*1024,rr=5,Zr=128,wc=0,Sc=1,Tn=4,Ou=1+Tn,fs=nr-rr-Ou,N={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12,DeliveryAck:13},Mu=new Set(Object.values(N)),_u=e=>Mu.has(e),Kt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},ut=globalThis.crypto.subtle,bc={name:"ECDH",namedCurve:"P-256"},Tc=16,Fo=32,Lu=16,ps=4,vc=8;class Pt extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Fu=()=>ut.generateKey(bc,!0,["deriveBits"]),ju=async e=>{const t=await ut.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Uu=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Pt("invalid ECDH public key JWK");try{return await ut.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},bc,!0,[])}catch{throw new Pt("invalid ECDH public key JWK")}},Nu=()=>{const e=new Uint8Array(Tc);return globalThis.crypto.getRandomValues(e),e},Bu=async(e,t,n)=>{if(n.length!==Tc)throw new Pt("invalid handshake nonce length");const r=await ut.deriveBits({name:"ECDH",public:t},e,256),o=await ut.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await ut.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Du)},o,Fo*2*8)),i=(a,c)=>ut.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,Fo),["encrypt","decrypt"]),hostToClient:await i(s.slice(Fo),["encrypt","decrypt"])}},Hu=(e,t,n)=>{for(let r=vc-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},zu=(e,t)=>{let n=0n;for(let r=0;r<vc;r+=1)n=n<<8n|BigInt(e[t+r]);return n},$u=e=>{const t=new Uint8Array(ps);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>nr)throw new Pt("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(yc);o.set(t,0),Hu(o,ps,n);const s=new Uint8Array(await ut.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(Jn+s.length);return i[0]=gc,i.set(o,1),i.set(s,Jn),i}}},Wu=e=>{let t=0n;return{async decrypt(n){if(n.length<Jn+Lu)throw new Pt("encrypted frame too short");if(n[0]!==gc)throw new Pt("unsupported encrypted frame version");const r=n.slice(1,Jn),o=zu(r,ps);if(o<=t)throw new Pt("frame counter regression");let s;try{s=await ut.decrypt({name:"AES-GCM",iv:r},e,n.slice(Jn))}catch{throw new Pt("frame decryption failed")}return t=o,new Uint8Array(s)}}},Tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ku=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+=Tr[r>>2],t+=Tr[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=Tr[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=Tr[s&63])}return t},Li=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!==qn)return null;const r=n.batch===!0,o=n.flowControl===!0;return n.t==="ready"?{t:"ready",v:qn,batch:r,flowControl:o}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:qn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r,flowControl:o}:null},Gu=e=>({type:"fail",closeCode:Kt.ChannelFailure,reason:e}),qu=async(e,t={})=>{const n=t.batch!==!1,r=await Uu(e),o=await Fu(),s=Nu(),i={t:"hello",v:qn,clientPubJwk:await ju(o.publicKey),nonce:Ku(s)};n&&(i.batch=!0),t.flowControl!==!1&&(i.flowControl=!0);let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Li(c)?.t==="ready"?{type:"ignore"}:Gu("plaintext frame on established channel");const l=Li(c);if(l?.t!=="ready")return{type:"ignore"};const u=await Bu(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,flowControl:t.flowControl!==!1&&l.flowControl===!0,channel:{encryptor:$u(u.clientToHost),decryptor:Wu(u.hostToClient)}}}}},kc=4294967295,Ju=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid delivery acknowledgement");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e)),t};class ge extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const He=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>kc)throw new ge("invalid stream id");if(n.length>fs)throw new ge("tunnel payload exceeds maximum size");const o=new Uint8Array(rr+n.length);return o[0]=r?e|Zr:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,rr),o},Vu=e=>{if(e.length<rr)throw new ge("tunnel frame too short");const t=e[0],n=(t&Zr)!==0,r=t&~Zr;if(!_u(r))throw new ge(`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(rr),hasMoreFragments:n}},Yu=new TextEncoder,Qu=new TextDecoder,vr=e=>Yu.encode(JSON.stringify(e)),kr=(e,t)=>{let n;try{n=JSON.parse(Qu.decode(e))}catch{throw new ge("malformed JSON tunnel payload")}if(!t(n))throw new ge("unexpected JSON tunnel payload shape");return n},Ec=(e,t=fs)=>{if(t<=0||t>fs)throw new ge("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},Fi=(e,t,n)=>{const r=Ec(n);return r.map((o,s)=>He(e,t,o,s<r.length-1))},Xu=(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 ge("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)}}},Zu=e=>{if(e.length===0)throw new ge("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=wc,s.set(o,1),s.length>nr)throw new ge("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=Tn+o.length;if(t>nr)throw new ge("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Sc;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},ed=e=>{if(e.length<1)throw new ge("empty batch plaintext");const t=e[0];if(t===wc)return[e.slice(1)];if(t!==Sc)throw new ge(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+Tn>e.length)throw new ge("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 ge("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ge("empty frame batch");return n},td=new Set([N.HttpBody,N.WsText,N.WsBinary]),Ac=150,nd=24*1024,rd=32,od=e=>{const t=e.windowMs??Ac,n=e.maxBatchBytes??nd,r=e.maxBatchFrames??rd,o=e.now??(()=>Date.now()),s=e.setTimer??((S,y)=>setTimeout(S,y)),i=e.clearTimer??(S=>clearTimeout(S));let a=[],c=0,l=null,u=0,d=!1;const f=()=>{l!==null&&(i(l),l=null)},h=()=>{if(f(),a.length===0)return;const S=a;a=[],c=0,u=o(),e.sendBatch(Zu(S))};return{enqueue:S=>{if(d)return;const y=S[0]&~Zr;if(!td.has(y)){a.push(S),h();return}const k=o();if(a.length===0&&k-u>=t){a.push(S),h();return}const v=Tn+S.length;if(a.length>0&&1+c+v>nr&&h(),a.push(S),c+=v,c>=n||a.length>=r){h();return}l===null&&(l=s(h,t))},flush:h,dispose(){d=!0,f(),a=[],c=0}}},sd=()=>{let e=1;return{next(){if(e>kc)throw new ge("stream id space exhausted");const t=e;return e+=2,t}}},To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),id=e=>To(e)&&Object.values(e).every(t=>typeof t=="string"),ad=e=>To(e)&&typeof e.status=="number"&&id(e.headers),ji=e=>To(e)&&typeof e.reason=="string",cd=e=>To(e)&&typeof e.code=="number"&&typeof e.reason=="string",Pc=/^[a-z][a-z\d+.-]*:\/\//i,Qs="http://tunnel.invalid",ld=e=>{try{const t=Pc.test(e)?new URL(e):new URL(e,Qs);return`${t.pathname}${t.search}`}catch{return e}},Er=e=>({async*[Symbol.asyncIterator](){yield e}}),ud=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()}}}),dd=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},fd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:ud(e)};if(typeof e=="string")return{body:Er(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Er(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Er(dd(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Er(r),contentType:n}},pd=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((d,f)=>r.set(f,d)),i=e.signal,s=e.body):n=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((d,f)=>r.set(f,d)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=Pc.test(n)?new URL(n):new URL(n,Qs),{body:c,contentType:l}=await fd(s);l&&!r.has("content-type")&&r.set("content-type",l);const u={};return r.forEach((d,f)=>{u[f]=d}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:u,body:c,signal:i}},Ic="__aiworkerAmbiguousTransport",xc=e=>(Object.defineProperty(e,Ic,{value:!0,enumerable:!1,configurable:!0}),e),hd=e=>!e||typeof e!="object"?!1:e[Ic]===!0,md=["local","remote",null],gd=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function Rc(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"||!md.includes(r)))return{valid:!1};if(typeof o!="string"||!gd.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 KS(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 GS(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function qS(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Cc(){if(yd()!=="valid")return null;const t=window.__AIWORKER_DESKTOP_BOOT_OUTCOME__,n=Rc(t);return n.valid?n.outcome:null}function yd(){if(typeof window>"u")return"not-injected";const e=window.__AIWORKER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":Rc(e).valid?"valid":"malformed"}const eo=/^[a-z][a-z\d+.-]*:\/\//i,wd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},to=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Sd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return to(e)},bd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_LOCAL_ORIGIN__;return to(e)},Td=()=>Object.keys(Po()).length>0,vd=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},hs=(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))},kd=(e,t)=>{if(!t)return e;const n=new URLSearchParams;hs({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},Ui=(e,t,n)=>{if(eo.test(t)){const s=new URL(t);return hs(s,n),s.toString()}const r=wd(t);if(!e)return kd(r,n);const o=new URL(r,`${e}/`);return hs(o,n),o.toString()},jo=e=>{const t=ef();if(!t)return e;const n=eo.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),eo.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Dc=(e,t)=>{const n=eo.test(e)?new URL(e):new URL(e,vd(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},Ni=(e,t,n)=>{if(!Td())return null;const r=bd();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=tf(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Dc(o.toString(),n)):o.toString()}catch{return null}},Xs=(e={})=>{const t=to(e.apiBaseUrl),n=to(e.realtimeBaseUrl),r=()=>t||Sd(),o=()=>n||r(),s=(a,c)=>Ui(r(),a,c),i=(a,c)=>Ui(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>jo(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=jo(i(a,c));return Ni("sse",l,e)||l},websocket:(a,c)=>{const l=Dc(jo(i(a,c)),e);return Ni("ws",l,e)||l}}};let no=Xs();const Ie=()=>no,Ed=e=>{no=e},Oc=e=>(no=Xs(e),no),ms="aiworker:runtime-endpoint-changed",gs="aiworker:runtime-endpoint-will-change";let vn="",or="";const Uo=(e,t,n)=>{try{e[t]=n}catch{}},Zs=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"}`}},Ad="mobile-disconnected",Pd="url:default",Mc=e=>e===""||e===Pd||e===Ad,_c=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Lc=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},Fc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},vo=()=>vn||_c();let No="",Bi=null,Hi,zi;const $i=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},$=()=>{if(or)return or;const e=$i("__AIWORKER_API_BASE_URL__"),t=$i("__AIWORKER_LOCAL_ORIGIN__");if(Bi===vn&&Hi===e&&zi===t)return No;const n=vo();return No=Fc(n,Lc())?"local":Zs(n),Bi=vn,Hi=e,zi=t,No},Id=(e={})=>{if(vn||or)return;const t=e.apiBaseUrl?.trim()||_c();t&&(vn=t,or=e.runtimeKey?.trim()||(Fc(t,Lc())?"local":Zs(t)))},ro=e=>{const t=e.apiBaseUrl.trim(),n=vo(),r=$(),o=e.runtimeKey?.trim()||Zs(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(gs,{detail:s})),vn=t,or=o,typeof window<"u"){const i=window;Uo(i,"__AIWORKER_API_BASE_URL__",t),Uo(i,"__AIWORKER_CLIENT_TOKEN__",e.clientToken||void 0),Uo(i,"__AIWORKER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Oc({apiBaseUrl:t,realtimeBaseUrl:t}),Jc(e.requestHeaders||null),qc(e.clientToken||null),e.relay?qd(e.relay):Jd(),Io(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ms,{detail:s}))},xd=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(gs,t),()=>window.removeEventListener(gs,t)},jc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(ms,t),()=>window.removeEventListener(ms,t)};let ys=null;const JS=e=>{ys=e},ko=()=>ys||(typeof window>"u"?null:window.__AIWORKER_RUNTIME_APIS__??null),Uc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Rd=(e=Uc())=>!!e,Cd=()=>typeof window>"u"?null:window.__AIWORKER_ELECTRON__??null,xn=()=>typeof window>"u"?null:window.__AIWORKER_DESKTOP__??null,Zt=()=>Cd()?.runtime==="electron",Dd=()=>{if(typeof window>"u")return null;const e=window.__AIWORKER_PLATFORM__;return typeof e=="string"?e:null},Od="right",VS=()=>{if(!Zt())return!1;const e=Dd();return e==="win32"||e==="linux"},YS=e=>e==="left"?"left":Od,QS=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],Te=()=>typeof xn()?.invoke=="function",Rn=()=>Zt()&&Te(),re=async(e,t)=>{const n=xn();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},XS=async()=>{if(!Rn()||!ve())return null;try{const e=await re("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}},ZS=async e=>{if(!Rn()||!ve())return null;try{const t=await re("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}},eb=async()=>{if(!Rn()||!ve())return null;try{const e=await re("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}},tb=async e=>{if(!Rn()||!ve())return null;try{const t=await re("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}},nb=async()=>{if(!Rn()||!ve())return null;try{const e=await re("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}},rb=async e=>{if(!Rn()||!ve())return null;try{const t=await re("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}},Wi=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}}},Bo=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}}},Md=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),jn=e=>{const t=Md(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ve=()=>{if(typeof window>"u"||!qe())return!1;if($()==="local")return!0;const e=typeof window.__AIWORKER_LOCAL_ORIGIN__=="string"?window.__AIWORKER_LOCAL_ORIGIN__:"",t=Bo(e),n=Bo(vo());if(!n&&t&&Cc()?.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&&jn(t.hostname)&&jn(n.hostname)}const r=Bo(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&&jn(t.hostname)&&jn(r.hostname)}const o=Wi(e),s=Wi(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&jn(r.hostname))},qe=()=>typeof window>"u"?!1:Zt(),ob=async()=>{if(!qe())return!1;try{return!!await re("desktop_focus_window")}catch{return!1}},_d=()=>qe()&&Te()&&ve(),sb=async()=>{if(!qe())return!1;try{return await re("desktop_start_window_drag"),!0}catch{return!1}},Me=()=>Rd()?!0:ko()?.runtime?.isVSCode===!0,ib=()=>{const t=ko()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Me()},ab=(e,t=qe())=>e==="web"&&!t,Nc=async()=>{if(typeof window<"u"){const e=window.__AIWORKER_HOME__;if(e&&e.length>0)return e}return null},cb=async e=>{if(_d())try{const t=await xn()?.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"}},Ld=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fd=I({path:w().min(1),outsideFileGrant:w().min(1),expiresAt:C().finite()}),lb=async e=>{if(Te()&&ve())try{const t=await xn()?.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(!Ld(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"}},ub=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Te()||!ve())return{success:!1,error:"Native file access not available"};try{const n=await xn()?.grantFileAccess?.(t),r=Fd.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)}}},db=async e=>({success:!0}),fb=async e=>({success:!0}),pb=async()=>Te()?await re("desktop_check_for_updates"):null,hb=async e=>{if(!Te())return!1;const t=xn();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("aiworker: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 u=l?.downloaded,d=l?.total;typeof u=="number"&&(r=u),typeof d=="number"&&(o=d),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await re("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{}}},mb=async()=>Te()?(await re("desktop_restart"),!0):!1,gb=async()=>{if(!Te())return!1;try{return await re("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},yb=async()=>{if(!Te()||!ve())return null;try{const e=await re("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}},jd=async(e,t)=>{if(!Te()||!ve())return!1;const n=e?.trim();if(!n)return!1;try{return await re("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}},wb=async e=>{if(!Te()||!ve())return!1;const t=e?.trim();if(!t)return!1;try{return await re("desktop_reveal_path",{path:t}),!0}catch{return jd(t)}},Sb=async(e,t)=>{if(!Te()||!ve())return null;const n=e?.trim();if(!n)return null;try{const r=await re("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}},bb=async(e,t,n)=>{if(!Te()||!ve())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await re("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},Tb=async(e,t,n)=>{if(!Te()||!ve())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await re("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}},vb=async(e,t)=>{if(!Te()||!ve())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 re("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}}},dr=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",Ud=()=>{if(typeof window>"u")return!1;const e=window.__AIWORKER_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"))},kb=()=>{if(typeof window>"u"||!dr()||Bc()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Bc=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Me()?"vscode":qe()?"desktop":"web"},Nd="1.23.1",Ar=new Uint8Array(0),Bd=new TextEncoder,Hd=new TextDecoder,je=e=>e instanceof Error?e:new Error(String(e)),Pr=()=>new DOMException("The operation was aborted.","AbortError"),zd=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},$d=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},Ki=0,Ho=1,Gi=2,qi=3,Wd=new Set([Kt.AuthFailed,Kt.DuplicateClient,Kt.LimitExceeded]),Kd={[Kt.AuthFailed]:"relay authentication failed",[Kt.DuplicateClient]:"relay connection replaced by another client",[Kt.LimitExceeded]:"relay connection limit reached"},Ji=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},ei=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Ac,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,u=e.createWireSocket??(x=>zd(new WebSocket(x)));let d=!1,f=null,h={state:"idle"};const m=new Set;let S=null,y=null,k=null,v=0,F=0,O=null,q=[],R=!1;const ye=x=>{if(!(h.state===x.state&&h.lastError===x.lastError)){h=x;for(const z of m)try{z(h)}catch{}}},oe=x=>{const z=q;q=[];for(const D of z)D.reject(x)},Mo=x=>{const z=q;q=[];for(const D of z)D.resolve(x)},Ee=(x,z)=>{x.dead=!0;const D=Array.from(x.streams.values());x.streams.clear();for(const M of D)try{M.fail(z)}catch{}},On=()=>{O!==null&&(clearTimeout(O),O=null)},Mn=()=>{d||O===null||Ji()||(On(),Je(),_n())},Dt=()=>{typeof document<"u"&&document.visibilityState==="visible"&&Mn()},L=()=>{R||typeof window>"u"||(R=!0,window.addEventListener("online",Mn),typeof document<"u"&&document.addEventListener("visibilitychange",Dt))},Je=()=>{!R||typeof window>"u"||(R=!1,window.removeEventListener("online",Mn),typeof document<"u"&&document.removeEventListener("visibilitychange",Dt))},rn=()=>{if(d||O!==null)return;const x=Math.max(0,F-1),z=a*2**Math.min(x,10),D=Ji()?l:c,M=Math.min(D,z);L(),O=setTimeout(()=>{O=null,Je(),_n()},M)},wr=()=>{const x=new URL(e.relayUrl);return x.searchParams.set("v",String(qn)),x.searchParams.set("role","client"),x.searchParams.set("serverId",e.serverId),x.searchParams.set("appId","aiworker"),x.searchParams.set("appVersion",Nd),x.searchParams.set("platform",Bc()),e.grant&&x.searchParams.set("grant",e.grant),x.toString()},_n=async()=>{if(d)return;On(),v+=1;const x=v;ye({state:F>0?"reconnecting":"connecting",lastError:h.lastError});let z;try{z=await qu(e.hostEncPubJwk,{batch:i,flowControl:e.flowControl})}catch(J){if(x!==v||d)return;Mi(x,je(J),!0);return}if(x!==v||d)return;let D;try{D=u(wr())}catch(J){Mi(x,je(J));return}y=D;let M=!1,j=null,W=null,xe=null,pe=null,U=Promise.resolve(),B=null,te=null,rt=!1,ce=!1,le=0,he=0,me=null,ot=null,Q=Date.now();const ht=()=>{me!==null&&(clearTimeout(me),me=null),j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null),xe!==null&&(clearInterval(xe),xe=null),pe!==null&&(clearTimeout(pe),pe=null),ot!==null&&(ot.dispose(),ot=null)};k=ht;function K(J,ne=!1,Y=!1){if(!(M||x!==v)){M=!0,Y&&(f=J),ht(),B&&(S=null,Ee(B,new Error(`relay tunnel reset: ${J.message}`))),oe(J);try{D.close()}catch{}if(y===D&&(y=null),!d){if(F+=1,Y){ye({state:"error",lastError:J.message});return}ye({state:ne?"error":"reconnecting",lastError:J.message}),rn()}}}const Ln=()=>{try{D.send(z.helloText)}catch{}},br=(J,ne,Y)=>{te=J,rt=ne,ce=Y,j!==null&&(clearInterval(j),j=null),W!==null&&(clearTimeout(W),W=null);const se=new Map,Ot=sd(),Fe=Xu();let Mt=Promise.resolve();const mt=Fn=>{Mt=Mt.then(async()=>{if(_t.dead)return;const xu=await J.encryptor.encrypt(Fn);_t.dead||D.send(xu)}).catch(()=>{K(new Error("relay encrypt/send failed"))})},Lo=ne?od({windowMs:s,sendBatch:mt}):null;ot=Lo;const _t={streams:se,assembler:Fe,nextStreamId:()=>Ot.next(),dead:!1,send(Fn){_t.dead||(Lo?Lo.enqueue(Fn):mt(Fn))}};B=_t,S=_t,F=0,Q=Date.now(),ye({state:"connected"}),Mo(_t),xe=setInterval(()=>{Date.now()-Q<r||(_t.send(He(N.Ping,0,Ar)),pe===null&&(pe=setTimeout(()=>{pe=null,K(new Error("relay keepalive timeout"))},o)))},r)},on=()=>{me!==null&&clearTimeout(me),me=null,!(!B||B.dead||le===he)&&(he=le,B.send(He(N.DeliveryAck,0,Ju(le))))},Iu=(J,ne)=>{let Y;try{Y=Vu(ne)}catch(Fe){K(je(Fe));return}if(Y.frameType===N.DeliveryAck){K(new Error("unexpected downstream delivery acknowledgement"));return}if(ce&&Y.streamId!==0&&(le+=ne.length,me===null&&(me=setTimeout(on,10))),Q=Date.now(),pe!==null&&(clearTimeout(pe),pe=null),Y.frameType===N.Ping){J.send(He(N.Pong,Y.streamId,Ar));return}if(Y.frameType===N.Pong)return;let se=Y.payload;if(Y.frameType===N.WsText||Y.frameType===N.WsBinary){let Fe;try{Fe=J.assembler.push(Y)}catch(Mt){K(je(Mt));return}if(Fe===null)return;se=Fe}else if(Y.hasMoreFragments){K(new Error("unexpected fragmented tunnel frame"));return}const Ot=J.streams.get(Y.streamId);Ot&&Ot.handleFrame(Y.frameType,se)};D.onopen=()=>{M||x!==v||(Ln(),j=setInterval(Ln,t))},D.onmessage=J=>{if(M||x!==v)return;const ne=J.data;if(typeof ne=="string"){U=U.then(async()=>{if(M||x!==v)return;const se=await z.handleText(ne);if(se.type==="established"){if(te)return;br(se.channel,se.batch,se.flowControl)}else se.type==="fail"&&K(new Error(`relay handshake failed: ${se.reason}`))}).catch(se=>{K(je(se))});return}const Y=ne instanceof ArrayBuffer?new Uint8Array(ne):ne instanceof Uint8Array?ne:null;Y&&(U=U.then(async()=>{if(M||x!==v)return;const se=B,Ot=te;if(!se||!Ot){K(new Error("encrypted frame before handshake completed"));return}let Fe;try{Fe=await Ot.decryptor.decrypt(Y)}catch(mt){K(je(mt));return}let Mt;try{Mt=rt?ed(Fe):[Fe]}catch(mt){K(je(mt));return}for(const mt of Mt){if(M||x!==v||se.dead)return;Iu(se,mt)}ce&&le-he>=16*1024&&on()}).catch(se=>{K(je(se))}))},D.onclose=J=>{const ne=Wd.has(J.code);K(new Error(Kd[J.code]??`relay socket closed (code ${J.code})`),ne,ne)},D.onerror=()=>{},W=setTimeout(()=>{W=null,K(new Error("relay handshake timeout"),!0)},n);function Mi(J,ne,Y=!1){J!==v||d||(oe(ne),F+=1,ye({state:Y?"error":"reconnecting",lastError:ne.message}),rn())}},Sr=x=>d?Promise.reject(new Error("relay tunnel closed")):x?.aborted?Promise.reject(Pr()):f?Promise.reject(f):S&&!S.dead?Promise.resolve(S):new Promise((z,D)=>{let M=null;const j={resolve(W){M&&x&&x.removeEventListener("abort",M),z(W)},reject(W){M&&x&&x.removeEventListener("abort",M),D(W)}};x&&(M=()=>{q=q.filter(W=>W!==j),D(Pr())},x.addEventListener("abort",M,{once:!0})),q.push(j)}),pt=async(x,z)=>{const D=await pd(x,z),M=D.signal;if(M?.aborted)throw Pr();const j=await Sr(M),W=j.nextStreamId();return await new Promise((xe,pe)=>{let U=!1,B=!1,te=null,rt=null;const ce=()=>{j.streams.delete(W),j.assembler.dropStream(W),rt&&M&&M.removeEventListener("abort",rt)},le=Q=>{if(!B){if(B=!0,ce(),!U){pe(Q);return}try{te?.error(Q)}catch{}}},he=Q=>{j.dead||j.send(He(N.StreamAbort,W,vr({reason:Q})))},me=Q=>xc(new Error(Q));rt=()=>{he("aborted"),le(Pr())},j.streams.set(W,{handleFrame(Q,ht){if(Q===N.HttpResponse){if(U||B)return;let K;try{K=kr(ht,ad)}catch(on){he("malformed response head"),le(me(je(on).message));return}const Ln=K.status===204||K.status===205||K.status===304;let br=null;Ln||(br=new ReadableStream({start(on){te=on},cancel(){B||(B=!0,ce(),he("response body cancelled"))}})),U=!0,xe(new Response(br,{status:K.status,headers:K.headers})),Ln&&(B=!0,ce());return}if(Q===N.HttpBody){if(!U||B)return;try{te?.enqueue(ht)}catch{}return}if(Q===N.StreamEnd){if(B)return;if(!U){le(me("tunnel stream ended before response head"));return}B=!0,ce();try{te?.close()}catch{}return}if(Q===N.StreamAbort){let K="stream aborted by host";try{K=kr(ht,ji).reason}catch{}le(me(K))}},fail(Q){le(me(Q.message))}}),M&&M.addEventListener("abort",rt,{once:!0});const ot={method:D.method,path:D.path,query:D.query,headers:D.headers,hasBody:D.body!==null};j.send(He(N.HttpRequest,W,vr(ot))),(async()=>{try{let Q=!1;if(D.body)for await(const ht of D.body){if(B||j.dead)return;for(const K of Ec(ht))j.send(He(N.HttpBody,W,K)),Q=!0}!B&&!j.dead&&(D.body&&!Q&&j.send(He(N.HttpBody,W,Ar)),j.send(He(N.StreamEnd,W,Ar)))}catch(Q){he("request body failed"),le(me(je(Q).message))}})()})},_o=x=>{const z=x.indexOf("?");return z===-1?{path:x,query:""}:{path:x.slice(0,z),query:x.slice(z+1)}},Au=(x,z)=>{let D=Ki,M=null,j=0,W=!1;const xe={get readyState(){return D},onopen:null,onmessage:null,onerror:null,onclose:null,send(U){if(D!==Ho||!M||M.dead)throw new Error("relay tunnel socket is not open");if(typeof U=="string"){for(const te of Fi(N.WsText,j,Bd.encode(U)))M.send(te);return}const B=U instanceof ArrayBuffer?new Uint8Array(U.slice(0)):(()=>{const te=new Uint8Array(U.byteLength);return te.set(new Uint8Array(U.buffer,U.byteOffset,U.byteLength)),te})();for(const te of Fi(N.WsBinary,j,B))M.send(te)},close(U=1e3,B=""){D===qi||D===Gi||(D===Ho&&M&&!M.dead&&(D=Gi,M.send(He(N.WsClose,j,vr({code:U,reason:B})))),pe(U,B))}},pe=(U,B,te=!1)=>{if(!W){if(W=!0,M&&(M.streams.delete(j),M.assembler.dropStream(j)),D=qi,te)try{xe.onerror?.()}catch{}try{xe.onclose?.({code:U,reason:B})}catch{}}};return(async()=>{let U;try{U=await Sr()}catch(ce){pe(1006,je(ce).message,!0);return}if(W)return;M=U,j=U.nextStreamId(),U.streams.set(j,{handleFrame(ce,le){if(ce===N.WsOpened){if(D===Ki){D=Ho;try{xe.onopen?.()}catch{}}return}if(ce===N.WsText){try{xe.onmessage?.({data:Hd.decode(le)})}catch{}return}if(ce===N.WsBinary){const he=new ArrayBuffer(le.byteLength);new Uint8Array(he).set(le);try{xe.onmessage?.({data:he})}catch{}return}if(ce===N.WsClose){let he=1e3,me="";try{const ot=kr(le,cd);he=ot.code,me=ot.reason}catch{}pe(he,me);return}if(ce===N.StreamAbort){let he="stream aborted";try{he=kr(le,ji).reason}catch{}pe(1006,he,!0)}},fail(ce){pe(1012,ce.message,!0)}});const{path:B,query:te}=_o(x),rt=z&&z.length>0?{path:B,query:te,protocols:z}:{path:B,query:te};U.send(He(N.WsOpen,j,vr(rt)))})(),xe},Pu=()=>{if(d)return;d=!0,v+=1,On(),Je(),k?.(),k=null;const x=S;S=null;const z=new Error("relay tunnel closed");x&&Ee(x,z),oe(z);try{y?.close()}catch{}y=null,ye({state:"idle"})};return _n(),{fetch:pt,openWebSocket:Au,getStatus:()=>h,subscribeStatus(x){return m.add(x),()=>{m.delete(x)}},close:Pu}};let De=null,dt=null;const Gd=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Eo=()=>De,Eb=()=>!De||!dt?null:{relayUrl:dt.relayUrl,serverId:dt.serverId,hostEncPubJwk:{...dt.hostEncPubJwk}},Ab=()=>De!==null,qd=e=>(De&&dt&&Gd(dt,e)||(De?.close(),dt=e,De=ei(e)),De),Pb=(e,t)=>{De!==t&&(De?.close(),dt=e,De=t)},Jd=()=>{De?.close(),De=null,dt=null};let Hc=()=>null,zc="",oo={},Vt="",sr=0,Ht=null,Sn="",ir=0,Yt="",zt=null,kt="",$r=0,Wr=0;const ti=1e4,Vd=e=>e.toLowerCase()==="authorization",$c=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!Vd(o)&&(t[o]=s)}return t},Yd=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},Ao=e=>typeof e!="string"?"":e.trim(),Qd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_CLIENT_TOKEN__;return Ao(e)},Xd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return typeof e=="string"?e.trim():""},Wc=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():Xd();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},ni=e=>{try{return new URL(e).origin}catch{return""}},Kc=()=>{Sn="",ir=0,Yt="",zt=null,kt="",$r+=1},fr=()=>{Vt="",sr=0,Kc()},Gc=()=>{Wr+=1,Ht=null,fr(),ri()},qc=e=>{const t=Ao(e);zc=t,Gc(),Hc=()=>t?{type:"bearer",token:t}:null},Jc=e=>{const t=$c(e);Yd(oo,t)||(oo=t,Gc())},Po=()=>{if(Object.keys(oo).length>0)return oo;if(typeof window>"u")return{};const e=window.__AIWORKER_RUNTIME_HEADERS__;return e&&typeof e=="object"?$c(e):{}},Vc=()=>zc||Qd(),Zd=(e,t)=>{const n=Ao(e);if(!n||typeof t!="number"||!Number.isFinite(t)){fr();return}const r=Vt;Vt=n,sr=t,r&&r!==n&&of()},Yc=()=>!Vt||sr<=Date.now()+ti?(fr(),""):Vt,Qc=e=>{const t=ni(e);return!t||Yt!==t?"":!Sn||ir<=Date.now()+ti?(Sn="",ir=0,Yt="",""):Sn},ef=()=>{const e=Yc();return!e&&(Vc()||typeof window<"u")&&Io().catch(()=>{}),e},tf=e=>{const t=e?Qc(e):"";return!t&&e&&typeof window<"u"&&el(e).catch(()=>{}),t},Xc=async()=>{const e=await Hc(),t=e?.type==="bearer"?Ao(e.token):Vc();return t?{type:"bearer",token:t}:null},Zc=e=>{if(Ht)return Ht;const t=Wr,r=(async()=>{const o=await Xc(),s=new Headers;for(const[d,f]of Object.entries(Po()))s.set(d,f);o?.type==="bearer"&&s.set("Authorization",`Bearer ${o.token}`);const i=Eo(),a=i?await i.fetch("/auth/url-token",{method:"POST",headers:s}):await fetch(Wc(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===Wr&&fr(),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():"",u=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==Wr)throw new Error("Runtime URL auth token response is stale");if(Zd(l,u),!Vt)throw new Error("Runtime URL auth token response was invalid");return Vt})().finally(()=>{Ht===r&&(Ht=null)});return Ht=r,Ht},nf=e=>{const t=ni(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(zt&&kt===t)return zt;const n=$r,o=(async()=>{const s=await fetch(Wc(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===$r&&t===kt&&(Sn="",ir=0,Yt=""),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!==$r||t!==kt)throw new Error("Local runtime URL auth token response is stale");return Sn=a,ir=c,Yt=t,a})().finally(()=>{zt===o&&(zt=null,kt="")});return zt=o,kt=t,zt},Io=async e=>{const t=Yc();return t||Zc(e)},el=async e=>{const t=ni(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Qc(t);return n||((Yt&&Yt!==t||kt&&kt!==t)&&Kc(),nf(t))};let mn=0,Vn=null,tl=null;const ws=new Set,rf=5e3,of=()=>{for(const e of ws)try{e()}catch{}},nl=()=>{Vn!==null&&(clearTimeout(Vn),Vn=null)},ri=()=>{if(nl(),mn<=0||typeof window>"u")return;const e=sr-ti-rf,t=sr>0?Math.max(0,e-Date.now()):0;Vn=setTimeout(()=>{Vn=null,!(mn<=0)&&Zc(tl).catch(()=>{}).finally(()=>{ri()})},t)},Ib=e=>{typeof e=="string"&&e.trim()&&(tl=e.trim()),mn+=1,ri();let t=!1;return()=>{t||(t=!0,mn=Math.max(0,mn-1),mn===0&&nl())}},xb=e=>(ws.add(e),()=>{ws.delete(e)}),sf=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(Po()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await Xc();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},so=ft(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),af=15e3,cf=5*6e4;let Ss=0,zo=!1;const lf=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),uf=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!lf(t)},rl=async()=>{if(!zo){zo=!0;try{const{runtimeFetch:e}=await Ys(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>vf);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){so.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=so.getState();n==="expired"&&r()}}catch{}finally{zo=!1}}},df=(e,t)=>{if(t!==401||so.getState().state==="expired"||!uf(e))return;const n=Date.now();n-Ss<af||(Ss=n,rl())};let Vi=!1;const Rb=()=>{if(Vi)return;Vi=!0;let e=Date.now();const t=()=>{if(so.getState().state!=="ok")return;const n=Date.now();n-e<cf||(e=n,Ss=n,rl())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},Qt=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",ff=()=>typeof window>"u"?"":window.location.origin||"",oi=e=>{if(typeof window>"u")return!1;const t=ff();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}},si=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),pf=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Tt=(e,t)=>{try{pf(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","aiworker")}catch{}return t},ii=(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))},Kr=e=>{try{const t=Ie().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:Qt(e.pathname)}catch{return!1}},$o=e=>{if(Qt(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return oi(t)&&Qt(t.pathname)}catch{return!1}},hf=(e,t)=>{try{const n=new URL(e);if(!oi(n))return e;const r=xt(`${n.pathname}${n.search}`,t);return!si(r)&&(n.protocol==="http:"||n.protocol==="https:")?(ii(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},xt=(e,t)=>e==="/health"?Ie().health(t):e.startsWith("/auth/")||e==="/auth"?Ie().auth(e,t):Qt(e)?Ie().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?hf(e,t):e,mf=e=>{const t=e instanceof Request?e.url:e.toString();if(!si(t))return Qt(t);try{return Kr(new URL(t))}catch{return!1}},ol=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},gf=(e,t)=>!ol(t),bs=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)gf(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},st=async(e,t,n=!0)=>{const r=new Headers(bs(e)??e);return t&&new Headers(bs(t)??t).forEach((o,s)=>r.set(s,o)),n?sf(r):r},yf=(e,t)=>{if(!t)return e;const n=new URL(e,Qs);return ii(n,t),`${n.pathname}${n.search}`},sl=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!si(n))return Qt(n)?yf(n,t):null;try{const r=new URL(n);return!oi(r)||!Qt(r.pathname)?null:(ii(r,t),`${r.pathname}${r.search}`)}catch{return null}},wf=async(e,t,n)=>{const r=Eo();if(!r)return null;const o=sl(e,n);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await st(s,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(o,{...t,headers:i})},il="half",Ts=(e,t={})=>{const n={...t,duplex:il};return new Request(e,n)},al=(e,t)=>{const n={method:e.method,headers:e.headers,body:e.body,signal:e.signal,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,duplex:il};return new Request(t,n)},Sf=(e,t)=>{if(typeof e=="string")return xt(e,t);if(e instanceof URL)return xt(e.toString(),t);const n=xt(e.url,t);return n===e.url?e:al(e,n)},bf=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ir=new Map,Tf=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!bf.test(t)?null:`GET ${t}`,g=async(e,t={})=>{const{query:n,...r}=t,o=Eo(),s=o?sl(e,n):null;let i,a,c;if(o&&s!==null){const m=e instanceof Request?e.headers:void 0,S=await st(m,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:S}):()=>o.fetch(s,{...r,headers:S}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const m=Sf(e,n),S=m instanceof Request?m.headers:void 0,y=await st(S,r.headers,mf(m)),k=m instanceof Request?m.url:m instanceof URL?m.toString():String(m);Tt(k,y),i=m instanceof Request?()=>fetch(Ts(m,{...r,headers:y})):()=>fetch(m,{...r,headers:y}),a=k,c=String(r.method??(m instanceof Request?m.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(m=>(df(a,m.status),m));const u=r.signal!=null||e instanceof Request,d=Tf(c,a,u);if(!d)return i();const f=Ir.get(d);if(f)return f.then(m=>m.clone());const h=i();return Ir.set(d,h),h.then(()=>Ir.delete(d),()=>Ir.delete(d)),h.then(m=>m.clone())};let Yi=!1;const cl=()=>{if(Yi||typeof window>"u")return;Yi=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await wf(t,n??{});if(r)return r;if(typeof t=="string"){if(!$o(t)){try{const i=new URL(t);if(Kr(i)){const a=await st(void 0,n?.headers);return Tt(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await st(void 0,n?.headers),s=xt(t);return Tt(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!$o(o)){if(Kr(t)){const a=await st(void 0,n?.headers);return Tt(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await st(void 0,n?.headers),i=xt(o);return Tt(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!$o(t.url)){try{const a=new URL(t.url);if(Kr(a)){const c=await st(t.headers,n?.headers);return Tt(a.toString(),c),e(Ts(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await st(t.headers,n?.headers),s=xt(t.url);Tt(s,o);const i=s===t.url?t:al(t,s);return e(Ts(i,{...n,headers:o}))}return e(t,n)}},vf=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Tt,buildRuntimeFetchUrl:xt,installRuntimeFetchBridge:cl,isLatin1Safe:ol,runtimeFetch:g,sanitizeHeadersForBrowser:bs},Symbol.toStringTag,{value:"Module"})),bn=16384,io=globalThis,kf=e=>{if(io.Buffer)return io.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,"")},ll=e=>{try{if(io.Buffer)return io.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}},Ef=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}},Af=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}},Qi=e=>typeof e=="string"&&e.length>0,Pf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!Qi(t.x)||!Qi(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},If=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,xf=e=>{if(!e||typeof e!="object")return null;const t=e,n=If(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Ef(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=Af(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=Pf(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},ai=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(xf).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}},Cb=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}),Db=e=>{const t=ai(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",kf(JSON.stringify(t))),`aiworker://connect?${n.toString()}`},Rf=e=>{const t=e.trim();if(!t||t.length>bn)return null;try{const n=new URL(t);if(n.protocol!=="aiworker:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>bn)return null;const o=ll(r);return!o||o.length>bn?null:ai(JSON.parse(o))}catch{return null}},Ob=e=>{const t=e.trim();if(!t||t.length>bn)return null;const n=t.indexOf("?");if(n===-1||!/^aiworker:\/\/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>bn)return null;const s=ll(o);if(!s||s.length>bn)return null;try{return ai(JSON.parse(s))}catch{return null}},kn=e=>typeof e=="object"&&e!==null,Cf=e=>e.trim().toLowerCase()==="authorization",Df=e=>{if(!kn(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)||Cf(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},Of=e=>`relay://${e}`,Mf=e=>{if(!kn(e))return null;const t=we(e,"relayUrl")||we(e,"relay_url"),n=we(e,"serverId")||we(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!kn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},_f=()=>{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"},Mb=async(e,t)=>{const n=Rf(e);if(!n)throw new Error("invalid-connect-link");const r=await Nf().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"AiWorker Desktop",clientKind:"desktop",deviceName:"AiWorker Desktop",devicePlatform:_f(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=async y=>{if(!y.ok)return null;const k=await y.json().catch(()=>null);return(typeof k?.clientToken=="string"?k.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((y,k)=>(y.type==="relay"?1:0)-(k.type==="relay"?1:0));for(const y of a){if(y.type==="relay"){const v=ei({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const F=await s(await v.fetch("/api/client-auth/pairing/redeem",o));if(F){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:F};break}}catch{}finally{v.close()}continue}const k=be(y.url);if(k)try{const v=await s(await fetch(`${k}/api/client-auth/pairing/redeem`,o));if(v){i={directUrl:k,token:v};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),u=n.candidates.filter(y=>y.type!=="relay").map(y=>be(y.url)).find(y=>!!y),d=i.directUrl||u,f=d||(l?Of(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const h=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&be(y.apiUrl||y.url)===f),m=h?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),S={...h||{},id:m,label:n.label||h?.label||ul(f),url:f,apiUrl:d,clientToken:i.token,...l?{relay:l}:{}};return{hostId:m,hosts:h?t.map(y=>y.id===m?S:y):[S,...t]}},Lf=/^(t|.*(?:token|auth|secret|api).*)$/i,be=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}},_b=e=>{const t=be(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"}},ul=e=>{const t=be(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)Lf.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},xr=(e,t)=>{const n=be(e),r=be(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}},we=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},Xi=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Ff=e=>{if(!kn(e))return null;const t=we(e,"id"),n=we(e,"label"),r=we(e,"url"),o=we(e,"apiUrl")||we(e,"api_url"),s=we(e,"clientToken")||we(e,"client_token"),i=Df(e.requestHeaders),a=Mf(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}:{}}},Yn=e=>be(e.apiUrl||e.url)||e.apiUrl||e.url,en=()=>Te()?(e,t)=>re(e,t):null,ci=async()=>{const e=en();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!kn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Ff).filter(a=>!!a):[],o=we(t,"defaultHostId")||we(t,"default_host_id")||we(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=we(t,"localOrigin")||we(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},jf=async e=>{const t=en();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})},Uf=async()=>{const e=en();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Nf=async()=>{const e=en();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Bf=8e3,Hf=15e3,zf=400,$f=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)}},Zi=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await $f(e,t,Math.min(Bf,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,zf))}}},Wf=async(e,t)=>{const n=ei({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+Hf;let s=!1;try{if(!(await Zi(n,"/health",o)).ok)return{status:"unreachable",latencyMs:0};const a=new Headers({Accept:"application/json"});for(const[u,d]of Object.entries(t?.requestHeaders||{}))u.toLowerCase()!=="authorization"&&a.set(u,d);const c=t?.clientToken?.trim();c&&a.set("Authorization",`Bearer ${c}`);const l=await Zi(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()}},li=async(e,t)=>{const n=en();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(!kn(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=Xi(r,"latencyMs")??Xi(r,"latency_ms")??0;return{status:s,latencyMs:i}},Lb=async(e,t)=>{const n=en();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Fb=async e=>{const t=en();t&&await t("desktop_new_window_for_host",{hostId:e})},It="local",Kf=e=>({id:It,label:"Local",url:e||dl()}),dl=()=>typeof window>"u"?"":window.__AIWORKER_LOCAL_ORIGIN__||window.location.origin,Gf=e=>e.id===It?"local":`host:${e.id}`,jb=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(u=>u.id===It)?.url||dl(),r=vo(),o=be(n)||n,s=be(t)||t,i=$(),a=e.find(u=>u.relay&&Gf(u)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&xr(r,n))return{id:It,label:"Local",url:o};const c=e.find(u=>r?xr(r,Yn(u)):!1);if(c)return{id:c.id,label:c.label,url:be(Yn(c))||Yn(c)};if(t&&xr(t,n))return{id:It,label:"Local",url:o};const l=e.find(u=>t?xr(t,u.url):!1);return l?{id:l.id,label:l.label,url:be(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:It,label:"Local",url:o}:{id:"custom",label:ul(s||"Instance"),url:s}},ao=new Map;let fl=0;const co=new Map;let vs=0,pl={byHostId:{},isProbing:!1};const ks=new Set,lo=()=>{pl={byHostId:Object.fromEntries(ao),isProbing:vs>0};for(const e of ks)try{e()}catch{}},Ub=e=>(ks.add(e),()=>{ks.delete(e)}),Nb=()=>pl,hl=(e,t)=>{ao.set(e,t),lo()},Bb=(e,t)=>{co.set(e,++fl),hl(e,t)},qf=e=>{const t=new Set([It,...e]);let n=!1;for(const r of Array.from(ao.keys()))t.has(r)||(ao.delete(r),co.delete(r),n=!0);n&&lo()},Jf=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Vf=async()=>Zt()?Uf().catch(()=>""):"",Yf=async(e,t)=>{const n=e.id===It?t:e.clientToken||"",r=async()=>{const i=await Wf(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=be(Zt()?Yn(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await li(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Jf(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},Qf=async e=>{if(!qe())return;const t=++fl;for(const n of e)co.set(n.id,t);vs+=1,lo();try{const n=await Vf();await Promise.all(e.map(async r=>{const o=await Yf(r,n);co.get(r.id)===t&&hl(r.id,o)}))}finally{vs-=1,lo()}};let ea=!1;const Xf=async()=>{if(ea||!qe())return;ea=!0;const e=await ci().catch(()=>null);e&&(qf(e.hosts.map(t=>t.id)),await Qf([Kf(e.localOrigin),...e.hosts]))},Zf=5e3,ep=1500;let Wo=!1;const tp=async e=>{if(!Zt()||Wo)return;const t=`host:${e}`;if($()===t){Wo=!0;try{const n=await ci().catch(()=>null),r=n?.hosts.find(d=>d.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?be(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await g("/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 d of a){if(!d||typeof d!="object")continue;const f=d;if(f.type!=="lan"||typeof f.url!="string")continue;const h=be(f.url);h&&!c.includes(h)&&c.push(h)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await jf({hosts:n.hosts.map(d=>d.id===e?{...d,apiUrl:l}:d),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const u=await li(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(u.status==="unreachable"||u.status==="wrong-service"||u.status==="incompatible"||$()!==t)return;ro({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{Wo=!1}}},np=e=>{typeof window>"u"||window.setTimeout(()=>{tp(e).catch(()=>{})},Zf)},rp=async e=>{if(!Zt())return;const t=await ci().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(d=>d.id===n);if(!r?.relay)return;const o=`host:${r.id}`;if($()===o)return;const s=d=>{ro({apiBaseUrl:d,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{ro({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),np(r.id)},a=r.apiUrl?be(Yn(r)):null;if(!a){i();return}const c=d=>d.status!=="unreachable"&&d.status!=="wrong-service"&&d.status!=="incompatible",l=li(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),u=await Promise.race([l,new Promise(d=>setTimeout(()=>d(null),ep))]);if(u){if(c(u)){s(a);return}i();return}i(),l.then(d=>{c(d)&&$()===o&&s(a)})};class Gt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const Hb=e=>e instanceof Gt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),uo=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},ta=500,ml=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("AIWORKER_STARTUP_TRACE")==="1"}catch{return!1}},zb=()=>ml(),ze=(e,t)=>{if(!ml())return;const n=typeof performance<"u"?performance.now():Date.now();window.__AIWORKER_STARTUP_TRACE_START__??=n,window.__AIWORKER_STARTUP_TRACE__??=[],window.__AIWORKER_STARTUP_TRACE__.push({t:Math.round(n-window.__AIWORKER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__AIWORKER_STARTUP_TRACE__.length>ta&&window.__AIWORKER_STARTUP_TRACE__.splice(0,window.__AIWORKER_STARTUP_TRACE__.length-ta)},op=()=>{const e=typeof window<"u"?window.__AIWORKER_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.__AIWORKER_STARTUP_TRACE_SUMMARY__=op);const $b=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();ze(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return ze(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw ze(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},sp=3,ip=3e4,ap=32e3,cp=3600*1e3,lp=600*1e3,up=200,dp=new Set([429,502,503,504]),at=new Map,ui=e=>JSON.stringify([$(),e]);function fp(){const e=Date.now();for(const[t,n]of at){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>cp&&at.delete(t)}}typeof setInterval<"u"&&setInterval(fp,lp).unref?.();function pp(e){const t=ui(e);let n=at.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:ip},at.set(t,n);at.size>up;){const r=at.keys().next().value;if(!r)break;at.delete(r)}return n}function hp(e){e&&at.delete(ui(e))}function na(e,t){if(!e)return;const n=pp(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),mp(t)&&n.consecutiveErrors>=sp&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function mp(e){return e!==void 0&&dp.has(e)}function gp(e){const t=at.get(ui(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,ap*4),!1):!0:!1}function yp(e){if(!(!e||!gp(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const ra="/api",wp=1e4,Sp=4e3;function gn(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 bp=I({reason:w().optional(),isDirectory:Xt().optional()});function Ue(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${gn(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 sn(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${gn(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const Tp=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,oa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",vp=14;let sa=0,Ko=0;const kp=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+=oa[t[r]%oa.length];return n},ia=e=>{const t=Date.now();t!==sa&&(sa=t,Ko=0),Ko+=1;const n=BigInt(t)*BigInt(4096)+BigInt(Ko),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}${kp(vp)}`},aa=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(Tp.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}},ca=()=>{try{return Ie().api("/api")}catch{return null}},gl=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)}},Ep=3e4,Ap=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),Go=e=>{const t=e.requestTimeoutMs??Ep;return Cu({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(Ap(n)||o==="POST")return g(n,r);const s=gl(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 u=new AbortController,d=()=>u.abort(i.reason),f=()=>u.abort(s.signal.reason);i.aborted?d():s.signal.aborted?f():(i.addEventListener("abort",d,{once:!0}),s.signal.addEventListener("abort",f,{once:!0}),l=()=>{i.removeEventListener("abort",d),s.signal.removeEventListener("abort",f)}),c=u.signal}else c=s.signal;try{return await g(n,{...r,signal:c})}catch(u){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):u}finally{l?.(),s.cleanup()}}})},an=e=>e.replace(/\\/g,"/"),la=400,ua=()=>{const e=ko();return e&&e.runtime?.isDesktop&&e.files?e.files:null},da=w().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),Pp=I({home:da,chatsRoot:da.optional()});class Ip{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=ra){const r=ca()||t;this.baseUrl=aa(r),this.client=Go({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==$())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=ca(),n=aa(t||ra);this.baseUrl=n,this.client=Go({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=Go({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&&ze("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 g("/api/fs/directory-stat",{query:{path:n}}),o=bp.safeParse(await r.json().catch(()=>null)).data;if(r.ok&&o?.isDirectory===!0)return"available";const s=uo(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 Ue(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 Ue(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 sn(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 Ue(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 Ue(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 Ys(async()=>{const{default:d}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:d}},__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 d=0;d<s.length;d++)i[d]=s.charCodeAt(d);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((d,f)=>{const h=new FileReader;h.onload=()=>d(h.result),h.onerror=f,h.readAsDataURL(c)});let u=t.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,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??ia("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 u=await this.toNormalizedFilePartInput(l);r.push(u)}if(t.additionalParts&&t.additionalParts.length>0)for(const l of t.additionalParts){if(l.text&&l.text.trim()){const u={type:"text",text:l.text};l.synthetic&&(u.synthetic=!0),l.metadata&&(u.metadata=l.metadata),r.push(u)}if(l.files&&l.files.length>0)for(const u of l.files){const d=await this.toNormalizedFilePartInput(u);r.push(d)}}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}),yp(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 u=l.response?.status;if(!u){const d=new Error(`Message send transport failure: ${gn(l.error)}`);throw hd(l.error)?xc(d):d}s=new Response(JSON.stringify(l.error),{status:u})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw na(t.providerID),l}if(s.ok)return hp(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,na(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??ia("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 sn(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 Ue(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 Ue(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 sn(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Ue(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 Ue(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 g("/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 sn(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():"",u=await this.client.permission.list(l?{directory:l}:void 0);if(u.error)throw new Error(`permission.list failed: ${gn(u.error)}`);return u.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 u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),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 sn(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return sn(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",u=await this.client.question.list(l?{directory:l}:void 0);if(u.error)throw new Error(`question.list failed: ${gn(u.error)}`);return u.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 u=l.id;typeof u!="string"||u.length===0||a.has(u)||(a.add(u),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 ze("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return ze("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{ze("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),u=await(n?this.getScopedApiClient(n):this.client).config.get();if(!u.data)throw new Error("Failed to get config");const d=typeof performance<"u"?performance.now():Date.now();return ze("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(d-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:u.data,expiresAt:Date.now()+wp}),u.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=Ue(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 Ue(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.get(r)===s&&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 g("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${gn(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.get(r)===s&&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(Ue(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`;ze("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=gl(Sp),o=await g(n,{signal:r.signal}).finally(r.cleanup);if(ze("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return ze("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=ua();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 g(`${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 g(`${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 g(`${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"?an(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 u=ua();try{if(u){const y=await u.listDirectory(t||"",n);if(!y||!Array.isArray(y.entries))throw new Gt("Directory listing returned an invalid response",{reason:"invalid-response"});const k=y.entries.map(v=>({name:v.name,path:an(v.path),isDirectory:!!v.isDirectory,isFile:!v.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:k,expiresAt:Date.now()+la}),k}const d=new URLSearchParams;t&&t.trim().length>0&&d.set("path",t),n?.respectGitignore&&d.set("respectGitignore","true");const f=d.toString(),h=await g(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!h.ok){const y=await h.json().catch(()=>({})),k=typeof y.error=="string"?y.error:"Failed to list directory";throw new Gt(k,{reason:uo(y.reason),status:h.status})}const m=await h.json();if(!m||!Array.isArray(m.entries))throw new Gt("Directory listing returned an invalid response",{reason:"invalid-response"});const S=m.entries;return this.listDirectoryCache.set(o,{entries:S,expiresAt:Date.now()+la}),S}catch(d){throw console.error("Failed to list directory contents:",d),d}})().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?an(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=an(c),u=l.split("/").filter(Boolean).pop()||l,d=an(o?`${o}/${l}`:l);return{name:u,path:d,relativePath:l,extension:u.includes(".")?u.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=$();if(!t||t==="local"){const n=await Nc();if(n)return n}try{const n=await g(`${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 g(`${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 Pp.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 g(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 tt=new Ip;let qo=null,Jo=null,Vo=null;const fa=new Set;let pa=!1;const yl=e=>{if(fa.add(e),pa||typeof window>"u")return;pa=!0;const t=()=>{for(const n of fa)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{}},xp=(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[u,d]of c)try{n.setItem(u,JSON.stringify(d,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(u)&&!o.has(u)&&r.set(u,d)}for(const u of l)try{n.removeItem(u)}catch(d){console.error("Failed to remove deferred storage value",d),r.has(u)||o.add(u)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return yl(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(o.has(c))return null;const l=d=>{if(d===null)return null;try{return JSON.parse(d,t?.reviver)}catch{try{n.removeItem(c)}catch{}return null}},u=n.getItem(c);return u instanceof Promise?u.then(l):l(u)},setItem:(c,l)=>{r.set(c,l),o.delete(c),a()},removeItem:c=>{r.delete(c),o.add(c),a()}}},di=e=>xp(()=>bl(),e),Rp=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(u){console.error("Failed to persist deferred storage value",u),!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 yl(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}}},wl=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},fi=()=>{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}}},Sl=e=>{const t=fi(),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,u)=>{try{e.setItem(l,u),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,u),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 u=0;u<e.length;u+=1){const d=e.key(u);d&&l.push(d)}}catch{}try{e.clear(),r.clear()}catch{for(const u of l)r.add(u)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let u=0;u<e.length;u+=1){const d=e.key(u);d&&!r.has(d)&&!n.has(d)&&l.add(d)}}catch{}for(const u of n)l.add(u);return[...l]};return{getItem:o,setItem:s,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},Cp=()=>{const e=wl("localStorage");return e?Sl(e):fi()},bl=()=>(qo||(qo=Cp()),qo),pr=()=>(Vo||(Vo=Rp(bl())),Vo),Dp=()=>{const e=wl("sessionStorage");return e?Sl(e):fi()},Op=()=>(Jo||(Jo=Dp()),Jo),Mp={markdown:"0.875rem",code:"0.75rem",uiHeader:"0.875rem",uiLabel:"0.8125rem",meta:"0.8125rem",micro:"0.8125rem",settingsPageTitle:"1.0625rem"},Wb={markdown:"0.8438rem",code:"0.8125rem",uiHeader:"0.8438rem",uiLabel:"0.7813rem",meta:"0.7813rem",micro:"0.75rem",settingsPageTitle:"1rem"};function ha(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Rr={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)"}}},Yo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Rr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Yo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Rr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Yo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Rr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Yo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Rr.tool.inline})},_p=[{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'}],Lp=[{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'}],Tl=e=>Object.fromEntries(e.map(t=>[t.id,t])),Fp=Tl(_p),jp=Tl(Lp),Up="system",Np="system-mono",Bp=e=>typeof e=="string"&&e in Fp,Hp=e=>typeof e=="string"&&e in jp,Es="aiworker.mobileKeyboardMode",zp='meta[name="viewport"]',ma="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Kb=()=>!0;function xo(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const $p=e=>xo(e)==="resize-content"?`${ma}, interactive-widget=resizes-content`:ma,Wp=()=>{if(typeof window>"u")return"resize-content";try{return xo(localStorage.getItem(Es))}catch{return"resize-content"}},vl=e=>{const t=xo(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Es):localStorage.setItem(Es,t)}catch{}return t},Gb=e=>{const t=vl(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(zp);if(n instanceof HTMLMetaElement){const r=$p(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},tn=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},Kp=e=>tn(e)??"",Qo=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Gp=new Set(["starting","running","stopping"]),qp=e=>!!e?.tabs.some(t=>yn(t.purpose)&&t.lifecycle!=="exited"),As=512*1024,Jp=new TextEncoder,Vp=new TextDecoder,Xo=e=>{const t=Jp.encode(e);if(t.byteLength<=As)return{text:e,byteLength:t.byteLength};let n=t.byteLength-As;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Vp.decode(r),byteLength:r.byteLength}},Ve=(e,t)=>`${e}\0${t}`,cn=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Yp="terminal-store";let ga=!1,ya=0;const Qp=I({type:H("project-action"),actionId:w()}),zn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ya+=1,`tab-${Date.now().toString(36)}-${ya.toString(36)}`),Zo=e=>typeof e=="object"&&e!==null,yn=e=>e.type==="project-action",Cr=(e,t)=>yn(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Xp=()=>zn().replace(/^tab-/,"exec-"),wa=e=>e==="running"?"running":"exited",Zp=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),eh=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()]},es={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},th=e=>e.trim()||"Action",nh=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},X=Kp,fo=(e,t)=>`${e}\0${t}`,Un=(e,t,n,r)=>{e.set(fo(t,n),r)},Sa=(e,t,n,r)=>{if(!r)return!1;const o=fo(t,n),s=e.actionMutationRevisions.get(o)??0,i=r.get(o)??0;return s>i},rh=/^Terminal(?: (\d+))?$/,ba=e=>{let t=0;for(const n of e){const r=rh.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}`},qb=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&Gp.has(e.lifecycle),oh=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),Dr=(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}),ts=e=>({tabs:[e],activeTabId:e.id}),Ae=(e,t)=>e.tabs.findIndex(n=>n.id===t);let ns=null,rs=null;const sh=e=>{if(rs&&ns?.sessions===e.sessions&&ns.nextTabId===e.nextTabId)return rs;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 ns={sessions:e.sessions,nextTabId:e.nextTabId},rs=t,t},ih=()=>{const e=Ru(()=>Op());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))}},Gr=ft()(In(ur((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=X(n);r&&e(o=>{if(o.sessions.has(r))return o;const s=new Map(o.sessions),i=zn(),a=Dr(i,"Terminal");return s.set(r,ts(a)),{sessions:s,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=X(n);return t().sessions.get(r)},getActiveTab:n=>{const r=X(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(Ve(X(n),r))??Qo,matchesActionExecution:(n,r,o)=>{const s=t().sessions.get(X(n))?.tabs.find(i=>i.id===r);return!!(s&&yn(s.purpose)&&s.purpose.executionId===o)},captureStartedActionMutationRevisions:n=>{const r=X(n),o=fo(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=X(n);if(!r)return"tab-invalid";const o=zn();return e(s=>{const i=new Map(s.sessions),a=i.get(r),c=s.nextTabId+1,l=ba(a?.tabs??[]),u=Dr(o,l);return a?i.set(r,{...a,tabs:[...a.tabs,u]}):i.set(r,ts(u)),{sessions:i,nextTabId:c}}),o},reconcileServerSessions:(n,r,o)=>{const s=X(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,u=!1,d=null;const f=new Set,h=new Set,m=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(Ve(s,c[0].id))?c[0]:null;m&&r.length>0&&(c.length=0);for(const R of eh(r)){let ye=c.findIndex(L=>L.terminalSessionId===R.sessionId||L.id===R.sessionId);const oe=R.purpose,Mo=oe?.type==="project-action"&&Sa(i,s,oe.actionId,o?.startedActionMutationRevisions);if(oe?.type==="project-action"){f.add(oe.actionId);const L=c.findIndex(Je=>yn(Je.purpose)&&Je.purpose.actionId===oe.actionId);if(Mo){L>=0&&h.add(c[L].id);continue}ye<0&&(ye=L)}const Ee=oe?.type==="project-action"?Zp(oe,R.status):{type:"terminal"};if(ye>=0){const L=c[ye];let Je=L.purpose.type==="project-action"||oe?.type==="project-action"?wa(R.status):R.status;L.lifecycle==="stopping"&&R.status==="running"&&L.purpose.type==="project-action"&&Ee.type==="project-action"&&L.purpose.executionId===Ee.executionId&&(Je="stopping");const rn=R.createdAt??L.createdAt,wr=oe?.type==="project-action"&&(L.terminalSessionId!==R.sessionId||Ee.type==="project-action"&&Ee.executionId!==null&&(L.purpose.type!=="project-action"||L.purpose.executionId!==Ee.executionId));if(wr){const pt=Ve(s,L.id);l=cn(l,_o=>_o===pt)??l}const _n=oe?.type==="project-action"&&R.status==="running"&&(L.terminalSessionId!==R.sessionId||L.lifecycle!=="running"),Sr=L.purpose.type!==Ee.type||L.purpose.type==="project-action"&&Ee.type==="project-action"&&(L.purpose.actionId!==Ee.actionId||L.purpose.executionId!==Ee.executionId);if((L.terminalSessionId!==R.sessionId||L.lifecycle!==Je||L.isConnecting!==!1||L.createdAt!==rn||Sr)&&(c[ye]={...L,terminalSessionId:R.sessionId,lifecycle:Je,purpose:Ee,isConnecting:!1,createdAt:rn},wr&&Object.assign(c[ye],es),u=!0),_n){const pt={tabId:L.id,createdAt:rn,index:ye};(!d||pt.createdAt>d.createdAt||pt.createdAt===d.createdAt&&pt.index>d.index)&&(d=pt)}h.add(L.id);continue}const On=oe?.type==="project-action"?th(oe.actionId):m&&c.length===0?m.label:ba(c),Mn=oe?.type==="project-action"?"play":null,Dt={...Dr(R.sessionId,On),terminalSessionId:R.sessionId,lifecycle:oe?.type==="project-action"?wa(R.status):R.status,purpose:Ee,iconKey:Mn,createdAt:R.createdAt??Date.now()};if(c.push(Dt),u=!0,oe?.type==="project-action"&&R.status==="running"){const L={tabId:Dt.id,createdAt:Dt.createdAt,index:c.length-1};(!d||L.createdAt>d.createdAt||L.createdAt===d.createdAt&&L.index>d.index)&&(d=L)}h.add(Dt.id)}let S=u||!!(m&&r.length>0);const y=c.map(R=>!yn(R.purpose)||f.has(R.purpose.actionId)||h.has(R.id)||R.lifecycle==="starting"||Sa(i,s,R.purpose.actionId,o?.startedActionMutationRevisions)||R.lifecycle==="exited"&&!R.isConnecting?R:(S=!0,{...R,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:R.purpose.actionId,executionId:null}})),k=a?.activeTabId??null,v=k&&y.some(R=>R.id===k)?k:y[0]?.id??null,F=v?y.find(R=>R.id===v):y[0],O=d&&!oh(F)?d.tabId:v;if(!S&&a&&O===a.activeTabId&&y.length===a.tabs.length&&y.every((R,ye)=>R===a.tabs[ye]))return i;const q=new Map(i.sessions);return q.set(s,{tabs:y,activeTabId:O}),{sessions:q,buffers:l}})},setActiveTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);return!a||a.activeTabId===r||Ae(a,r)<0?s:(i.set(o,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,o)=>{const s=X(n),i=o.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(s);if(!l)return a;const u=Ae(l,r);if(u<0||l.tabs[u]?.label===i)return a;const d=[...l.tabs];return d[u]={...d[u],label:i},c.set(s,{...l,tabs:d}),{sessions:c}})},setTabIconKey:(n,r,o)=>{const s=X(n);e(i=>{const a=new Map(i.sessions),c=a.get(s);if(!c)return i;const l=Ae(c,r);if(l<0)return i;const u=o?.trim()||null;if(c.tabs[l]?.iconKey===u)return i;const d=[...c.tabs];return d[l]={...d[l],iconKey:u},a.set(s,{...c,tabs:d}),{sessions:a}})},closeTab:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c].purpose;let u=s.actionMutationRevisions,d=s.nextActionMutationRevision;l.type==="project-action"&&(u=new Map(u),Un(u,o,l.actionId,d),d+=1);const f={actionMutationRevisions:u,nextActionMutationRevision:d},h=a.tabs.filter(v=>v.id!==r),m=Ve(o,r),S=s.buffers.has(m)?cn(s.buffers,v=>v===m):null;if(h.length===0){const v=zn(),F=Dr(v,"Terminal");i.set(o,ts(F));const O={sessions:i,nextTabId:s.nextTabId+1};return S&&(O.buffers=S),{...O,...f}}let y=a.activeTabId;a.activeTabId===r&&(y=h[Math.min(c,h.length-1)]?.id??h[0]?.id??null),i.set(o,{...a,tabs:h,activeTabId:y});const k={sessions:i};return S&&(k.buffers=S),{...k,...f}})},setTabPurpose:(n,r,o)=>{const s=X(n);e(i=>{const a=i.sessions.get(s);if(!a)return i;const c=Ae(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(o))return i;const u=[...a.tabs],d=o.type==="project-action"&&o.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==o.executionId);u[c]={...l,purpose:o},d&&Object.assign(u[c],es);const f=Ve(s,r),h=d?cn(i.buffers,y=>y===f)??i.buffers:i.buffers,m=new Map(i.sessions);if(m.set(s,{...a,tabs:u}),o.type!=="project-action")return{sessions:m};const S=new Map(i.actionMutationRevisions);return Un(S,s,o.actionId,i.nextActionMutationRevision),{sessions:m,buffers:h,actionMutationRevisions:S,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,o)=>{const s=X(n),i=t().sessions.get(s);if(!i||Ae(i,r)<0)return null;const a=Xp();return e(c=>{const l=c.sessions.get(s);if(!l)return c;const u=Ae(l,r);if(u<0)return c;const d=[...l.tabs];d[u]={...d[u],purpose:{type:"project-action",actionId:o,executionId:a},lifecycle:"starting",terminalSessionId:null,...es,isConnecting:!1};const f=new Map(c.sessions);f.set(s,{...l,tabs:d});const h=new Map(c.actionMutationRevisions);Un(h,s,o,c.nextActionMutationRevision);const m=Ve(s,r),S=cn(c.buffers,y=>y===m)??c.buffers;return{sessions:f,buffers:S,actionMutationRevisions:h,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!Cr(d,s?.expectedExecutionId))return a;const f=o!==null&&d.terminalSessionId!==o,h=o?"running":d.terminalSessionId?"exited":d.lifecycle,m={...d,terminalSessionId:o,lifecycle:h,isConnecting:!1},S=Ve(i,r),y=f&&a.buffers.has(S)?cn(a.buffers,F=>F===S):null,k=[...l.tabs];k[u]=m,c.set(i,{...l,tabs:k});const v={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(yn(d.purpose)){const F=new Map(a.actionMutationRevisions);Un(F,i,d.purpose.actionId,a.nextActionMutationRevision),v.actionMutationRevisions=F,v.nextActionMutationRevision=a.nextActionMutationRevision+1}return y&&(v.buffers=y),v})},setTabLifecycle:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!Cr(l.tabs[u],s?.expectedExecutionId))return a;const d=l.tabs[u];if(d.lifecycle===o&&!d.isConnecting)return a;const f=[...l.tabs];if(f[u]={...d,lifecycle:o,isConnecting:!1},c.set(i,{...l,tabs:f}),d.purpose.type!=="project-action"||d.lifecycle===o)return{sessions:c};const h=new Map(a.actionMutationRevisions);return Un(h,i,d.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:h,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,o,s)=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0||!Cr(l.tabs[u],s?.expectedExecutionId))return a;const d=[...l.tabs];return d[u]={...d[u],isConnecting:o},c.set(i,{...l,tabs:d}),{sessions:c}})},replaceBuffer:(n,r,o,s,i)=>{const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Ve(a,r),d=c.buffers.get(u)??Qo;if(d.lastSequence>s)return c;const f=Xo(o),h=d.chunks[0]?.size;if(d.lastSequence===s&&d.byteLength===f.byteLength&&d.chunks.map(y=>y.data).join("")===f.text&&h?.cols===i?.cols&&h?.rows===i?.rows)return c;const m=c.nextChunkId,S=new Map(c.buffers);return S.set(u,{chunks:f.text?[{id:m,data:f.text,byteLength:f.byteLength,...i?{size:i}:{}}]:[],byteLength:f.byteLength,lastSequence:s}),{buffers:S,nextChunkId:f.text?m+1:m}})},appendToBuffer:(n,r,o,s,i)=>{if(!o)return;const a=X(n);e(c=>{const l=c.sessions.get(a);if(!l||Ae(l,r)<0)return c;const u=Ve(a,r),d=c.buffers.get(u)??Qo;if(s!==void 0&&s<=d.lastSequence)return c;const f=c.nextChunkId,h=Xo(o),m=i!==void 0&&i!==o?Xo(i).text:void 0,S={id:f,data:h.text,...m!==void 0?{replayData:m}:{},byteLength:h.byteLength},y=[...d.chunks,S];let k=d.byteLength+S.byteLength;for(;k>As&&y.length>1;){const F=y.shift();if(!F)break;k-=F.byteLength}const v=new Map(c.buffers);return v.set(u,{chunks:y,byteLength:k,lastSequence:s??d.lastSequence}),{buffers:v,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,s={})=>{const i=X(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const u=Ae(l,r);if(u<0)return a;const d=l.tabs[u];if(!Cr(d,s.expectedExecutionId))return a;const f=s.autoOpened??d.previewAutoOpened,h=s.locked??d.previewUrlLocked;if(d.previewUrl===o&&d.previewAutoOpened===f&&d.previewUrlLocked===h)return a;const m=[...l.tabs];return m[u]={...d,previewUrl:o,previewAutoOpened:f,previewUrlLocked:h},c.set(i,{...l,tabs:m}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const o=X(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=Ae(a,r);if(c<0)return s;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return s;const u=[...a.tabs];return u[c]={...l,previewAutoOpened:!0},i.set(o,{...a,tabs:u}),{sessions:i}})},removeDirectory:n=>{const r=X(n);e(o=>{const s=new Map(o.sessions);s.delete(r);const i=Ve(r,""),a=cn(o.buffers,d=>d.startsWith(i)),c=fo(r,"");let l;for(const d of o.actionMutationRevisions.keys())d.startsWith(c)&&(l??=new Map(o.actionMutationRevisions),l.delete(d));const u={sessions:s};return a&&(u.buffers=a),l&&(u.actionMutationRevisions=l),u})},clearAll:()=>{e({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1})}}),{name:Yp,storage:ih(),partialize:sh,merge:(e,t)=>{if(!Zo(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"||!Zo(l))continue;const u=Array.isArray(l.tabs)?l.tabs:[],d=[],f=new Map;for(const y of u){if(!Zo(y))continue;const k=typeof y.id=="string"?y.id:null;if(!k)continue;const v=nh(k);v!==null&&(o=Math.max(o,v));const F=v===null?k:zn();f.set(k,F);const O=Qp.safeParse(y.purpose).data,q=O?{type:"project-action",actionId:O.actionId,executionId:null}:{type:"terminal"};d.push({id:F,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:q,createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(d.length===0)continue;const h=typeof l.activeTabId=="string"?l.activeTabId:null,m=h?f.get(h)??h:null,S=m?d.some(y=>y.id===m):!1;r.set(c,{tabs:d,activeTabId:S?m:d[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"&&!ga){ga=!0;const e=Gr.persist,t=()=>{Gr.getState().hasHydrated||Gr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ye=20,ah=8,Ta=4096,ch=2160*60*6e4,V=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},vt=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Et=(e,t)=>{const n=V(t),r=V(e);if(!n||!r)return!1;const o=vt(n),s=vt(r);return s===o||s.startsWith(`${o}/`)},Nn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=V(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(h=>typeof h=="string").map(h=>V(h)).filter(h=>h.length<=Ta&&Et(h,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(h=>typeof h=="string").map(h=>V(h)).filter(h=>h.length<=Ta&&Et(h,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?V(i.selectedPath):null,u=l&&Et(l,s)?l:a[0]??null,d=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-d>ch)continue;const f=n[s];if(f){const h=Array.from(new Set([...f.openPaths,...a])),m=Array.from(new Set([...f.expandedPaths,...c])),S=f.selectedPath??u??h[0]??null;n[s]={openPaths:h,selectedPath:S,expandedPaths:m,touchedAt:Math.max(f.touchedAt,d)};continue}n[s]={openPaths:a,selectedPath:u,expandedPaths:c,touchedAt:d}}return Qe(n,Ye)},Qe=(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},ln=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},lh=ft()(In(ur((e,t)=>({byRoot:{},activeRuntimeKey:$(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Nn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:Nn(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=V((n||"").trim()),i=V((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!Et(i,s)||e(a=>{const c=a.byRoot[s],l=ln(c),u=l.openPaths.includes(i),d=u?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&u&&c.selectedPath===f)return a;const h={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:f}};return{byRoot:Qe(h,Ye)}})},removeOpenPath:(n,r)=>{const o=V((n||"").trim()),s=V((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=vt(s),l=m=>vt(m)===c,u=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!u)return i;const d=a.openPaths.filter(m=>!l(m)),f=u?d[0]??null:a.selectedPath,h={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Qe(h,Ye)}})},removeOpenPathsByPrefix:(n,r)=>{const o=V((n||"").trim()),s=V((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=vt(s),l=c.endsWith("/")?c:`${c}/`,u=m=>{const S=vt(m);return S===c||S.startsWith(l)},d=a.openPaths.filter(m=>!u(m));if(d.length===a.openPaths.length)return i;const f=a.selectedPath&&u(a.selectedPath)?d[0]??null:a.selectedPath,h={...i.byRoot,[o]:{...a,openPaths:d,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Qe(h,Ye)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=V((n||"").trim()),s=V((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=vt(s),l=c.endsWith("/")?c:`${c}/`,u=a.expandedPaths.filter(f=>{const h=vt(f);return h!==c&&!h.startsWith(l)});if(u.length===a.expandedPaths.length)return i;const d={...i.byRoot,[o]:{...a,expandedPaths:u,touchedAt:Date.now()}};return{byRoot:Qe(d,Ye)}})},setSelectedPath:(n,r,o)=>{const s=V((n||"").trim()),i=r?V(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!Et(i,s)||e(a=>{const c=a.byRoot[s],l=ln(c),u=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&u===c.openPaths)return a;const d={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:i}};return{byRoot:Qe(d,Ye)}})},ensureSelectedPath:n=>{const r=V((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=V((n||"").trim()),s=V((r||"").trim());!o||!s||!Et(s,o)||e(i=>{const a=i.byRoot[o],c=ln(a),u=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===u&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:u}};return{byRoot:Qe(d,Ye)}})},collapseAllExpandedPaths:n=>{const r=V((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...ln(s),expandedPaths:[]}};return{byRoot:Qe(i,Ye)}})},expandPath:(n,r)=>{const o=V((n||"").trim()),s=V((r||"").trim());!o||!s||!Et(s,o)||e(i=>{const a=i.byRoot[o],c=ln(a);if(c.expandedPaths.includes(s)&&a)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:Qe(u,Ye)}})},expandPaths:(n,r)=>{const o=V((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>V((i||"").trim())).filter(i=>i&&Et(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=ln(a),l=new Set(c.expandedPaths),u=s.filter(f=>!l.has(f));if(u.length===0)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...u]}};return{byRoot:Qe(d,Ye)}})}}),{name:"files-view-tabs-store",version:3,storage:di(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:$(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Nn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,ah).map(([r,o])=>[r,{byRoot:Nn(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=$();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:Nn(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),uh=ke(["diff","walkthrough","file","context","plan","chat","browser","git","pr","linear","notes","terminal"]),dh=I({widthByMode:qt(w(),C().finite().optional().catch(void 0)).catch({}),widthFractionByMode:qt(w(),C().positive().max(1).optional().catch(void 0)).catch({})}),kl="ask",va=e=>e==="attach"||e==="inline"||e==="ask"?e:kl;function ka(e){return e==="vim"?"vim":"default"}const ct="all";function Ea(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Aa(e){return e==="me"||e==="any"?e:"any"}function El(e){return typeof e!="string"?ct:e.trim()||ct}function Pa(e,t){const n=$();if(Mc(n))return e;const r={...e};return t===ct?delete r[n]:r[n]=t,r}function fh(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=El(r);o!==ct&&(t[n]=o)}return t}function Ia(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const Or={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}"}},gt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Mr=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,ph=e=>{if(!e||typeof e!="object")return!1;const t=e;return Mr(t.completion,Or.completion)&&Mr(t.error,Or.error)&&Mr(t.question,Or.question)&&Mr(t.subtask,Or.subtask)},hh=380,mh=320,gh=1400,Al=12,xa=120,yh=280;let Ra=0;const wh=e=>ue(e),ue=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},Pl=e=>Number.isFinite(e)?Math.min(gh,Math.max(mh,Math.round(e))):hh,ar=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},po=e=>{const t=ar(e);return t&&wh(t)||null},ho=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>xa?t.slice(0,xa):t:null},pi=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"||e==="commit"||e==="pr"?e:null,Il=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},Sh=(e,t)=>(e==="file"||e==="browser")&&t||e,xl=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return Sh(e,t)},Rl=(e,t)=>t===e?e:`${e}:${t}`,Cl=e=>{const t=ar(e.targetPath),n=e.mode==="terminal"?po(e.targetDirectory):null,r=xl(e.mode,t,e.dedupeKey);return{id:Rl(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Il(e.projectPlanRef),dedupeKey:r,label:ho(e.label),sessionTitleFallback:ho(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:pi(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Dl=(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(u=>u.mode===i)].sort((u,d)=>u.touchedAt-d.touchedAt).filter(u=>u.id!==n);for(const u of l.slice(0,a-t))s.add(u.id)}return s.size===0?e:e.filter(i=>!s.has(i.id))},Ol=e=>{if(!Array.isArray(e))return[];const t=Me(),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=ar(typeof s.targetPath=="string"?s.targetPath:null),a=s.mode==="terminal"?po(s.targetDirectory):null,c=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,l=Il(s.projectPlanRef);if(s.mode==="plan"&&c!==null!=(l!==null))continue;const u=xl(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),d=Rl(s.mode,u);!d||r.has(d)||(r.add(d),n.push({id:d,mode:s.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:u,label:ho(typeof s.label=="string"?s.label:null),sessionTitleFallback:ho(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:pi(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},En=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Lt=e=>{if(e){const t=Ol(e.tabs),n=En(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},widthFractionByMode:{},touchedAt:Date.now()}},bh=(e,t,n)=>{const r=n?.reveal!==!1,o=Cl(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(u=>!(u.mode==="file"&&!u.targetPath)):e.tabs,i=s.findIndex(u=>u.id===o.id),a=i===-1?[...s,o]:s.map((u,d)=>d===i?{...u,mode:o.mode,targetPath:o.targetPath||u.targetPath,targetDirectory:o.targetDirectory,projectPlanId:o.projectPlanId??u.projectPlanId,projectPlanRef:o.projectPlanRef??u.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||u.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:u),c=r?o.id:e.activeTabId??o.id,l=Dl(a,Al,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:En(l,c),touchedAt:Date.now()}},Th=(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:En(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,u)=>u.touchedAt>=l.touchedAt?u:l):null;return{...e,tabs:o,activeTabId:c?.id??En(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},vh=(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},kh=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),os=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=ue(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=Ol(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=[Cl({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=En(a,c),u=Dl(a,Al,l),d={},f={},h=dh.parse(o);for(const m of uh.options){const S=h.widthByMode[m],y=h.widthFractionByMode[m];S!==void 0&&(d[m]=Pl(S)),y!==void 0&&(f[m]=y)}n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:En(u,l),widthByMode:d,widthFractionByMode:f,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},Ft=(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},T=ft()(In(ur((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:yh,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],workStatusHiddenSectionsExplicit:!1,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",sessionRetentionOnlyArchived:!1,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:Up,monoFont:Np,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Wp(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:ct,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,alwaysShowScrollbars:!1,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...gt.completion},error:{...gt.error},question:{...gt.question},subtask:{...gt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!Ud(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:kl,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=>({isSidebarOpen:!n.isSidebarOpen}))},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?r:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n})},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=ue((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const f=(a.find(h=>h.mode==="terminal")??null)?.targetDirectory??null;if(f){const h=Gr.getState().getDirectoryState(f);if(qp(h))return}s.openContextPanelTab(o,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),s.closeContextPanel(o);return}const u=a.filter(d=>d.mode===r);if(u.length>0){l();const d=u.reduce((f,h)=>h.touchedAt>=f.touchedAt?h:f);s.setActiveContextPanelTab(o,d.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=ue((n||"").trim());if(!s)return;const i=r.mode==="terminal"?{...r,targetDirectory:po(r.targetDirectory)===s?null:po(r.targetDirectory)}:r;e(a=>{const c=a.contextPanelByDirectory[s],l=Lt(c),u={...a.contextPanelByDirectory,[s]:bh(l,i,o)};return{contextPanelByDirectory:Ft(u,20)}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=ue((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=pi(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=ue((n||"").trim()),s=ar(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=ue((n||"").trim()),a=ar(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=ue((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=ue((n||"").trim()),s=(r||"").trim();!o||!s||Me()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=ue((n||"").trim());!r||Me()||(Ra+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${Ra}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=ue((n||"").trim());if(!s||Me())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=ue((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:kh(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=ue((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Lt(a);if(!c.tabs.some(u=>u.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(u=>u.id===s?{...u,touchedAt:Date.now()}:u)}};return{contextPanelByDirectory:Ft(l,20)}})},reorderContextPanelTabs:(n,r,o)=>{const s=ue((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],u=Lt(l);if(!u.tabs.some(h=>h.id===i)||!u.tabs.some(h=>h.id===a))return c;const d=vh(u,i,a);if(d.tabs===u.tabs)return c;const f={...c.contextPanelByDirectory,[s]:d};return{contextPanelByDirectory:Ft(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=ue((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=Lt(c);if(!l.tabs.some(d=>s.includes(d.id)))return a;const u={...a.contextPanelByDirectory,[o]:Th(l,s)};return{contextPanelByDirectory:Ft(u,20)}});for(const a of i)a.mode==="file"&&a.targetPath&&lh.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=ue((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Lt(s),isOpen:!1}};return{contextPanelByDirectory:Ft(i,20)}})},toggleContextPanelExpanded:n=>{const r=ue((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=Lt(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Ft(a,20)}})},setContextPanelWidth:(n,r,o,s)=>{const i=ue((n||"").trim());i&&e(a=>{const c=a.contextPanelByDirectory[i],l=Lt(c),u=Pl(o),d={...l.widthFractionByMode};s!==void 0&&Number.isFinite(s)&&s>0?d[r]=Math.min(1,u/s):delete d[r];const f={...a.contextPanelByDirectory,[i]:{...l,widthByMode:{...l.widthByMode,[r]:u},widthFractionByMode:d}};return{contextPanelByDirectory:Ft(f,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:{workStatusHiddenSectionsExplicit:!0,workStatusHiddenSections:r?s.filter(a=>a!==n):[...s,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)],workStatusHiddenSectionsExplicit:!0})},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(r=>({sessionRetentionAction:r.sessionRetentionOnlyArchived?"delete":n}))},setSessionRetentionOnlyArchived:n=>{e(r=>({sessionRetentionOnlyArchived:n,sessionRetentionAction:n?"delete":r.sessionRetentionAction}))},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(Mp);if(o===1){r.style.removeProperty("font-size");for(const[i]of s)r.style.removeProperty(ha(i));return}r.style.fontSize=`${o*100}%`;for(const[i]of s)r.style.removeProperty(ha(i))},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:Ea(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Aa(n)})},setLinearIssueListTeamId:n=>{const r=El(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Pa(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=$();e(r=>({linearIssueListTeamId:Mc(n)?ct:r.linearIssueListTeamIdByRuntime[n]??ct}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Ia(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:ct,linearIssueListTeamIdByRuntime:Pa(n.linearIssueListTeamIdByRuntime,ct),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(d=>d.providerID===n&&d.modelID===r),c=i.favoriteModels.findIndex(d=>d.providerID===o&&d.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[u]=l.splice(a,1);return u?(l.splice(c,0,u),{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 u=l.recentEfforts[a]??[];if(u.includes(c))return l;const d=u;return{recentEfforts:{...l.recentEfforts,[a]:[c,...d].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})},setAlwaysShowScrollbars:n=>{e({alwaysShowScrollbars: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:va(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:ka(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:di(),version:21,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<21&&n.workStatusHiddenSectionsExplicit!==!0&&(n.workStatusHiddenSections=Array.isArray(n.workStatusHiddenSections)?n.workStatusHiddenSections.filter(r=>r!=="telemetry"):[],n.workStatusHiddenSectionsExplicit=!1),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 u=l;if(u.mode!=="preview"){typeof u.id=="string"&&a.add(u.id),c.push(u);continue}const d=typeof u.targetPath=="string"?u.targetPath:"",f=typeof u.dedupeKey=="string"&&u.dedupeKey.trim()?u.dedupeKey.trim():d||"browser",h=f==="browser"?"browser":`browser:${f}`;a.has(h)||(a.add(h),c.push({...u,mode:"browser",id:h,dedupeKey:f}))}if(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(u=>typeof u.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("aiworker:files:auto-save-enabled");o!==null&&(r=o!=="false",localStorage.removeItem("aiworker: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&&ph(n.notificationTemplates)&&(n.notificationTemplates={completion:{...gt.completion},error:{...gt.error},question:{...gt.question},subtask:{...gt.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=os(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=os(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=os(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ea(n.linearIssueListStatus),n.linearIssueListAssignee=Aa(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=fh(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Ia(n.linearIssueListPriority),n.fileEditorKeymap=ka(n.fileEditorKeymap),n.largeTextPasteBehavior=va(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,workStatusHiddenSectionsExplicit:e.workStatusHiddenSectionsExplicit,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,sessionRetentionOnlyArchived:e.sessionRetentionOnlyArchived,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,alwaysShowScrollbars:e.alwaysShowScrollbars,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,inputBarOffset:e.inputBarOffset,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"})),Eh=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},Ah=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Ph=e=>{const t=T.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Ih=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=Ah(t);return Eh(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},xh=(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},Ps=ft()(ur(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:xh})),Ml="directoryTreeShowHidden",Is="directory-show-hidden-change",xs=()=>{if(typeof window>"u")return!0;try{const e=pr().getItem(Ml);return e===null?!0:e==="true"}catch{return!0}},Rh=()=>{typeof window>"u"||window.dispatchEvent(new Event(Is))},Ch=()=>xs(),Dh=(e,t={})=>{if(!(typeof window>"u")){try{pr().setItem(Ml,e?"true":"false"),Rh()}catch{}t.persist!==!1&&lt({directoryShowHidden:e})}},Jb=()=>{const e=mc.c(2),[t,n]=Xr.useState(xs);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(xs())};return window.addEventListener("storage",s),window.addEventListener(Is,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Is,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),Xr.useEffect(r,o),t},_l=[{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"}],Oh=new Map(_l.map(e=>[e.name,e])),Vb=e=>Oh.get(e),Yb=_l.map(e=>({type:"command",name:e.name})),Qb="terminal-box",Xb="book-open",Zb=e=>`${e.type}:${e.name}`,eT=(e,t)=>e.type===t.type&&e.name===t.name,tT=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Mh=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},Ll="filesViewShowGitignored",Rs="files-view-show-gitignored-change",Cs=()=>{if(typeof window>"u")return!1;try{return pr().getItem(Ll)==="true"}catch{return!1}},_h=()=>{typeof window>"u"||window.dispatchEvent(new Event(Rs))},Lh=()=>Cs(),Fh=(e,t={})=>{if(!(typeof window>"u")){try{pr().setItem(Ll,e?"true":"false"),_h()}catch{}t.persist!==!1&&lt({filesViewShowGitignored:e})}},nT=()=>{const e=mc.c(2),[t,n]=Xr.useState(Cs);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Cs())};return window.addEventListener("storage",s),window.addEventListener(Rs,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Rs,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),Xr.useEffect(r,o),t},Fl="session",jl=40,jh=1,Uh=100,Ul=e=>e==="global"||e==="session",hi=e=>e!=null&&Number.isInteger(e)&&e>=jh&&e<=Uh,Nh=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],mi=e=>e==="auto"||typeof e=="string"&&Nh.includes(e),Nl=["session","repository","usage","telemetry","subagents","tasks","mcp","pinned","contextSources"],rT={session:"chat.workStatus.section.session",repository:"chat.workStatus.section.project",usage:"chat.workStatus.section.usage",telemetry:"chat.workStatus.section.telemetry",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"},Bh=new Set(Nl),Hh=e=>typeof e=="string"&&Bh.has(e),oT=(e,t)=>!e?.includes(t),sT=e=>e!=null&&Nl.every(t=>e.includes(t)),iT=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Bl=(e,t=!0)=>{if(!Array.isArray(e))return[];const n=new Set;for(const r of e)Hh(r)&&n.add(r);return t||n.delete("telemetry"),[...n]},wn="openchamber-input-history.v1",zh=8,$h=50,Wh=[40,25,10,5,1],ss=Object.freeze([]);let it=null,Ca=0;const Qn=(e=Fl,t=jl)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),Hl=()=>(Ca+=1,Date.now()*1e3+Ca),zl=e=>JSON.stringify([e]),Ds=(e,t,n)=>JSON.stringify([e,t,n]),gi=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},Kh=()=>{const e=gi(),t=$e?JSON.stringify(Jr($e.base)):it;if(!e)return t;try{return e.getItem(wn)??($e?null:it)}catch{return t}},Da=qt(w(),fe()),Gh=I({key:w().min(1),source:Jt([H("file-url"),H("vscode-file")]),filename:w().min(1),mimeType:w().min(1),size:C().finite().nonnegative(),reference:w().min(1)}),qh=I({text:w(),attachmentKeys:G(w()),restorableAttachments:G(Gh),submittedAt:C().finite().nonnegative()}),Jh=I({touchedAt:C().finite().nonnegative(),entries:G(fe())}),Vh=(e,t)=>{try{const n=JSON.parse(e),o=(t===1?_i([w().trim().min(1)]):_i([w().trim().min(1),w().trim().min(1),w().trim().min(1)])).safeParse(n);if(!o.success)return null;if(t===3){const s=tn(o.data[1]);if(!s||s!==o.data[1])return null}return o.data}catch{return null}},Oa=(e,t)=>{const n=[];for(const[r,o]of Object.entries(e)){if(!Vh(r,t))continue;const s=Jh.safeParse(o);if(!s.success)continue;const i=s.data.entries.map(a=>qh.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:s.data.touchedAt,entries:i}])}return Object.fromEntries(n)},Yh=()=>{const e=Kh();if(e===null)return Qn();try{const t=JSON.parse(e),n=I({version:H(1),entryLimit:C().int().optional(),scope:Jt([H("global"),H("session")]).optional(),global:Da.default({}),session:Da.default({})}).safeParse(t);return n.success?{entryLimit:hi(n.data.entryLimit)?n.data.entryLimit:jl,scope:n.data.scope??Fl,globalBuckets:Oa(n.data.global,1),sessionBuckets:Oa(n.data.session,3)}:Qn()}catch{const t=gi();if(t)try{t.removeItem(wn)}catch{}return it=null,Qn()}};let $e=null,qr=Qn();const Ma=(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(u=>JSON.stringify(u))),a=new Set(s.entries.map(u=>JSON.stringify(u))),c=(e[o]?.entries??[]).filter(u=>{const d=JSON.stringify(u);return!i.has(d)||a.has(d)}),l=new Set(c.map(u=>JSON.stringify(u)));for(const u of s.entries){const d=JSON.stringify(u);!i.has(d)&&!l.has(d)&&c.push(u)}c.sort((u,d)=>u.submittedAt-d.submittedAt),r[o]={touchedAt:Math.max(s.touchedAt,e[o]?.touchedAt??0),entries:c}}return r},$n=()=>{const e=Yh();if(qr=e,!$e)return e;const{base:t,value:n}=$e;return Os({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Ma(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Ma(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},$l=(e,t)=>e.slice(Math.max(0,e.length-t)),_a=(e,t,n)=>{const r=Object.entries(e).map(([o,s])=>[o,{touchedAt:s.touchedAt,entries:$l(s.entries,n)}]).sort((o,s)=>s[1].touchedAt-o[1].touchedAt).slice(0,t);return Object.fromEntries(r)},Os=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:_a(e.globalBuckets,zh,t),sessionBuckets:_a(e.sessionBuckets,$h,t)}),Jr=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),La=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Wn=e=>{const t=Os(e),n=JSON.stringify(Jr(t));$e={base:qr,value:t};const r=gi();if(!r)return it=n,t;try{return r.setItem(wn,n),$e=null,it=n,t}catch(i){if(!(i instanceof Error)||!La(i))return it=n,t}try{r.removeItem(wn)}catch{}for(const i of Wh){const a=Os(t,i),c=JSON.stringify(Jr(a));try{return r.setItem(wn,c),$e=null,it=c,a}catch(l){if(!(l instanceof Error)||!La(l))return $e={base:qr,value:a},it=c,a}}const o=Qn(t.scope,t.entryLimit),s=JSON.stringify(Jr(o));try{r.setItem(wn,s),$e=null}catch{$e={base:qr,value:o}}return it=s,o},Qh=(e,t,n)=>{const r=e.trim(),o=tn(t),s=n.trim();return!r||!o||!s?null:{runtimeKey:r,directory:o,sessionId:s}},Wl=e=>e.source==="vscode"&&e.vscodeSource==="file"?tn(e.vscodePath??null):e.dataUrl.trim()||null,Xh=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Ms=e=>{const t=Wl(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("|")},Zh=e=>{const t=Wl(e);return!t||!Xh(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Ms(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Ms(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},em=(e,t)=>({text:e,attachmentKeys:t.map(Ms),restorableAttachments:t.map(Zh).filter(n=>n!==null)}),tm=(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}),nm=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&tm(e.restorableAttachments,t.restorableAttachments),Fa=(e,t,n,r)=>{const o=e?[...e.entries]:[];for(const s of t){const i=o.at(-1);nm(i,s)||o.push({text:s.text,attachmentKeys:[...s.attachmentKeys],restorableAttachments:s.restorableAttachments.map(a=>({...a})),submittedAt:Hl()})}return{touchedAt:n,entries:$l(o,r)}},rm=Wn($n()),Kn=ft(e=>({...rm,applyEntryLimit:t=>{hi(t)&&e(n=>{const r=$n();if(r.entryLimit===t)return{...n,...r};const o=Wn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},applyScope:t=>{Ul(t)&&e(n=>{const r=$n();if(r.scope===t)return{...n,...r};const o=Wn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const o=$n(),s=Hl(),i=zl(t.runtimeKey),a=Ds(t.runtimeKey,t.directory,t.sessionId),c=Wn({entryLimit:o.entryLimit,scope:o.scope,globalBuckets:{...o.globalBuckets,[i]:Fa(o.globalBuckets[i],n,s,o.entryLimit)},sessionBuckets:{...o.sessionBuckets,[a]:Fa(o.sessionBuckets[a],n,s,o.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=$n(),o=Ds(t.runtimeKey,t.directory,t.sessionId);if(!(o in r.sessionBuckets))return{...n,...r};const s={...r.sessionBuckets};delete s[o];const i=Wn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:s});return{...n,...i}})}})),aT=(e,t)=>t?e.scope==="session"?e.sessionBuckets[Ds(t.runtimeKey,t.directory,t.sessionId)]?.entries??ss:e.globalBuckets[zl(t.runtimeKey)]?.entries??ss:ss,om=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,sm=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}},im=(e,t)=>{const n=t.map(sm).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},cT=e=>{const t=om.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}},yi="aiworkerContext",wi="opencodeComment";function am(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 im("",[{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 lT(e,t){const n=t??am(e),r={[yi]:e};return e.kind==="code-comment"&&(r[wi]={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 uT(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 Kl=bo("kind",[I({kind:H("code-comment"),source:ke(["diff","file","plan"]),fileLabel:w(),startLine:C(),endLine:C(),side:ke(["original","modified"]).optional(),language:w(),code:w(),text:w()}),I({kind:H("terminal"),terminalId:w(),terminalLabel:w(),startLine:C(),endLine:C(),output:w()}),I({kind:H("browser-annotation"),pageUrl:w(),prompt:w(),text:w()}),I({kind:H("pr-comment"),label:w(),body:w(),text:w()}),I({kind:H("pr-check"),label:w(),output:w(),text:w()}),I({kind:H("file-quote"),fileLabel:w(),startLine:C().optional(),endLine:C().optional(),quote:w(),text:w()}),I({kind:H("chat-quote"),messageId:w().optional(),quote:w(),text:w()}),I({kind:H("github-issue"),number:C().int().positive(),title:w(),url:w()}),I({kind:H("github-pr"),number:C().int().positive(),title:w(),url:w()}),I({kind:H("linear-issue"),identifier:w().min(1),title:w(),url:w()})]),Gl=I({path:w(),selection:I({startLine:C().finite(),endLine:C().finite(),startChar:C().finite().optional(),endChar:C().finite().optional()}).optional(),comment:w(),preview:w().optional(),origin:ke(["file","review"]).optional()}),cm=I({[yi]:Kl,[wi]:Gl.optional()});function lm(e){if(e.type!=="text")return null;const t=Kl.safeParse(e.metadata?.[yi]);if(t.success)return t.data;const n=Gl.safeParse(e.metadata?.[wi]);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 dT(e){return e.some(t=>lm(t)!==null)}function fT(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}}function um(e){switch(e.kind){case"code-comment":return e.text.trim()||e.code.trim()||e.fileLabel;case"chat-quote":case"file-quote":return e.text.trim()||e.quote;case"browser-annotation":return e.text.trim()||e.prompt.trim()||e.pageUrl;case"pr-comment":return e.text.trim()||e.body.trim()||e.label;case"pr-check":return e.text.trim()||e.label.trim()||e.output;case"terminal":return e.output.trim()||e.terminalLabel;case"github-issue":case"github-pr":case"linear-issue":return e.title.trim()||e.url}}function dm(e){let t=e.content.trim()||e.contextPreview?.trim()||"";if(!t){for(const r of e.context??[])if(r.kind!=="instruction"&&(t=(r.kind==="context"?um(r.metadata.aiworkerContext):r.text).trim(),t))break}t||=e.attachments?.[0]?.filename??"";const n=t.split(`
36
+ `,1)[0];return n.slice(0,100)+(t.length>n.length||n.length>100?"...":"")}const ql="queue",fm=e=>e==="steer"||e==="queue",pm=(e,t)=>e==="immediate"?"steer":fm(e)?e:t===!1?"steer":t===!0?"queue":ql,bt=()=>!Me(),ja=50,_s=(e,t,n=$())=>{const r=tn(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},Le=e=>`${e.runtimeKey}
37
+ ${e.directory}
38
+ ${e.sessionId}`,$t=e=>{const[t,n,...r]=e.split(`
39
+ `);return _s(r.join(`
40
+ `),n,t)},hm=I({providerID:w().min(1),modelID:w().min(1),agent:w().optional(),variant:w().optional()}),mm=I({id:w(),filename:w(),mimeType:w(),size:C(),source:ke(["local","server","vscode"]),serverPath:w().optional(),dataUrl:w().optional()}),gm=bo("kind",[I({kind:H("context"),text:w(),metadata:cm,instructions:w().optional()}),I({kind:H("instruction"),text:w()}),I({kind:H("synthetic"),text:w()})]),Si=I({id:w().min(1),createdAt:C(),content:w(),text:w(),agentMention:w().optional(),attachments:G(mm),context:G(gm).optional(),contextPreview:w().optional(),sendConfig:hm}),bi=I({sessionId:w().min(1),directory:w(),items:G(Si),sendingId:w().nullable()}),Ua=I({revision:C(),sessions:G(bi)}),Xn=I({revision:C(),session:bi}),ym=Xn.extend({item:Si}),wm=Xn.extend({items:G(Si)}),Sm=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}},bm=e=>{const t=e.dataUrl??"",n=t?Sm(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},_r=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(bm)),e.context&&(t.context=e.context),e.contextPreview&&(t.contextPreview=e.contextPreview),t},Tm=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},Na=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(o=>!!o.dataUrl).map(Tm),context:e.context??[],sendConfig:t};e.agentMention&&(n.agentMention=e.agentMention);const r=dm({content:"",context:e.context});return r&&(n.contextPreview=r),n},jt=async(e,t,n)=>{const r=await g(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},yt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},wt=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,is=new Set,Ba=new Map,Xe=new Map,Lr=new Map;let as=0;const Ha=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),vm=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:Ha(n.queuedMessages??{}),quarantinedLegacyMessages:Ha({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:pm(n.followUpBehavior,n.queueModeEnabled??null)}},Ze=(e,t)=>{const{[t]:n,...r}=e;return r},Fr=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(o=>o.id!==n);return r.length===0?{queuedMessages:Ze(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},km=(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=$t(i);a?.runtimeKey!==t||a.sessionId!==n||(Xe.get(i)??-1)>r||(Xe.set(i,r),o=Ze(o,i),s=Ze(s,i))}return{queuedMessages:o,sendingIds:s}},Ls=ft()(In(ur((e,t)=>{let n=null,r=!1;const o=(a,c,l)=>{if(l!==$()||(Lr.get(l)??-1)>c)return;const u=_s(a.sessionId,a.directory,l);if(!u){if(a.items.length>0)return;e(f=>km(f,l,a.sessionId,c));return}const d=Le(u);(Xe.get(d)??-1)>c||(Xe.set(d,c),e(f=>{const h=a.items.map(_r),m=h.length>0?{...f.queuedMessages,[d]:h}:Ze(f.queuedMessages,d),S=a.sendingId?{...f.sendingIds,[d]:[a.sendingId]}:Ze(f.sendingIds,d);return{queuedMessages:m,sendingIds:S}}))},s=async a=>{try{const c=await jt(Ua,"/api/message-queue"),l=c.sessions.find(u=>u.sessionId===a.sessionId)??{sessionId:a.sessionId,directory:a.directory,items:[],sendingId:null};o(l,c.revision,a.runtimeKey)}catch{}},i=async(a,c,l)=>{try{const u=await jt(Xn,c,l);o(u.session,u.revision,a.runtimeKey)}catch(u){console.warn("[queue] server update failed:",u),await s(a)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:ql,sendingIds:{},addToQueue:async(a,c)=>{const l=Le(a),u=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,d={id:u,content:c.content,text:c.text??c.content,createdAt:Date.now(),sendConfig:c.sendConfig};if(c.agentMention&&(d.agentMention=c.agentMention),c.attachments&&c.attachments.length>0&&(d.attachments=c.attachments),c.context&&c.context.length>0&&(d.context=c.context),e(m=>{const S=m.queuedMessages[l]??[],y={...m.queuedMessages,[l]:[...S,d].slice(-20)},k=Object.keys(y);if(k.length>ja){k.sort((v,F)=>(y[v]?.[0]?.createdAt??0)-(y[F]?.[0]?.createdAt??0));for(const v of k.slice(0,k.length-ja))delete y[v]}return{queuedMessages:y}}),!bt())return;if(!c.sendConfig)throw e(m=>Fr(m,l,u)),new Error("A queued message needs a provider and model to be delivered later.");const f=Qh(a.runtimeKey,a.directory,a.sessionId),h=em(c.content,c.attachments??[]);try{const m=await jt(Xn,`${wt(a.sessionId)}/items`,yt("POST",{directory:a.directory,item:Na(c,c.sendConfig)}));e(S=>Fr(S,l,u)),o(m.session,m.revision,a.runtimeKey),f&&Kn.getState().appendSubmissions(f,[h])}catch(m){throw e(S=>Fr(S,l,u)),m}},removeFromQueue:(a,c)=>{const l=Le(a);e(u=>Fr(u,l,c)),bt()&&i(a,`${wt(a.sessionId)}/items/${encodeURIComponent(c)}`,yt("DELETE"))},reorderQueue:(a,c,l)=>{if(c===l)return;const u=Le(a),d=t().queuedMessages[u];if(!d)return;const f=d.findIndex(y=>y.id===c),h=d.findIndex(y=>y.id===l);if(f===-1||h===-1)return;const m=d.slice(),[S]=m.splice(f,1);if(m.splice(h,0,S),e(y=>({queuedMessages:{...y.queuedMessages,[u]:m}})),bt()){const y=m.map(k=>k.id);i(a,`${wt(a.sessionId)}/order`,yt("PUT",{itemIds:y}))}},popToInput:async(a,c)=>{const[l]=await t().takeForSend(a,c);return l??null},takeForSend:async(a,c)=>{const l=Le(a);if(bt())try{if(c){const S=await jt(ym,`${wt(a.sessionId)}/items/${encodeURIComponent(c)}/take`,yt("POST"));return o(S.session,S.revision,a.runtimeKey),[_r(S.item)]}const m=await jt(wm,`${wt(a.sessionId)}/take`,yt("POST"));return o(m.session,m.revision,a.runtimeKey),m.items.map(_r)}catch(m){throw await s(a),m}const u=t(),d=u.sendingIds[l]??[],f=(u.queuedMessages[l]??[]).filter(m=>(c?m.id===c:!0)&&!d.includes(m.id));if(f.length===0)return[];const h=new Set(f.map(m=>m.id));return e(m=>{const S=(m.queuedMessages[l]??[]).filter(y=>!h.has(y.id));return S.length===0?{queuedMessages:Ze(m.queuedMessages,l)}:{queuedMessages:{...m.queuedMessages,[l]:S}}}),f},clearQueue:a=>{const c=Le(a);e(l=>{const u=l.sendingIds[c]??[],d=(l.queuedMessages[c]??[]).filter(f=>u.includes(f.id));return d.length>0?{queuedMessages:{...l.queuedMessages,[c]:d}}:{queuedMessages:Ze(l.queuedMessages,c)}}),bt()&&i(a,wt(a.sessionId),yt("DELETE"))},forgetQueue:a=>{const c=Le(a);Xe.delete(c),e(l=>({queuedMessages:Ze(l.queuedMessages,c),sendingIds:Ze(l.sendingIds,c)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(a,c)=>{const l=Le(a);e(u=>{const d=u.sendingIds[l]??[];return d.includes(c)?u:{sendingIds:{...u.sendingIds,[l]:[...d,c]}}})},clearSending:(a,c)=>{const l=Le(a);e(u=>{const d=u.sendingIds[l];if(!d||!d.includes(c))return u;const f=d.filter(h=>h!==c);return f.length===0?{sendingIds:Ze(u.sendingIds,l)}:{sendingIds:{...u.sendingIds,[l]:f}}})},getSendableQueue:a=>{const c=Le(a),l=t(),u=l.queuedMessages[c]??[],d=l.sendingIds[c];return!d||d.length===0?u:u.filter(f=>!d.includes(f.id))},setFollowUpBehavior:a=>{e({followUpBehavior:a}),lt({followUpBehavior:a})},getQueueForTarget:a=>t().queuedMessages[Le(a)]??[],hydrate:()=>{if(!bt())return Promise.resolve();const a=$();if(n?.runtimeKey===a)return n.promise;const c=++as,l=()=>c===as&&a===$(),u=(async()=>{let h=Ba.get(a);for(h||(h={items:Object.entries(t().queuedMessages).flatMap(([S,y])=>{const k=$t(S);return!k||k.runtimeKey!==a?[]:y.map(v=>({target:k,message:v}))}),pending:null},Ba.set(a,h));h.pending||h.items.length>0;){if(!l())return;if(h.pending){await h.pending;continue}const m=h.items.shift();if(!m?.message.sendConfig)continue;const{target:S,message:y}=m,k=jt(Xn,`${wt(S.sessionId)}/items`,yt("POST",{directory:S.directory,item:Na(y,m.message.sendConfig)})).then(()=>{}).catch(F=>{console.warn("[queue] failed to migrate a locally queued message to the server:",F)});h.pending=k;const v=h;k.then(()=>{v.pending===k&&(v.pending=null)}),await k}if(l())do{r=!1;let m;try{m=await jt(Ua,"/api/message-queue",{signal:AbortSignal.timeout(15e3)})}catch(S){if(!l())return;if(r)continue;throw S}if(!l())return;is.add(a),!((Lr.get(a)??-1)>m.revision)&&(Lr.set(a,m.revision),e(S=>{const y=O=>(Xe.get(O)??-1)>m.revision,k=O=>$t(O)?.runtimeKey!==a||y(O),v={},F={};for(const[O,q]of Object.entries(S.queuedMessages))k(O)&&(v[O]=q);for(const[O,q]of Object.entries(S.sendingIds))k(O)&&(F[O]=q);for(const O of m.sessions){const q=_s(O.sessionId,O.directory,a);if(!q)continue;const R=Le(q);y(R)||(Xe.set(R,m.revision),O.items.length>0&&(v[R]=O.items.map(_r)),O.sendingId&&(F[R]=[O.sendingId]))}return{queuedMessages:v,sendingIds:F}}))}while(r&&l())})(),d={runtimeKey:a,promise:u};n=d;const f=()=>{n===d&&(n=null)};return u.then(f,f),u},resync:()=>(n?.runtimeKey===$()&&(r=!0),t().hydrate()),applyServerSession:o,setServerHold:async(a,c)=>{if(!bt())return;const l=await g(`${wt(a)}/hold`,yt("PUT",{held:c}));if(!l.ok)throw new Error(`Message queue hold request failed (${l.status})`)},resetForRuntimeSwitch:a=>{if(as+=1,n=null,r=!1,a){Lr.delete(a);for(const c of Xe.keys())$t(c)?.runtimeKey===a&&Xe.delete(c)}!a||!is.has(a)||e(c=>{const l={},u={};for(const[d,f]of Object.entries(c.queuedMessages))$t(d)?.runtimeKey===a?Xe.delete(d):l[d]=f;for(const[d,f]of Object.entries(c.sendingIds))$t(d)?.runtimeKey!==a&&(u[d]=f);return{queuedMessages:l,sendingIds:u}})}}},{name:"message-queue-store",version:3,storage:di(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=$t(t)?.runtimeKey;return!n||!is.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:vm}),{name:"message-queue-store"})),Em=I({type:H("aiworker:message-queue.updated"),properties:I({revision:C(),session:bi})}),pT=(e,t)=>{if(!bt())return;const n=Em.safeParse(e);if(!n.success)return;const{session:r,revision:o}=n.data.properties;Ls.getState().applyServerSession(r,o,t)},Am=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,"_")}`},_=e=>t=>{const n=e.safeParse(t);return n.success?n.data:void 0},Cn=C().refine(Number.isFinite),_e=w().transform(e=>e.trim()),Se=_e.pipe(w().min(1)),Rt=qt(w(),fe()),A=_(Xt()),Ne=_(w().min(1)),hn=_(_e),un=_(Se),za=e=>_(w().max(e)),Bn=e=>_(_e.transform(t=>t.slice(0,e))),Z=e=>_(_e.pipe(ke(e))),Ut=_(Cn),Pm=(e,t)=>_(Cn.transform(n=>Math.max(e,Math.min(t,Math.round(n))))),cs=e=>_(Cn.transform(t=>Math.max(e,Math.round(t)))),Im=_(Cn.positive().transform(Math.floor)),xm=_(Jt([tr(),Cn])),Rm=_(Jt([tr(),_e.transform(e=>e.length>0?e:null)])),Cm=_(Jt([tr(),_e])),Ti=G(fe()).transform(e=>e.filter(t=>w().min(1).safeParse(t).success)),jr=_(Ti.transform(e=>Array.from(new Set(e.map(String))))),$a=_(Ti.transform(e=>e.map(String))),Dm=Rt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const o=G(fe()).safeParse(r);o.success&&(t[n]=o.data.filter(s=>w().safeParse(s).success).map(String))}return t}),ls=_(Dm.pipe(qt(w(),G(w())).refine(e=>Object.keys(e).length>0))),Om=I({providerID:Se,modelID:Se}),us=e=>_(G(fe()).transform(t=>{const n=[],r=new Set;for(const o of t){const s=Om.safeParse(o);if(!s.success)continue;const i=`${s.data.providerID}/${s.data.modelID}`;if(!r.has(i)&&(r.add(i),n.push(s.data),n.length>=e))break}return n})),Mm=_(Rt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){if(!n)continue;const o=Ti.safeParse(r);if(!o.success)continue;const s=Array.from(new Set(o.data.map(String)));s.length>0&&(t[n]=s.slice(0,5))}return t}).refine(e=>Object.keys(e).length>0)),_m=_(Rt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=Se.safeParse(r);!o||!s.success||(t[o]=s.data)}return t})),Ur={completion:{title:"Task Complete",message:"Your task has finished."},error:{title:"Error Occurred",message:"An error occurred while processing your task."},question:{title:"Input Needed",message:"Please provide input to continue."},subtask:{title:"Subtask Complete",message:"A subtask has finished."}},Lm=I({title:w().catch(""),message:w().catch("")}),Fm=_(Rt.transform(e=>{const t=i=>{const a=Lm.safeParse(e[i]);return a.success?a.data:void 0},n=t("completion"),r=t("error"),o=t("question"),s=t("subtask");if(!(!n&&!r&&!o&&!s))return{completion:n??Ur.completion,error:r??Ur.error,question:o??Ur.question,subtask:s??Ur.subtask}}).pipe(hc(e=>e!==void 0))),Wa=Rt.transform(e=>Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{const r=w().safeParse(n);return r.success?[[t,r.data]]:[]}))),jm=I({id:fe().transform(e=>String(e??"")),label:fe().transform(e=>String(e??"")),models:G(fe()).transform(e=>e.filter(t=>w().safeParse(t).success).map(String)).catch([]),order:C().catch(0)}),Um=_(Rt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const o=Rt.safeParse(r);if(!o.success)continue;const s={},i=G(fe()).safeParse(o.data.customGroups);i.success&&(s.customGroups=i.data.flatMap(l=>{const u=jm.safeParse(l);return u.success?[u.data]:[]}));const a=Wa.safeParse(o.data.modelAssignments);a.success&&(s.modelAssignments=a.data);const c=Wa.safeParse(o.data.renamedGroups);c.success&&(s.renamedGroups=c.data),Object.keys(s).length>0&&(t[n]=s)}return t}).refine(e=>Object.keys(e).length>0)),Nm=I({id:Se,name:Se,hostname:Se.transform(e=>e.toLowerCase())}),Bm=_(G(fe()).transform(e=>{const t=[],n=new Set,r=new Set;for(const o of e){const s=Nm.safeParse(o);s.success&&(n.has(s.data.id)||r.has(s.data.hostname)||(n.add(s.data.id),r.add(s.data.hostname),t.push(s.data)))}return t})),Hm=_(Rt.transform(e=>{const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=Se.safeParse(r);!o||!s.success||(t[o]=s.data)}return t}).refine(e=>Object.keys(e).length>0)),zm=I({id:Se,label:Se,source:Se,subpath:_e.optional().catch(void 0),gitIdentityId:_e.optional().catch(void 0)}),$m=_(G(fe()).transform(e=>{const t=[],n=new Set;for(const r of e){const o=zm.safeParse(r);if(!o.success||n.has(o.data.id))continue;n.add(o.data.id);const s={id:o.data.id,label:o.data.label,source:o.data.source};o.data.subpath&&(s.subpath=o.data.subpath),o.data.gitIdentityId&&(s.gitIdentityId=o.data.gitIdentityId),t.push(s)}return t})),Wm=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,ds=Cn.nonnegative(),Km=I({path:Se,label:Se.optional().catch(void 0),icon:Se.optional().catch(void 0),iconImage:Jt([tr(),I({mime:Se,updatedAt:ds.transform(Math.round).pipe(C().positive()),source:ke(["custom","auto"])})]).optional().catch(void 0),color:Se.optional().catch(void 0),iconBackground:Jt([tr(),_e.pipe(w().regex(Wm)).transform(e=>e.toLowerCase())]).optional().catch(void 0),addedAt:ds.optional().catch(void 0),lastOpenedAt:ds.optional().catch(void 0),sidebarCollapsed:Xt().optional().catch(void 0)}),Gm=_(G(fe()).transform(e=>{const t=[],n=new Set,r=new Set;for(const o of e){const s=Km.safeParse(o);if(!s.success)continue;const i=s.data.path,a=i==="/"?i:i.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=Am(a);if(!c||n.has(c)||r.has(a))continue;n.add(c),r.add(a);const l={id:c,path:a};s.data.label&&(l.label=s.data.label),s.data.icon&&(l.icon=s.data.icon),s.data.iconImage!==void 0&&(l.iconImage=s.data.iconImage),s.data.color&&(l.color=s.data.color),s.data.iconBackground!==void 0&&(l.iconBackground=s.data.iconBackground),s.data.addedAt!==void 0&&(l.addedAt=s.data.addedAt),s.data.lastOpenedAt!==void 0&&(l.lastOpenedAt=s.data.lastOpenedAt),s.data.sidebarCollapsed!==void 0&&(l.sidebarCollapsed=s.data.sidebarCollapsed),t.push(l)}return t}).refine(e=>e.length>0)),qm=ke(["steer","queue"]),Jm=(e,t)=>{const n=qm.safeParse(e);if(n.success)return n.data;if(e==="immediate")return"steer";const r=Xt().safeParse(t.queueModeEnabled);if(r.success)return r.data?"queue":"steer"},Vm=_(_e.pipe(ke(["local","openai-compatible","server","browser","wasm"])).transform(e=>e==="server"?"openai-compatible":e==="browser"||e==="wasm"?"local":e)),Ym=_(_e.pipe(ke(["left","right","auto"])).transform(e=>e==="left"?"left":"right")),Qm=_(_e.transform(e=>e.replace(/\s+/g," ").slice(0,64))),Xm=e=>_(G(fe()).transform(t=>{const n=[];for(const r of t){const o=_e.transform(s=>s.toLowerCase()).safeParse(r);o.success&&e(o.data)&&!n.includes(o.data)&&n.push(o.data)}return n})),vi=e=>_(hc(e)),Ro=(e,t)=>(n,r)=>{const o=e(n,r);return o===void 0?void 0:t(o)},p=e=>e,b=(e,t,n={})=>({read:()=>T.getState()[e],write:t,autoSave:n.autoSave??!0}),Nt=e=>t=>{T.setState({[e]:t})},Ka=()=>globalThis.window?.__zustand_config_store__??null,Bt=e=>({read:()=>Ka()?.getState()[e],write:t=>{Ka()?.setState({[e]:t})},autoSave:!1}),Nr=e=>({read:()=>Ps.getState()[e],write:t=>{Ps.setState({[e]:t})},autoSave:!1}),Zm=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer","custom"],eg=vi(mi),tg=vi(Bp),ng=vi(Hp),rg=_(w().refine(Ul)),og=_(C().refine(hi)),sg=Ro(hn,e=>xo(e,void 0)),ig=Ro(_(G(fe())),Mh),ag=Ro(_(G(fe())),e=>Bl(e)),cg=Z(["ask","attach","inline"]),lg=Z(["default","vim"]),ug=(e,t)=>{let n=e;const r=(o,s)=>{if(n.some(c=>c.type==="command"&&c.name===o))return;const i=n.findIndex(c=>c.type==="command"&&c.name===s),a=i>=0?i+1:n.length;n=[...n.slice(0,a),{type:"command",name:o},...n.slice(a)]};return t.draftStartersCraftGoalAdded!==!0&&r("craft-goal","plan-feature"),t.draftStartersScheduleTaskAdded!==!0&&r("schedule-task","craft-goal"),n},hr={themeId:p({scope:"profile",perSurface:!0,parse:Ne}),useSystemTheme:p({scope:"profile",perSurface:!0,parse:A}),themeVariant:p({scope:"profile",derived:!0,parse:Z(["light","dark"])}),lightThemeId:p({scope:"profile",perSurface:!0,parse:Ne}),darkThemeId:p({scope:"profile",perSurface:!0,parse:Ne}),lastDirectory:p({scope:"instance",adopt:"bootstrap-only",parse:Ne}),homeDirectory:p({scope:"instance",parse:Ne}),opencodeBinary:p({scope:"instance",parse:hn}),projects:p({scope:"instance",parse:Gm}),activeProjectId:p({scope:"instance",adopt:"bootstrap-only",parse:Ne}),securityScopedBookmarks:p({scope:"instance",surfaces:["desktop"],parse:$a}),pinnedDirectories:p({scope:"instance",parse:jr}),desktopLanAccessEnabled:p({scope:"instance",surfaces:["desktop"],parse:A}),desktopKeepAwakeEnabled:p({scope:"instance",surfaces:["desktop"],parse:A}),desktopMinimizeToTrayEnabled:p({scope:"instance",surfaces:["desktop"],parse:A}),desktopMacMenuBarEnabled:p({scope:"instance",surfaces:["desktop"],parse:A}),desktopUiPassword:p({scope:"instance",secret:!0,surfaces:["desktop"],parse:hn}),hasDesktopUiPassword:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessActive:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:A}),desktopLanAccessBlockedReason:p({scope:"instance",computed:!0,surfaces:["desktop"],parse:hn}),githubClientId:p({scope:"instance",parse:un}),githubScopes:p({scope:"instance",parse:un}),skillCatalogs:p({scope:"instance",parse:$m}),defaultGitIdentityId:p({scope:"instance",parse:hn}),permissionAutoAccept:p({scope:"instance",parse:_(I({sessions:qt(w().min(1),Xt()).catch({}),revision:C().int().nonnegative().catch(0)}))}),agentControlToolEnabled:p({scope:"instance",parse:A,ui:b("agentControlToolEnabled",e=>T.getState().setAgentControlToolEnabled(e))}),agentWebToolEnabled:p({scope:"instance",parse:A,ui:b("agentWebToolEnabled",e=>T.getState().setAgentWebToolEnabled(e))}),agentMemoryToolEnabled:p({scope:"instance",parse:A,ui:b("agentMemoryToolEnabled",e=>T.getState().setAgentMemoryToolEnabled(e))}),agentMemoryFeatureAvailable:p({scope:"instance",computed:!0,parse:A,ui:b("agentMemoryFeatureAvailable",e=>T.getState().setAgentMemoryFeatureAvailable(e),{autoSave:!1})}),openCodeUpdateToastDismissedVersion:p({scope:"instance",parse:Bn(128)}),autoDeleteEnabled:p({scope:"instance",parse:A,ui:b("autoDeleteEnabled",e=>T.getState().setAutoDeleteEnabled(e))}),autoDeleteAfterDays:p({scope:"instance",parse:Pm(1,365),ui:b("autoDeleteAfterDays",e=>T.getState().setAutoDeleteAfterDays(e))}),sessionRetentionOnlyArchived:p({scope:"instance",parse:A,ui:b("sessionRetentionOnlyArchived",e=>T.getState().setSessionRetentionOnlyArchived(e))}),sessionRetentionAction:p({scope:"instance",parse:Z(["archive","delete"]),ui:b("sessionRetentionAction",e=>T.getState().setSessionRetentionAction(e))}),terminalShell:p({scope:"instance",parse:eg,ui:b("terminalShell",e=>T.getState().setTerminalShell(e))}),terminalLoginShells:p({scope:"instance",parse:Xm(mi),ui:b("terminalLoginShells",e=>T.getState().setTerminalLoginShells(e))}),openInAppId:p({scope:"instance",parse:un}),dictationEnabled:p({scope:"profile",parse:A,ui:Bt("dictationEnabled")}),sttProvider:p({scope:"instance",parse:Vm,ui:Bt("sttProvider")}),sttServerUrl:p({scope:"instance",parse:Bn(2048),ui:Bt("sttServerUrl")}),sttModel:p({scope:"instance",parse:Bn(256),ui:Bt("sttModel")}),sttLocalModel:p({scope:"instance",parse:Bn(256),ui:Bt("sttLocalModel")}),sttLanguage:p({scope:"profile",parse:Bn(64),ui:Bt("sttLanguage")}),tunnelProvider:p({scope:"instance",parse:Ro(un,e=>e.toLowerCase())}),tunnelMode:p({scope:"instance",parse:_(w().transform(e=>e.trim().toLowerCase()).pipe(ke(["quick","managed-remote","managed-local"])))}),tunnelBootstrapTtlMs:p({scope:"instance",parse:xm}),tunnelSessionTtlMs:p({scope:"instance",parse:Ut}),managedLocalTunnelConfigPath:p({scope:"instance",parse:Rm}),managedRemoteTunnelHostname:p({scope:"instance",parse:hn}),managedRemoteTunnelToken:p({scope:"instance",secret:!0,parse:Cm}),hasManagedRemoteTunnelToken:p({scope:"instance",computed:!0,parse:A}),managedRemoteTunnelPresets:p({scope:"instance",parse:Bm}),managedRemoteTunnelSelectedPresetId:p({scope:"instance",parse:un}),managedRemoteTunnelPresetTokens:p({scope:"instance",secret:!0,parse:Hm}),sidebarProjectDisplayMode:p({scope:"profile",parse:Z(["all","single"]),ui:Nr("projectDisplayMode")}),sidebarSessionGroupingMode:p({scope:"profile",parse:Z(["by-worktree","flat"]),ui:Nr("sessionGroupingMode")}),sidebarProjectSortOrder:p({scope:"profile",parse:Z(["manual","a-z","z-a","date-added","recent"]),ui:Nr("projectSortOrder")}),sidebarShowRecentSection:p({scope:"profile",parse:A,ui:Nr("showRecentSection")}),workStatusPanelEnabled:p({scope:"profile",parse:A,ui:b("workStatusPanelEnabled",e=>T.getState().setWorkStatusPanelEnabled(e))}),workStatusHiddenSections:p({scope:"profile",parse:ag,ui:{read:()=>T.getState().workStatusHiddenSections,write:(e,t)=>{const n=t.workStatusHiddenSectionsExplicit===!0;T.setState({workStatusHiddenSections:Bl(e,n),workStatusHiddenSectionsExplicit:n})},autoSave:!0}}),workStatusHiddenSectionsExplicit:p({scope:"profile",parse:A,ui:b("workStatusHiddenSectionsExplicit",()=>{})}),showReasoningTraces:p({scope:"profile",parse:A,ui:b("showReasoningTraces",e=>T.getState().setShowReasoningTraces(e))}),streamingAutoFollowEnabled:p({scope:"profile",perSurface:!0,parse:A,ui:b("streamingAutoFollowEnabled",e=>T.getState().setStreamingAutoFollowEnabled(e))}),collapsibleThinkingBlocks:p({scope:"profile",parse:A,ui:b("collapsibleThinkingBlocks",e=>T.getState().setCollapsibleThinkingBlocks(e))}),showTextJustificationActivity:p({scope:"profile",parse:A}),chatRenderMode:p({scope:"profile",parse:Z(["sorted","live"]),ui:b("chatRenderMode",e=>T.getState().setChatRenderMode(e))}),activityRenderMode:p({scope:"profile",parse:Z(["collapsed","summary"]),ui:b("activityRenderMode",e=>T.getState().setActivityRenderMode(e))}),mermaidRenderingMode:p({scope:"profile",parse:Z(["svg","ascii"]),ui:b("mermaidRenderingMode",e=>T.getState().setMermaidRenderingMode(e))}),userMessageRenderingMode:p({scope:"profile",parse:Z(["markdown","plain"]),ui:b("userMessageRenderingMode",e=>T.getState().setUserMessageRenderingMode(e))}),collapsibleUserMessages:p({scope:"profile",parse:A,ui:b("collapsibleUserMessages",e=>T.getState().setCollapsibleUserMessages(e))}),stickyUserHeader:p({scope:"profile",perSurface:!0,parse:A,ui:b("stickyUserHeader",e=>T.getState().setStickyUserHeader(e))}),promptNavigatorEnabled:p({scope:"profile",perSurface:!0,parse:A,ui:b("promptNavigatorEnabled",e=>T.getState().setPromptNavigatorEnabled(e))}),wideChatLayoutEnabled:p({scope:"profile",perSurface:!0,parse:A,ui:b("wideChatLayoutEnabled",e=>T.getState().setWideChatLayoutEnabled(e))}),showSplitAssistantMessageActions:p({scope:"profile",parse:A,ui:b("showSplitAssistantMessageActions",e=>T.getState().setShowSplitAssistantMessageActions(e))}),showToolFileIcons:p({scope:"profile",parse:A,ui:b("showToolFileIcons",e=>T.getState().setShowToolFileIcons(e))}),codeBlockLineWrap:p({scope:"profile",parse:A,ui:b("codeBlockLineWrap",e=>T.getState().setCodeBlockLineWrap(e))}),showTurnChangedFiles:p({scope:"profile",parse:A,ui:b("showTurnChangedFiles",e=>T.getState().setShowTurnChangedFiles(e))}),showExpandedBashTools:p({scope:"profile",parse:A,ui:b("showExpandedBashTools",e=>T.getState().setShowExpandedBashTools(e))}),showExpandedEditTools:p({scope:"profile",parse:A,ui:b("showExpandedEditTools",e=>T.getState().setShowExpandedEditTools(e))}),toolJsonViewMode:p({scope:"profile",parse:Z(["summary","formatted","raw"]),ui:b("toolJsonViewMode",e=>T.getState().setToolJsonViewMode(e))}),timeFormatPreference:p({scope:"profile",parse:Z(["auto","12h","24h"]),ui:b("timeFormatPreference",e=>T.getState().setTimeFormatPreference(e))}),weekStartPreference:p({scope:"profile",parse:Z(["auto","sunday","monday"]),ui:b("weekStartPreference",e=>T.getState().setWeekStartPreference(e))}),messageStreamTransport:p({scope:"profile",parse:Z(["auto","ws","sse"]),ui:Bt("settingsMessageStreamTransport")}),diffLayoutPreference:p({scope:"profile",parse:Z(["dynamic","inline","side-by-side"]),ui:b("diffLayoutPreference",e=>T.getState().setDiffLayoutPreference(e))}),diffWrapLines:p({scope:"profile",parse:A,ui:b("diffWrapLines",e=>T.getState().setDiffWrapLines(e))}),gitChangesViewMode:p({scope:"profile",parse:Z(["flat","tree"]),ui:b("gitChangesViewMode",e=>T.getState().setGitChangesViewMode(e))}),gitmojiEnabled:p({scope:"profile",parse:A}),defaultFileViewerPreview:p({scope:"profile",parse:A}),directoryShowHidden:p({scope:"profile",parse:A,ui:{read:Ch,write:e=>Dh(e,{persist:!1}),autoSave:!1}}),filesViewShowGitignored:p({scope:"profile",parse:A,ui:{read:Lh,write:e=>Fh(e,{persist:!1}),autoSave:!1}}),fileEditorKeymap:p({scope:"profile",parse:lg,ui:b("fileEditorKeymap",e=>T.getState().setFileEditorKeymap(e))}),autoSaveEnabled:p({scope:"profile",parse:A,ui:b("autoSaveEnabled",e=>T.getState().setAutoSaveEnabled(e))}),autoCreateWorktree:p({scope:"profile",parse:A}),sessionTabsEnabled:p({scope:"profile",surfaces:["web","desktop","vscode"],parse:A,ui:b("sessionTabsEnabled",e=>T.getState().setSessionTabsEnabled(e))}),showOpenCodeRestartConfirm:p({scope:"profile",parse:A,ui:b("showOpenCodeRestartConfirm",e=>T.getState().setShowOpenCodeRestartConfirm(e))}),allowPromptingSubagentSessions:p({scope:"profile",parse:A,ui:b("allowPromptingSubagentSessions",e=>T.getState().setAllowPromptingSubagentSessions(e))}),inputSpellcheckEnabled:p({scope:"profile",parse:A,ui:b("inputSpellcheckEnabled",e=>T.getState().setInputSpellcheckEnabled(e))}),enterToSend:p({scope:"profile",parse:A,ui:b("enterToSend",e=>T.getState().setEnterToSend(e))}),enterToSendConfigured:p({scope:"profile",parse:A,ui:b("enterToSendConfigured",e=>T.getState().setEnterToSendConfigured(e))}),persistChatDraft:p({scope:"profile",parse:A,ui:b("persistChatDraft",e=>T.getState().setPersistChatDraft(e))}),largeTextPasteBehavior:p({scope:"profile",parse:cg,ui:b("largeTextPasteBehavior",e=>T.getState().setLargeTextPasteBehavior(e))}),followUpBehavior:p({scope:"profile",parse:Jm,ui:{read:()=>Ls.getState().followUpBehavior,write:e=>Ls.getState().setFollowUpBehavior(e),autoSave:!1}}),queueModeEnabled:p({scope:"profile",parse:A}),inputHistoryScope:p({scope:"profile",parse:rg,ui:{read:()=>Kn.getState().scope,write:e=>Kn.getState().applyScope(e),autoSave:!1}}),inputHistoryLimit:p({scope:"profile",parse:og,ui:{read:()=>Kn.getState().entryLimit,write:e=>Kn.getState().applyEntryLimit(e),autoSave:!1}}),draftStarters:p({scope:"profile",parse:ig,ui:{read:()=>T.getState().globalDraftStarters??void 0,write:(e,t)=>T.getState().setGlobalDraftStarters(ug(e,t)),autoSave:!1}}),draftStartersVisible:p({scope:"profile",parse:A,ui:b("draftStartersVisible",e=>T.getState().setDraftStartersVisible(e))}),draftStartersCraftGoalAdded:p({scope:"profile",parse:A}),draftStartersScheduleTaskAdded:p({scope:"profile",parse:A}),fontSize:p({scope:"profile",perSurface:!0,parse:Ut,ui:b("fontSize",e=>T.getState().setFontSize(e))}),terminalFontSize:p({scope:"profile",perSurface:!0,parse:Ut,ui:b("terminalFontSize",e=>T.getState().setTerminalFontSize(e))}),editorFontSize:p({scope:"profile",perSurface:!0,parse:Ut,ui:b("editorFontSize",e=>T.getState().setEditorFontSize(e))}),uiFont:p({scope:"profile",parse:tg,ui:b("uiFont",e=>T.getState().setUiFont(e))}),monoFont:p({scope:"profile",parse:ng,ui:b("monoFont",e=>T.getState().setMonoFont(e))}),padding:p({scope:"profile",perSurface:!0,parse:Ut,ui:b("padding",e=>T.getState().setPadding(e))}),cornerRadius:p({scope:"profile",perSurface:!0,parse:Ut,ui:b("cornerRadius",e=>T.getState().setCornerRadius(e))}),shortcutOverrides:p({scope:"profile",parse:_m,ui:b("shortcutOverrides",Nt("shortcutOverrides"))}),defaultModel:p({scope:"profile",parse:Ne}),defaultVariant:p({scope:"profile",parse:Ne}),defaultAgent:p({scope:"profile",parse:Ne}),smallModelUseDefault:p({scope:"profile",parse:A}),smallModelOverride:p({scope:"profile",parse:Ne}),walkthroughModelOverride:p({scope:"profile",parse:Ne}),zenModel:p({scope:"profile",parse:un}),favoriteModels:p({scope:"profile",parse:us(64),ui:b("favoriteModels",Nt("favoriteModels"),{autoSave:!1})}),hiddenModels:p({scope:"profile",parse:us(1024),ui:b("hiddenModels",Nt("hiddenModels"),{autoSave:!1})}),collapsedModelProviders:p({scope:"profile",parse:jr,ui:b("collapsedModelProviders",Nt("collapsedModelProviders"),{autoSave:!1})}),recentModels:p({scope:"profile",parse:us(16),ui:b("recentModels",Nt("recentModels"),{autoSave:!1})}),recentAgents:p({scope:"profile",parse:jr,ui:b("recentAgents",Nt("recentAgents"),{autoSave:!1})}),recentEfforts:p({scope:"profile",parse:Mm,ui:b("recentEfforts",Nt("recentEfforts"),{autoSave:!1})}),providerOrder:p({scope:"profile",parse:jr,ui:b("providerOrder",e=>T.getState().setProviderOrder(e))}),sessionRecapEnabled:p({scope:"profile",parse:A,ui:b("sessionRecapEnabled",e=>T.getState().setSessionRecapEnabled(e))}),sessionSuggestionEnabled:p({scope:"profile",parse:A,ui:b("sessionSuggestionEnabled",e=>T.getState().setSessionSuggestionEnabled(e))}),sessionGoalEnabled:p({scope:"profile",parse:A,ui:b("sessionGoalEnabled",e=>T.getState().setSessionGoalEnabled(e))}),sessionGoalDefaultBudgetEnabled:p({scope:"profile",parse:A,ui:b("sessionGoalDefaultBudgetEnabled",e=>T.getState().setSessionGoalDefaultBudgetEnabled(e))}),sessionGoalDefaultBudget:p({scope:"profile",parse:Im,ui:b("sessionGoalDefaultBudget",e=>T.getState().setSessionGoalDefaultBudget(e))}),summarizeLastMessage:p({scope:"profile",parse:A,ui:b("summarizeLastMessage",e=>T.getState().setSummarizeLastMessage(e))}),summaryThreshold:p({scope:"profile",parse:cs(0),ui:b("summaryThreshold",e=>T.getState().setSummaryThreshold(e))}),summaryLength:p({scope:"profile",parse:cs(10),ui:b("summaryLength",e=>T.getState().setSummaryLength(e))}),maxLastMessageLength:p({scope:"profile",parse:cs(10),ui:b("maxLastMessageLength",e=>T.getState().setMaxLastMessageLength(e))}),showDeletionDialog:p({scope:"profile",parse:A,ui:b("showDeletionDialog",e=>T.getState().setShowDeletionDialog(e))}),nativeNotificationsEnabled:p({scope:"profile",parse:A,ui:b("nativeNotificationsEnabled",e=>T.getState().setNativeNotificationsEnabled(e))}),notificationMode:p({scope:"profile",parse:Z(["always","hidden-only"]),ui:b("notificationMode",e=>T.getState().setNotificationMode(e))}),notifyOnSubtasks:p({scope:"profile",parse:A,ui:b("notifyOnSubtasks",e=>T.getState().setNotifyOnSubtasks(e))}),notifyOnCompletion:p({scope:"profile",parse:A,ui:b("notifyOnCompletion",e=>T.getState().setNotifyOnCompletion(e))}),notifyOnError:p({scope:"profile",parse:A,ui:b("notifyOnError",e=>T.getState().setNotifyOnError(e))}),notifyOnQuestion:p({scope:"profile",parse:A,ui:b("notifyOnQuestion",e=>T.getState().setNotifyOnQuestion(e))}),notificationTemplates:p({scope:"profile",parse:Fm,ui:b("notificationTemplates",e=>T.getState().setNotificationTemplates(e))}),showOpenCodeUpdateNotifications:p({scope:"profile",parse:A,ui:b("showOpenCodeUpdateNotifications",e=>T.getState().setShowOpenCodeUpdateNotifications(e))}),reportUsage:p({scope:"profile",parse:A,ui:b("reportUsage",e=>T.getState().setReportUsage(e))}),usageDisplayMode:p({scope:"profile",parse:Z(["usage","remaining"])}),usageDropdownProviders:p({scope:"profile",parse:$a}),usageSelectedModels:p({scope:"profile",parse:ls}),usageCollapsedFamilies:p({scope:"profile",parse:ls}),usageExpandedFamilies:p({scope:"profile",parse:ls}),usageModelGroups:p({scope:"profile",parse:Um}),globalBehaviorPrompt:p({scope:"profile",parse:za(1024*1024)}),responseStyleEnabled:p({scope:"profile",parse:A}),responseStylePreset:p({scope:"profile",parse:Z(Zm)}),responseStyleCustomInstructions:p({scope:"profile",parse:za(5e4)}),optimizeSystemPrompt:p({scope:"profile",parse:A}),pwaAppName:p({scope:"instance",surfaces:["web"],parse:Qm}),pwaOrientation:p({scope:"instance",surfaces:["web"],parse:Z(["system","portrait","landscape"])}),mobileKeyboardMode:p({scope:"device",surfaces:["mobile"],parse:sg,ui:b("mobileKeyboardMode",e=>T.getState().setMobileKeyboardMode(e))}),desktopWindowControlsPosition:p({scope:"device",surfaces:["desktop"],parse:Ym,ui:b("desktopWindowControlsPosition",e=>T.getState().setDesktopWindowControlsPosition(e))}),desktopWindowControlsStyle:p({scope:"device",surfaces:["desktop"],parse:Z(["classic","traffic-lights"]),ui:b("desktopWindowControlsStyle",e=>T.getState().setDesktopWindowControlsStyle(e))}),inputBarOffset:p({scope:"device",surfaces:["mobile","web"],parse:Ut,ui:b("inputBarOffset",e=>T.getState().setInputBarOffset(e))})},dg=e=>Object.prototype.hasOwnProperty.call(hr,e),mr=Object.keys(hr).filter(dg),Jl=e=>hr[e].scope==="device",gr=e=>hr[e],fg=e=>!hr[e].computed&&!Jl(e),pg=qt(w(),fe()),hg=e=>{const t=pg.safeParse(e);if(!t.success)return null;const n=t.data,r={};for(const o of mr){const i=gr(o).parse(n[o],n);i!==void 0&&Object.assign(r,{[o]:i})}return r},mg=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),gg=e=>{for(const t of mr){const n=gr(t);if(!n.ui)continue;const r=e[t];r!==void 0&&(mg(n.ui.read(),r)||n.ui.write(r,e))}},yg=mr.filter(e=>gr(e).ui?.autoSave===!0),hT=()=>{const e={};for(const t of yg){const r=gr(t).ui?.read();r!==void 0&&Object.assign(e,{[t]:r})}return e},wg=mr.filter(e=>{const t=gr(e);return t.scope!=="device"&&!t.secret&&!t.computed}),Sg=768,bg=800,Tg=()=>{if(typeof window>"u")return!1;const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches||window.matchMedia("(hover: none)").matches:!1,t=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return e||t>0},vg=()=>{if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search).get("surface");return e==="mobile"||e==="desktop"},Vl=()=>{if(typeof window>"u")return!1;const e=Math.min(window.innerWidth||Number.POSITIVE_INFINITY,window.screen?.width||Number.POSITIVE_INFINITY);return Number.isFinite(e)&&e<=Sg&&Tg()},Yl=()=>{if(typeof window>"u")return"desktop";const e=window.__AIWORKER_SURFACE__;if(e==="mobile"||e==="desktop")return e;const t=new URLSearchParams(window.location.search).get("surface");return t==="mobile"||t==="desktop"?t:dr()?"mobile":qe()||Me()?"desktop":Vl()?"mobile":"desktop"},mT=()=>{const e=Yl();return typeof window<"u"&&(window.__AIWORKER_SURFACE__=e),e},kg=()=>Yl()==="mobile",gT=()=>{if(typeof window>"u")return()=>{};if(dr()||qe()||Me())return()=>{};if(vg())return()=>{};let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null;const n=window.__AIWORKER_SURFACE__,r=Vl()?"mobile":"desktop";n&&n!==r&&(window.__AIWORKER_SURFACE__=void 0,window.location.reload())},bg)};return window.addEventListener("resize",t),()=>{e&&clearTimeout(e),window.removeEventListener("resize",t)}},Ql="surface",Xl=()=>{try{if(Me())return"vscode";if(qe())return"desktop";if(dr()||kg())return"mobile"}catch{}return"web"},Eg=e=>{if(!(typeof window>"u")&&!(typeof window.__AIWORKER_HOME__=="string"&&window.__AIWORKER_HOME__.length>0))try{window.__AIWORKER_HOME__=e}catch{}},Ga="aiworker.settingsMirror.v2.index",Ag="aiworker.deviceSeeded.v1:",Pg=e=>`${Ag}${encodeURIComponent(e)}`,Ig=(e,t)=>{const n=Pg(t);let r=!1;try{r=localStorage.getItem(n)===null,r&&localStorage.setItem(n,String(Date.now()))}catch{r=!1}if(r)return e;const o={};for(const s of mr)e[s]===void 0||Jl(s)||Object.assign(o,{[s]:e[s]});return o},xg="aiworker.settingsMirror.v2:",Rg=5,qa=e=>`${xg}${encodeURIComponent(e)}`,dn=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Cg=(e,t)=>{const n={};for(const s of wg)e[s]!==void 0&&Object.assign(n,{[s]:e[s]});localStorage.setItem(qa(t),JSON.stringify(n));let r=[];try{const s=JSON.parse(localStorage.getItem(Ga)??"[]");Array.isArray(s)&&(r=s.filter(i=>typeof i=="string"))}catch{r=[]}const o=[t,...r.filter(s=>s!==t)].slice(0,Rg);for(const s of r)o.includes(s)||localStorage.removeItem(qa(s));localStorage.setItem(Ga,JSON.stringify(o))},Dg=e=>{if(!(typeof window>"u")){if(Cg(e,$()),dn("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),Eg(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"),dn("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("aiworker.pwaName",t):localStorage.removeItem("aiworker.pwaName")}else localStorage.removeItem("aiworker.pwaName");if(vl(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"),dn("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),dn("sttModel",typeof e.sttModel=="string"?e.sttModel:null),dn("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),dn("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},Fs=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("aiworker:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let js="idle",Br=null;const Us=new Set,yT=()=>js,wT=e=>(Us.add(e),()=>Us.delete(e)),ST=e=>{et(e)},et=e=>{Br&&(clearTimeout(Br),Br=null);const t=e==="saved"?"idle":e;t!==js&&(js=t,Us.forEach(n=>n())),t==="error"&&(Br=setTimeout(()=>et("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("aiworker:settings-save-state",{detail:e}))},Zl=()=>{const e=T.persist;if(e&&typeof e=="object")return e},eu=()=>ko()?.settings??null,tu=()=>`/api/config/settings?${Ql}=${Xl()}`,Og=e=>{gg(e)},mo=e=>hg(e);class Mg{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 ki=0,At=null,An={},Ns=!1;const bT=()=>Ns,Bs=e=>{Ns=!0;try{Og(e)}finally{Ns=!1}};let Wt=null,Ge=null,nt=null,Pe=null,Zn=[],Ja=!1,go=0,Vr=[];const Oe=new Mg,_g=2e3,Lg=200,Ei=()=>({runtimeKey:$(),generation:ki}),Co=e=>Object.keys(e),nu=(e,t)=>e===t?!0:e===void 0||t===void 0?!1:JSON.stringify(e)===JSON.stringify(t),Yr=e=>{An={...An,...e}},Fg=e=>{const t={...An};for(const n of e)delete t[n];An=t},jg=e=>{const t={};for(const n of Co(e))nu(e[n],An[n])||Object.assign(t,{[n]:e[n]});return t},cr=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,ru=e=>{let t=null;for(const n of Vr)cr(n.context,e)&&(t={...t??{},...n.changes});return Ge&&nt&&cr(nt,e)&&(t={...t??{},...Ge}),t},Va=(e,t)=>{const n=ru(t);return e&&n?{...e,...n}:e},de=e=>e.generation===ki&&e.runtimeKey===$(),Hn=()=>{Ge&&(Pe&&(clearTimeout(Pe),Pe=null),yo({keepalive:!0}))},Ai=()=>{if(!(Ja||typeof window>"u")){Ja=!0,xd(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Pe&&clearTimeout(Pe),Ge&&yo())}),jc(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ki+=1,Oe.reset(),go=0,At=null,Wt=null,An={})});try{window.addEventListener("pagehide",Hn,{capture:!0}),window.addEventListener("beforeunload",Hn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Hn()}),document.addEventListener("freeze",Hn)),dr()&&Ys(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||Hn()})).catch(()=>{})}catch{}}},ou=async(e=Ei())=>{if(Ai(),At&&cr(At.context,e)&&Date.now()-At.at<_g)return Va(At.value,e);if(Wt&&cr(Wt.context,e))return Wt.promise;const t=Oe.begin(),n=ru(e),r=s=>{if(!de(e)||!s)return null;const i=Va(Oe.reconcile({...s,...n},t),e);At={value:i,at:Date.now(),context:e};const a={};for(const c of Co(s))nu(s[c],i?.[c])&&Object.assign(a,{[c]:s[c]});return Yr(a),i},o={context:e,promise:(async()=>{const s=eu();if(s)try{const i=await s.load();if(!de(e))return null;const a=mo(i.settings);return r(a)}catch(i){if(!de(e))return null;console.warn("Failed to load shared settings from runtime settings API:",i)}if(!de(e))return null;try{const i=await g(tu(),{method:"GET",headers:{Accept:"application/json"}});if(!de(e)||!i.ok)return null;const a=await i.json().catch(()=>null);if(!de(e))return null;const c=mo(a);return r(c)}catch(i){return de(e)&&console.warn("Failed to load shared settings from server:",i),null}})()};return Wt=o,o.promise.finally(()=>{Oe.finish(t),Wt===o&&(Wt=null)}),o.promise},TT=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Ai();const r=Ei(),o=Oe.begin(),s=[Zl(),Ps.persist],i=u=>!u?.hasHydrated||u.hasHydrated()||!u.onFinishHydration?Promise.resolve():new Promise(d=>{let f=!1;const h=()=>{f||(f=!0,d())},m=u.onFinishHydration(()=>{m?.(),h()});u.hasHydrated?.()&&h()}),a=()=>Promise.all(s.map(i)).then(()=>{}),c=u=>!Ge||!nt||!de(nt)?u:{...u,...Ge},l=async u=>{if(!de(r))return;let d=c(Oe.reconcile(u,o));if(await a(),!!de(r)){d=Ig(c(Oe.reconcile(u,o)),r.runtimeKey);try{Dg(d)}catch(f){console.warn("persistToLocalStorage failed:",f)}try{Bs(d)}catch(f){console.warn("applyDesktopUiPreferences failed:",f)}Fs(d,t,n)}};try{const u=await ou(r);u&&de(r)&&await l(u)}catch(u){console.warn("Failed to synchronise settings:",u)}finally{Oe.finish(o)}};async function yo({keepalive:e=!1}={}){let t=!1;const n=Ge,r=nt,o=go,s=Zn;Ge=null,nt=null,go=0,Pe=null,Zn=[];try{if(!n||!r||Object.keys(n).length===0||!de(r)){t=!0,et("saved");return}const i=Oe.begin(o),a={context:r,changes:{...n}};Vr.push(a),Yr(n);const c=()=>Fg(Co(n));try{const l=eu();if(l)try{const u=mo(await l.save(n));if(!de(r))return;if(u){Yr(u);const d=Oe.reconcile(u,i);Bs(d),Fs(d,!1),At=null}u||c(),t=!!u,et(u?"saved":"error");return}catch(u){if(!de(r))return;console.warn("Failed to update settings via runtime settings API:",u)}if(!de(r))return;try{const u=await g(tu(),{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:e});if(!de(r))return;if(!u.ok){console.warn("Failed to update shared settings via API:",u.status,u.statusText),c(),et("error");return}const d=mo(await u.json().catch(()=>null));if(!de(r))return;if(d){Yr(d);const f=Oe.reconcile(d,i);Bs(f),Fs(f,!1),t=!0,et("saved"),At=null}else c(),et("error")}catch(u){de(r)&&(console.warn("Failed to update shared settings via API:",u),c(),et("error"))}}finally{Vr=Vr.filter(l=>l!==a),Oe.finish(i)}}finally{s.forEach(i=>i({ok:t}))}}const vT=()=>ou(),lt=async e=>{if(typeof window>"u")return{ok:!1};Ai();const t=Ei();nt&&!cr(nt,t)&&(Pe&&clearTimeout(Pe),yo());const n={};for(const i of Co(e))fg(i)&&Object.assign(n,{[i]:e[i]});const r=Oe.record(n),o=jg({...Ge??{},...n});if(Object.keys(o).length===0){Ge=null,nt=null,Pe&&(clearTimeout(Pe),Pe=null);const i=Zn;return Zn=[],i.forEach(a=>a({ok:!0})),et("saved"),{ok:!0}}Ge=o,nt=t,go=r,et("saving"),Pe&&clearTimeout(Pe);const s=new Promise(i=>{Zn.push(i)});return Pe=setTimeout(()=>{yo()},Lg),s},kT=async()=>{if(typeof window>"u")return;const e=Zl();try{const t=await Ih();if(!t)return;const n=()=>Ph(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)}},Ug=3e4,Ng=40,Bg=60,Hg=(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])},Ya=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},zg=ft()(In((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,o=Bg,s){if(!n||n.trim().length===0)return[];const i=n.trim(),a=$(),c=typeof r=="string"?r.trim():"",l=!!s?.includeHidden,u=s?.respectGitignore??!0,d=s?.type==="directory"?"directory":"file",f=Hg(a,i,c,o,l,u,d),h=Date.now(),m=t().cache[f];if(m&&h-m.timestamp<Ug)return m.files;const S=t().inFlight[f];if(S)return S;const y=tt.searchFiles(c,{directory:i,limit:o,includeHidden:l,respectGitignore:u,dirs:d!=="file",type:d}).then(k=>(e(v=>{if(v.inFlight[f]!==y)return v;const F={...v.cache,[f]:{files:k,timestamp:Date.now()}},O=v.cacheKeys.filter(q=>q!==f);for(O.push(f);O.length>Ng;){const q=O.shift();q&&delete F[q]}return{cache:F,cacheKeys:O}}),k)).finally(()=>{e(k=>{if(k.inFlight[f]!==y)return k;const v={...k.inFlight};return delete v[f],{inFlight:v}})});return e(k=>({inFlight:{...k.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=>Ya(l,r)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!Ya(l,r)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),$g=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("aiworker_stream_debug")==="1"}catch{return!1}},Hs="aiworker_stream_perf",Wg=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Hs)==="1"}catch{return!1}};let nn=Wg();const Qa=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Kg=()=>{if(!nn||typeof window>"u")return null;if(!window.__aiworkerStreamPerfState){const e=Date.now();window.__aiworkerStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__aiworkerStreamPerfState},su=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),Pi=(e,t)=>{const n=Kg();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()},Gg=e=>{if(nn=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(Hs,"1"),window.__aiworkerStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Hs),delete window.__aiworkerStreamPerfState,delete window.__aiworkerVsCodeStreamPerfState}catch{}},qg=()=>{typeof window>"u"||(nn&&(window.__aiworkerStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__aiworkerVsCodeStreamPerfState&&(window.__aiworkerVsCodeStreamPerfState={...window.__aiworkerVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Jg=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__aiworkerStreamPerfState;return!nn||!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:su(e.counters)}},ET=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__aiworkerVsCodeStreamPerfState;if(!nn||!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:su(e.counters)}},AT=(e,t=1)=>{Pi(e,t)},PT=(e,t)=>{Pi(e,t)},IT=e=>{!nn||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`aiworker.${e}`)},xT=(e,t)=>{if(!nn)return t();const n=Qa();try{return t()}finally{Pi(e,Qa()-n)}};typeof window<"u"&&(window.__aiworkerStreamPerformance={setEnabled:Gg,reset:qg,getSnapshot:Jg});var Vg={};let Ke=null,Xa=0;const We=pr(),Za=We.getItem("lastDirectory"),Yg=typeof Za=="string"&&Za.length>0,Hr=e=>{try{zg.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Pn=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},Qg=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},Qr=(e,t)=>{const n=Qg(e,t);return Pn(n)},Xg=()=>{const e=We.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Pn(e);return t.length>0?t:null},Zg=()=>{const e=We.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Pn(e);return t.length>0?t:null},ey=()=>{if(typeof process>"u")return null;const e=Vg,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=Pn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Pn(n);return r.length>0?r:null}return null},wo=()=>{if(typeof window<"u"){if(Ke)return Ke;const t=typeof window.__AIWORKER_HOME__=="string"&&window.__AIWORKER_HOME__.length>0?window.__AIWORKER_HOME__:null;if(t&&t.length>0)return Ke=t,We.setItem("homeDirectory",t),t;const n=Xg();if(n&&!Me())return Ke=n,n}const e=ey();return e||"/"},ty=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},ny=e=>(Ke=e,typeof window<"u"&&We.setItem("homeDirectory",e),lt({homeDirectory:e}),e),zs=async()=>{const e=r=>{const o=ty(r);return o?ny(o):null};try{const r=await tt.getFilesystemHome(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await tt.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 Nc(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=wo(),n=e(t);return n||t},ry=()=>{if(!Me())return null;const e=Uc()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Pn(e);return t.length>0?t:null},lr=ry()||wo(),So=(()=>{const e=Zg();return e&&!Me()?Qr(e,lr):lr})();So&&tt.setDirectory(So);const oy=!!(lr&&lr!=="/"),$s=ft()(In((e,t)=>({currentDirectory:So,directoryHistory:[So],historyIndex:0,homeDirectory:lr,hasPersistedDirectory:Yg,isHomeReady:oy,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const o=Ke||t().homeDirectory||We.getItem("homeDirectory"),s=Qr(n,o);$g()&&console.log("[DirectoryStore] setDirectory called with path:",s),tt.setDirectory(s),Hr(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return We.setItem("lastDirectory",s),lt({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];tt.setDirectory(o),Hr(),We.setItem("lastDirectory",o),lt({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];tt.setDirectory(o),Hr(),We.setItem("lastDirectory",o),lt({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),o=Ke||t().homeDirectory||wo();if(n===o||n==="/")return;const s=n.endsWith("/")?n.slice(0,-1):n,i=s.lastIndexOf("/");if(i===-1){const a=Ke||wo();r(a)}else r(i===0?"/":s.substring(0,i))},goHome:async()=>{const n=Ke||t().homeDirectory||await zs();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),o=n;Ke=o;const s=r.homeDirectory!==o,i=We.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!=="/",u=r.currentDirectory?Qr(r.currentDirectory,o):r.currentDirectory,d=r.directoryHistory.map(S=>Qr(S,o)),f=d.some((S,y)=>S!==r.directoryHistory[y]),h=!!(u&&u!==r.currentDirectory),m={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(m.currentDirectory=o,m.directoryHistory=[o],m.historyIndex=0,m.isSwitchingDirectory=!1):(h||f)&&(m.currentDirectory=u,m.directoryHistory=d,m.historyIndex=Math.min(r.historyIndex,d.length-1),m.isSwitchingDirectory=!1),e(()=>m),(c||h)&&l){const S=c?o:u;tt.setDirectory(S),Hr(),We.setItem("lastDirectory",S),lt({lastDirectory:S})}lt({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(zs().then(e=>{$s.getState().synchronizeHomeDirectory(e)}),jc(()=>{Ke=null;const e=++Xa;zs().then(t=>{e===Xa&&$s.getState().synchronizeHomeDirectory(t)})}));const sy=(e,t)=>{const n=Eo();return n?n.openWebSocket(ld(e),t):$d(new WebSocket(e))},iu=1,ec=512*1024,iy=0,fn=1,ay=15e3,Ii=new TextEncoder,au=new TextDecoder,xi=ke(["interactive","command"]),cu=ke(["running","exited","error"]),cy=ke(["node","bun"]),Ri=bo("type",[I({type:H("terminal")}),I({type:H("project-action"),actionId:w(),executionId:w()})]),ly=I({sessionId:w(),cols:C(),rows:C(),status:cu,mode:xi.optional(),purpose:Ri.optional()}),uy=I({sessionId:w(),cwd:w(),status:ke(["running","exited"]),createdAt:C().nullable().optional().transform(e=>e??null),mode:xi.optional(),purpose:Ri.optional()}),tc={mode:xi.optional(),purpose:Ri.optional()},dy=bo("t",[I({t:H("hello")}),I({t:H("pong")}),I({t:H("error"),s:w().optional(),message:w().optional(),code:w().optional(),fatal:Xt().optional()}),I({t:H("snapshot"),s:w(),q:C().int().nonnegative().default(0),history:w().default(""),status:cu,cols:C().int().positive().optional(),rows:C().int().positive().optional(),exitCode:C().nullish().transform(e=>e??void 0),signal:C().nullable().optional(),runtime:cy.optional(),ptyBackend:w().optional(),...tc}),I({t:H("output"),s:w(),q:C().int().nonnegative(),d:w(),r:w().optional()}),I({t:H("exit"),s:w(),q:C().int().nonnegative(),exitCode:C().nullish().transform(e=>e??void 0),signal:C().nullable().optional()}),I({t:H("restarted"),s:w(),q:C().int().nonnegative(),history:w().default(""),...tc})]),fy=e=>{const t=Ii.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=iu,n.set(t,1),n},py=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):Ii.encode(e);t[0]===iu&&(t=t.subarray(1));try{return dy.safeParse(JSON.parse(au.decode(t))).data??null}catch{return null}};class hy extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const RT=e=>e.cols!==void 0&&e.rows!==void 0?{cols:e.cols,rows:e.rows}:void 0,my=I({error:w().optional(),code:w().optional()}),Do=async(e,t)=>{const n=my.safeParse(await e.json().catch(()=>null)).data;return new hy(n?.error??t,n?.code??null)},gy=e=>{const t=Ii.encode(e);if(t.byteLength<=ec)return e;let n=t.byteLength-ec;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return au.decode(t.subarray(n))},yy=I({sessions:G(fe())});class lu{constructor(t={refreshAuth:Io,openSocket:()=>sy(Ie().websocket("/api/terminal/ws")),clearUrlAuthToken:fr}){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,cols:i.cols,rows:i.rows,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===fn;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===fn){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)}noteResize(t,n,r){const o=this.projections.get(t);o&&this.projections.set(t,{...o,cols:n,rows:r})}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===fn)return;if(this.opening)return await this.opening,this.socket?.readyState===fn?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,u=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},d=h=>{s||(s=!0,clearTimeout(f),h?o(h):r())},f=setTimeout(()=>{u(),c?.close(),d(new Error("Terminal connection timed out"))},1e4);try{const h=this.dependencies.openSocket();c=h,h.binaryType="arraybuffer",this.socket=h,h.onopen=()=>{if(!l()){h.close(),d(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const m of this.subscribers.keys())this.send({t:"attach",v:3,s:m});this.startKeepalive(),d()},h.onmessage=m=>{this.handleMessage(m.data)},h.onerror=()=>{const m=l();m&&u(),d(new Error("Terminal WebSocket failed")),m&&this.subscribers.size>0&&this.scheduleReconnect()},h.onclose=()=>{const m=l();m&&(this.stopKeepalive(),u()),this.socket===h&&(this.socket=null),d(new Error("Terminal WebSocket closed")),m&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(h){d(h instanceof Error?h: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=py(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??"",cols:n.cols,rows:n.rows,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,cols:s.cols,rows:s.rows,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:gy(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!==fn)return!1;try{return this.socket.send(fy(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())},ay))}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===iy||t.readyState===fn)&&t.close()}}let Ct=new lu;async function wy(e){const t=await g("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Do(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=ly.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function Sy(e){const t=await g(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await Do(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=yy.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=uy.safeParse(s).data;i&&o.push(i)}return o}async function by(e){e.length!==0&&await Dn("/api/terminal/touch","POST",{sessionIds:e})}async function Ty(){const e=await g("/api/terminal/shells");if(!e.ok)throw await Do(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&mi(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function vy(e,t,n){return Ct.subscribe(e,{onEvent:t,onError:n})}async function ky(e,t){await Ct.write(e,t)}async function Dn(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const o=await g(e,r);if(!o.ok)throw await Do(o,"Terminal command failed");return o}async function Ey(e,t,n){await Dn(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n}),Ct.noteResize(e,t,n)}async function Ay(e,t){await Dn(`/api/terminal/${e}/appearance`,"POST",t)}async function Py(e){await Dn(`/api/terminal/${e}`,"DELETE"),Ct.forget(e)}async function Iy(e,t){return(await Dn(`/api/terminal/${e}/restart`,"POST",t)).json()}async function xy(e){const n=await(await Dn("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&Ct.forget(r);else e.sessionId&&Ct.forget(e.sessionId)}function CT(){Ct.dispose(),Ct=new lu}const Ry=()=>({async listShells(){return Ty()},async listSessions(e){return Sy(e)},async touchSessions(e){await by(e)},async createSession(e){return wy(e)},connect(e,t){const n=vy(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await ky(e,t)},async resize(e){await Ey(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await Ay(e,t)},async close(e){await Py(e)},async restartSession(e,t){return Iy(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 xy(e)}}),Ws=new Set,Cy=e=>(Ws.add(e),()=>{Ws.delete(e)}),Dy=e=>{for(const t of Ws)t(e)},Ks=new Set,Oy=(e,t)=>JSON.stringify([t,tn(e)]);function DT(e){return Ks.add(e),()=>{Ks.delete(e)}}function My(e,t){const n=Oy(e,t);for(const r of Ks)r(n)}const E="/api/git",uu=I({diff:w()}),_y=I({files:G(I({path:w(),status:w()}))}),Ly=I({error:w()}),Fy=I({files:G(I({path:w(),previousPath:w().optional(),changeType:w(),insertions:C(),deletions:C(),isBinary:Xt()}))}),nc=I({hash:w(),date:w(),message:w(),refs:w(),body:w(),author_name:w(),author_email:w(),filesChanged:C(),insertions:C(),deletions:C(),parents:G(w())}),jy=I({all:G(nc),latest:nc.nullable(),total:C()});async function Oo(e,t){const n=Ly.safeParse(await e.json().catch(()=>null));return new Error(n.success?n.data.error:`${t}: ${e.statusText}`)}const Uy=1200,Ny=5e3,Gs=new Map,Gn=new Map,du=new Map,rc=new Map,zr=new Map,fu=e=>e.trim(),Ci=(e,t)=>JSON.stringify([e,fu(t)]),pu=(e,t,n)=>JSON.stringify([e,fu(t),n??"full"]),qs=(e,t)=>du.get(Ci(e,t))??0,hu=(e,t)=>{const n=Ci(e,t);du.set(n,qs(e,t)+1);for(const r of[void 0,"light"]){const o=pu(e,t,r);Gs.delete(o),Gn.delete(o)}};Cy(e=>{hu($(),e)});const yr=e=>{Dy(e)},ee=async(e,t)=>{const n=await t.json();return yr(e),n};function P(e,t,n){const r={...n};return t&&(r.directory=t),Ie().api(e,r)}async function By(e){const t=Ci($(),e),n=Date.now(),r=rc.get(t);if(r&&r.expiresAt>n)return r.value;const o=zr.get(t);if(o)return o;const s=(async()=>{const i=await g(P(`${E}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return rc.set(t,{value:c,expiresAt:Date.now()+Ny}),c})();zr.set(t,s);try{return await s}finally{zr.get(t)===s&&zr.delete(t)}}class Hy extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function OT(e){const t=await g("/api/fs/git-dirs",{query:{path:e}});if(t.status===501)throw new Hy;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=>tn(r?.path??null)).filter(r=>r!==null)}async function zy(e,t){const n=t?.mode,r=$();t?.fresh&&hu(r,e);const o=pu(r,e,n),s=Date.now(),i=Gs.get(o);if(i&&i.expiresAt>s)return i.value;const a=Gn.get(o);if(a)return a;const c=(async()=>{const l=qs(r,e),u=await g(P(`${E}/status`,e,n?{mode:n}:void 0));if(!u.ok)throw new Error(`Failed to get git status: ${u.statusText}`);const d=await u.json();return qs(r,e)===l&&Gs.set(o,{value:d,expiresAt:Date.now()+Uy}),d})();Gn.set(o,c);try{return await c}finally{Gn.get(o)===c&&Gn.delete(o)}}async function MT(e){const t=await g(P(`${E}/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 _T(e){const t=await g(P(`${E}/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 LT(e,t){const n=await g(P(`${E}/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 $y(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 g(P(`${E}/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 Wy(e,t){const{base:n,head:r,path:o,contextLines:s,includeWorkingTree:i}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const a=await g(P(`${E}/range-diff`,e,{base:n,head:r,path:o||void 0,context:s,includeWorkingTree:i}));if(!a.ok)throw await Oo(a,"Failed to get git range diff");return uu.parse(await a.json())}async function Ky(e,t){const n=await g(P(`${E}/commit-diff`,e,{hash:t.hash,path:t.path,previousPath:t.previousPath,context:t.contextLines}));if(!n.ok)throw await Oo(n,"Failed to get commit diff");return uu.parse(await n.json())}async function Gy(e,t){const{base:n,head:r,includeWorkingTree:o}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const s=await g(P(`${E}/range-files`,e,{base:n,head:r,includeWorkingTree:o}));if(!s.ok)throw await Oo(s,"Failed to get git range files");return _y.parse(await s.json()).files}async function qy(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await g(P(`${E}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function Jy(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const o=await g(P(`${E}/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 Vy(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await g(P(`${E}/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")}yr(e)}async function Yy(e,t){await mu(e,[t])}async function mu(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 g(P(`${E}/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")}yr(e)}async function Qy(e,t){await gu(e,[t])}async function gu(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 g(P(`${E}/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")}yr(e)}async function Xy(e,t,n){await Di(e,t,n,"stage")}async function Zy(e,t,n){await Di(e,t,n,"unstage")}async function ew(e,t,n){await Di(e,t,n,"discard")}async function Di(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 g(P(`${E}/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")}yr(e)}async function tw(e){if(!e)return!1;const t=await g(P(`${E}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function nw(e){const t=await g(P(`${E}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function rw(e,t){const n=await g(P(`${E}/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 ow(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await g(P(`${E}/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 ee(e,n)}async function sw(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await g(P(`${E}/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 ee(e,n)}async function iw(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await g(P(`${E}/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 ee(e,r)}async function aw(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 g(P(`${E}/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 cw(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 g(P(`${E}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const h=await l.json().catch(()=>({error:l.statusText}));throw new Error(h.error||"Failed to generate PR description")}const u=await l.json().catch(()=>null),d=typeof u?.title=="string"?u.title:"",f=typeof u?.body=="string"?u.body:"";if(!d&&!f)throw new Error("Malformed PR description response");return{title:d,body:f}}async function oc(e){const t=await g(P(`${E}/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 sc(e,t){const n=await g(P(`${E}/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 lw(e){const t=await g(P(`${E}/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 uw(e,t){const n=await g(P(`${E}/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 ic(e,t){const n=await g(P(`${E}/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 ac(e,t){const n=await g(P(`${E}/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 dw(e,t,n={}){const r=await g(P(`${E}/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 ee(e,r)}async function fw(e,t={}){const n=$(),r=await g(P(`${E}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to push")}const o=await ee(e,r);return o.success&&My(e,n),o}async function pw(e,t={}){const n=await g(P(`${E}/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 ee(e,n)}async function hw(e,t={}){const n=await g(P(`${E}/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 ee(e,n)}async function mw(e){const t=await g(P(`${E}/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 gw(e,t){const n=await g(P(`${E}/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 yu(e,t={}){const n=await g(P(`${E}/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 ee(e,n)}const Oi=async(e,t,n)=>{const r=await g(P(`${E}/${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 ee(e,r)},yw=(e,t)=>Oi(e,"stash/apply",t),wu=(e,t)=>Oi(e,"stash/pop",t),ww=(e,t)=>Oi(e,"stash/drop",t);async function Sw(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function bw(e,t,n){const r=await g(P(`${E}/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 ee(e,r)}async function Tw(e,t,n){const r=await g(P(`${E}/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 ee(e,r)}async function vw(e,t={}){const n=await g(P(`${E}/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 jy.parse(await n.json())}async function kw(e,t){const n=await g(P(`${E}/commit-files`,e,{hash:t}));if(!n.ok)throw await Oo(n,"Failed to get commit files");return Fy.parse(await n.json())}async function FT(e,t,n,r){const o=await g(P(`${E}/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 Ew(){const e=await g(P(`${E}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Aw(e){const t=await g(P(`${E}/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 Pw(e,t){const n=await g(P(`${E}/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 Iw(e){const t=await g(P(`${E}/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 xw(e){if(!e)return null;const t=await g(P(`${E}/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 Rw(e){if(!e)return!1;const t=await g(P(`${E}/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 jT(){const e=await g(P(`${E}/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 Cw(e,t){const n=await g(P(`${E}/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 UT(){const e=await g(P(`${E}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function NT(e,t){if(!e)return null;const n=await g(P(`${E}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function Dw(e){const t=await g(P(`${E}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Ow(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function Mw(e){const t=await g(P(`${E}/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 ee(e,t)}async function _w(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function Lw(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function Fw(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function jw(e,t){const n=await g(P(`${E}/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 ee(e,n)}async function Uw(e,t,n,r){const o=await g(P(`${E}/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 ee(e,o)}async function Nw(e){const t=await g(P(`${E}/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 ee(e,t)}async function Bw(e){const t=await g(P(`${E}/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 ee(e,t)}async function Hw(e){const t=await g(P(`${E}/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 ee(e,t)}async function zw(e,t){return await yu(e,{message:t?.message}),{success:!0}}async function $w(e){return await wu(e,{ref:"stash@{0}"}),{success:!0}}async function Ww(e){const t=await g(P(`${E}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Kw(e,t){const n=await g(`${E}/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 Gw(e){const t=await g(`${E}/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 qw=()=>({checkIsGitRepository:By,getGitStatus:zy,getGitDiff:$y,getGitFileDiff:Jy,getGitRangeDiff:Wy,getGitRangeFiles:Gy,getBranchBase:qy,revertGitFile:Vy,stageGitFile:Yy,stageGitFiles:mu,unstageGitFile:Qy,unstageGitFiles:gu,stageGitHunk:Xy,unstageGitHunk:Zy,revertGitHunk:ew,isLinkedWorktree:tw,getGitBranches:nw,getGitUnpushedBranchCounts:rw,deleteGitBranch:ow,deleteRemoteBranch:sw,removeRemote:iw,generateCommitMessage:aw,generatePullRequestDescription:cw,listGitWorktrees:oc,validateGitWorktree:sc,createGitWorktree:ic,deleteGitWorktree:ac,validateWorktreeDirectory:Kw,canonicalizeWorktreeState:Gw,createGitCommit(e,t,n){return dw(e,t,n)},gitPush:fw,gitPull:pw,gitFetch:hw,listGitStashes:mw,countGitStashFiles:gw,stashGitChanges:yu,applyGitStash:yw,popGitStash:wu,dropGitStash:ww,checkoutBranch:Sw,createBranch:bw,renameBranch:Tw,getGitLog(e,t){return vw(e,t)},getCommitFiles:kw,getGitCommitDiff:Ky,getCurrentGitIdentity:xw,hasLocalIdentity:Rw,setGitIdentity:Cw,getGitIdentities:Ew,createGitIdentity:Aw,updateGitIdentity:Pw,deleteGitIdentity:Iw,getRemotes:Dw,rebase:Ow,abortRebase:Mw,continueRebase:Bw,merge:_w,abortMerge:Nw,continueMerge:Hw,checkoutCommit:Lw,cherryPick:Fw,revertCommit:jw,resetToCommit:Uw,stash:zw,stashPop:$w,getConflictDetails:Ww,worktree:{list:oc,validate:sc,bootstrapStatus:lw,preview:uw,create:ic,remove:ac}}),ae=e=>e.replace(/\\/g,"/"),Jw=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Gt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:ae(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:ae(r.path),isDirectory:!!r.isDirectory}))}},Be=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},Vw=({getDirectory:e})=>({async listDirectory(t,n){const r=ae(t),o=new URLSearchParams;r&&o.set("path",r),n?.respectGitignore&&o.set("respectGitignore","true");const s=await g("/api/fs/list",{query:o,headers:Be(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Gt(a.error||"Failed to list directory",{reason:uo(a.reason),status:s.status})}const i=await s.json();return Jw(r,i)},async search(t){const n=new URLSearchParams,r=ae(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 g("/api/find/file",{query:n,headers:Be(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:ae(`${r}/${a}`),preview:[ae(a)]}))},async createDirectory(t){const n=ae(t),r=await g("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Be(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"?ae(o.path):n}},async statFile(t,n){const r=ae(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant);const s=await g("/api/fs/stat",{query:o,headers:Be(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"?ae(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=ae(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 g("/api/fs/read",{query:o,cache:n?.optional||n?.fresh?"no-store":"default",headers:Be(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=ae(t),o=await g("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Be(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"?ae(s.path):r}},async uploadFile(t,n,r){const o=ae(t),s=await g("/api/fs/upload",{method:"POST",query:{path:o,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Be(e,r?.directory)},body:n});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Gt(a.error||"Failed to upload file",{reason:uo(a.reason),status:s.status})}const i=await s.json().catch(()=>({}));return{success:!!i.success,path:i.path?ae(i.path):o}},async delete(t){const n=ae(t),r=await g("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Be(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 g("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...Be(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"?ae(o.path):n}},async revealPath(t){const n=await g("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Be(e)},body:JSON.stringify({path:ae(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=ae(t),r=await g("/api/fs/raw",{query:{path:n,download:!0},headers:Be(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)}}),Yw="/api/config/settings",cc=()=>`${Yw}?${Ql}=${Xl()}`,Qw="/api/config/reload",lc=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},Xw=()=>({async load(){const e=await g(cc(),{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:lc(await e.json()),source:"web"}},async save(e){const t=await g(cc(),{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 lc(await t.json())},async restartOpenCode(){const e=await g(Qw,{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}}}),Zw=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),eS=1500,Js=5e3,tS="openchamber-notification-claim:",er=new Map,nS=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),rS=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("|")},oS=e=>{for(const[t,n]of er)e-n>Js&&er.delete(t)},sS=e=>{const t=rS(e);if(!t)return!0;const n=Date.now();oS(n);const r=er.get(t)??0;if(n-r<Js)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${tS}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<Js)return er.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return er.set(t,n),!0},Su=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),eS)})])??e}catch{return e}},iS=async e=>{const t=await Su();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"AiWorker",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},aS=async()=>{const e=await Su();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},cS=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(!nS()&&await aS()||!sS(e))return!0;try{return await iS(e)||new Notification(e?.title??"AiWorker",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},lS=async e=>{if(typeof window>"u")return!1;const t=window.__AIWORKER_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}},uS=()=>({async notifyAgentCompletion(e){return await lS(e)||await cS(e)},canNotify:()=>typeof window<"u"&&window.__AIWORKER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),dS=()=>({async getAvailableTools(){const e=await g("/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()}}),pn=async(e,t)=>{try{const n=await g(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},fS=()=>({async getVapidPublicKey(){return pn("/api/push/vapid-public-key")},async subscribe(e){return pn("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return pn("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return pn("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return pn("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return pn("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),ie=async e=>await e.json().catch(()=>null),pS=({urls:e})=>({async authStatus(){const t=await g("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await ie(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await g("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await ie(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 g("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await ie(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await g("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await ie(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 g("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await ie(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 g("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await ie(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 g("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await ie(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 g(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await ie(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 g("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ie(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await g("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ie(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await g("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ie(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await g("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ie(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 g(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await ie(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 g(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await ie(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 g(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ie(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 g(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ie(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 g(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ie(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 g(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ie(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 g(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ie(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}});async function Re(e){try{return await e.json()}catch{return null}}function Ce(e,t){return e?.error?.trim()||t}function bu(e){return Number.isFinite(e)?e??null:null}function Tu(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function vu(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 hS(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function mS(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:vu(e?.user),authorizedAt:bu(n)}}function uc(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(mS).filter(n=>n!=null):[];return{connected:e.connected,user:vu(e.user),organization:hS(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function gS(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 yS(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 wS(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:bu(r)??0}}function SS(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 bS(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 TS(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function vS(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 kS(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:vS(e.color)}}function ES(e){return Array.isArray(e)?e.map(kS).filter(t=>t!=null):[]}function ku(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:yS(e.state),assignee:SS(e.assignee),team:bS(e.team),priority:TS(e.priority),labels:ES(e.labels)}}function AS(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:Tu(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 Eu(e){const t=ku(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(AS).filter(o=>o!=null):[],r=e?.description;return{...t,description:Tu(r),comments:n}}function PS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(ku).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function IS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:Eu(e.issue)}}function xS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(wS).filter(n=>n!=null):[]}}function RS(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:Eu(e.issue)}}function CS(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 dc(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(CS).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const DS=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function OS(e){return DS.find(t=>t===e)??null}function fc(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function MS(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=OS(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const _S=()=>({async authStatus(){const e=await g("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await Re(e),n=uc(t);if(!e.ok||!n)throw new Error(Ce(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await g("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await Re(t),r=gS(n);if(!t.ok||!r)throw new Error(Ce(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await g("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Re(e);if(!e.ok)throw new Error(Ce(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await g("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await Re(t),r=uc(n);if(!t.ok||!r)throw new Error(Ce(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}`:"",u=await g(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await Re(u),f=PS(d);if(!u.ok||!f)throw new Error(Ce(d,u.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await g(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Re(n),o=IS(r);if(!n.ok||!o)throw new Error(Ce(r,n.statusText||"Failed to load Linear issue"));return o},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await g(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await Re(n),o=xS(r);if(!n.ok||!o)throw new Error(Ce(r,n.statusText||"Failed to load Linear workflow states"));return o},async issueUpdate(e){const t=await g("/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 Re(t),r=RS(n);if(!t.ok||!r)throw new Error(Ce(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await g("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await Re(e),n=dc(t);if(!e.ok||!n)throw new Error(Ce(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await g("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await Re(t),r=dc(n);if(!t.ok||!r)throw new Error(Ce(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await g("/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 Re(t),r=MS(n);if(!t.ok||!r)throw new Error(Ce(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await g("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await Re(e),n=fc(t);if(!e.ok||!n)throw new Error(Ce(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await g("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await Re(t),r=fc(n);if(!t.ok||!r)throw new Error(Ce(n,t.statusText||"Failed to save Linear preferences"));return r}}),St=async e=>await e.json().catch(()=>null),LS=()=>({async listClients(){const e=await g("/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 g("/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 g("/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 g("/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 g("/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 g(`/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 g(`/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 g("/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}}),FS=()=>({api:(...e)=>Ie().api(...e),authenticatedAsset:(...e)=>Ie().authenticatedAsset(...e),auth:(...e)=>Ie().auth(...e),health:(...e)=>Ie().health(...e),rawFile:(...e)=>Ie().rawFile(...e),sse:(...e)=>Ie().sse(...e),websocket:(...e)=>Ie().websocket(...e)}),jS=(e={})=>{const t=e.urls??Xs();Ed(t);const n=FS();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Ry(),git:qw(),files:Vw({getDirectory:()=>$s.getState().currentDirectory}),settings:Xw(),permissions:Zw(),notifications:uS(),github:pS({urls:n}),linear:_S(),push:fS(),clientAuth:LS(),tools:dS()}},US=3e3,pc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},NS=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__AIWORKER_API_BASE_URL__),clientToken:e(window.__AIWORKER_CLIENT_TOKEN__),localOrigin:e(window.__AIWORKER_LOCAL_ORIGIN__),runtimeHeaders:window.__AIWORKER_RUNTIME_HEADERS__,relayHostId:e(window.__AIWORKER_RELAY_HOST_ID__)}};let Vs=Promise.resolve();const BT=()=>Vs,HT=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:o,relayHostId:s,relay:i}=e??NS(),a=e?null:Cc(),c=s||(a?.target==="remote"?a.hostId:""),l=Oc({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return Id({apiBaseUrl:t,runtimeKey:pc(t,r)?"local":c?`host:${c}`:null}),qc(n||null),Jc(o||null),i&&ro({apiBaseUrl:t,clientToken:n||null,requestHeaders:o||null,runtimeKey:s?`host:${s}`:null,relay:i}),tt.reconnectToRuntimeBaseUrl(),Io(t||void 0).catch(()=>{}),r&&!pc(t,r)&&Object.keys(Po()).length>0&&el(r).catch(()=>{}),cl(),Vs=i?Promise.resolve():Promise.race([rp(s||void 0).catch(()=>{}),new Promise(u=>{window.setTimeout(u,1e4)})]).then(()=>{tt.reconnectToRuntimeBaseUrl()}),Vs.then(()=>{window.setTimeout(()=>{Xf().catch(()=>{})},US)}),jS({urls:l})};export{nT as $,tt as A,kT as B,TT as C,qe as D,ve as E,bb as F,jd as G,Gr as H,RT as I,Sb as J,Me as K,wb as L,Ad as M,tn as N,AT as O,Rn as P,ci as Q,dl as R,jb as S,Kf as T,It as U,ul as V,re as W,Vc as X,sb as Y,ab as Z,Jb as _,$ as a,Kn as a$,zg as a0,Hb as a1,di as a2,Eo as a3,Io as a4,Ie as a5,sy as a6,Po as a7,Eb as a8,wh as a9,ST as aA,vT as aB,db as aC,fb as aD,lm as aE,cT as aF,xd as aG,lb as aH,Gp as aI,jp as aJ,Np as aK,CT as aL,Ls as aM,VS as aN,YS as aO,QS as aP,Rd as aQ,Uc as aR,Am as aS,$g as aT,$b as aU,bl as aV,Dy as aW,kg as aX,_s as aY,bt as aZ,Qh as a_,ib as aa,qb as ab,Kp as ac,IT as ad,_d as ae,cb as af,Jg as ag,ET as ah,qg as ai,xr as aj,Yn as ak,Op as al,ze as am,zb as an,yd as ao,Cc as ap,KS as aq,Gg as ar,Gb as as,GS as at,qS as au,gb as av,mb as aw,pb as ax,hb as ay,Zt as az,Bc as b,MT as b$,hd as b0,fT as b1,xc as b2,lw as b3,Mh as b4,fr as b5,Em as b6,pT as b7,Nw as b8,Mw as b9,LT as bA,$y as bB,Jy as bC,Ew as bD,vw as bE,Wy as bF,Gy as bG,zy as bH,rw as bI,jT as bJ,NT as bK,Dw as bL,sc as bM,oc as bN,hw as bO,pw as bP,fw as bQ,Rw as bR,tw as bS,mw as bT,_w as bU,wu as bV,uw as bW,Ow as bX,iw as bY,Tw as bZ,Uw as b_,yw as ba,Gw as bb,By as bc,Sw as bd,Lw as be,Fw as bf,Hw as bg,Bw as bh,gw as bi,bw as bj,dw as bk,Aw as bl,ic as bm,ow as bn,Iw as bo,ac as bp,sw as bq,UT as br,ww as bs,qy as bt,FT as bu,kw as bv,Ww as bw,xw as bx,nw as by,Ky as bz,HT as c,ob as c$,_T as c0,jw as c1,Vy as c2,ew as c3,Cw as c4,Yy as c5,mu as c6,Xy as c7,zw as c8,yu as c9,Lb as cA,Uf as cB,np as cC,Rb as cD,Rr as cE,Yo as cF,PT as cG,OT as cH,Hy as cI,Cy as cJ,ub as cK,dm as cL,Le as cM,Vb as cN,Qb as cO,tT as cP,Xb as cQ,Yb as cR,Zb as cS,_l as cT,eT as cU,lT as cV,uT as cW,em as cX,aT as cY,yi as cZ,xT as c_,$w as ca,Qy as cb,gu as cc,Zy as cd,Pw as ce,Kw as cf,Te as cg,Wb as ch,Mp as ci,Mc as cj,hT as ck,bT as cl,yg as cm,kb as cn,Ub as co,Nb as cp,be as cq,jf as cr,qf as cs,Qf as ct,Gf as cu,li as cv,Wf as cw,Bb as cx,_b as cy,Fb as cz,pr as d,sT as d0,Nl as d1,rT as d2,oT as d3,iT as d4,dT as d5,$t as d6,Fp as d7,Up as d8,wT as d9,vb as dA,Ib as dB,xb as dC,Tb as dD,Mb as dE,ct as dF,yT as da,Nf as db,Of as dc,Cb as dd,Db as de,yb as df,Fh as dg,hi as dh,Kb as di,_p as dj,Lp as dk,mi as dl,Uh as dm,jh as dn,Dh as dp,xo as dq,Ud as dr,XS as ds,eb as dt,nb as du,ZS as dv,tb as dw,rb as dx,Oy as dy,DT as dz,vo as e,Ab as f,BT as g,g as h,dr as i,Pb as j,ei as k,Tt as l,Ob as m,$s as n,Ps as o,Rf as p,lt as q,mT as r,ro as s,lh as t,T as u,ko as v,gT as w,so as x,JS as y,jc as z};