@openchamber/web 1.15.0 → 1.16.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 (102) hide show
  1. package/README.md +5 -5
  2. package/dist/assets/{DiagramView-HR2xZxJ8.js → DiagramView-Elkp8b4l.js} +1 -1
  3. package/dist/assets/{MarkdownRendererImpl-sm01Q7R7.js → MarkdownRendererImpl-DLhrL6oX.js} +3 -3
  4. package/dist/assets/{MultiRunWindow-DlFUaNQK.js → MultiRunWindow-DVpNCqnE.js} +1 -1
  5. package/dist/assets/{OnboardingScreen-DVRz82mJ.js → OnboardingScreen-CpcR0gyq.js} +1 -1
  6. package/dist/assets/SessionSwitcherDropdown-DHO5Je6v.js +1 -0
  7. package/dist/assets/{SettingsWindow-CkInZcj7.js → SettingsWindow-Bewo7vwh.js} +1 -1
  8. package/dist/assets/{TerminalView-D_9BAjtv.js → TerminalView-D9C7fNLm.js} +3 -3
  9. package/dist/assets/es-D9nOo8Wx.js +15 -0
  10. package/dist/assets/fr-DEF71lgt.js +13 -0
  11. package/dist/assets/index-BklNmnVr.js +2 -0
  12. package/dist/assets/index-C3uMIExE.css +1 -0
  13. package/dist/assets/ja-CpNfaEje.js +15 -0
  14. package/dist/assets/ko-DLS_rnE-.js +15 -0
  15. package/dist/assets/main-B0CxEOP5.js +237 -0
  16. package/dist/assets/{main-DzNa8r0N.js → main-Ck3ZNw8-.js} +2 -2
  17. package/dist/assets/miniChat-BAJj2Ome.js +2 -0
  18. package/dist/assets/mobile-CJoX4Cdj.js +2 -0
  19. package/dist/assets/pl-BjtFn5-n.js +15 -0
  20. package/dist/assets/pt-BR-C0_4Rnzn.js +15 -0
  21. package/dist/assets/renderElectronMiniChatApp-D4-OXCXM.js +2 -0
  22. package/dist/assets/renderMobileApp-DHWdI195.js +16 -0
  23. package/dist/assets/runtimeEndpointReset-B0P2DED1.js +167 -0
  24. package/dist/assets/uk-BDu4E0s0.js +15 -0
  25. package/dist/assets/{useAppFontEffects-DzBg8hrC.js → useAppFontEffects-9LFMCKYW.js} +195 -136
  26. package/dist/assets/zh-CN-BcwMqxIR.js +15 -0
  27. package/dist/assets/zh-TW-bNDQjKEu.js +15 -0
  28. package/dist/index.html +3 -3
  29. package/dist/mini-chat.html +3 -3
  30. package/dist/mobile.html +3 -3
  31. package/package.json +1 -1
  32. package/server/index.js +106 -1
  33. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  34. package/server/lib/notifications/apns-runtime.js +3 -1
  35. package/server/lib/notifications/runtime.js +135 -33
  36. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  37. package/server/lib/opencode/agents.js +3 -0
  38. package/server/lib/opencode/bootstrap-runtime.js +5 -0
  39. package/server/lib/opencode/core-routes.js +75 -2
  40. package/server/lib/opencode/core-routes.test.js +81 -0
  41. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  42. package/server/lib/opencode/settings-helpers.js +30 -0
  43. package/server/lib/opencode/settings-helpers.test.js +14 -0
  44. package/server/lib/opencode/settings-normalization-runtime.js +19 -4
  45. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  46. package/server/lib/opencode/settings-runtime.js +25 -0
  47. package/server/lib/opencode/shutdown-runtime.js +2 -0
  48. package/server/lib/opencode/tunnel-auth.js +4 -9
  49. package/server/lib/package-manager.js +1 -1
  50. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  51. package/server/lib/permission-auto-accept/runtime.js +263 -0
  52. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  53. package/server/lib/projects/project-config.js +8 -0
  54. package/server/lib/quota/DOCUMENTATION.md +5 -2
  55. package/server/lib/quota/credentials/providers.js +43 -0
  56. package/server/lib/quota/credentials/store.js +48 -0
  57. package/server/lib/quota/credentials/store.test.js +26 -0
  58. package/server/lib/quota/opencode-go-credentials.js +11 -0
  59. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  60. package/server/lib/quota/providers/codex.js +7 -4
  61. package/server/lib/quota/providers/codex.test.js +48 -0
  62. package/server/lib/quota/providers/cursor.js +28 -39
  63. package/server/lib/quota/providers/index.js +7 -0
  64. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  65. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  66. package/server/lib/quota/providers/opencode-go.js +70 -0
  67. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  68. package/server/lib/quota/routes.js +78 -7
  69. package/server/lib/quota/routes.test.js +40 -0
  70. package/server/lib/relay/DOCUMENTATION.md +20 -0
  71. package/server/lib/relay/host-lock.js +101 -0
  72. package/server/lib/relay/host-lock.test.js +129 -0
  73. package/server/lib/relay/identity.js +24 -4
  74. package/server/lib/relay/service.js +95 -8
  75. package/server/lib/relay/signing-key.js +30 -7
  76. package/server/lib/scheduled-tasks/runtime.js +104 -0
  77. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  78. package/server/lib/session-goal/objectives.js +61 -0
  79. package/server/lib/session-goal/routes.js +36 -0
  80. package/server/lib/session-goal/runtime.js +764 -0
  81. package/server/lib/small-model/DOCUMENTATION.md +3 -1
  82. package/server/lib/small-model/call.js +45 -8
  83. package/server/lib/small-model/call.test.js +338 -0
  84. package/server/lib/small-model/index.js +1 -0
  85. package/dist/assets/SessionSwitcherDropdown-DvoOalMY.js +0 -1
  86. package/dist/assets/es-cjUissX4.js +0 -15
  87. package/dist/assets/fr-DqbXnTdK.js +0 -13
  88. package/dist/assets/index-Dg0nmvQU.css +0 -1
  89. package/dist/assets/index-ltrmNGAf.js +0 -2
  90. package/dist/assets/ja-Cetyq6Eg.js +0 -15
  91. package/dist/assets/ko-DtunWisP.js +0 -15
  92. package/dist/assets/main-BC0m8s1v.js +0 -236
  93. package/dist/assets/miniChat-BRYDE-Se.js +0 -2
  94. package/dist/assets/mobile-C3QJVA97.js +0 -2
  95. package/dist/assets/pl-DctGLgve.js +0 -15
  96. package/dist/assets/pt-BR-CXPhf78S.js +0 -15
  97. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +0 -2
  98. package/dist/assets/renderMobileApp-wkBjh5WR.js +0 -16
  99. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +0 -167
  100. package/dist/assets/uk-Bdrc-kqF.js +0 -15
  101. package/dist/assets/zh-CN-CeCVKrHP.js +0 -15
  102. package/dist/assets/zh-TW-CoqiQING.js +0 -15
@@ -0,0 +1,2 @@
1
+ import{_ as Ys,c as Qs,a as tr,d as rr,p as vo,b as ko,R as zt}from"./vendor-.bun-BE757pvp.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const at=1,Xs="openchamber-relay-v1",Ao=1,Po=12,ct=1+Po,ft=64*1024,pt=5,ht=128,Do=0,Co=1,Je=4,Zs=1+Je,Br=ft-pt-Zs,D={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},ei=new Set(Object.values(D)),ti=e=>ei.has(e),Fe={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},we=globalThis.crypto.subtle,Mo={name:"ECDH",namedCurve:"P-256"},Ro=16,gr=32,ri=16,Ur=4,Oo=8;class Ee extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const ni=()=>we.generateKey(Mo,!0,["deriveBits"]),oi=async e=>{const t=await we.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},si=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Ee("invalid ECDH public key JWK");try{return await we.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Mo,!0,[])}catch{throw new Ee("invalid ECDH public key JWK")}},ii=()=>{const e=new Uint8Array(Ro);return globalThis.crypto.getRandomValues(e),e},ai=async(e,t,r)=>{if(r.length!==Ro)throw new Ee("invalid handshake nonce length");const n=await we.deriveBits({name:"ECDH",public:t},e,256),o=await we.importKey("raw",n,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await we.deriveBits({name:"HKDF",hash:"SHA-256",salt:r,info:new TextEncoder().encode(Xs)},o,gr*2*8)),i=(a,c)=>we.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,gr),["encrypt","decrypt"]),hostToClient:await i(s.slice(gr),["encrypt","decrypt"])}},ci=(e,t,r)=>{for(let n=Oo-1;n>=0;n-=1)e[t+n]=Number(r&0xffn),r>>=8n},li=(e,t)=>{let r=0n;for(let n=0;n<Oo;n+=1)r=r<<8n|BigInt(e[t+n]);return r},di=e=>{const t=new Uint8Array(Ur);globalThis.crypto.getRandomValues(t);let r=0n;return{async encrypt(n){if(n.length>ft)throw new Ee("plaintext frame exceeds maximum size");r+=1n;const o=new Uint8Array(Po);o.set(t,0),ci(o,Ur,r);const s=new Uint8Array(await we.encrypt({name:"AES-GCM",iv:o},e,n)),i=new Uint8Array(ct+s.length);return i[0]=Ao,i.set(o,1),i.set(s,ct),i}}},ui=e=>{let t=0n;return{async decrypt(r){if(r.length<ct+ri)throw new Ee("encrypted frame too short");if(r[0]!==Ao)throw new Ee("unsupported encrypted frame version");const n=r.slice(1,ct),o=li(n,Ur);if(o<=t)throw new Ee("frame counter regression");let s;try{s=await we.decrypt({name:"AES-GCM",iv:n},e,r.slice(ct))}catch{throw new Ee("frame decryption failed")}return t=o,new Uint8Array(s)}}},Pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",fi=e=>{let t="";for(let r=0;r<e.length;r+=3){const n=e[r],o=r+1<e.length?e[r+1]:void 0,s=r+2<e.length?e[r+2]:void 0;t+=Pt[n>>2],t+=Pt[(n&3)<<4|(o??0)>>4],o!==void 0&&(t+=Pt[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=Pt[s&63])}return t},Rn=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const r=t;if(r.v!==at)return null;const n=r.batch===!0;return r.t==="ready"?{t:"ready",v:at,batch:n}:r.t==="hello"&&typeof r.nonce=="string"&&typeof r.clientPubJwk=="object"&&r.clientPubJwk!==null?{t:"hello",v:at,clientPubJwk:r.clientPubJwk,nonce:r.nonce,batch:n}:null},pi=e=>({type:"fail",closeCode:Fe.ChannelFailure,reason:e}),hi=async(e,t={})=>{const r=t.batch!==!1,n=await si(e),o=await ni(),s=ii(),i={t:"hello",v:at,clientPubJwk:await oi(o.publicKey),nonce:fi(s),...r?{batch:!0}:{}};let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Rn(c)?.t==="ready"?{type:"ignore"}:pi("plaintext frame on established channel");const l=Rn(c);if(l?.t!=="ready")return{type:"ignore"};const d=await ai(o.privateKey,n,s);return a=!0,{type:"established",batch:r&&l.batch===!0,channel:{encryptor:di(d.clientToHost),decryptor:ui(d.hostToClient)}}}}},Io=4294967295;class q extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const ye=(e,t,r,n=!1)=>{if(!Number.isInteger(t)||t<0||t>Io)throw new q("invalid stream id");if(r.length>Br)throw new q("tunnel payload exceeds maximum size");const o=new Uint8Array(pt+r.length);return o[0]=n?e|ht:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(r,pt),o},mi=e=>{if(e.length<pt)throw new q("tunnel frame too short");const t=e[0],r=(t&ht)!==0,n=t&~ht;if(!ti(n))throw new q(`unknown tunnel frame type ${n}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:n,streamId:o,payload:e.slice(pt),hasMoreFragments:r}},yi=new TextEncoder,gi=new TextDecoder,Dt=e=>yi.encode(JSON.stringify(e)),Ct=(e,t)=>{let r;try{r=JSON.parse(gi.decode(e))}catch{throw new q("malformed JSON tunnel payload")}if(!t(r))throw new q("unexpected JSON tunnel payload shape");return r},_o=(e,t=Br)=>{if(t<=0||t>Br)throw new q("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r},On=(e,t,r)=>{const n=_o(r);return n.map((o,s)=>ye(e,t,o,s<n.length-1))},wi=(e=16*1024*1024)=>{const t=new Map;return{push(r){const n=`${r.streamId}:${r.frameType}`,o=t.get(n);if(!r.hasMoreFragments&&!o)return r.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+r.payload.length;if(i>e)throw t.delete(n),new q("fragmented message exceeds maximum size");if(s.push(r.payload),r.hasMoreFragments)return t.set(n,{chunks:s,totalBytes:i}),null;t.delete(n);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(r){for(const n of t.keys())n.startsWith(`${r}:`)&&t.delete(n)}}},bi=e=>{if(e.length===0)throw new q("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=Do,s.set(o,1),s.length>ft)throw new q("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=Je+o.length;if(t>ft)throw new q("frame batch exceeds maximum plaintext size");const r=new Uint8Array(t);r[0]=Co;let n=1;for(const o of e)r[n]=o.length>>>24&255,r[n+1]=o.length>>>16&255,r[n+2]=o.length>>>8&255,r[n+3]=o.length&255,n+=Je,r.set(o,n),n+=o.length;return r},Si=e=>{if(e.length<1)throw new q("empty batch plaintext");const t=e[0];if(t===Do)return[e.slice(1)];if(t!==Co)throw new q(`unknown batch container tag ${t}`);const r=[];let n=1;for(;n<e.length;){if(n+Je>e.length)throw new q("truncated batch frame length");const o=(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0;if(n+=Je,n+o>e.length)throw new q("truncated batch frame body");r.push(e.slice(n,n+o)),n+=o}if(r.length===0)throw new q("empty frame batch");return r},Ti=new Set([D.HttpBody,D.WsText,D.WsBinary]),Fo=150,Ei=24*1024,vi=32,ki=e=>{const t=e.windowMs??Fo,r=e.maxBatchBytes??Ei,n=e.maxBatchFrames??vi,o=e.now??(()=>Date.now()),s=e.setTimer??((b,T)=>setTimeout(b,T)),i=e.clearTimer??(b=>clearTimeout(b));let a=[],c=0,l=null,d=0,u=!1;const g=()=>{l!==null&&(i(l),l=null)},h=()=>{if(g(),a.length===0)return;const b=a;a=[],c=0,d=o(),e.sendBatch(bi(b))};return{enqueue:b=>{if(u)return;const T=b[0]&~ht;if(!Ti.has(T)){a.push(b),h();return}const S=o();if(a.length===0&&S-d>=t){a.push(b),h();return}const R=Je+b.length;if(a.length>0&&1+c+R>ft&&h(),a.push(b),c+=R,c>=r||a.length>=n){h();return}l===null&&(l=s(h,t))},flush:h,dispose(){u=!0,g(),a=[],c=0}}},Ai=()=>{let e=1;return{next(){if(e>Io)throw new q("stream id space exhausted");const t=e;return e+=2,t}}},nr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pi=e=>nr(e)&&Object.values(e).every(t=>typeof t=="string"),Di=e=>nr(e)&&typeof e.status=="number"&&Pi(e.headers),In=e=>nr(e)&&typeof e.reason=="string",Ci=e=>nr(e)&&typeof e.code=="number"&&typeof e.reason=="string",xo=/^[a-z][a-z\d+.-]*:\/\//i,sn="http://tunnel.invalid",Mi=e=>{try{const t=xo.test(e)?new URL(e):new URL(e,sn);return`${t.pathname}${t.search}`}catch{return e}},Mt=e=>({async*[Symbol.asyncIterator](){yield e}}),Ri=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)return;n&&(yield n)}}finally{t.releaseLock()}}}),Oi=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Ii=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Ri(e)};if(typeof e=="string")return{body:Mt(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Mt(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Mt(Oi(e))};const t=new Response(e),r=t.headers.get("content-type")??void 0,n=new Uint8Array(await t.arrayBuffer());return{body:Mt(n),contentType:r}},_i=async(e,t)=>{let r;const n=new Headers;let o="GET",s=null,i;e instanceof Request?(r=e.url,o=e.method,e.headers.forEach((u,g)=>n.set(g,u)),i=e.signal,s=e.body):r=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((u,g)=>n.set(g,u)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=xo.test(r)?new URL(r):new URL(r,sn),{body:c,contentType:l}=await Ii(s);l&&!n.has("content-type")&&n.set("content-type",l);const d={};return n.forEach((u,g)=>{d[g]=u}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:d,body:c,signal:i}},wr=new Uint8Array(0),Fi=new TextEncoder,xi=new TextDecoder,se=e=>e instanceof Error?e:new Error(String(e)),Rt=()=>new DOMException("The operation was aborted.","AbortError"),Li=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(r){e.send(r)},close(r,n){e.close(r,n)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>t.onmessage?.({data:r.data}),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),e.onerror=()=>t.onerror?.(),t},Ni=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(r){r&&(e.binaryType=r)},onopen:null,onmessage:null,onerror:null,onclose:null,send(r){e.send(r)},close(r,n){e.close(r,n)}};return e.onopen=()=>t.onopen?.(),e.onmessage=r=>{const n=r.data;(typeof n=="string"||n instanceof ArrayBuffer)&&t.onmessage?.({data:n})},e.onerror=()=>t.onerror?.(),e.onclose=r=>t.onclose?.({code:r.code,reason:r.reason}),t},_n=0,br=1,Fn=2,xn=3,Bi=new Set([Fe.AuthFailed,Fe.DuplicateClient,Fe.LimitExceeded]),Ui={[Fe.AuthFailed]:"relay authentication failed",[Fe.DuplicateClient]:"relay connection replaced by another client",[Fe.LimitExceeded]:"relay connection limit reached"},Ln=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},Lo=e=>{const t=e.helloRetryMs??1e3,r=e.helloTimeoutMs??3e4,n=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Fo,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(w=>Li(new WebSocket(w)));let u=!1,g={state:"idle"};const h=new Set;let p=null,b=null,T=null,S=0,R=0,E=null,M=[],be=!1;const oe=w=>{if(!(g.state===w.state&&g.lastError===w.lastError)){g=w;for(const C of h)try{C(g)}catch{}}},tt=w=>{const C=M;M=[];for(const v of C)v.reject(w)},fr=w=>{const C=M;M=[];for(const v of C)v.resolve(w)},Pn=(w,C)=>{w.dead=!0;const v=Array.from(w.streams.values());w.streams.clear();for(const k of v)try{k.fail(C)}catch{}},pr=()=>{E!==null&&(clearTimeout(E),E=null)},hr=()=>{u||E===null||Ln()||(pr(),mr(),yr())},Dn=()=>{typeof document<"u"&&document.visibilityState==="visible"&&hr()},$s=()=>{be||typeof window>"u"||(be=!0,window.addEventListener("online",hr),typeof document<"u"&&document.addEventListener("visibilitychange",Dn))},mr=()=>{!be||typeof window>"u"||(be=!1,window.removeEventListener("online",hr),typeof document<"u"&&document.removeEventListener("visibilitychange",Dn))},Cn=()=>{if(u||E!==null)return;const w=Math.max(0,R-1),C=a*2**Math.min(w,10),v=Ln()?l:c,k=Math.min(v,C);$s(),E=setTimeout(()=>{E=null,mr(),yr()},k)},Ws=()=>{const w=new URL(e.relayUrl);return w.searchParams.set("v",String(at)),w.searchParams.set("role","client"),w.searchParams.set("serverId",e.serverId),e.grant&&w.searchParams.set("grant",e.grant),w.toString()},yr=async()=>{if(u)return;pr(),S+=1;const w=S;oe({state:R>0?"reconnecting":"connecting",lastError:g.lastError});let C;try{C=await hi(e.hostEncPubJwk,{batch:i})}catch(_){if(w!==S||u)return;rt(w,se(_),!0);return}if(w!==S||u)return;let v;try{v=d(Ws())}catch(_){rt(w,se(_));return}b=v;let k=!1,A=null,O=null,ee=null,z=null,P=Promise.resolve(),I=null,L=null,he=!1,B=null,G=Date.now();const K=()=>{A!==null&&(clearInterval(A),A=null),O!==null&&(clearTimeout(O),O=null),ee!==null&&(clearInterval(ee),ee=null),z!==null&&(clearTimeout(z),z=null),B!==null&&(B.dispose(),B=null)};T=K;function $(_,F=!1,N=!1){if(!(k||w!==S)){k=!0,K(),I&&(p=null,Pn(I,new Error(`relay tunnel reset: ${_.message}`))),tt(_);try{v.close()}catch{}if(b===v&&(b=null),!u){if(R+=1,N){oe({state:"error",lastError:_.message});return}oe({state:F?"error":"reconnecting",lastError:_.message}),Cn()}}}const x=()=>{try{v.send(C.helloText)}catch{}},De=(_,F)=>{L=_,he=F,A!==null&&(clearInterval(A),A=null),O!==null&&(clearTimeout(O),O=null);const N=new Map,U=Ai(),Ce=wi();let re=Promise.resolve();const me=je=>{re=re.then(async()=>{if(Ue.dead)return;const At=await _.encryptor.encrypt(je);v.send(At)}).catch(()=>{})},Me=F?ki({windowMs:s,sendBatch:me}):null;B=Me;const Ue={streams:N,assembler:Ce,nextStreamId:()=>U.next(),dead:!1,send(je){if(Ue.dead)return;const At=je[0]&~ht;At!==D.Ping&&At!==D.Pong&&(G=Date.now()),Me?Me.enqueue(je):me(je)}};I=Ue,p=Ue,R=0,G=Date.now(),oe({state:"connected"}),fr(Ue),ee=setInterval(()=>{Date.now()-G<n||(Ue.send(ye(D.Ping,0,wr)),z===null&&(z=setTimeout(()=>{z=null,$(new Error("relay keepalive timeout"))},o)))},n)},te=(_,F)=>{let N;try{N=mi(F)}catch(re){$(se(re));return}if(z!==null&&(clearTimeout(z),z=null),N.frameType===D.Ping){_.send(ye(D.Pong,N.streamId,wr));return}if(N.frameType===D.Pong)return;G=Date.now();let U=N.payload;if(N.frameType===D.WsText||N.frameType===D.WsBinary){let re;try{re=_.assembler.push(N)}catch(me){$(se(me));return}if(re===null)return;U=re}else if(N.hasMoreFragments){$(new Error("unexpected fragmented tunnel frame"));return}const Ce=_.streams.get(N.streamId);Ce&&Ce.handleFrame(N.frameType,U)};v.onopen=()=>{k||w!==S||(x(),A=setInterval(x,t))},v.onmessage=_=>{if(k||w!==S)return;const F=_.data;if(typeof F=="string"){P=P.then(async()=>{if(k||w!==S)return;const U=await C.handleText(F);if(U.type==="established"){if(L)return;De(U.channel,U.batch)}else U.type==="fail"&&$(new Error(`relay handshake failed: ${U.reason}`))}).catch(U=>{$(se(U))});return}const N=F instanceof ArrayBuffer?new Uint8Array(F):F instanceof Uint8Array?F:null;N&&(P=P.then(async()=>{if(k||w!==S)return;const U=I,Ce=L;if(!U||!Ce){$(new Error("encrypted frame before handshake completed"));return}let re;try{re=await Ce.decryptor.decrypt(N)}catch(me){$(se(me));return}if(he){let me;try{me=Si(re)}catch(Me){$(se(Me));return}for(const Me of me){if(k||w!==S||U.dead)return;te(U,Me)}return}te(U,re)}).catch(U=>{$(se(U))}))},v.onclose=_=>{const F=Bi.has(_.code);$(new Error(Ui[_.code]??`relay socket closed (code ${_.code})`),F,F)},v.onerror=()=>{},O=setTimeout(()=>{O=null,$(new Error("relay handshake timeout"),!0)},r);function rt(_,F,N=!1){_!==S||u||(tt(F),R+=1,oe({state:N?"error":"reconnecting",lastError:F.message}),Cn())}},Mn=w=>u?Promise.reject(new Error("relay tunnel closed")):w?.aborted?Promise.reject(Rt()):p&&!p.dead?Promise.resolve(p):new Promise((C,v)=>{let k=null;const A={resolve(O){k&&w&&w.removeEventListener("abort",k),C(O)},reject(O){k&&w&&w.removeEventListener("abort",k),v(O)}};w&&(k=()=>{M=M.filter(O=>O!==A),v(Rt())},w.addEventListener("abort",k,{once:!0})),M.push(A)}),qs=async(w,C)=>{const v=await _i(w,C),k=v.signal;if(k?.aborted)throw Rt();const A=await Mn(k),O=A.nextStreamId();return await new Promise((ee,z)=>{let P=!1,I=!1,L=null,he=null;const B=()=>{A.streams.delete(O),A.assembler.dropStream(O),he&&k&&k.removeEventListener("abort",he)},G=x=>{if(!I){if(I=!0,B(),!P){z(x);return}try{L?.error(x)}catch{}}},K=x=>{A.dead||A.send(ye(D.StreamAbort,O,Dt({reason:x})))};he=()=>{K("aborted"),G(Rt())},A.streams.set(O,{handleFrame(x,De){if(x===D.HttpResponse){if(P||I)return;let te;try{te=Ct(De,Di)}catch(F){K("malformed response head"),G(se(F));return}const rt=te.status===204||te.status===205||te.status===304;let _=null;rt||(_=new ReadableStream({start(F){L=F},cancel(){I||(I=!0,B(),K("response body cancelled"))}})),P=!0,ee(new Response(_,{status:te.status,headers:te.headers})),rt&&(I=!0,B());return}if(x===D.HttpBody){if(!P||I)return;try{L?.enqueue(De)}catch{}return}if(x===D.StreamEnd){if(I)return;if(!P){G(new Error("tunnel stream ended before response head"));return}I=!0,B();try{L?.close()}catch{}return}if(x===D.StreamAbort){let te="stream aborted by host";try{te=Ct(De,In).reason}catch{}G(new Error(te))}},fail(x){G(x)}}),k&&k.addEventListener("abort",he,{once:!0});const $={method:v.method,path:v.path,query:v.query,headers:v.headers};A.send(ye(D.HttpRequest,O,Dt($))),(async()=>{try{if(v.body)for await(const x of v.body){if(I||A.dead)return;for(const De of _o(x))A.send(ye(D.HttpBody,O,De))}!I&&!A.dead&&A.send(ye(D.StreamEnd,O,wr))}catch(x){K("request body failed"),G(se(x))}})()})},Ks=w=>{const C=w.indexOf("?");return C===-1?{path:w,query:""}:{path:w.slice(0,C),query:w.slice(C+1)}},Vs=(w,C)=>{let v=_n,k=null,A=0,O=!1;const ee={get readyState(){return v},onopen:null,onmessage:null,onerror:null,onclose:null,send(P){if(v!==br||!k||k.dead)throw new Error("relay tunnel socket is not open");if(typeof P=="string"){for(const L of On(D.WsText,A,Fi.encode(P)))k.send(L);return}const I=P instanceof ArrayBuffer?new Uint8Array(P.slice(0)):(()=>{const L=new Uint8Array(P.byteLength);return L.set(new Uint8Array(P.buffer,P.byteOffset,P.byteLength)),L})();for(const L of On(D.WsBinary,A,I))k.send(L)},close(P=1e3,I=""){v===xn||v===Fn||(v===br&&k&&!k.dead&&(v=Fn,k.send(ye(D.WsClose,A,Dt({code:P,reason:I})))),z(P,I))}},z=(P,I,L=!1)=>{if(!O){if(O=!0,k&&(k.streams.delete(A),k.assembler.dropStream(A)),v=xn,L)try{ee.onerror?.()}catch{}try{ee.onclose?.({code:P,reason:I})}catch{}}};return(async()=>{let P;try{P=await Mn()}catch(B){z(1006,se(B).message,!0);return}if(O)return;k=P,A=P.nextStreamId(),P.streams.set(A,{handleFrame(B,G){if(B===D.WsOpened){if(v===_n){v=br;try{ee.onopen?.()}catch{}}return}if(B===D.WsText){try{ee.onmessage?.({data:xi.decode(G)})}catch{}return}if(B===D.WsBinary){const K=new ArrayBuffer(G.byteLength);new Uint8Array(K).set(G);try{ee.onmessage?.({data:K})}catch{}return}if(B===D.WsClose){let K=1e3,$="";try{const x=Ct(G,Ci);K=x.code,$=x.reason}catch{}z(K,$);return}if(B===D.StreamAbort){let K="stream aborted";try{K=Ct(G,In).reason}catch{}z(1006,K,!0)}},fail(B){z(1012,B.message,!0)}});const{path:I,query:L}=Ks(w),he=C&&C.length>0?{path:I,query:L,protocols:C}:{path:I,query:L};P.send(ye(D.WsOpen,A,Dt(he)))})(),ee},Js=()=>{if(u)return;u=!0,S+=1,pr(),mr(),T?.(),T=null;const w=p;p=null;const C=new Error("relay tunnel closed");w&&Pn(w,C),tt(C);try{b?.close()}catch{}b=null,oe({state:"idle"})};return yr(),{fetch:qs,openWebSocket:Vs,getStatus:()=>g,subscribeStatus(w){return h.add(w),()=>{h.delete(w)}},close:Js}};let ne=null,lt=null;const ji=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),or=()=>ne,fu=()=>ne!==null,Hi=e=>(ne&&lt&&ji(lt,e)||(ne?.close(),lt=e,ne=Lo(e)),ne),pu=(e,t)=>{ne!==t&&(ne?.close(),lt=e,ne=t)},zi=()=>{ne?.close(),ne=null,lt=null};let No=()=>null,Bo="",Gt={},Le="",mt=0,Ie=null,Ve="",yt=0,He=null,Bt=0;const an=1e4,Gi=e=>e.toLowerCase()==="authorization",Uo=e=>{const t={};for(const[r,n]of Object.entries(e||{})){const o=r.trim(),s=n.trim();o&&s&&!Gi(o)&&(t[o]=s)}return t},$i=(e,t)=>{const r=Object.entries(e);return r.length!==Object.keys(t).length?!1:r.every(([n,o])=>t[n]===o)},sr=e=>typeof e!="string"?"":e.trim(),Wi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return sr(e)},qi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},jo=(e,t)=>{const r=typeof e=="string"&&e.trim()?e.trim():qi();if(!r)return t;try{return new URL(t,`${r.replace(/\/+$/,"")}/`).toString()}catch{return t}},ir=()=>{Le="",mt=0,Ve="",yt=0},Ho=()=>{Bt+=1,Ie=null,ir(),ln()},zo=e=>{const t=sr(e);Bo=t,Ho(),No=()=>t?{type:"bearer",token:t}:null},Go=e=>{const t=Uo(e);$i(Gt,t)||(Gt=t,Ho())},ar=()=>{if(Object.keys(Gt).length>0)return Gt;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Uo(e):{}},$o=()=>Bo||Wi(),Ki=(e,t)=>{const r=sr(e);if(!r||typeof t!="number"||!Number.isFinite(t)){ir();return}const n=Le;Le=r,mt=t,n&&n!==r&&Xi()},Wo=()=>!Le||mt<=Date.now()+an?(ir(),""):Le,qo=()=>!Ve||yt<=Date.now()+an?(Ve="",yt=0,""):Ve,Vi=()=>{const e=Wo();return!e&&($o()||typeof window<"u")&&cn().catch(()=>{}),e},Ji=e=>{const t=qo();return!t&&e&&typeof window<"u"&&Jo(e).catch(()=>{}),t},Ko=async()=>{const e=await No(),t=e?.type==="bearer"?sr(e.token):$o();return t?{type:"bearer",token:t}:null},Vo=e=>{if(Ie)return Ie;const t=Bt,n=(async()=>{const o=await Ko(),s=new Headers;for(const[u,g]of Object.entries(ar()))s.set(u,g);o?.type==="bearer"&&s.set("Authorization",`Bearer ${o.token}`);const i=or(),a=i?await i.fetch("/auth/url-token",{method:"POST",headers:s}):await fetch(jo(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===Bt&&ir(),new Error(`Failed to mint runtime URL auth token (${a.status})`);const c=await a.json().catch(()=>null),l=typeof c?.token=="string"?c.token.trim():"",d=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==Bt)throw new Error("Runtime URL auth token response is stale");if(Ki(l,d),!Le)throw new Error("Runtime URL auth token response was invalid");return Le})().finally(()=>{Ie===n&&(Ie=null)});return Ie=n,Ie},Yi=e=>{if(He)return He;const r=(async()=>{const n=await fetch(jo(e,"/auth/url-token"),{method:"POST",credentials:"include"});if(!n.ok)throw Ve="",yt=0,new Error(`Failed to mint local runtime URL auth token (${n.status})`);const o=await n.json().catch(()=>null),s=typeof o?.token=="string"?o.token.trim():"",i=typeof o?.expiresAt=="number"?o.expiresAt:0;if(!s||!Number.isFinite(i))throw new Error("Local runtime URL auth token response was invalid");return Ve=s,yt=i,s})().finally(()=>{He===r&&(He=null)});return He=r,He},cn=async e=>{const t=Wo();return t||Vo(e)},Jo=async e=>{const t=qo();return t||Yi(e)};let We=0,dt=null,Yo=null;const jr=new Set,Qi=5e3,Xi=()=>{for(const e of jr)try{e()}catch{}},Qo=()=>{dt!==null&&(clearTimeout(dt),dt=null)},ln=()=>{if(Qo(),We<=0||typeof window>"u")return;const e=mt-an-Qi,t=mt>0?Math.max(0,e-Date.now()):0;dt=setTimeout(()=>{dt=null,!(We<=0)&&Vo(Yo).catch(()=>{}).finally(()=>{ln()})},t)},hu=e=>{typeof e=="string"&&e.trim()&&(Yo=e.trim()),We+=1,ln();let t=!1;return()=>{t||(t=!0,We=Math.max(0,We-1),We===0&&Qo())}},mu=e=>(jr.add(e),()=>{jr.delete(e)}),Zi=async e=>{const t=new Headers(e);for(const[n,o]of Object.entries(ar()))t.has(n)||t.set(n,o);if(t.has("Authorization"))return t;const r=await Ko();return r?.type==="bearer"&&t.set("Authorization",`Bearer ${r.token}`),t},$t=/^[a-z][a-z\d+.-]*:\/\//i,ea=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},Wt=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),ta=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return Wt(e)},ra=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return Wt(e)},na=()=>Object.keys(ar()).length>0,oa=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Hr=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of r)o!=null&&e.searchParams.set(n,String(o))},sa=(e,t)=>{if(!t)return e;const r=new URLSearchParams;Hr({searchParams:r},t);const n=r.toString();return n?e.includes("?")?`${e}&${n}`:`${e}?${n}`:e},Nn=(e,t,r)=>{if($t.test(t)){const s=new URL(t);return Hr(s,r),s.toString()}const n=ea(t);if(!e)return sa(n,r);const o=new URL(n,`${e}/`);return Hr(o,r),o.toString()},Sr=e=>{const t=Vi();if(!t)return e;const r=$t.test(e)?new URL(e):new URL(e,"http://openchamber.local");return r.searchParams.set("oc_url_token",t),$t.test(e)?r.toString():`${r.pathname}${r.search}${r.hash}`},Xo=(e,t)=>{const r=$t.test(e)?new URL(e):new URL(e,oa(t));return r.protocol==="ws:"||r.protocol==="wss:"||(r.protocol=r.protocol==="https:"?"wss:":"ws:"),r.toString()},Bn=(e,t,r)=>{if(!na())return null;const n=ra();if(!n)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${n}/`);o.searchParams.set("url",t);const s=Ji(n);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Xo(o.toString(),r)):o.toString()}catch{return null}},dn=(e={})=>{const t=Wt(e.apiBaseUrl),r=Wt(e.realtimeBaseUrl),n=()=>t||ta(),o=()=>r||n(),s=(a,c)=>Nn(n(),a,c),i=(a,c)=>Nn(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>Sr(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=Sr(i(a,c));return Bn("sse",l,e)||l},websocket:(a,c)=>{const l=Xo(Sr(i(a,c)),e);return Bn("ws",l,e)||l}}};let qt=dn();const X=()=>qt,ia=e=>{qt=e},Zo=e=>(qt=dn(e),qt),Ne=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",aa=()=>typeof window>"u"?"":window.location.origin||"",un=e=>{if(typeof window>"u")return!1;const t=aa();if(t&&e.origin===t)return!0;try{const r=new URL(window.location.href||t);return e.protocol===r.protocol&&e.host===r.host}catch{return!1}},fn=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),pn=(e,t)=>{if(!t)return;const r=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[n,o]of r)o!=null&&e.searchParams.set(n,String(o))},Ut=e=>{try{const t=X().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const r=new URL(t);return e.origin!==r.origin?!1:Ne(e.pathname)}catch{return!1}},Tr=e=>{if(Ne(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return un(t)&&Ne(t.pathname)}catch{return!1}},ca=(e,t)=>{try{const r=new URL(e);if(!un(r))return e;const n=xe(`${r.pathname}${r.search}`,t);return!fn(n)&&(r.protocol==="http:"||r.protocol==="https:")?(pn(r,t),r.toString()):r.hash?`${n}${r.hash}`:n}catch{return e}},xe=(e,t)=>e==="/health"?X().health(t):e.startsWith("/auth/")||e==="/auth"?X().auth(e,t):Ne(e)?X().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?ca(e,t):e,la=e=>{const t=e instanceof Request?e.url:e.toString();if(!fn(t))return Ne(t);try{return Ut(new URL(t))}catch{return!1}},da=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},ua=(e,t)=>!da(t),Un=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 r=[];let n=!1,o=!1;for(const[s,i]of t)ua(s,i)?(r.push([s,encodeURIComponent(i)]),n=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):r.push([s,i]);return o&&r.push(["x-opencode-directory-encoding","uri"]),n?r:void 0},ge=async(e,t,r=!0)=>{const n=new Headers(Un(e)??e);return t&&new Headers(Un(t)??t).forEach((o,s)=>n.set(s,o)),r?Zi(n):n},fa=(e,t)=>{if(!t)return e;const r=new URL(e,sn);return pn(r,t),`${r.pathname}${r.search}`},es=(e,t)=>{const r=e instanceof Request?e.url:e.toString();if(!fn(r))return Ne(r)?fa(r,t):null;try{const n=new URL(r);return!un(n)||!Ne(n.pathname)?null:(pn(n,t),`${n.pathname}${n.search}`)}catch{return null}},pa=async(e,t,r)=>{const n=or();if(!n)return null;const o=es(e,r);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await ge(s,t.headers,!0);return e instanceof Request?n.fetch(e,{...t,headers:i}):n.fetch(o,{...t,headers:i})},ha=(e,t)=>{if(typeof e=="string")return xe(e,t);if(e instanceof URL)return xe(e.toString(),t);const r=xe(e.url,t);return r===e.url?e:new Request(r,e)},ma=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Ot=new Map,ya=(e,t,r)=>r||e!=="GET"||t.includes("/event")||!ma.test(t)?null:`GET ${t}`,f=async(e,t={})=>{const{query:r,...n}=t,o=or(),s=o?es(e,r):null;let i,a,c;if(o&&s!==null){const h=e instanceof Request?e.headers:void 0,p=await ge(h,n.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...n,headers:p}):()=>o.fetch(s,{...n,headers:p}),a=s,c=String(n.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const h=ha(e,r),p=h instanceof Request?h.headers:void 0,b=await ge(p,n.headers,la(h));i=h instanceof Request?()=>fetch(new Request(h,{...n,headers:b})):()=>fetch(h,{...n,headers:b}),a=h instanceof Request?h.url:h instanceof URL?h.toString():String(h),c=String(n.method??(h instanceof Request?h.method:"GET")).toUpperCase()}const l=n.signal!=null||e instanceof Request,d=ya(c,a,l);if(!d)return i();const u=Ot.get(d);if(u)return u.then(h=>h.clone());const g=i();return Ot.set(d,g),g.then(()=>Ot.delete(d),()=>Ot.delete(d)),g.then(h=>h.clone())};let jn=!1;const ga=()=>{if(jn||typeof window>"u")return;jn=!0;const e=window.fetch.bind(window);window.fetch=async(t,r)=>{const n=await pa(t,r??{});if(n)return n;if(typeof t=="string"){if(!Tr(t)){try{const s=new URL(t);if(Ut(s)){const i=await ge(void 0,r?.headers);return e(t,{...r,headers:i})}}catch{}return e(t,r)}const o=await ge(void 0,r?.headers);return e(xe(t),{...r,headers:o})}if(t instanceof URL){const o=t.toString();if(!Tr(o)){if(Ut(t)){const i=await ge(void 0,r?.headers);return e(t,{...r,headers:i})}return e(t,r)}const s=await ge(void 0,r?.headers);return e(xe(o),{...r,headers:s})}if(t instanceof Request){if(!Tr(t.url)){try{const a=new URL(t.url);if(Ut(a)){const c=await ge(t.headers,r?.headers);return e(new Request(t,{...r,headers:c}))}}catch{}return e(t,r)}const o=await ge(t.headers,r?.headers),s=xe(t.url),i=s===t.url?t:new Request(s,t);return e(new Request(i,{...r,headers:o}))}return e(t,r)}},zr="openchamber:runtime-endpoint-changed";let Kt="",gt="";const Er=(e,t,r)=>{try{e[t]=r}catch{}},hn=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"}`}},ts=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},rs=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ns=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},mn=()=>Kt||ts(),ke=()=>{if(gt)return gt;const e=mn();return ns(e,rs())?"local":hn(e)},wa=(e={})=>{if(Kt||gt)return;const t=e.apiBaseUrl?.trim()||ts();t&&(Kt=t,gt=e.runtimeKey?.trim()||(ns(t,rs())?"local":hn(t)))},Gr=e=>{const t=e.apiBaseUrl.trim(),r=mn(),n=ke(),o=e.runtimeKey?.trim()||hn(t);if(Kt=t,gt=o,typeof window<"u"){const s=window;Er(s,"__OPENCHAMBER_API_BASE_URL__",t),Er(s,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Er(s,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Zo({apiBaseUrl:t,realtimeBaseUrl:t}),Go(e.requestHeaders||null),zo(e.clientToken||null),e.relay?Hi(e.relay):zi(),cn(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zr,{detail:{apiBaseUrl:t,previousApiBaseUrl:r,runtimeKey:o,previousRuntimeKey:n}}))},ba=e=>{if(typeof window>"u")return()=>{};const t=r=>{e(r.detail)};return window.addEventListener(zr,t),()=>window.removeEventListener(zr,t)},Sa=["local","remote",null],Ta=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function os(e){if(!e||typeof e!="object")return{valid:!1};const t=e,r=t.target,n=t.status;if(r!==null&&(typeof r!="string"||!Sa.includes(r)))return{valid:!1};if(typeof n!="string"||!Ta.includes(n))return{valid:!1};if(r==="remote"||r==="local"){if(n==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok"}};if(n==="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}};if(n==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable"}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url}};if(n==="incompatible"||n==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:n,hostId:t.hostId,url:t.url}};if(n==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId}}}if(r===null){if(n==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured"}};if(n==="missing")return{valid:!1}}return{valid:!1}}function yu(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;if(t.status==="ok"){if(t.target==="local")return{screen:"main"};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser"};if(t.target==="local"&&t.status==="unreachable")return{screen:"recovery",variant:"local-unavailable"};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId}}return null}function gu(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function wu(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function Ea(){if(va()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,r=os(t);return r.valid?r.outcome:null}function va(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":os(e).valid?"valid":"malformed"}let $r=null;const bu=e=>{$r=e},cr=()=>$r||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),ka=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,Ze=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Et=()=>ka()?.runtime==="electron",lr=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},Su=()=>{if(!Et())return!1;const e=lr();return e==="win32"||e==="linux"},Aa=(e=lr())=>e==="linux"?"left":"right",Tu=(e,t=lr())=>e==="left"||e==="right"?e:Aa(t),Y=()=>typeof Ze()?.invoke=="function",et=()=>Et()&&Y(),H=async(e,t)=>{const r=Ze();return typeof r?.invoke!="function"?null:r.invoke(e,t??{})},Eu=async()=>{if(!et()||!Q())return null;try{const e=await H("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}},vu=async e=>{if(!et()||!Q())return null;try{const t=await H("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}},ku=async()=>{if(!et()||!Q())return null;try{const e=await H("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}},Au=async e=>{if(!et()||!Q())return null;try{const t=await H("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}},Pu=async()=>{if(!et()||!Q())return null;try{const e=await H("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}},Du=async e=>{if(!et()||!Q())return null;try{const t=await H("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}},Hn=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}}},vr=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}}},Pa=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),nt=e=>{const t=Pa(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Q=()=>{if(typeof window>"u"||!ss())return!1;if(ke()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=vr(e),r=vr(mn());if(!r&&t&&Ea()?.target==="local")return!0;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&&nt(t.hostname)&&nt(r.hostname)}const n=vr(window.location.origin);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&&nt(t.hostname)&&nt(n.hostname)}const o=Hn(e),s=Hn(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(n&&nt(n.hostname))},ss=()=>typeof window>"u"?!1:Et(),Cu=async()=>{if(!ss())return!1;try{return await H("desktop_start_window_drag"),!0}catch{return!1}},dr=()=>cr()?.runtime?.isVSCode===!0,Mu=()=>{const t=cr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!dr()},is=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},Ru=async e=>{if(Y()&&Q())try{const t=await Ze()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory"});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:!0,path:e}},as=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ou=async e=>{if(Y()&&Q())try{const t=await Ze()?.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(!as(t))return{success:!1,error:"File selection cancelled"};const r=typeof t.path=="string"?t.path:"";return r?{success:!0,path:r,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"}},Iu=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!Y()||!Q())return{success:!1,error:"Native file access not available"};try{const r=await Ze()?.grantFileAccess?.(t);if(!as(r))return{success:!1,error:"File access was not granted"};const n=typeof r.path=="string"?r.path:"",o=typeof r.outsideFileGrant=="string"?r.outsideFileGrant:"";return!n||!o?{success:!1,error:"File access was not granted"}:{success:!0,path:n,outsideFileGrant:o}}catch(r){return console.warn("Failed to request existing file access",r),{success:!1,error:r instanceof Error?r.message:String(r)}}},_u=async e=>({success:!0}),Fu=async e=>({success:!0}),xu=async()=>Y()?await H("desktop_check_for_updates"):null,Lu=async e=>{if(!Y())return!1;const t=Ze();let r=null,n=0,o;try{return typeof e=="function"&&t?.listen&&(r=await t.listen("openchamber:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){n=0,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:n,total:o});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(n=d),typeof u=="number"&&(o=u),e({downloaded:n,total:o});return}c==="Finished"&&e({downloaded:n,total:o})})),await H("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(r)try{const s=r();s instanceof Promise&&await s}catch{}}},Nu=async()=>Y()?Da():!1,Da=async()=>{if(!Y())return!1;try{return await H("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},Bu=async()=>{if(!Y()||!Q())return null;try{const e=await H("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}},Ca=async(e,t)=>{if(!Y()||!Q())return!1;const r=e?.trim();if(!r)return!1;try{return await H("desktop_open_path",{path:r,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(n){return console.warn("Failed to open path",n),!1}},Uu=async e=>{if(!Y()||!Q())return!1;const t=e?.trim();if(!t)return!1;try{return await H("desktop_reveal_path",{path:t}),!0}catch{return Ca(t)}},ju=async(e,t)=>{if(!Y()||!Q())return null;const r=e?.trim();if(!r)return null;try{const n=await H("desktop_save_markdown_file",{defaultFileName:r,content:t});return typeof n=="string"&&n.trim().length>0?n:null}catch(n){return console.warn("Failed to save markdown file",n),null}},Hu=async(e,t,r)=>{if(!Y()||!Q())return!1;const n=e?.trim(),o=t?.trim(),s=r?.trim();if(!n||!o||!s)return!1;try{return await H("desktop_open_in_app",{projectPath:n,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},zu=async(e,t,r)=>{if(!Y()||!Q())return!1;const n=e?.trim(),o=t?.trim(),s=r?.trim();if(!n||!o||!s)return!1;try{return await H("desktop_open_file_in_app",{filePath:n,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},Gu=async(e,t)=>{if(!Y()||!Q())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};if(lr()==="linux")return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};const r=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];if(r.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const n=await H("desktop_get_installed_apps",{apps:r,force:t===!0?!0:void 0});if(!n||typeof n!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=n;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(n){return console.warn("Failed to fetch installed apps",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Ye=e=>typeof e=="object"&&e!==null,Ma=e=>e.trim().toLowerCase()==="authorization",Ra=e=>{if(!Ye(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=r.trim(),s=typeof n=="string"?n.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||Ma(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},$u=e=>`relay://${e}`,Oa=e=>{if(!Ye(e))return null;const t=J(e,"relayUrl")||J(e,"relay_url"),r=J(e,"serverId")||J(e,"server_id"),n=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!r||!Ye(n)?null:{relayUrl:t,serverId:r,hostEncPubJwk:n}},Ia=/^(t|.*(?:token|auth|secret|api).*)$/i,Ae=e=>{const t=e.trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Wu=e=>{const t=Ae(e);if(!t)return null;try{const r=new URL(t);if((r.pathname.replace(/\/+$/,"")||"/")==="/connect"&&r.searchParams.has("t"))return{persistedUrl:r.origin,redeemUrl:r.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},qu=e=>{const t=Ae(e);if(!t)return e;try{const r=new URL(t);(r.username||r.password)&&(r.username="",r.password="");const n=Array.from(new Set(Array.from(r.searchParams.keys())));for(const o of n)Ia.test(o)&&r.searchParams.set(o,"[REDACTED]");return r.toString()}catch{return t}},Ku=(e,t)=>{const r=Ae(e),n=Ae(t);if(!r||!n)return!1;try{const o=new URL(r),s=new URL(n);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}},J=(e,t)=>{const r=e[t];return typeof r=="string"?r:null},zn=(e,t)=>{const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:null},_a=e=>{if(!Ye(e))return null;const t=J(e,"id"),r=J(e,"label"),n=J(e,"url"),o=J(e,"apiUrl")||J(e,"api_url"),s=J(e,"clientToken")||J(e,"client_token"),i=Ra(e.requestHeaders),a=Oa(e.relay);return!t||!r||!n?null:{id:t,label:r,url:n,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Fa=e=>Ae(e.apiUrl||e.url)||e.apiUrl||e.url,Be=()=>Y()?(e,t)=>H(e,t):null,cs=async()=>{const e=Be();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Ye(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const r=t.hosts,n=Array.isArray(r)?r.map(_a).filter(a=>!!a):[],o=J(t,"defaultHostId")||J(t,"default_host_id")||J(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=J(t,"localOrigin")||J(t,"local_origin");return{hosts:n,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},xa=async e=>{const t=Be();if(!t)return;const r={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(r.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:r})},Vu=async()=>{const e=Be();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Ju=async()=>{const e=Be();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},La=8e3,Yu=async(e,t)=>{const r=Lo({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),n=Date.now();let o=!1;try{return(await Promise.race([r.fetch("/health"),new Promise(i=>{const a=window.setTimeout(()=>i(null),La);typeof a!="number"&&typeof a.unref=="function"&&a.unref()})]))?.ok?(o=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-n),...o?{tunnel:r}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{o||r.close()}},ls=async(e,t)=>{const r=Be();if(!r)return{status:"unreachable",latencyMs:0};const n=await r("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Ye(n))return{status:"unreachable",latencyMs:0};const o=n.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=zn(n,"latencyMs")??zn(n,"latency_ms")??0;return{status:s,latencyMs:i}},Qu=async(e,t)=>{const r=Be();r&&await r("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Xu=async e=>{const t=Be();t&&await t("desktop_new_window_for_host",{hostId:e})},Na=5e3,Ba=1500;let kr=!1;const Ua=async e=>{if(!Et()||kr)return;const t=`host:${e}`;if(ke()===t){kr=!0;try{const r=await cs().catch(()=>null),n=r?.hosts.find(u=>u.id===e);if(!r||!n?.relay)return;const o=n.apiUrl?Ae(n.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await f("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.json().catch(()=>null);if(!i||i.serverId!==n.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const u of a){if(!u||typeof u!="object")continue;const g=u;if(g.type!=="lan"||typeof g.url!="string")continue;const h=Ae(g.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 xa({hosts:r.hosts.map(u=>u.id===e?{...u,apiUrl:l}:u),defaultHostId:r.defaultHostId,initialHostChoiceCompleted:r.initialHostChoiceCompleted}).catch(()=>{});const d=await ls(l,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(d.status==="unreachable"||d.status==="wrong-service"||d.status==="incompatible"||ke()!==t)return;Gr({apiBaseUrl:l,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:t})}finally{kr=!1}}},ja=e=>{typeof window>"u"||window.setTimeout(()=>{Ua(e).catch(()=>{})},Na)},Ha=async e=>{if(!Et())return;const t=await cs().catch(()=>null);if(!t)return;const r=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!r)return;const n=t.hosts.find(u=>u.id===r);if(!n?.relay)return;const o=`host:${n.id}`;if(ke()===o)return;const s=u=>{Gr({apiBaseUrl:u,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:o})},i=()=>{Gr({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:n.clientToken||null,runtimeKey:o,relay:n.relay??void 0}),ja(n.id)},a=n.apiUrl?Ae(Fa(n)):null;if(!a){i();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",l=ls(a,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),d=await Promise.race([l,new Promise(u=>setTimeout(()=>u(null),Ba))]);if(d){if(c(d)){s(a);return}i();return}i(),l.then(u=>{c(u)&&ke()===o&&s(a)})},Gn=500,ds=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("OPENCHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},Zu=()=>ds(),ie=(e,t)=>{if(!ds())return;const r=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=r,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(r-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>Gn&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Gn)},za=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(n=>n.name==="ModelControls:ready"),r=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,r).filter(n=>n.name.includes("checkConnection")||n.name.includes("checkHealth")||n.name.includes("initializeApp")||n.name.includes("initApp")||n.name.includes("loadProviders")||n.name.includes("loadAgents")||n.name.includes("config.defaults")||n.name.includes("modelsMetadata")||n.name.includes("ModelControls")||n.name.includes("activateDirectory")||n.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=za);const ef=async(e,t,r)=>{const n=typeof performance<"u"?performance.now():Date.now();ie(`${e}:start`,r);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return ie(`${e}:end`,{durationMs:Math.round(s-n)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw ie(`${e}:error`,{durationMs:Math.round(s-n),error:o instanceof Error?o.message:String(o)}),o}},Ga=3,$a=3e4,Wa=32e3,qa=3600*1e3,Ka=600*1e3,Va=new Set([429,502,503,504]),Qe=new Map;function Ja(){const e=Date.now();for(const[t,r]of Qe)r.consecutiveErrors===0&&e-r.lastErrorAt>qa&&Qe.delete(t)}typeof setInterval<"u"&&setInterval(Ja,Ka).unref?.();function Ya(e){let t=Qe.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:$a},Qe.set(e,t)),t}function Qa(e){if(!e)return;const t=Qe.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function $n(e,t){if(!e)return;const r=Ya(e);r.consecutiveErrors+=1,r.lastErrorAt=Date.now(),Xa(t)&&r.consecutiveErrors>=Ga&&(r.circuitOpen=!0,r.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${r.consecutiveErrors} consecutive errors`))}function Xa(e){return e!==void 0&&Va.has(e)}function Za(e){const t=Qe.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Wa*4),!1):!0:!1}function ec(e){if(!(!e||!Za(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const Wn="/api",tc=1e4,rc=4e3;function qe(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)}}function Z(e,t){if(e.error){const r=e.response?.status,n=new Error(`${t} failed${r?` (${r})`:""}: ${qe(e.error)}`);throw r!==void 0&&(n.status=r),n}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function ze(e,t){if(e.error){const r=e.response?.status,n=new Error(`${t} failed${r?` (${r})`:""}: ${qe(e.error)}`);throw r!==void 0&&(n.status=r),n}return e.data}const nc=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,qn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",oc=14;let Kn=0,Ar=0;const sc=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<e;n+=1)t[n]=Math.floor(Math.random()*256);let r="";for(let n=0;n<e;n+=1)r+=qn[t[n]%qn.length];return r},Vn=e=>{const t=Date.now();t!==Kn&&(Kn=t,Ar=0),Ar+=1;const r=BigInt(t)*BigInt(4096)+BigInt(Ar),n=new Uint8Array(6);for(let s=0;s<6;s+=1)n[s]=Number(r>>BigInt(40-8*s)&BigInt(255));const o=Array.from(n,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${sc(oc)}`},Jn=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(nc.test(t)||typeof window>"u")return t;const r=window.location?.href||window.location?.origin;if(!r)return t;try{return new URL(t,r).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),t}},Yn=()=>{try{return X().api("/api")}catch{return null}},ic=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>clearTimeout(n)}},Pr=e=>Qs({...e,fetch:f}),Ge=e=>e.replace(/\\/g,"/"),Qn=400,Xn=()=>{const e=cr();return e&&e.runtime?.isDesktop&&e.files?e.files:null};class ac{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=Wn){const n=Yn()||t;this.baseUrl=Jn(n),this.client=Pr({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Yn(),r=Jn(t||Wn);r!==this.baseUrl&&(this.baseUrl=r,this.client=Pr({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 r=this.normalizeCandidatePath(t)??t,n=r||"",o=this.scopedClients.get(n);if(o)return o;const s=Pr({baseUrl:this.baseUrl,directory:r});return this.scopedClients.set(n,s),s}normalizeCandidatePath(t){if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const n=r.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(t){const r=t.match(/^([A-Za-z]:)(?:\/|$)/);if(r){const s=r[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 n=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?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 r=this.normalizeCandidatePath(t)??t;this.currentDirectory!==r&&ie("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:r??null}),this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(t,r){const n=async()=>{if(t==null)return r();const s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await r()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,r=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&&(r(s.directory),r(s.worktree),r(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);r(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>r(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(r(this.currentDirectory),typeof window<"u")try{r(window.localStorage.getItem("lastDirectory")),r(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&r(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(t);return this.deriveHomeDirectory(n)}async probeDirectory(t){const r=this.normalizeCandidatePath(t);if(!r)return!1;try{const o=(await this.client.path.get({directory:r})).data,s=typeof o?.directory=="string"?o.directory:null;return!!(s&&s.trim().length>0)}catch{return!1}}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,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.create({...n?{directory:n}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Z(o,"session.create")}async getSession(t,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...n?{directory:n}:{}});return Z(o,"session.get")}async deleteSession(t,r){const n=this.normalizeCandidatePath(r)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...n?{directory:n}:{}});return ze(o,"session.delete")===!0}async updateSession(t,r,n){const o=this.normalizeCandidatePath(n)??this.currentDirectory,s={...r.title!==void 0?{title:r.title}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},...r.time?.archived!==void 0&&r.time.archived!==null?{time:{archived:r.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Z(i,"session.update")}async getSessionMessages(t,r){const n=await this.client.session.messages({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof r=="number"?{limit:r}:{}});return Z(n,"session.messages")}async getSessionTodos(t){try{const r=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(r.error)return[];const n=r.data;return!n||!Array.isArray(n)?[]:n}catch{return[]}}shouldNormalizeToTextPlain(t){if(!t)return!1;const r=t.toLowerCase();return r.startsWith("text/")&&r!=="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(r)}isHeicMime(t){if(!t)return!1;const r=t.toLowerCase();return r==="image/heic"||r==="image/heif"}async convertHeicToJpeg(t){try{const r=(await Ys(async()=>{const{default:u}=await import("./vendor-.bun-BE757pvp.js").then(g=>g.h);return{default:u}},[])).default,n=t.url.indexOf(",");if(n===-1)return t;const o=t.url.substring(n+1),s=atob(o),i=new Uint8Array(s.length);for(let u=0;u<s.length;u++)i[u]=s.charCodeAt(u);const a=new Blob([i],{type:t.mime}),c=await r({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((u,g)=>{const h=new FileReader;h.onload=()=>u(h.result),h.onerror=g,h.readAsDataURL(c)});let d=t.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(r){return console.warn("Failed to convert HEIC to JPEG:",r),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let r=t.url;if(t.url.startsWith("data:")){const n=t.url.indexOf(",");if(n!==-1){const o=t.url.substring(5,n),s=t.url.substring(n);r=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:r}}async toNormalizedFilePartInput(t){const r=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:r.mime,filename:r.filename,url:r.url}}async sendMessage(t){const r=t.messageId??Vn("msg"),n=[];if(t.prefaceText&&t.prefaceText.trim()&&n.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};n.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const d=await this.toNormalizedFilePartInput(l);n.push(d)}if(t.additionalParts&&t.additionalParts.length>0){for(const l of t.additionalParts)if(l.text&&l.text.trim()&&n.push({type:"text",text:l.text,...l.synthetic?{synthetic:!0}:{}}),l.files&&l.files.length>0)for(const d of l.files){const u=await this.toNormalizedFilePartInput(d);n.push(u)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&n.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(n.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}),ec(t.providerID);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:r,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:n});if(l.response instanceof Response)s=l.response;else if(l.error){const d=l.response?.status;if(!d)throw new Error(`Message send transport failure: ${qe(l.error)}`);s=new Response(JSON.stringify(l.error),{status:d})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw $n(t.providerID),l}if(s.ok)return Qa(t.providerID),r;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,$n(t.providerID,s.status),c}async sendCommand(t){const r=t.messageId??Vn("msg"),n=[];if(t.files&&t.files.length>0)for(const i of t.files)n.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,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,...n.length>0?{parts:n}:{},messageID:r});return ze(s,"session.command"),r}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){const r=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,n=await this.client.session.shell({sessionID:t.sessionId,...r?{directory:r}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Z(n,"session.shell")}async revertSession(t,r,n,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:r,partID:n});return Z(i,"session.revert")}async summarizeSession(t,r,n,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:r,modelID:n});return ze(i,"session.summarize")===!0}async unrevertSession(t){const r=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Z(r,"session.unrevert")}async forkSession(t,r,n){const o=this.normalizeCandidatePath(n)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:r});return Z(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const r=typeof t=="string"?t.trim():"",n=await this.client.session.status(r?{directory:r}:void 0);return n.error||!n.data||typeof n.data!="object"?null:n.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const t=await f("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const r=await t.json().catch(()=>null);return!r||typeof r!="object"?null:r}catch{return null}}async listToolIds(t){try{const r=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(r?{directory:r}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,r,n){const o=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:r,...n?.message?{message:n.message}:{}});return ze(s,"permission.reply")===!0}async createPermission(t,r,n,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:r,resources:n,...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,r){try{const n=await this.client.v2.session.permission.get({sessionID:t,requestID:r});if(n.error===void 0){const o=n.data?.data;if(o!==void 0)return{state:"ok",permission:o}}return n.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const r=[],n=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${qe(d.error)}`);return d.data||[]};r.push(n(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)r.push(n(c));const s=await Promise.all(r),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}async replyToQuestion(t,r,n){const o=!Array.isArray(r)||r.length===0?[]:Array.isArray(r[0])?r:[r],s=this.normalizeCandidatePath(n)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return ze(i,"question.reply")===!0}async rejectQuestion(t){const r=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return ze(r,"question.reject")===!0}async listPendingQuestions(t){const r=[],n=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${qe(d.error)}`);return d.data||[]};r.push(n(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)r.push(n(c));const s=await Promise.all(r),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.configCache.get(n);if(o&&o.expiresAt>Date.now())return ie("opencodeClient.getConfig:cacheHit",{directory:r??null}),o.config;const s=this.configInFlight.get(n);if(s)return ie("opencodeClient.getConfig:deduped",{directory:r??null}),s;const i=this.configCacheGeneration,a=(async()=>{ie("opencodeClient.getConfig:start",{directory:r??null});const c=typeof performance<"u"?performance.now():Date.now(),d=await(r?this.getScopedApiClient(r):this.client).config.get();if(!d.data)throw new Error("Failed to get config");const u=typeof performance<"u"?performance.now():Date.now();return ie("opencodeClient.getConfig:end",{directory:r??null,durationMs:Math.round(u-c)}),i===this.configCacheGeneration&&this.configCache.set(n,{config:d.data,expiresAt:Date.now()+tc}),d.data})();this.configInFlight.set(n,a);try{return await a}finally{this.configInFlight.get(n)===a&&this.configInFlight.delete(n)}}async updateConfig(t){const r=await this.client.config.update({config:t}),n=Z(r,"global.config.update");return this.clearConfigCache(),n}async updateConfigPartial(t){const r=await this.getConfig(),n=t(r);return await this.updateConfig(n)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.configProvidersInFlight.get(n);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(r?{directory:r}:void 0);return Z(i,"config.providers")})();this.configProvidersInFlight.set(n,s);try{return await s}finally{this.configProvidersInFlight.delete(n)}}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 r=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,n=r??"",o=this.listAgentsInFlight.get(n);if(o)return o;const s=(async()=>{const i=r?{directory:r}: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 f("/api/agent",{...r?{query:{directory:r}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${qe(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(n,s);try{return await s}finally{this.listAgentsInFlight.delete(n)}}async readFile(t){try{const r=await this.client.file.read({path:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(Z(r,"file.read"))}catch{return`// Content of ${t}
2
+ // This would be loaded from the server`}}async listFiles(t){try{const r=t||this.currentDirectory||"/",n=await this.client.file.list({path:r,...this.currentDirectory?{directory:this.currentDirectory}:{}}),o=Z(n,"file.list");return Array.isArray(o)?o:[]}catch{return[]}}async listCommands(){const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(Z(t,"command.list")||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model,source:n.source}))}async listCommandsWithDetails(){const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return(Z(t,"command.list")||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model,source:n.source,template:n.template}))}async listSkillsWithDetails(){try{const r=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(r))return[];const n=[];for(const o of r){const s=typeof o.name=="string"?o.name.trim():"",i=typeof o.location=="string"?o.location:"";if(!s||!i)continue;const a={name:s,location:i};typeof o.description=="string"&&(a.description=o.description),typeof o.content=="string"&&(a.content=o.content),n.push(a)}return n}catch{return[]}}async getCommandDetails(t){try{const r=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(r.data){const n=r.data.find(o=>o.name===t);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,r=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;ie("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:r});const n=ic(rc),o=await f(r,{signal:n.signal}).finally(n.cleanup);if(ie("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return ie("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,r){const n=Xn();if(n?.createDirectory)try{return await n.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}const o={path:t,...r?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await f(`${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 r=await f(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(n.error||"Failed to clone repository")}return await r.json()}async listLocalDirectory(t,r){const o=`${typeof t=="string"?Ge(t.trim()):""}|${r?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const d=Xn();if(d)try{const u=await d.listDirectory(t||"",r);if(!u||!Array.isArray(u.entries))return[];const g=u.entries.map(h=>({name:h.name,path:Ge(h.path),isDirectory:!!h.isDirectory,isFile:!h.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:g,expiresAt:Date.now()+Qn}),g}catch(u){throw console.error("Failed to list directory contents:",u),u}try{const u=new URLSearchParams;t&&t.trim().length>0&&u.set("path",t),r?.respectGitignore&&u.set("respectGitignore","true");const g=u.toString(),h=await f(`${this.baseUrl}/fs/list${g?`?${g}`:""}`);if(!h.ok){const T=await h.json().catch(()=>({})),S=typeof T.error=="string"?T.error:"Failed to list directory";throw new Error(S)}const p=await h.json();if(!p||!Array.isArray(p.entries))return[];const b=p.entries;return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+Qn}),b}catch(u){throw console.error("Failed to list directory contents:",u),u}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,r){const n=typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():this.currentDirectory,o=n?Ge(n):null,s=n?this.getScopedApiClient(n):this.client;try{const i=await s.find.files({query:t,limit:typeof r?.limit=="number"&&Number.isFinite(r.limit)?r.limit:void 0,dirs:r?.dirs===!1||r?.type==="file"?"false":"true",type:r?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=Ge(c),d=l.split("/").filter(Boolean).pop()||l,u=Ge(o?`${o}/${l}`:l);return{name:d,path:u,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=ke();if(!t||t==="local"){const r=await is();if(r)return r}try{const r=await f(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){const o=await r.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const n=await r.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(r){return console.warn("Failed to resolve filesystem home directory:",r),null}}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const r=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",r,"with path:",t);try{const n=await f(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await n.json().catch(()=>null);if(!n.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(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const ve=new ac,cc=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const r=new TextEncoder().encode(t);let n="";for(const s of r)n+=String.fromCharCode(s);return`path_${typeof btoa=="function"?btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let Dr=null,Cr=null,Mr=null;const Zn=new Set;let eo=!1;const us=e=>{if(Zn.add(e),eo||typeof window>"u")return;eo=!0;const t=()=>{for(const r of Zn)r()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),window.addEventListener("visibilitychange",()=>{typeof document<"u"&&document.visibilityState==="hidden"&&t()}),window.addEventListener("freeze",t)}catch{}},lc=(e,t)=>{let r;try{r=e()}catch{return}const n=new Map,o=new Set;let s;const i=()=>{if(s=void 0,n.size===0&&o.size===0)return;const c=Array.from(n.entries()),l=Array.from(o);n.clear(),o.clear();for(const[d,u]of c)try{r.setItem(d,JSON.stringify(u,t?.replacer))}catch(g){console.error("Failed to persist deferred storage value",g)}for(const d of l)try{r.removeItem(d)}catch(u){console.error("Failed to remove deferred storage value",u)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return us(i),{getItem:c=>{if(n.has(c))return n.get(c)??null;if(o.has(c))return null;const l=u=>u===null?null:JSON.parse(u,t?.reviver),d=r.getItem(c);return d instanceof Promise?d.then(l):l(d)},setItem:(c,l)=>{n.set(c,l),o.delete(c),a()},removeItem:c=>{n.delete(c),o.add(c),a()}}},fs=e=>lc(()=>hs(),e),dc=e=>{const t=new Map,r=new Set;let n;const o=()=>{if(n=void 0,t.size===0&&r.size===0)return;const i=Array.from(t.entries()),a=Array.from(r);t.clear(),r.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(d){console.error("Failed to persist deferred storage value",d)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l)}},s=()=>{n===void 0&&(n=setTimeout(o,0))};return us(o),{getItem:i=>t.has(i)?t.get(i)??null:r.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),r.delete(i),s()},removeItem:i=>{t.delete(i),r.add(i),s()},clear:()=>{t.clear(),r.clear(),n!==void 0&&(clearTimeout(n),n=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},ps=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Vt=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,r)=>{e.set(t,r)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},uc=()=>{const e=ps("localStorage");if(!e)return Vt();const t=Vt();let r=!0;const n=()=>{r=!1};return{getItem:l=>{if(r)try{const d=e.getItem(l);if(d!==null)return d}catch{n()}return t.getItem(l)},setItem:(l,d)=>{if(r)try{e.setItem(l,d),t.removeItem(l);return}catch{n();try{e.removeItem(l)}catch{}}t.setItem(l,d)},removeItem:l=>{try{e.removeItem(l)}catch{n()}t.removeItem(l)},clear:()=>{try{e.clear()}catch{n()}t.clear()},key:l=>{if(r)try{return e.key(l)}catch{n()}return t.key(l)},get length(){if(r)try{return e.length+t.length}catch{n()}return t.length}}},hs=()=>(Dr||(Dr=uc()),Dr),vt=()=>(Mr||(Mr=dc(hs())),Mr),fc=()=>{const e=ps("sessionStorage");if(!e)return Vt();const t=Vt();let r=!0;const n=()=>{r=!1};return{getItem:l=>{if(r)try{const d=e.getItem(l);if(d!==null)return d}catch{n()}return t.getItem(l)},setItem:(l,d)=>{if(r)try{e.setItem(l,d),t.removeItem(l);return}catch{n();try{e.removeItem(l)}catch{}}t.setItem(l,d)},removeItem:l=>{try{e.removeItem(l)}catch{n()}t.removeItem(l)},clear:()=>{try{e.clear()}catch{n()}t.clear()},key:l=>{if(r)try{return e.key(l)}catch{n()}return t.key(l)},get length(){if(r)try{return e.length+t.length}catch{n()}return t.length}}},tf=()=>(Cr||(Cr=fc()),Cr),pc={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},rf={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function to(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const It={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)"}}},Rr={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...It.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Rr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...It.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Rr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...It.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Rr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...It.tool.inline})},hc=[{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:"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'}],mc=[{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'}],ms=e=>Object.fromEntries(e.map(t=>[t.id,t])),yc=ms(hc),gc=ms(mc),wc="system",bc="system-mono",ys=e=>typeof e=="string"&&e in yc,gs=e=>typeof e=="string"&&e in gc,Wr="openchamber.mobileKeyboardMode",Sc='meta[name="viewport"]',ro="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",nf=()=>!0;function ur(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Tc=e=>ur(e)==="resize-content"?`${ro}, interactive-widget=resizes-content`:ro,Ec=()=>{if(typeof window>"u")return"resize-content";try{return ur(localStorage.getItem(Wr))}catch{return"resize-content"}},ws=e=>{const t=ur(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Wr):localStorage.setItem(Wr,t)}catch{}return t},of=e=>{const t=ws(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const r=document.querySelector(Sc);if(r instanceof HTMLMetaElement){const n=Tc(t);r.getAttribute("content")!==n&&r.setAttribute("content",n)}return t};function no(e){return e==="vim"?"vim":"default"}const _t={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}"}},Se={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Ft=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,vc=e=>{if(!e||typeof e!="object")return!1;const t=e;return Ft(t.completion,_t.completion)&&Ft(t.error,_t.error)&&Ft(t.question,_t.question)&&Ft(t.subtask,_t.subtask)},yn=380,kc=380,Ac=1400,bs=12,oo=120,ot=280,st=360,Pc=860,Or=new Map,Ir=e=>(e??ke()).trim()||"default",V=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),r=t.startsWith("//");let n=t.replace(/\/+$/g,"");return n=n.replace(/\/+/g,"/"),r&&!n.startsWith("//")&&(n=`/${n}`),n===""?t.startsWith("/")?"/":"":n},Ss=e=>Number.isFinite(e)?Math.min(Ac,Math.max(kc,Math.round(e))):yn,Jt=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Yt=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>oo?t.slice(0,oo):t:null},gn=e=>e==="working"||e==="staged"||e==="turn"?e:null,Dc=(e,t)=>(e==="file"||e==="preview")&&t||e,Ts=(e,t,r)=>{if(e==="diff")return e;if(typeof r=="string"){const n=r.trim();if(n)return n}return Dc(e,t)},Es=(e,t)=>t===e?e:`${e}:${t}`,vs=e=>{const t=Jt(e.targetPath),r=Ts(e.mode,t,e.dedupeKey);return{id:Es(e.mode,r),mode:e.mode,targetPath:t,dedupeKey:r,label:Yt(e.label),sessionTitleFallback:Yt(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:gn(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},ks=(e,t,r)=>{if(e.length<=t)return e;const o=[...e].sort((a,c)=>a.touchedAt-c.touchedAt).filter(a=>a.id!==r),s=e.length-t;if(s<=0||o.length===0)return e.slice(-t);const i=new Set(o.slice(0,s).map(a=>a.id));return e.filter(a=>!i.has(a.id))},As=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n;if(o.mode!=="diff"&&o.mode!=="file"&&o.mode!=="context"&&o.mode!=="plan"&&o.mode!=="chat"&&o.mode!=="preview"&&o.mode!=="browser")continue;const s=Jt(typeof o.targetPath=="string"?o.targetPath:null),i=Ts(o.mode,s,typeof o.dedupeKey=="string"?o.dedupeKey:null),a=Es(o.mode,i);!a||r.has(a)||(r.add(a),t.push({id:a,mode:o.mode,targetPath:s,dedupeKey:i,label:Yt(typeof o.label=="string"?o.label:null),sessionTitleFallback:Yt(typeof o.sessionTitleFallback=="string"?o.sessionTitleFallback:null),readOnly:o.readOnly===!0,stagedDiff:o.stagedDiff===!0,diffScope:gn(o.diffScope)??(o.stagedDiff===!0?"staged":"working"),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return t},wt=(e,t)=>t&&e.some(r=>r.id===t)?t:e.length===0?null:e[e.length-1].id,Re=e=>{if(e){const t=As(e.tabs),r=wt(t,e.activeTabId);return{...e,tabs:t,activeTabId:r,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:yn,touchedAt:Date.now()}},Cc=(e,t)=>{const r=vs(t),n=e.tabs.findIndex(a=>a.id===r.id),o=n===-1?[...e.tabs,r]:e.tabs.map((a,c)=>c===n?{...a,mode:r.mode,targetPath:r.targetPath||a.targetPath,dedupeKey:r.dedupeKey,label:r.label,sessionTitleFallback:r.sessionTitleFallback||a.sessionTitleFallback,stagedDiff:r.stagedDiff,diffScope:r.diffScope,readOnly:r.readOnly,touchedAt:Date.now()}:a),s=r.id,i=ks(o,bs,s);return{...e,isOpen:!0,tabs:i,activeTabId:wt(i,s),touchedAt:Date.now()}},Mc=(e,t)=>{const r=e.tabs.filter(o=>o.id!==t),n=e.activeTabId===t?r[r.length-1]?.id??null:wt(r,e.activeTabId);return{...e,tabs:r,activeTabId:n,isOpen:r.length>0?e.isOpen:!1,touchedAt:Date.now()}},Rc=(e,t,r)=>{if(t===r)return e;const n=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===r);if(n===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(n,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},Oc=(e,t,r)=>({...e,tabs:e.tabs.map(n=>n.id===t?{...n,targetPath:r}:n)}),_r=e=>{if(!e||typeof e!="object")return{};const t=e,r={};for(const[n,o]of Object.entries(t)){const s=V(n);if(!s||!o||typeof o!="object")continue;const i=o;let a=As(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")&&(a=[vs({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=wt(a,c),d=ks(a,bs,l);r[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:wt(d,l),width:Ss(typeof i.width=="number"?i.width:yn),touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return r},Oe=(e,t)=>{const r=Object.entries(e);if(r.length<=t)return e;r.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const n={};for(const[o,s]of r.slice(0,t))n[o]=s;return n},ue=tr()(rr(vo((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:ot,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:st,hasManuallyResizedRightSidebar:!1,rightSidebarTab:"git",contextPanelByDirectory:{},isBottomTerminalOpen:!1,isBottomTerminalExpanded:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,notesPanelHeight:112,todoPanelHeight:259,isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingDiagramFile:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:13,editorFontSize:13,uiFont:wc,monoFont:bc,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Ec(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,gitChangesViewMode:"flat",isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!0,inputSpellcheckEnabled:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"auto",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!1,expandedEditorToolbar:!1,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,isMobileSessionStatusBarCollapsed:!1,mobileSessionPanelOpen:!1,mobileSessionFilterProjectId:null,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:r=>{e({theme:r}),t().applyTheme()},toggleSidebar:()=>{e(r=>{const n=!r.isSidebarOpen;return n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:ot}:{isSidebarOpen:n}})},setSidebarOpen:r=>{e(n=>n.isSidebarOpen===r?r&&!n.hasManuallyResizedLeftSidebar&&n.sidebarWidth!==ot?{isSidebarOpen:r,sidebarWidth:ot}:n:r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:ot}:{isSidebarOpen:r})},setSidebarWidth:r=>{e({sidebarWidth:r,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{e(r=>{const n=!r.isRightSidebarOpen;return n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:st}:{isRightSidebarOpen:n}})},setRightSidebarOpen:r=>{e(n=>{if(n.isRightSidebarOpen===r)return n;const o=r&&!n.hasManuallyResizedRightSidebar&&n.rightSidebarWidth!==st;return{isRightSidebarOpen:r,rightSidebarWidth:o?st:n.rightSidebarWidth}})},setRightSidebarWidth:r=>{const n=Math.min(Pc,Math.max(st,r));e({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:r=>{e({rightSidebarTab:r})},openContextPanelTab:(r,n)=>{const o=V((r||"").trim());o&&e(s=>{const i=s.contextPanelByDirectory[o],a=Re(i),c={...s.contextPanelByDirectory,[o]:Cc(a,n)};return{contextPanelByDirectory:Oe(c,20)}})},openContextDiff:(r,n,o=!1,s=null)=>{const i=V((r||"").trim()),a=(n||"").trim();if(!i||!a)return;const c=gn(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(r,n)=>{const o=V((r||"").trim()),s=Jt(n);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(r,n,o,s)=>{const i=V((r||"").trim()),a=Jt(n),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:r=>{const n=V((r||"").trim());n&&t().openContextPanelTab(n,{mode:"context"})},openContextPlan:r=>{const n=V((r||"").trim());n&&t().openContextPanelTab(n,{mode:"plan"})},openContextPreview:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();if(!o||!s)return;let i=null;try{const a=new URL(s);(a.protocol==="http:"||a.protocol==="https:")&&(i=a.host||a.hostname||"Preview")}catch{}t().openContextPanelTab(o,{mode:"preview",targetPath:s,dedupeKey:s,label:i})},openContextBrowser:(r,n="")=>{const o=V((r||"").trim());if(!o)return;const s=typeof n=="string"&&n.trim().length>0?n.trim():"";t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:"desktop-browser",label:"Browser"})},setContextPanelTabTargetPath:(r,n,o)=>{const s=V((r||"").trim()),i=(n||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:Oc(c,i,o)}}:a})},setActiveContextPanelTab:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Re(a);if(!c.tabs.some(d=>d.id===s)||c.activeTabId===s&&c.isOpen)return i;const l={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===s?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:Oe(l,20)}})},reorderContextPanelTabs:(r,n,o)=>{const s=V((r||"").trim()),i=(n||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],d=Re(l);if(!d.tabs.some(h=>h.id===i)||!d.tabs.some(h=>h.id===a))return c;const u=Rc(d,i,a);if(u.tabs===d.tabs)return c;const g={...c.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:Oe(g,20)}})},closeContextPanelTab:(r,n)=>{const o=V((r||"").trim()),s=(n||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Re(a);if(!c.tabs.some(d=>d.id===s))return i;const l={...i.contextPanelByDirectory,[o]:Mc(c,s)};return{contextPanelByDirectory:Oe(l,20)}})},closeContextPanel:r=>{const n=V((r||"").trim());n&&e(o=>{const s=o.contextPanelByDirectory[n];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[n]:{...Re(s),isOpen:!1}};return{contextPanelByDirectory:Oe(i,20)}})},toggleContextPanelExpanded:r=>{const n=V((r||"").trim());n&&e(o=>{const s=o.contextPanelByDirectory[n],i=Re(s),a={...o.contextPanelByDirectory,[n]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:Oe(a,20)}})},setContextPanelWidth:(r,n)=>{const o=V((r||"").trim());o&&e(s=>{const i=s.contextPanelByDirectory[o],a=Re(i),c={...s.contextPanelByDirectory,[o]:{...a,width:Ss(n)}};return{contextPanelByDirectory:Oe(c,20)}})},toggleBottomTerminal:()=>{e(r=>{const n=!r.isBottomTerminalOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalOpen:r=>{e(n=>{if(n.isBottomTerminalOpen===r){if(!r)return n;if(!n.hasManuallyResizedBottomTerminal&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return n.bottomTerminalHeight===o&&n.hasManuallyResizedBottomTerminal===!1?n:{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return n}if(r&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalExpanded:r=>{e({isBottomTerminalExpanded:r})},setBottomTerminalHeight:r=>{e({bottomTerminalHeight:r,hasManuallyResizedBottomTerminal:!0})},setNotesPanelHeight:r=>{e({notesPanelHeight:r})},setTodoPanelHeight:r=>{e({todoPanelHeight:r})},setSessionSwitcherOpen:r=>{t().isSessionSwitcherOpen!==r&&e({isSessionSwitcherOpen:r})},setSessionDropdownOpen:r=>{t().isSessionDropdownOpen!==r&&e({isSessionDropdownOpen:r})},setMainTabGuard:r=>{t().mainTabGuard!==r&&e({mainTabGuard:r})},setActiveMainTab:r=>{const n=t().mainTabGuard;n&&!n(r)||(Or.set(Ir(),r),e({activeMainTab:r}))},prepareForRuntimeSwitch:r=>{Or.set(Ir(r),t().activeMainTab)},restoreForRuntimeSwitch:r=>{const n=Or.get(Ir(r))??"chat";e({activeMainTab:n})},setPendingDiffFile:(r,n=!1,o=null)=>{e({pendingDiffFile:r,pendingDiffStaged:r?n:!1,pendingDiffScope:r?o:null})},setPendingDiagramFile:r=>{e({pendingDiagramFile:r})},setPendingFileNavigation:r=>{e({pendingFileNavigation:r})},setPendingFileFocusPath:r=>{e({pendingFileFocusPath:r})},navigateToDiff:(r,n=!1,o=null)=>{const s=t().mainTabGuard;s&&!s("diff")||e({pendingDiffFile:r,pendingDiffStaged:n,pendingDiffScope:o,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:r}=t();return r&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),r},navigateToDiagram:r=>{const n=t().mainTabGuard;n&&!n("diagram")||e({pendingDiagramFile:r,activeMainTab:"diagram"})},consumePendingDiagramFile:()=>{const{pendingDiagramFile:r}=t();return r&&e({pendingDiagramFile:null}),r},setIsMobile:r=>{e({isMobile:r})},toggleCommandPalette:()=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen}))},setCommandPaletteOpen:r=>{e({isCommandPaletteOpen:r})},toggleHelpDialog:()=>{e(r=>({isHelpDialogOpen:!r.isHelpDialogOpen}))},setHelpDialogOpen:r=>{e({isHelpDialogOpen:r})},setAboutDialogOpen:r=>{e({isAboutDialogOpen:r})},setOpenCodeStatusDialogOpen:r=>{e({isOpenCodeStatusDialogOpen:r})},setOpenCodeStatusText:r=>{e({openCodeStatusText:r})},setSessionCreateDialogOpen:r=>{e({isSessionCreateDialogOpen:r})},setScheduledTasksDialogOpen:r=>{e({isScheduledTasksDialogOpen:r})},setSettingsDialogOpen:r=>{e(n=>r?n.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:r=>{e({isNewWorktreeDialogOpen:r})},setModelSelectorOpen:r=>{e({isModelSelectorOpen:r})},setSidebarSection:r=>{e({sidebarSection:r})},setSettingsPage:r=>{e({settingsPage:r})},setSettingsProjectsSelectedId:r=>{e({settingsProjectsSelectedId:r})},setSettingsRemoteInstancesSelectedId:r=>{e({settingsRemoteInstancesSelectedId:r})},setEventStreamStatus:(r,n)=>{e({eventStreamStatus:r,eventStreamHint:n??null})},setShowReasoningTraces:r=>{e({showReasoningTraces:r})},setSessionRecapEnabled:r=>{e({sessionRecapEnabled:r})},setSessionSuggestionEnabled:r=>{e({sessionSuggestionEnabled:r})},setSessionGoalEnabled:r=>{e({sessionGoalEnabled:r})},setSessionGoalDefaultBudgetEnabled:r=>{e({sessionGoalDefaultBudgetEnabled:r})},setSessionGoalDefaultBudget:r=>{e({sessionGoalDefaultBudget:r})},setCollapsibleThinkingBlocks:r=>{e({collapsibleThinkingBlocks:r})},setChatRenderMode:r=>{e({chatRenderMode:r})},setActivityRenderMode:r=>{e({activityRenderMode:r})},setShowDeletionDialog:r=>{e({showDeletionDialog:r})},setAutoDeleteEnabled:r=>{e({autoDeleteEnabled:r})},setAutoDeleteAfterDays:r=>{const n=Math.max(1,Math.min(365,r));e({autoDeleteAfterDays:n})},setSessionRetentionAction:r=>{e({sessionRetentionAction:r})},setAutoDeleteLastRunAt:r=>{e({autoDeleteLastRunAt:r})},setMessageLimit:r=>{const n=Math.max(10,Math.min(500,Math.round(r)));e({messageLimit:n})},setFontSize:r=>{const n=Math.max(50,Math.min(200,r));e({fontSize:n}),t().applyTypography()},setGlobalDraftStarters:r=>{e({globalDraftStarters:r})},setTerminalFontSize:r=>{const n=Math.round(r),o=Math.max(9,Math.min(52,n));e({terminalFontSize:o})},setEditorFontSize:r=>{const n=Math.round(r),o=Math.max(9,Math.min(32,n));e({editorFontSize:o})},setUiFont:r=>{e({uiFont:r})},setMonoFont:r=>{e({monoFont:r})},setPadding:r=>{const n=Math.max(50,Math.min(200,r));e({padding:n}),t().applyPadding()},setCornerRadius:r=>{e({cornerRadius:r})},applyTypography:()=>{const{fontSize:r}=t(),n=document.documentElement,o=r/100,s=Object.entries(pc);if(o===1){for(const[i]of s)n.style.removeProperty(to(i));return}for(const[i,a]of s){const c=parseFloat(a);Number.isFinite(c)&&n.style.setProperty(to(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:r}=t(),n=document.documentElement,o=r/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);n.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:r=>{e({diffLayoutPreference:r})},setDiffFileLayout:(r,n)=>{e(o=>({diffFileLayout:{...o.diffFileLayout,[r]:n}}))},setDiffWrapLines:r=>{e({diffWrapLines:r})},setGitChangesViewMode:r=>{e({gitChangesViewMode:r})},setInputBarOffset:r=>{e({inputBarOffset:r})},setMobileKeyboardMode:r=>{e(n=>n.mobileKeyboardMode===r?n:{mobileKeyboardMode:r})},toggleFavoriteModel:(r,n)=>{e(o=>o.favoriteModels.some(i=>i.providerID===r&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===r&&i.modelID===n))}:{favoriteModels:[{providerID:r,modelID:n},...o.favoriteModels]})},reorderFavoriteModel:(r,n,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(u=>u.providerID===r&&u.modelID===n),c=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):i})},setProviderOrder:r=>{e(n=>{const o=r.filter(i=>typeof i=="string"&&i.length>0),s=n.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?n:{providerOrder:o}})},toggleHiddenModel:(r,n)=>{e(o=>o.hiddenModels.some(i=>i.providerID===r&&i.modelID===n)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===r&&i.modelID===n))}:{hiddenModels:[{providerID:r,modelID:n},...o.hiddenModels]})},isHiddenModel:(r,n)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===r&&s.modelID===n)},hideAllModels:(r,n)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==r);return{hiddenModels:[...n.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:r,modelID:a})),...s]}})},showAllModels:r=>{e(n=>({hiddenModels:n.hiddenModels.filter(o=>o.providerID!==r)}))},toggleModelProviderCollapsed:r=>{const n=typeof r=="string"?r.trim():"";n&&e(o=>o.collapsedModelProviders.includes(n)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==n)}:{collapsedModelProviders:[...o.collapsedModelProviders,n]})},setModelProvidersCollapsed:(r,n)=>{const o=Array.from(new Set(r.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:n?[...a,...o]:a}})},isFavoriteModel:(r,n)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===r&&s.modelID===n)},addRecentModel:(r,n)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===r&&i.modelID===n));return{recentModels:[{providerID:r,modelID:n},...s].slice(0,5)}})},addRecentAgent:r=>{const n=typeof r=="string"?r.trim():"";n&&e(o=>{if(o.recentAgents.includes(n))return o;const s=o.recentAgents;return{recentAgents:[n,...s].slice(0,5)}})},addRecentEffort:(r,n,o)=>{const s=typeof r=="string"?r.trim():"",i=typeof n=="string"?n.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";e(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const u=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...u].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||e(r=>{const n={};if(r.isBottomTerminalOpen&&!r.hasManuallyResizedBottomTerminal){const o=Math.floor(window.innerHeight*.32);r.bottomTerminalHeight!==o&&(n.bottomTerminalHeight=o)}return Object.keys(n).length>0?n:r})},applyTheme:()=>{const{theme:r}=t(),n=document.documentElement;if(n.classList.remove("light","dark"),r==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(r)},setMultiRunLauncherOpen:r=>{e(n=>({isMultiRunLauncherOpen:r,multiRunLauncherPrefillPrompt:r?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:r=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:r,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:r=>{e({isTimelineDialogOpen:r})},setPromptNavigatorPanelOpen:r=>{e({isPromptNavigatorPanelOpen:r})},togglePromptNavigatorPanel:()=>{e(r=>({isPromptNavigatorPanelOpen:!r.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:r=>{e({isImagePreviewOpen:r})},setNativeNotificationsEnabled:r=>{e({nativeNotificationsEnabled:r})},setNotificationMode:r=>{e({notificationMode:r})},setShowTerminalQuickKeysOnDesktop:r=>{e({showTerminalQuickKeysOnDesktop:r})},setNotifyOnSubtasks:r=>{e({notifyOnSubtasks:r})},setDockBadgeEnabled:r=>{e({dockBadgeEnabled:r})},setNotifyOnCompletion:r=>{e({notifyOnCompletion:r})},setNotifyOnError:r=>{e({notifyOnError:r})},setNotifyOnQuestion:r=>{e({notifyOnQuestion:r})},setNotificationTemplates:r=>{e({notificationTemplates:r})},setSummarizeLastMessage:r=>{e({summarizeLastMessage:r})},setSummaryThreshold:r=>{e({summaryThreshold:r})},setSummaryLength:r=>{e({summaryLength:r})},setMaxLastMessageLength:r=>{e({maxLastMessageLength:r})},setPersistChatDraft:r=>{e({persistChatDraft:r})},setShowOpenCodeUpdateNotifications:r=>{e({showOpenCodeUpdateNotifications:r})},setInputSpellcheckEnabled:r=>{e({inputSpellcheckEnabled:r})},setWideChatLayoutEnabled:r=>{e({wideChatLayoutEnabled:r})},setCodeBlockLineWrap:r=>{e({codeBlockLineWrap:r})},setShowToolFileIcons:r=>{e({showToolFileIcons:r})},setShowTurnChangedFiles:r=>{e({showTurnChangedFiles:r})},setShowExpandedBashTools:r=>{e({showExpandedBashTools:r})},setShowExpandedEditTools:r=>{e({showExpandedEditTools:r})},setTimeFormatPreference:r=>{e({timeFormatPreference:r})},setWeekStartPreference:r=>{e({weekStartPreference:r})},setDesktopWindowControlsPosition:r=>{e({desktopWindowControlsPosition:r})},setMermaidRenderingMode:r=>{e({mermaidRenderingMode:r})},setUserMessageRenderingMode:r=>{e({userMessageRenderingMode:r})},setCollapsibleUserMessages:r=>{e({collapsibleUserMessages:r})},setStickyUserHeader:r=>{e({stickyUserHeader:r})},setPromptNavigatorEnabled:r=>{e({promptNavigatorEnabled:r})},setExpandedEditorToolbar:r=>{e({expandedEditorToolbar:r})},setShowSplitAssistantMessageActions:r=>{e({showSplitAssistantMessageActions:r})},setAllowPromptingSubagentSessions:r=>{e({allowPromptingSubagentSessions:r})},setIsMobileSessionStatusBarCollapsed:r=>{e({isMobileSessionStatusBarCollapsed:r})},setMobileSessionPanelOpen:r=>{e({mobileSessionPanelOpen:r})},setMobileSessionFilterProjectId:r=>{e({mobileSessionFilterProjectId:r})},setReportUsage:r=>{e({reportUsage:r})},viewPagerPage:"center",setViewPagerPage:r=>{e({viewPagerPage:r}),e(r==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:r==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(r,n)=>{e(o=>({shortcutOverrides:{...o.shortcutOverrides,[r]:n}}))},clearShortcutOverride:r=>{e(n=>{const o={...n.shortcutOverrides};return delete o[r],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:r=>{e({fileEditorKeymap:no(r)})},toggleExpandedInput:()=>{e(r=>({isExpandedInput:!r.isExpandedInput}))},setExpandedInput:r=>{e({isExpandedInput:r})}}),{name:"ui-store",storage:fs(),version:10,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const r=e;if(t<10&&delete r.diffViewMode,t<9&&((typeof r.notesPanelHeight!="number"||!Number.isFinite(r.notesPanelHeight))&&(r.notesPanelHeight=112),(typeof r.todoPanelHeight!="number"||!Number.isFinite(r.todoPanelHeight))&&(r.todoPanelHeight=259)),t<1&&vc(r.notificationTemplates)&&(r.notificationTemplates={completion:{...Se.completion},error:{...Se.error},question:{...Se.question},subtask:{...Se.subtask}}),t<3){const n=new Set([90,120,180,220]),o=r.memoryLimitHistorical,s=r.memoryLimitActiveSession;typeof o=="number"&&!n.has(o)?r.messageLimit=o:typeof s=="number"&&!n.has(s)&&(r.messageLimit=s),delete r.memoryLimitHistorical,delete r.memoryLimitViewport,delete r.memoryLimitActiveSession}if((typeof r.rightSidebarTab!="string"||r.rightSidebarTab!=="git"&&r.rightSidebarTab!=="files"&&r.rightSidebarTab!=="context")&&(r.rightSidebarTab="git"),r.contextPanelByDirectory=_r(r.contextPanelByDirectory),t<5)if(!r.shortcutOverrides||typeof r.shortcutOverrides!="object")r.shortcutOverrides={};else{const n=r.shortcutOverrides,o={};for(const[s,i]of Object.entries(n))typeof s=="string"&&typeof i=="string"&&(o[s]=i);r.shortcutOverrides=o}return t<6&&(r.contextPanelByDirectory=_r(r.contextPanelByDirectory)),t<7&&(r.contextPanelByDirectory=_r(r.contextPanelByDirectory)),t<8&&r.gitChangesViewMode!=="flat"&&r.gitChangesViewMode!=="tree"&&(r.gitChangesViewMode="flat"),r.fileEditorKeymap=no(r.fileEditorKeymap),r},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,isRightSidebarOpen:e.isRightSidebarOpen,rightSidebarWidth:e.rightSidebarWidth,rightSidebarTab:e.rightSidebarTab,contextPanelByDirectory:e.contextPanelByDirectory,isBottomTerminalOpen:e.isBottomTerminalOpen,isBottomTerminalExpanded:e.isBottomTerminalExpanded,bottomTerminalHeight:e.bottomTerminalHeight,notesPanelHeight:e.notesPanelHeight,todoPanelHeight:e.todoPanelHeight,isSessionSwitcherOpen:e.isSessionSwitcherOpen,activeMainTab:e.activeMainTab,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,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,autoDeleteEnabled:e.autoDeleteEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,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,gitChangesViewMode:e.gitChangesViewMode,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,inputSpellcheckEnabled:e.inputSpellcheckEnabled,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,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,expandedEditorToolbar:e.expandedEditorToolbar,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,isMobileSessionStatusBarCollapsed:e.isMobileSessionStatusBarCollapsed,mobileSessionFilterProjectId:e.mobileSessionFilterProjectId,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Ps="queue",wn=e=>e==="steer"||e==="queue",bn=(e,t)=>e==="immediate"?"steer":wn(e)?e:t===!1?"steer":t===!0?"queue":Ps,Ic=tr()(rr(vo((e,t)=>({queuedMessages:{},followUpBehavior:Ps,addToQueue:(r,n)=>{const s={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now(),sendConfig:n.sendConfig};e(i=>{const a=i.queuedMessages[r]??[];return{queuedMessages:{...i.queuedMessages,[r]:[...a,s]}}})},removeFromQueue:(r,n)=>{e(o=>{const i=(o.queuedMessages[r]??[]).filter(a=>a.id!==n);if(i.length===0){const{[r]:a,...c}=o.queuedMessages;return{queuedMessages:c}}return{queuedMessages:{...o.queuedMessages,[r]:i}}})},reorderQueue:(r,n,o)=>{n!==o&&e(s=>{const i=s.queuedMessages[r];if(!i)return s;const a=i.findIndex(u=>u.id===n),c=i.findIndex(u=>u.id===o);if(a===-1||c===-1)return s;const l=i.slice(),[d]=l.splice(a,1);return l.splice(c,0,d),{queuedMessages:{...s.queuedMessages,[r]:l}}})},popToInput:(r,n)=>{const i=(t().queuedMessages[r]??[]).find(a=>a.id===n);return i?(e(a=>{const l=(a.queuedMessages[r]??[]).filter(d=>d.id!==n);if(l.length===0){const{[r]:d,...u}=a.queuedMessages;return{queuedMessages:u}}return{queuedMessages:{...a.queuedMessages,[r]:l}}}),i):null},clearQueue:r=>{e(n=>{const{[r]:o,...s}=n.queuedMessages;return{queuedMessages:s}})},clearAllQueues:()=>{e({queuedMessages:{}})},setFollowUpBehavior:r=>{e({followUpBehavior:r}),fe({followUpBehavior:r})},getQueueForSession:r=>t().queuedMessages[r]??[]}),{name:"message-queue-store",version:1,storage:fs(),partialize:e=>({queuedMessages:e.queuedMessages,followUpBehavior:e.followUpBehavior}),migrate:e=>{const t=e??{};return{queuedMessages:t.queuedMessages??{},followUpBehavior:bn(t.followUpBehavior,t.queueModeEnabled??null)}}}),{name:"message-queue-store"})),Ds="directoryTreeShowHidden",qr="directory-show-hidden-change",so=()=>{if(typeof window>"u")return!0;try{const e=vt().getItem(Ds);return e===null?!0:e==="true"}catch{return!0}},_c=()=>{typeof window>"u"||window.dispatchEvent(new Event(qr))},Fc=(e,t={})=>{if(!(typeof window>"u")){try{vt().setItem(Ds,e?"true":"false"),_c()}catch{}t.persist!==!1&&fe({directoryShowHidden:e})}},sf=()=>{const e=ko.c(2),[t,r]=zt.useState(so);let n,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{r(so())};return window.addEventListener("storage",s),window.addEventListener(qr,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(qr,s)}},o=[],e[0]=n,e[1]=o):(n=e[0],o=e[1]),zt.useEffect(n,o),t},Cs="filesViewShowGitignored",Kr="files-view-show-gitignored-change",io=()=>{if(typeof window>"u")return!1;try{return vt().getItem(Cs)==="true"}catch{return!1}},xc=()=>{typeof window>"u"||window.dispatchEvent(new Event(Kr))},Lc=(e,t={})=>{if(!(typeof window>"u")){try{vt().setItem(Cs,e?"true":"false"),xc()}catch{}t.persist!==!1&&fe({filesViewShowGitignored:e})}},af=()=>{const e=ko.c(2),[t,r]=zt.useState(io);let n,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{r(io())};return window.addEventListener("storage",s),window.addEventListener(Kr,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Kr,s)}},o=[],e[0]=n,e[1]=o):(n=e[0],o=e[1]),zt.useEffect(n,o),t},Nc=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},Bc=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Uc=e=>{const t=ue.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},jc=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),r=Bc(t);return Nc(r)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},Ms=[{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:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],Hc=new Map(Ms.map(e=>[e.name,e])),cf=e=>Hc.get(e),lf=Ms.map(e=>({type:"command",name:e.name})),df="terminal-box",uf="book-open",ff=e=>`${e.type}:${e.name}`,pf=(e,t)=>e.type===t.type&&e.name===t.name,hf=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Rs=e=>{if(!Array.isArray(e))return[];const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n,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}`;r.has(a)||(r.add(a),t.push({type:s,name:i}))}return t},zc=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Vr=e=>{if(!(typeof window>"u")){if(e.themeId&&localStorage.setItem("selectedThemeId",e.themeId),e.themeVariant&&localStorage.setItem("selectedThemeVariant",e.themeVariant),e.lightThemeId&&localStorage.setItem("lightThemeId",e.lightThemeId),e.darkThemeId&&localStorage.setItem("darkThemeId",e.darkThemeId),typeof e.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(e.useSystemTheme)),e.lastDirectory&&localStorage.setItem("lastDirectory",e.lastDirectory),e.homeDirectory&&(localStorage.setItem("homeDirectory",e.homeDirectory),zc(e.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(r=>r.sidebarCollapsed===!0).map(r=>r.id).filter(r=>typeof r=="string"&&r.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):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"),typeof e.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&localStorage.setItem("openInAppId",e.openInAppId),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}if(typeof e.mobileKeyboardMode=="string"&&ws(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")}typeof e.dictationEnabled=="boolean"&&localStorage.setItem("dictationEnabled",String(e.dictationEnabled)),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&localStorage.setItem("sttProvider",e.sttProvider),typeof e.sttServerUrl=="string"&&localStorage.setItem("sttServerUrl",e.sttServerUrl),typeof e.sttModel=="string"&&localStorage.setItem("sttModel",e.sttModel),typeof e.sttLocalModel=="string"&&localStorage.setItem("sttLocalModel",e.sttLocalModel),typeof e.sttLanguage=="string"&&localStorage.setItem("sttLanguage",e.sttLanguage)}},Jr=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:e}))},Gc=e=>{if(!Array.isArray(e))return;const t=[],r=new Set;for(const n of e){if(!n||typeof n!="object")continue;const o=n,s=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",a=typeof o.source=="string"?o.source.trim():"",c=typeof o.subpath=="string"?o.subpath.trim():"",l=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!s||!i||!a||r.has(s)||(r.add(s),t.push({id:s,label:i,source:a,...c?{subpath:c}:{},...l?{gitIdentityId:l}:{}}))}return t},$c=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=typeof r=="string"?r.trim():"",s=typeof n=="string"?n.trim():"";!o||!s||(t[o]=s)}return t},Wc=(e,t)=>{const r=Object.entries(e),n=Object.entries(t);return r.length!==n.length?!1:r.every(([o,s])=>t[o]===s)},Fr=(e,t)=>e.length===t.length&&e.every((r,n)=>r.providerID===t[n]?.providerID&&r.modelID===t[n]?.modelID),Yr=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),Qr=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.length>0)))},qc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e)){if(!r||!Array.isArray(n))continue;const o=Qr(n);o&&o.length>0&&(t[r]=o.slice(0,5))}return Object.keys(t).length>0?t:void 0},Kc=(e,t)=>{const r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Array.isArray(t[n])&&Yr(e[n],t[n]))},Vc=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Jc=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&Vc.test(t)?t.toLowerCase():null},Yc=e=>{if(!Array.isArray(e))return;const t=[],r=new Set,n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.path=="string"?s.path.trim():"";if(!i)continue;const a=i==="/"?i:i.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=cc(a);if(!c||r.has(c)||n.has(a))continue;r.add(c),n.add(a);const l={id:c,path:a};if(typeof s.label=="string"&&s.label.trim().length>0&&(l.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(l.icon=s.icon.trim()),s.iconImage===null)l.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,u=typeof d.mime=="string"?d.mime.trim():"",g=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,h=d.source==="custom"||d.source==="auto"?d.source:null;u&&g>0&&h&&(l.iconImage={mime:u,updatedAt:g,source:h})}if(typeof s.color=="string"&&s.color.trim().length>0&&(l.color=s.color.trim()),s.iconBackground===null)l.iconBackground=null;else{const d=Jc(s.iconBackground);d&&(l.iconBackground=d)}typeof s.addedAt=="number"&&Number.isFinite(s.addedAt)&&s.addedAt>=0&&(l.addedAt=s.addedAt),typeof s.lastOpenedAt=="number"&&Number.isFinite(s.lastOpenedAt)&&s.lastOpenedAt>=0&&(l.lastOpenedAt=s.lastOpenedAt),typeof s.sidebarCollapsed=="boolean"&&(l.sidebarCollapsed=s.sidebarCollapsed),t.push(l)}return t.length>0?t:void 0},Qc=e=>{if(!Array.isArray(e))return;const t=[],r=new Set,n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.name=="string"?s.name.trim():"",c=typeof s.hostname=="string"?s.hostname.trim().toLowerCase():"";!i||!a||!c||r.has(i)||n.has(c)||(r.add(i),n.add(c),t.push({id:i,name:a,hostname:c}))}return t},Xc=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r={};for(const[n,o]of Object.entries(t)){const s=n.trim(),i=typeof o=="string"?o.trim():"";!s||!i||(r[s]=i)}return Object.keys(r).length>0?r:void 0},xr=(e,t)=>{if(!Array.isArray(e))return;const r=[],n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.providerID=="string"?s.providerID.trim():"",a=typeof s.modelID=="string"?s.modelID.trim():"";if(!i||!a)continue;const c=`${i}/${a}`;if(!n.has(c)&&(n.add(c),r.push({providerID:i,modelID:a}),r.length>=t))break}return r},Os=()=>{const e=ue.persist;if(e&&typeof e=="object")return e},Is=()=>cr()?.settings??null,Xr=e=>{const t=ue.getState(),r=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,n=typeof window<"u"?window.__zustand_config_store__??null:null,o=Ic.getState();if(typeof e.showReasoningTraces=="boolean"&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.sessionRecapEnabled=="boolean"&&e.sessionRecapEnabled!==t.sessionRecapEnabled&&t.setSessionRecapEnabled(e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&e.sessionSuggestionEnabled!==t.sessionSuggestionEnabled&&t.setSessionSuggestionEnabled(e.sessionSuggestionEnabled),typeof e.sessionGoalEnabled=="boolean"&&e.sessionGoalEnabled!==t.sessionGoalEnabled&&t.setSessionGoalEnabled(e.sessionGoalEnabled),typeof e.sessionGoalDefaultBudgetEnabled=="boolean"&&e.sessionGoalDefaultBudgetEnabled!==t.sessionGoalDefaultBudgetEnabled&&t.setSessionGoalDefaultBudgetEnabled(e.sessionGoalDefaultBudgetEnabled),typeof e.sessionGoalDefaultBudget=="number"&&Number.isFinite(e.sessionGoalDefaultBudget)&&e.sessionGoalDefaultBudget!==t.sessionGoalDefaultBudget&&t.setSessionGoalDefaultBudget(e.sessionGoalDefaultBudget),typeof e.collapsibleThinkingBlocks=="boolean"&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)){const i=Math.max(1,Math.min(365,e.autoDeleteAfterDays));i!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(i)}(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let s=null;if(wn(e.followUpBehavior)?s=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(s=bn(void 0,e.queueModeEnabled)),s&&s!==o.followUpBehavior&&o.setFollowUpBehavior(s),typeof e.showDeletionDialog=="boolean"&&e.showDeletionDialog!==t.showDeletionDialog&&t.setShowDeletionDialog(e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&e.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&t.setNativeNotificationsEnabled(e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&e.notificationMode!==t.notificationMode&&t.setNotificationMode(e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&e.notifyOnSubtasks!==t.notifyOnSubtasks&&t.setNotifyOnSubtasks(e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&e.notifyOnCompletion!==t.notifyOnCompletion&&t.setNotifyOnCompletion(e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&e.notifyOnError!==t.notifyOnError&&t.setNotifyOnError(e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&e.notifyOnQuestion!==t.notifyOnQuestion&&t.setNotifyOnQuestion(e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"&&t.setNotificationTemplates(e.notificationTemplates),typeof e.summarizeLastMessage=="boolean"&&e.summarizeLastMessage!==t.summarizeLastMessage&&t.setSummarizeLastMessage(e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&t.setSummaryThreshold(e.summaryThreshold),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&t.setSummaryLength(e.summaryLength),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&t.setMaxLastMessageLength(e.maxLastMessageLength),typeof e.inputSpellcheckEnabled=="boolean"&&e.inputSpellcheckEnabled!==t.inputSpellcheckEnabled&&t.setInputSpellcheckEnabled(e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications=="boolean"&&e.showOpenCodeUpdateNotifications!==t.showOpenCodeUpdateNotifications&&t.setShowOpenCodeUpdateNotifications(e.showOpenCodeUpdateNotifications),typeof e.showToolFileIcons=="boolean"&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap=="boolean"&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles=="boolean"&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&e.showExpandedEditTools!==t.showExpandedEditTools&&t.setShowExpandedEditTools(e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.desktopWindowControlsPosition=="string"&&(e.desktopWindowControlsPosition==="auto"||e.desktopWindowControlsPosition==="left"||e.desktopWindowControlsPosition==="right")&&e.desktopWindowControlsPosition!==t.desktopWindowControlsPosition&&t.setDesktopWindowControlsPosition(e.desktopWindowControlsPosition),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&r&&e.messageStreamTransport!==r.settingsMessageStreamTransport&&r.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.stickyUserHeader=="boolean"&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.promptNavigatorEnabled=="boolean"&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.expandedEditorToolbar=="boolean"&&e.expandedEditorToolbar!==t.expandedEditorToolbar&&t.setExpandedEditorToolbar(e.expandedEditorToolbar),typeof e.wideChatLayoutEnabled=="boolean"&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.reportUsage=="boolean"&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){let i=Rs(e.draftStarters);if(e.draftStartersCraftGoalAdded!==!0&&!i.some(a=>a.type==="command"&&a.name==="craft-goal")){const a=i.findIndex(l=>l.type==="command"&&l.name==="plan-feature"),c=a>=0?a+1:i.length;i=[...i.slice(0,c),{type:"command",name:"craft-goal"},...i.slice(c)]}JSON.stringify(t.globalDraftStarters)!==JSON.stringify(i)&&t.setGlobalDraftStarters(i),e.draftStartersCraftGoalAdded!==!0&&(e.draftStarters=i,e.draftStartersCraftGoalAdded=!0)}else e.draftStartersCraftGoalAdded!==!0&&(e.draftStartersCraftGoalAdded=!0);if(typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),typeof e.editorFontSize=="number"&&Number.isFinite(e.editorFontSize)&&e.editorFontSize!==t.editorFontSize&&t.setEditorFontSize(e.editorFontSize),ys(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),gs(e.monoFont)&&e.monoFont!==t.monoFont&&t.setMonoFont(e.monoFont),typeof e.padding=="number"&&Number.isFinite(e.padding)&&e.padding!==t.padding&&t.setPadding(e.padding),typeof e.cornerRadius=="number"&&Number.isFinite(e.cornerRadius)&&e.cornerRadius!==t.cornerRadius&&t.setCornerRadius(e.cornerRadius),typeof e.inputBarOffset=="number"&&Number.isFinite(e.inputBarOffset)&&e.inputBarOffset!==t.inputBarOffset&&t.setInputBarOffset(e.inputBarOffset),e.shortcutOverrides&&!Wc(e.shortcutOverrides,t.shortcutOverrides)&&ue.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode=="string"){const i=ur(e.mobileKeyboardMode,t.mobileKeyboardMode);i!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(i)}if(n&&r){const i={};typeof e.dictationEnabled=="boolean"&&e.dictationEnabled!==r.dictationEnabled&&(i.dictationEnabled=e.dictationEnabled),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&e.sttProvider!==r.sttProvider&&(i.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&e.sttServerUrl!==r.sttServerUrl&&(i.sttServerUrl=e.sttServerUrl),typeof e.sttModel=="string"&&e.sttModel!==r.sttModel&&(i.sttModel=e.sttModel),typeof e.sttLocalModel=="string"&&e.sttLocalModel!==r.sttLocalModel&&(i.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage=="string"&&e.sttLanguage!==r.sttLanguage&&(i.sttLanguage=e.sttLanguage),Object.keys(i).length>0&&n.setState(i)}if(Array.isArray(e.favoriteModels)){const i=t.favoriteModels,a=e.favoriteModels;Fr(i,a)||ue.setState({favoriteModels:a})}if(Array.isArray(e.hiddenModels)){const i=t.hiddenModels,a=e.hiddenModels;Fr(i,a)||ue.setState({hiddenModels:a})}if(Array.isArray(e.collapsedModelProviders)){const i=t.collapsedModelProviders,a=e.collapsedModelProviders;Yr(i,a)||ue.setState({collapsedModelProviders:a})}if(Array.isArray(e.recentModels)){const i=t.recentModels,a=e.recentModels;Fr(i,a)||ue.setState({recentModels:a})}if(Array.isArray(e.recentAgents)){const i=t.recentAgents,a=e.recentAgents;Yr(i,a)||ue.setState({recentAgents:a})}if(e.recentEfforts&&typeof e.recentEfforts=="object"){const i=t.recentEfforts,a=e.recentEfforts;Kc(i,a)||ue.setState({recentEfforts:a})}typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&e.diffLayoutPreference!==t.diffLayoutPreference&&t.setDiffLayoutPreference(e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&e.gitChangesViewMode!==t.gitChangesViewMode&&t.setGitChangesViewMode(e.gitChangesViewMode),typeof e.directoryShowHidden=="boolean"&&Fc(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored=="boolean"&&Lc(e.filesViewShowGitignored,{persist:!1})},ao=e=>{if(!e||typeof e!="object")return null;const t=e,r={};if(typeof t.themeId=="string"&&t.themeId.length>0&&(r.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(r.useSystemTheme=t.useSystemTheme),typeof t.themeVariant=="string"&&(t.themeVariant==="light"||t.themeVariant==="dark")&&(r.themeVariant=t.themeVariant),typeof t.lightThemeId=="string"&&t.lightThemeId.length>0&&(r.lightThemeId=t.lightThemeId),typeof t.darkThemeId=="string"&&t.darkThemeId.length>0&&(r.darkThemeId=t.darkThemeId),typeof t.lastDirectory=="string"&&t.lastDirectory.length>0&&(r.lastDirectory=t.lastDirectory),typeof t.homeDirectory=="string"&&t.homeDirectory.length>0&&(r.homeDirectory=t.homeDirectory),typeof t.opencodeBinary=="string"){const p=t.opencodeBinary.trim();r.opencodeBinary=p.length>0?p:void 0}typeof t.desktopLanAccessEnabled=="boolean"&&(r.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled=="boolean"&&(r.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled=="boolean"&&(r.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled);const n=Yc(t.projects);if(n&&(r.projects=n),typeof t.activeProjectId=="string"&&t.activeProjectId.length>0&&(r.activeProjectId=t.activeProjectId),Array.isArray(t.securityScopedBookmarks)&&(r.securityScopedBookmarks=t.securityScopedBookmarks.filter(p=>typeof p=="string"&&p.length>0)),Array.isArray(t.pinnedDirectories)&&(r.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(p=>typeof p=="string"&&p.length>0)))),Array.isArray(t.draftStarters)&&(r.draftStarters=Rs(t.draftStarters)),typeof t.draftStartersCraftGoalAdded=="boolean"&&(r.draftStartersCraftGoalAdded=t.draftStartersCraftGoalAdded),typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),typeof t.sessionRecapEnabled=="boolean"&&(r.sessionRecapEnabled=t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&(r.sessionSuggestionEnabled=t.sessionSuggestionEnabled),typeof t.sessionGoalEnabled=="boolean"&&(r.sessionGoalEnabled=t.sessionGoalEnabled),typeof t.sessionGoalDefaultBudgetEnabled=="boolean"&&(r.sessionGoalDefaultBudgetEnabled=t.sessionGoalDefaultBudgetEnabled),typeof t.sessionGoalDefaultBudget=="number"&&Number.isFinite(t.sessionGoalDefaultBudget)&&t.sessionGoalDefaultBudget>0&&(r.sessionGoalDefaultBudget=Math.floor(t.sessionGoalDefaultBudget)),typeof t.collapsibleThinkingBlocks=="boolean"&&(r.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&(r.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)&&(r.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&(r.sessionRetentionAction=t.sessionRetentionAction),typeof t.tunnelProvider=="string"){const p=t.tunnelProvider.trim().toLowerCase();p.length>0&&(r.tunnelProvider=p)}if(typeof t.tunnelMode=="string"){const p=t.tunnelMode.trim().toLowerCase();(p==="quick"||p==="managed-remote"||p==="managed-local")&&(r.tunnelMode=p)}if(t.tunnelBootstrapTtlMs===null?r.tunnelBootstrapTtlMs=null:typeof t.tunnelBootstrapTtlMs=="number"&&Number.isFinite(t.tunnelBootstrapTtlMs)&&(r.tunnelBootstrapTtlMs=t.tunnelBootstrapTtlMs),typeof t.tunnelSessionTtlMs=="number"&&Number.isFinite(t.tunnelSessionTtlMs)&&(r.tunnelSessionTtlMs=t.tunnelSessionTtlMs),t.managedLocalTunnelConfigPath===null)r.managedLocalTunnelConfigPath=null;else if(typeof t.managedLocalTunnelConfigPath=="string"){const p=t.managedLocalTunnelConfigPath.trim();r.managedLocalTunnelConfigPath=p.length>0?p:null}typeof t.managedRemoteTunnelHostname=="string"&&(r.managedRemoteTunnelHostname=t.managedRemoteTunnelHostname.trim()),t.managedRemoteTunnelToken===null?r.managedRemoteTunnelToken=null:typeof t.managedRemoteTunnelToken=="string"&&(r.managedRemoteTunnelToken=t.managedRemoteTunnelToken.trim());const o=Qc(t.managedRemoteTunnelPresets);if(o&&(r.managedRemoteTunnelPresets=o),typeof t.managedRemoteTunnelSelectedPresetId=="string"){const p=t.managedRemoteTunnelSelectedPresetId.trim();r.managedRemoteTunnelSelectedPresetId=p.length>0?p:void 0}const s=Xc(t.managedRemoteTunnelPresetTokens);if(s&&(r.managedRemoteTunnelPresetTokens=s),typeof t.defaultModel=="string"&&t.defaultModel.length>0&&(r.defaultModel=t.defaultModel),typeof t.defaultVariant=="string"&&t.defaultVariant.length>0&&(r.defaultVariant=t.defaultVariant),typeof t.defaultAgent=="string"&&t.defaultAgent.length>0&&(r.defaultAgent=t.defaultAgent),typeof t.smallModelUseDefault=="boolean"&&(r.smallModelUseDefault=t.smallModelUseDefault),typeof t.smallModelOverride=="string"&&t.smallModelOverride.length>0&&(r.smallModelOverride=t.smallModelOverride),typeof t.autoCreateWorktree=="boolean"&&(r.autoCreateWorktree=t.autoCreateWorktree),typeof t.gitmojiEnabled=="boolean"&&(r.gitmojiEnabled=t.gitmojiEnabled),wn(t.followUpBehavior)?r.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(r.followUpBehavior=bn(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog=="boolean"&&(r.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&(r.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&(r.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&(r.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&(r.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&(r.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&(r.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"){const p=t.notificationTemplates,b=M=>{const be=p[M];if(!be||typeof be!="object")return;const oe=be,tt=typeof oe.title=="string"?oe.title:"",fr=typeof oe.message=="string"?oe.message:"";return{title:tt,message:fr}},T=b("completion"),S=b("error"),R=b("question"),E=b("subtask");(T||S||R||E)&&(r.notificationTemplates={completion:T??{title:"Task Complete",message:"Your task has finished."},error:S??{title:"Error Occurred",message:"An error occurred while processing your task."},question:R??{title:"Input Needed",message:"Please provide input to continue."},subtask:E??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof t.summarizeLastMessage=="boolean"&&(r.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&(r.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&(r.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&(r.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),typeof t.usageAutoRefresh=="boolean"&&(r.usageAutoRefresh=t.usageAutoRefresh),typeof t.usageRefreshIntervalMs=="number"&&Number.isFinite(t.usageRefreshIntervalMs)&&(r.usageRefreshIntervalMs=t.usageRefreshIntervalMs),(t.usageDisplayMode==="usage"||t.usageDisplayMode==="remaining")&&(r.usageDisplayMode=t.usageDisplayMode),typeof t.usageShowPredValues=="boolean"&&(r.usageShowPredValues=t.usageShowPredValues),Array.isArray(t.usageDropdownProviders)&&(r.usageDropdownProviders=t.usageDropdownProviders.filter(p=>typeof p=="string"&&p.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels=="object"){const p={};for(const[b,T]of Object.entries(t.usageSelectedModels))Array.isArray(T)&&(p[b]=T.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(r.usageSelectedModels=p)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies=="object"){const p={};for(const[b,T]of Object.entries(t.usageCollapsedFamilies))Array.isArray(T)&&(p[b]=T.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(r.usageCollapsedFamilies=p)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies=="object"){const p={};for(const[b,T]of Object.entries(t.usageExpandedFamilies))Array.isArray(T)&&(p[b]=T.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(r.usageExpandedFamilies=p)}if(t.usageModelGroups&&typeof t.usageModelGroups=="object"){const p={};for(const[b,T]of Object.entries(t.usageModelGroups))if(T&&typeof T=="object"){const S=T,R={};Array.isArray(S.customGroups)&&(R.customGroups=S.customGroups.filter(E=>E&&typeof E=="object").map(E=>({id:String(E.id??""),label:String(E.label??""),models:Array.isArray(E.models)?E.models.filter(M=>typeof M=="string"):[],order:typeof E.order=="number"?E.order:0}))),S.modelAssignments&&typeof S.modelAssignments=="object"&&(R.modelAssignments=Object.fromEntries(Object.entries(S.modelAssignments).filter(([,E])=>typeof E=="string").map(([E,M])=>[E,String(M)]))),S.renamedGroups&&typeof S.renamedGroups=="object"&&(R.renamedGroups=Object.fromEntries(Object.entries(S.renamedGroups).filter(([,E])=>typeof E=="string").map(([E,M])=>[E,String(M)]))),Object.keys(R).length>0&&(p[b]=R)}Object.keys(p).length>0&&(r.usageModelGroups=p)}typeof t.inputSpellcheckEnabled=="boolean"&&(r.inputSpellcheckEnabled=t.inputSpellcheckEnabled),typeof t.showOpenCodeUpdateNotifications=="boolean"&&(r.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.openCodeUpdateToastDismissedVersion=="string"&&(r.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons=="boolean"&&(r.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap=="boolean"&&(r.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles=="boolean"&&(r.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&(r.showExpandedBashTools=t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&(r.showExpandedEditTools=t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&(r.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&(r.weekStartPreference=t.weekStartPreference),typeof t.desktopWindowControlsPosition=="string"&&(t.desktopWindowControlsPosition==="auto"||t.desktopWindowControlsPosition==="left"||t.desktopWindowControlsPosition==="right")&&(r.desktopWindowControlsPosition=t.desktopWindowControlsPosition),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&(r.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&(r.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&(r.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&(r.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&(r.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&(r.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader=="boolean"&&(r.stickyUserHeader=t.stickyUserHeader),typeof t.promptNavigatorEnabled=="boolean"&&(r.promptNavigatorEnabled=t.promptNavigatorEnabled),typeof t.wideChatLayoutEnabled=="boolean"&&(r.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&(r.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&(r.fontSize=t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&(r.terminalFontSize=t.terminalFontSize),typeof t.editorFontSize=="number"&&Number.isFinite(t.editorFontSize)&&(r.editorFontSize=t.editorFontSize),ys(t.uiFont)&&(r.uiFont=t.uiFont),gs(t.monoFont)&&(r.monoFont=t.monoFont),typeof t.padding=="number"&&Number.isFinite(t.padding)&&(r.padding=t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&(r.cornerRadius=t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&(r.inputBarOffset=t.inputBarOffset);const i=$c(t.shortcutOverrides);i&&(r.shortcutOverrides=i),typeof t.mobileKeyboardMode=="string"&&(t.mobileKeyboardMode==="native"||t.mobileKeyboardMode==="resize-content")&&(r.mobileKeyboardMode=t.mobileKeyboardMode);const a=xr(t.favoriteModels,64);a&&(r.favoriteModels=a);const c=xr(t.hiddenModels,1024);c&&(r.hiddenModels=c);const l=Qr(t.collapsedModelProviders);l&&(r.collapsedModelProviders=l);const d=xr(t.recentModels,16);d&&(r.recentModels=d);const u=Qr(t.recentAgents);u&&(r.recentAgents=u);const g=qc(t.recentEfforts);if(g&&(r.recentEfforts=g),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&(r.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&(r.gitChangesViewMode=t.gitChangesViewMode),typeof t.directoryShowHidden=="boolean"&&(r.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored=="boolean"&&(r.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&(r.openInAppId=t.openInAppId),typeof t.pwaAppName=="string"){const p=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.pwaAppName=p.length>0?p:""}const h=Gc(t.skillCatalogs);return h&&(r.skillCatalogs=h),typeof t.reportUsage=="boolean"&&(r.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt=="string"&&(r.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled=="boolean"&&(r.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset=="string"&&(t.responseStylePreset==="concise"||t.responseStylePreset==="detailed"||t.responseStylePreset==="mentor"||t.responseStylePreset==="pushback"||t.responseStylePreset==="noFiller"||t.responseStylePreset==="matchEnergy"||t.responseStylePreset==="warmPeer"||t.responseStylePreset==="custom")&&(r.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions=="string"&&(r.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled=="boolean"&&(r.dictationEnabled=t.dictationEnabled),t.sttProvider==="local"||t.sttProvider==="openai-compatible"?r.sttProvider=t.sttProvider:t.sttProvider==="server"?r.sttProvider="openai-compatible":(t.sttProvider==="browser"||t.sttProvider==="wasm")&&(r.sttProvider="local"),typeof t.sttServerUrl=="string"&&(r.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel=="string"&&(r.sttModel=t.sttModel.trim()),typeof t.sttLocalModel=="string"&&(r.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage=="string"&&(r.sttLanguage=t.sttLanguage.trim()),r};let _e=null,it=null;const Zc=2e3,el=async()=>_e&&Date.now()-_e.at<Zc?_e.value:it||(it=(async()=>{const e=Is();if(e)try{const t=await e.load(),r=ao(t.settings);return _e={value:r,at:Date.now()},r}catch(t){console.warn("Failed to load shared settings from runtime settings API:",t)}try{const t=await f("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const r=await t.json().catch(()=>null),n=ao(r);return _e={value:n,at:Date.now()},n}catch(t){return console.warn("Failed to load shared settings from server:",t),null}})().finally(()=>{it=null}),it),mf=async()=>{if(typeof window>"u")return;const e=Os(),t=()=>!e?.hasHydrated||e.hasHydrated()||!e.onFinishHydration?Promise.resolve():new Promise(n=>{let o=!1;const s=()=>{o||(o=!0,n())},i=e.onFinishHydration(()=>{i?.(),s()});e.hasHydrated?.()&&s()}),r=async n=>{const o=n.draftStartersCraftGoalAdded!==!0;try{Vr(n)}catch(s){console.warn("persistToLocalStorage failed:",s)}await t();try{Xr(n)}catch(s){console.warn("applyDesktopUiPreferences failed:",s)}o&&await fe({...n.draftStarters?{draftStarters:n.draftStarters}:{},draftStartersCraftGoalAdded:!0}),Jr(n)};try{const n=await el();n&&await r(n)}catch(n){console.warn("Failed to synchronise settings:",n)}};let Qt=null,jt=null,Zr=[];const tl=200,rl=async()=>{const e=Qt,t=Zr;if(Qt=null,jt=null,Zr=[],!e||Object.keys(e).length===0){t.forEach(n=>n());return}const r=Is();if(r)try{const n=await r.save(e);n&&(Vr(n),Xr(n),Jr(n),_e=null),t.forEach(o=>o());return}catch(n){console.warn("Failed to update settings via runtime settings API:",n)}try{const n=await f("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok){console.warn("Failed to update shared settings via API:",n.status,n.statusText);return}const o=await n.json().catch(()=>null);o&&(Vr(o),Xr(o),Jr(o),_e=null)}catch(n){console.warn("Failed to update shared settings via API:",n)}finally{t.forEach(n=>n())}},fe=async e=>{if(typeof window>"u")return;Qt={...Qt??{},...e},jt&&clearTimeout(jt);const t=new Promise(r=>{Zr.push(r)});return jt=setTimeout(()=>{rl()},tl),t},yf=async()=>{if(typeof window>"u")return;const e=Os();try{const t=await jc();if(!t)return;const r=()=>Uc(t);if(e?.hasHydrated?.()){r();return}if(r(),e?.onFinishHydration){const n=e.onFinishHydration(()=>{n?.(),r()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},nl=3e4,ol=40,sl=60,il=(e,t,r,n,o,s)=>{const i=e.trim(),a=t.trim().toLowerCase();return JSON.stringify([i,a,r,n,o,s])},co=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r)&&r[0]===t}catch{return!1}},al=tr()(rr((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(r,n,o=sl,s){if(!r||r.trim().length===0)return[];const i=r.trim(),a=typeof n=="string"?n.trim():"",c=!!s?.includeHidden,l=s?.respectGitignore??!0,d=s?.type==="directory"?"directory":"file",u=il(i,a,o,c,l,d),g=Date.now(),h=t().cache[u];if(h&&g-h.timestamp<nl)return h.files;const p=t().inFlight[u];if(p)return p;const b=ve.searchFiles(a,{directory:i,limit:o,includeHidden:c,respectGitignore:l,dirs:d!=="file",type:d}).then(T=>(e(S=>{if(S.inFlight[u]!==b)return S;const R={...S.cache,[u]:{files:T,timestamp:Date.now()}},E=S.cacheKeys.filter(M=>M!==u);for(E.push(u);E.length>ol;){const M=E.shift();M&&delete R[M]}return{cache:R,cacheKeys:E}}),T)).finally(()=>{e(T=>{if(T.inFlight[u]!==b)return T;const S={...T.inFlight};return delete S[u],{inFlight:S}})});return e(T=>({inFlight:{...T.inFlight,[u]:b}})),b},invalidateDirectory(r){if(!r||r.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const n=r.trim();e(o=>{const s={...o.cache},i=o.cacheKeys.filter(l=>co(l,n)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!co(l,n)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})}}),{name:"file-search-store"})),cl=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},en="openchamber_stream_perf",kt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(en)==="1"}catch{return!1}},lo=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),ll=()=>{if(!kt()||typeof window>"u")return null;if(!window.__openchamberStreamPerfState){const e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},_s=e=>Array.from(e.entries()).map(([t,r])=>({metric:t,count:r.count,avg:r.count>0?Number((r.total/r.count).toFixed(3)):0,max:Number(r.max.toFixed(3)),total:Number(r.total.toFixed(3)),last:Number(r.last.toFixed(3))})).sort((t,r)=>r.total-t.total||r.count-t.count),Sn=(e,t)=>{const r=ll();if(!r)return;const n=r.counters.get(e)??{count:0,total:0,max:0,last:0};n.count+=1,n.total+=t,n.max=Math.max(n.max,t),n.last=t,r.counters.set(e,n),r.lastUpdatedAt=Date.now()},gf=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(en,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(en),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},wf=()=>{typeof window>"u"||(kt()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},bf=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberStreamPerfState;return!kt()||!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:_s(e.counters)}},Sf=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__openchamberVsCodeStreamPerfState;if(!kt()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,r=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:r,durationMs:t?Math.max(0,Date.now()-t):0,entries:_s(e.counters)}},Tf=(e,t=1)=>{Sn(e,t)},Ef=(e,t)=>{Sn(e,t)},vf=(e,t)=>{if(!kt())return t();const r=lo();try{return t()}finally{Sn(e,lo()-r)}};var dl={};let ce=null,uo=0;const ae=vt(),fo=ae.getItem("lastDirectory"),ul=typeof fo=="string"&&fo.length>0,xt=e=>{try{al.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Xe=e=>{const t=e.trim();if(!t)return t;const r=t.replace(/\\/g,"/").replace(/^([a-z]):/,(n,o)=>o.toUpperCase()+":");return r.length>1?r.replace(/\/+$/,""):r},fl=(e,t)=>{const r=e.trim();return r.startsWith("~")?r==="~"?t||r:(r.startsWith("~/")||r.startsWith("~\\"))&&t?`${t}${r.slice(1)}`:r:r},Ht=(e,t)=>{const r=fl(e,t);return Xe(r)},pl=()=>{const e=ae.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Xe(e);return t.length>0?t:null},hl=()=>{const e=ae.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Xe(e);return t.length>0?t:null},ml=()=>{if(typeof process>"u")return null;const e=dl,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const n=Xe(t);return n.length>0?n:null}const r=process?.cwd?.();if(typeof r=="string"&&r.trim().length>0){const n=Xe(r);return n.length>0?n:null}return null},Xt=()=>{if(typeof window<"u"){if(ce)return ce;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ce=t,ae.setItem("homeDirectory",t),t;const r=pl();if(r&&!dr())return ce=r,r}const e=ml();return e||"/"},yl=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const r=t.replace(/\\/g,"/");if(r.length>1){const n=r.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return r==="/"||r.length===0?null:r},gl=e=>(ce=e,typeof window<"u"&&ae.setItem("homeDirectory",e),fe({homeDirectory:e}),e),tn=async()=>{const e=n=>{const o=yl(n);return o?gl(o):null};try{const n=await ve.getFilesystemHome(),o=e(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await ve.getSystemInfo(),o=e(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await is(),o=e(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const t=Xt(),r=e(t);return r||t},wl=()=>{if(!dr())return null;const e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Xe(e);return t.length>0?t:null},bt=wl()||Xt(),Zt=(()=>{const e=hl();return e&&!dr()?Ht(e,bt):bt})();Zt&&ve.setDirectory(Zt);const bl=!!(bt&&bt!=="/"),rn=tr()(rr((e,t)=>({currentDirectory:Zt,directoryHistory:[Zt],historyIndex:0,homeDirectory:bt,hasPersistedDirectory:ul,isHomeReady:bl,isSwitchingDirectory:!1,setDirectory:(r,n)=>{const o=ce||t().homeDirectory||ae.getItem("homeDirectory"),s=Ht(r,o);cl()&&console.log("[DirectoryStore] setDirectory called with path:",s),ve.setDirectory(s),xt(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return ae.setItem("lastDirectory",s),fe({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const r=t();if(r.historyIndex>0){const n=r.historyIndex-1,o=r.directoryHistory[n];ve.setDirectory(o),xt(),ae.setItem("lastDirectory",o),fe({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const r=t();if(r.historyIndex<r.directoryHistory.length-1){const n=r.historyIndex+1,o=r.directoryHistory[n];ve.setDirectory(o),xt(),ae.setItem("lastDirectory",o),fe({lastDirectory:o}),e({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:r,setDirectory:n}=t(),o=ce||t().homeDirectory||Xt();if(r===o||r==="/")return;const s=r.endsWith("/")?r.slice(0,-1):r,i=s.lastIndexOf("/");if(i===-1){const a=ce||Xt();n(a)}else n(i===0?"/":s.substring(0,i))},goHome:async()=>{const r=ce||t().homeDirectory||await tn();t().setDirectory(r)},synchronizeHomeDirectory:r=>{const n=t(),o=r;ce=o;const s=n.homeDirectory!==o,i=ae.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!s&&!c){n.isHomeReady||e({isHomeReady:!0});return}const l=typeof o=="string"&&o!==""&&o!=="/",d=n.currentDirectory?Ht(n.currentDirectory,o):n.currentDirectory,u=n.directoryHistory.map(b=>Ht(b,o)),g=u.some((b,T)=>b!==n.directoryHistory[T]),h=!!(d&&d!==n.currentDirectory),p={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(p.currentDirectory=o,p.directoryHistory=[o],p.historyIndex=0,p.isSwitchingDirectory=!1):(h||g)&&(p.currentDirectory=d,p.directoryHistory=u,p.historyIndex=Math.min(n.historyIndex,u.length-1),p.isSwitchingDirectory=!1),e(()=>p),(c||h)&&l){const b=c?o:d;ve.setDirectory(b),xt(),ae.setItem("lastDirectory",b),fe({lastDirectory:b})}fe({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(tn().then(e=>{rn.getState().synchronizeHomeDirectory(e)}),ba(()=>{ce=null;const e=++uo;tn().then(t=>{e===uo&&rn.getState().synchronizeHomeDirectory(t)})}));const Sl=(e,t)=>{const r=or();return r?r.openWebSocket(Mi(e),t):Ni(new WebSocket(e))},Fs=1,le=1,Lt=0,xs="/api/terminal/ws",Tl=1200,El=250,vl=2e4,kl=5e3,Lr="__openchamberTerminalTransportState",Al=new TextEncoder,po=new TextDecoder,Tn=e=>X().websocket(e),Nr=e=>{const t=Al.encode(JSON.stringify(e)),r=new Uint8Array(t.length+1);return r[0]=Fs,r.set(t,1),r},St=e=>e?((e.transports??[]).includes("ws")||e.preferred==="ws")&&typeof e.ws?.path=="string"&&e.ws.path.length>0:!1,En=e=>e.streamCapability?.ws?.path??e.inputCapability?.ws?.path??xs,Pl=e=>{switch(e){case"SESSION_NOT_FOUND":return new Error("Terminal session not found");case"NOT_BOUND":return new Error("Terminal session is not bound");case"WRITE_FAIL":return new Error("Failed to write to terminal");case"RATE_LIMIT":return new Error("Terminal websocket is rate limited");case"BAD_FRAME":return new Error("Terminal websocket protocol violation");default:return new Error("Terminal websocket error")}};class Dl{socket=null;socketUrl="";boundSessionId=null;requestedSessionId=null;openPromise=null;reconnectTimeout=null;keepaliveInterval=null;closed=!1;subscriptions=new Map;activeSubscriptionToken=null;replayCursorBySession=new Map;configure(t){if(t){if(this.socketUrl===t){this.closed=!1,this.isConnectedOrConnecting()||this.ensureConnected();return}this.socketUrl=t,this.closed=!1,this.resetConnection(),this.ensureConnected()}}subscribe(t,r,n,o){const s=Symbol(t),i={token:s,sessionId:t,onEvent:r,onError:n,maxRetries:o?.maxRetries??3,initialRetryDelay:o?.initialRetryDelay??1e3,maxRetryDelay:o?.maxRetryDelay??8e3,connectionTimeout:o?.connectionTimeout??1e4,retryCount:0,connected:!1,connectionTimeoutId:null};return this.subscriptions.set(s,i),this.activeSubscriptionToken=s,this.boundSessionId=null,this.requestedSessionId=t,this.ensureConnected(),this.startConnectionTimeout(i),this.bindActiveSession(),()=>{this.clearConnectionTimeout(i),this.subscriptions.delete(s),this.activeSubscriptionToken===s&&(this.activeSubscriptionToken=null),this.boundSessionId===t&&(this.boundSessionId=null),this.requestedSessionId===t&&(this.requestedSessionId=null),this.subscriptions.size===0&&(this.clearReconnectTimeout(),this.resetConnection())}}async sendInput(t,r){if(!t||!r||this.closed||!this.socketUrl)return!1;const n=await this.getOpenSocket(Tl);if(!n||n.readyState!==le)return!1;try{return this.boundSessionId!==t&&(this.requestedSessionId=t,n.send(Nr({t:"b",s:t,r:this.replayCursorBySession.get(t)??0,v:2}))),n.send(r),!0}catch{return this.handleSocketFailure(new Error("Terminal websocket send failed")),!1}}unbindSession(t){t&&(this.boundSessionId===t&&(this.boundSessionId=null),this.requestedSessionId===t&&(this.requestedSessionId=null))}close(){this.closed=!0,this.clearReconnectTimeout();for(const t of this.subscriptions.values())this.clearConnectionTimeout(t);this.resetConnection(),this.socketUrl="",this.subscriptions.clear(),this.activeSubscriptionToken=null,this.replayCursorBySession.clear()}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(t){return this.closed||t&&this.socketUrl!==t?!1:this.socket&&(this.socket.readyState===le||this.socket.readyState===Lt)?!0:this.openPromise!==null}getActiveSubscription(){return this.activeSubscriptionToken?this.subscriptions.get(this.activeSubscriptionToken)??null:null}startConnectionTimeout(t){this.clearConnectionTimeout(t),t.connectionTimeoutId=setTimeout(()=>{this.getActiveSubscription()?.token!==t.token||t.connected||this.handleSocketFailure(new Error("Connection timeout"))},t.connectionTimeout)}clearConnectionTimeout(t){t.connectionTimeoutId&&(clearTimeout(t.connectionTimeoutId),t.connectionTimeoutId=null)}async getOpenSocket(t){if(this.socket&&this.socket.readyState===le)return this.socket;if(this.ensureConnected(),this.socket&&this.socket.readyState===le)return this.socket;const r=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(n=>{setTimeout(()=>n(null),t)})]);return r&&r.readyState===le?r:this.socket&&this.socket.readyState===le?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===le||this.socket.readyState===Lt)||this.openPromise||(this.clearReconnectTimeout(),this.openPromise=new Promise(t=>{let r=!1,n=null;const o=s=>{r||(r=!0,n&&(clearTimeout(n),n=null),this.openPromise=null,t(s))};try{const s=Sl(this.socketUrl);s.binaryType="arraybuffer",s.onopen=()=>{this.socket=s,this.startKeepalive(),o(s)},s.onmessage=i=>{this.handleSocketMessage(i.data)},s.onerror=()=>{!this.closed&&!this.getActiveSubscription()&&this.scheduleReconnect(new Error("Terminal websocket error"))},s.onclose=()=>{this.socket===s&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect(new Error("Terminal stream connection error"))),o(null)},this.socket=s,n=setTimeout(()=>{s.readyState===Lt&&(s.close(),o(null))},kl)}catch{o(null),this.closed||this.scheduleReconnect(new Error("Terminal websocket open failed"))}}))}bindActiveSession(){const t=this.getActiveSubscription();if(!(!t||!this.socket||this.socket.readyState!==le)){this.requestedSessionId=t.sessionId;try{this.socket.send(Nr({t:"b",s:t.sessionId,r:this.replayCursorBySession.get(t.sessionId)??0,v:2}))}catch{this.handleSocketFailure(new Error("Terminal websocket bind failed"))}}}scheduleReconnect(t){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;const r=this.getActiveSubscription();if(!r)return;const n=r.retryCount+1,o=r.initialRetryDelay,s=r.maxRetryDelay,i=r.maxRetries;if(n>i){this.clearConnectionTimeout(r),r.onError?.(t,!0);return}r.retryCount=n,r.connected=!1,r.onEvent({type:"reconnecting",attempt:n,maxAttempts:i}),this.startConnectionTimeout(r);const a=Math.min(o*Math.pow(2,Math.max(n-1,0)),s),c=Math.floor(Math.random()*El),l=a+c;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},l)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}sendControl(t){if(!this.socket||this.socket.readyState!==le)return!1;try{return this.socket.send(Nr(t)),!0}catch{return this.handleSocketFailure(new Error("Terminal websocket control send failed")),!1}}startKeepalive(){this.stopKeepalive(),this.keepaliveInterval=setInterval(()=>{this.closed||this.sendControl({t:"p",v:2})},vl)}stopKeepalive(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}async handleSocketMessage(t){const r=await this.asUint8Array(t);if(r&&r.length>0&&r[0]===Fs){this.handleControlMessage(r);return}const n=await this.asText(t);if(!n)return;const o=this.getActiveSubscription();o&&o.onEvent({type:"data",data:n})}handleControlMessage(t){if(t.length<2)return;let r;try{r=JSON.parse(po.decode(t.subarray(1)))}catch{this.handleSocketFailure(new Error("Terminal websocket control parse failed"));return}const n=this.getActiveSubscription();switch(r.t){case"ok":this.bindActiveSession();return;case"po":return;case"d":{const o=r.s??this.boundSessionId??this.requestedSessionId;if(!n||!o||o!==n.sessionId)return;typeof r.i=="number"&&Number.isFinite(r.i)&&this.replayCursorBySession.set(o,Math.max(this.replayCursorBySession.get(o)??0,Math.trunc(r.i))),typeof r.d=="string"&&r.d.length>0&&n.onEvent({type:"data",data:r.d});return}case"bok":{if(this.boundSessionId=r.s??this.requestedSessionId,!n)return;n.retryCount=0,n.connected=!0,this.clearConnectionTimeout(n),n.onEvent({type:"connected",runtime:r.runtime,ptyBackend:r.ptyBackend});return}case"x":{if(!n){this.boundSessionId=null;return}if(r.s&&r.s!==n.sessionId)return;n.connected=!1,this.clearConnectionTimeout(n),this.boundSessionId=null,this.requestedSessionId=null,this.replayCursorBySession.delete(n.sessionId),n.onEvent({type:"exit",exitCode:r.exitCode,signal:r.signal??null});return}case"e":{const o=Pl(r.c),s=r.f===!0||r.c==="SESSION_NOT_FOUND";(r.c==="NOT_BOUND"||r.c==="SESSION_NOT_FOUND")&&(this.boundSessionId=null),n&&(n.connected=!1,s&&this.clearConnectionTimeout(n),n.onError?.(o,s)),r.f===!0&&this.handleSocketFailure(o);return}default:return}}async asUint8Array(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(t instanceof Uint8Array)return t;if(typeof Blob<"u"&&t instanceof Blob){const r=await t.arrayBuffer();return new Uint8Array(r)}return null}async asText(t){if(typeof t=="string")return t;const r=await this.asUint8Array(t);return r?po.decode(r):""}handleSocketFailure(t){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(t)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){const t=this.socket;this.socket=null,t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,(t.readyState===le||t.readyState===Lt)&&t.close()}this.boundSessionId=null}}const pe=()=>{const e=globalThis;return e[Lr]||(e[Lr]={inputCapability:null,streamCapability:null,manager:null}),e[Lr]},vn=()=>{const e=pe();return e.manager||(e.manager=new Dl),e.manager},Ls=e=>{const t=pe();if(t.inputCapability=e?.input??null,t.streamCapability=e?.stream??null,!St(t.inputCapability)&&!St(t.streamCapability)){t.manager?.close(),t.manager=null;return}const r=Tn(En(t));if(!r)return;vn().configure(r)},Cl=async(e,t)=>{const r=await f(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain"},body:t});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to send terminal input"}));throw new Error(n.error||"Failed to send terminal input")}};async function Ml(e){const t=await f("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.cwd,cols:e.cols??80,rows:e.rows??24})});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}const r=await t.json();return Ls(r.capabilities),r}const ho=(e,t,r,n={})=>{const o=n.maxRetries??3,s=n.initialRetryDelay??1e3,i=n.maxRetryDelay??8e3,a=n.connectionTimeout??1e4;let c=null,l=0,d=null,u=null,g=!1,h=!1;const p=()=>{d&&(clearTimeout(d),d=null),u&&(clearTimeout(u),u=null)},b=()=>{g||(g=!0,p(),c&&(c.close(),c=null))},T=(R,E)=>{if(!(g||h)){if(l<o&&!E){l+=1;const M=Math.min(s*Math.pow(2,l-1),i);t({type:"reconnecting",attempt:l,maxAttempts:o}),d=setTimeout(()=>{!g&&!h&&S()},M);return}r?.(R,!0),b()}},S=()=>{if(g||h||c&&c.readyState!==EventSource.CLOSED)return;c=new EventSource(X().sse(`/api/terminal/${e}/stream`));let R=!1;u=setTimeout(()=>{!R&&c?.readyState!==EventSource.OPEN&&(c?.close(),T(new Error("Connection timeout"),!1))},a),c.onopen=()=>{R||(R=!0,l=0,p(),t({type:"connected"}))},c.onmessage=E=>{try{const M=JSON.parse(E.data);M.type==="exit"&&(pe().manager?.unbindSession(e),h=!0,b()),t(M)}catch(M){r?.(M,!1)}},c.onerror=()=>{p();const E=h||c?.readyState===EventSource.CLOSED;c?.close(),c=null,h||T(new Error("Terminal stream connection error"),E)}};return S(),b};function Rl(e,t,r,n={}){const o=pe();if(!St(o.streamCapability))return ho(e,t,r,n);const s=vn(),i=Tn(En(o));return i?(s.configure(i),s.subscribe(e,t,r,n)):ho(e,t,r,n)}async function Ol(e,t){const r=pe();r.manager&&await r.manager.sendInput(e,t)||await Cl(e,t)}async function Il(e,t,r){const n=await f(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:t,rows:r})});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(o.error||"Failed to resize terminal")}}async function _l(e){pe().manager?.unbindSession(e);const t=await f(`/api/terminal/${e}`,{method:"DELETE"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(r.error||"Failed to close terminal")}}async function Fl(e,t){pe().manager?.unbindSession(e);const r=await f(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t.cwd,cols:t.cols??80,rows:t.rows??24})});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(o.error||"Failed to restart terminal")}const n=await r.json();return Ls(n.capabilities),n}async function xl(e){const t=await f("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}e.sessionId&&pe().manager?.unbindSession(e.sessionId)}function kf(){const e=pe();e.manager?.close(),e.manager=null,e.inputCapability=null,e.streamCapability=null}function Af(){const e=pe();if(e.inputCapability&&e.streamCapability&&!St(e.inputCapability)&&!St(e.streamCapability))return;const t=En(e)||xs,r=Tn(t);if(!r)return;const n=vn();n.isConnectedOrConnecting(r)||(n.configure(r),n.prime())}const Ll=e=>{const t=e?.retry;return{maxRetries:t?.maxRetries??3,initialRetryDelay:t?.initialDelayMs??1e3,maxRetryDelay:t?.maxDelayMs??8e3,connectionTimeout:e?.connectionTimeoutMs??1e4}},Nl=()=>({async createSession(e){return Ml(e)},connect(e,t,r){const n=Rl(e,t.onEvent,t.onError,Ll(r));return{close:()=>n()}},async sendInput(e,t){await Ol(e,t)},async resize(e){await Il(e.sessionId,e.cols,e.rows)},async close(e){await _l(e)},async restartSession(e,t){return Fl(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows})},async forceKill(e){await xl(e)}}),m="/api/git",Bl=1200,Ul=5e3,er=new Map,Ke=new Map,Ns=new Map,mo=new Map,Nt=new Map,Tt=e=>e.trim(),jl=(e,t)=>t==="light"?`${Tt(e)}::light`:Tt(e),nn=e=>Ns.get(Tt(e))??0,Pe=e=>{const t=Tt(e);Ns.set(t,nn(e)+1);for(const r of Array.from(er.keys()))(r===t||r.startsWith(`${t}::`))&&er.delete(r);for(const r of Array.from(Ke.keys()))(r===t||r.startsWith(`${t}::`))&&Ke.delete(r)};function y(e,t,r){const n={...r};return t&&(n.directory=t),X().api(e,n)}async function Hl(e){const t=Tt(e),r=Date.now(),n=mo.get(t);if(n&&n.expiresAt>r)return n.value;const o=Nt.get(t);if(o)return o;const s=(async()=>{const i=await f(y(`${m}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return mo.set(t,{value:c,expiresAt:Date.now()+Ul}),c})();Nt.set(t,s);try{return await s}finally{Nt.get(t)===s&&Nt.delete(t)}}async function zl(e,t){const r=t?.mode,n=jl(e,r),o=Date.now(),s=er.get(n);if(s&&s.expiresAt>o)return s.value;const i=Ke.get(n);if(i)return i;const a=(async()=>{const c=nn(e),l=await f(y(`${m}/status`,e,r?{mode:r}:void 0));if(!l.ok)throw new Error(`Failed to get git status: ${l.statusText}`);const d=await l.json();return nn(e)===c&&er.set(n,{value:d,expiresAt:Date.now()+Bl}),d})();Ke.set(n,a);try{return await a}finally{Ke.get(n)===a&&Ke.delete(n)}}async function Pf(e){const t=await f(y(`${m}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const r=await t.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:e}}async function Df(e){const t=await f(y(`${m}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const r=await t.json().catch(()=>({}));return{root:typeof r.root=="string"&&r.root?r.root:e}}async function Cf(e,t){const r=await f(y(`${m}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!r.ok)throw new Error(`Failed to get git commit summaries: ${r.statusText}`);const n=await r.json().catch(()=>({}));return{commits:Array.isArray(n.commits)?n.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 Gl(e,t){const{path:r,staged:n,contextLines:o}=t;if(!r)throw new Error("path is required to fetch git diff");const s=await f(y(`${m}/diff`,e,{path:r,staged:n?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function $l(e,t){const{path:r,staged:n}=t;if(!r)throw new Error("path is required to fetch git file diff");const o=await f(y(`${m}/file-diff`,e,{path:r,staged:n?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function Wl(e,t,r){if(!t)throw new Error("path is required to revert git changes");const n=await f(y(`${m}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:r?.scope})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to revert git changes")}Pe(e)}async function ql(e,t){await Bs(e,[t])}async function Bs(e,t){const r=t.map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to stage git changes");const n=await f(y(`${m}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to stage git changes")}Pe(e)}async function Kl(e,t){await Us(e,[t])}async function Us(e,t){const r=t.map(o=>o.trim()).filter(Boolean);if(r.length===0)throw new Error("path is required to unstage git changes");const n=await f(y(`${m}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to unstage git changes")}Pe(e)}async function Vl(e,t,r){await kn(e,t,r,"stage")}async function Jl(e,t,r){await kn(e,t,r,"unstage")}async function Yl(e,t,r){await kn(e,t,r,"discard")}async function kn(e,t,r,n){if(!t)throw new Error("path is required to apply a git hunk");if(typeof r!="string"||!r.trim())throw new Error("patch is required to apply a git hunk");const o=await f(y(`${m}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:r,action:n})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to apply git hunk")}Pe(e)}async function Ql(e){if(!e)return!1;const t=await f(y(`${m}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Xl(e){const t=await f(y(`${m}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function Zl(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const r=await f(y(`${m}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete branch")}return r.json()}async function ed(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const r=await f(y(`${m}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete remote branch")}return r.json()}async function td(e,t){const r=t?.remote?.trim();if(!r)throw new Error("remote is required to remove a remote");const n=await f(y(`${m}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to remove remote")}return n.json()}async function rd(e,t,r){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const n={files:t};r?.zenModel&&(n.zenModel=r.zenModel),r?.providerId&&(n.providerId=r.providerId),r?.modelId&&(n.modelId=r.modelId);const o=await f(y(`${m}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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 nd(e,t){const{base:r,head:n,context:o,zenModel:s,providerId:i,modelId:a}=t;if(!r||!n)throw new Error("base and head are required");const c={base:r,head:n};o?.trim()&&(c.context=o.trim()),s&&(c.zenModel=s),i&&(c.providerId=i),a&&(c.modelId=a);const l=await f(y(`${m}/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 d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",g=typeof d?.body=="string"?d.body:"";if(!u&&!g)throw new Error("Malformed PR description response");return{title:u,body:g}}async function yo(e){const t=await f(y(`${m}/worktrees`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to list worktrees")}return t.json()}async function go(e,t){const r=await f(y(`${m}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to validate worktree")}return r.json()}async function od(e){const t=await f(y(`${m}/worktrees/bootstrap-status`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to get worktree bootstrap status")}return t.json()}async function sd(e,t){const r=await f(y(`${m}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to preview worktree")}return r.json()}async function wo(e,t){const r=await f(y(`${m}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to create worktree")}return r.json()}async function bo(e,t){const r=await f(y(`${m}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to delete worktree")}return r.json()}async function id(e,t,r={}){const n=await f(y(`${m}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:r.addAll??!1,files:r.files,stageFiles:r.stageFiles})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create commit")}const o=await n.json();return Pe(e),o}async function ad(e,t={}){const r=await f(y(`${m}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to push")}const n=await r.json();return Pe(e),n}async function cd(e,t={}){const r=await f(y(`${m}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to pull")}const n=await r.json();return Pe(e),n}async function ld(e,t={}){const r=await f(y(`${m}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to fetch")}const n=await r.json();return Pe(e),n}async function dd(e){const t=await f(y(`${m}/stashes`,e));if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to list stashes")}return t.json()}async function ud(e,t){const r=await f(y(`${m}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to count stash files")}return r.json()}async function js(e,t={}){const r=await f(y(`${m}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to stash changes")}return r.json()}const An=async(e,t,r)=>{const n=await f(y(`${m}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||`Failed to ${t}`)}return n.json()},fd=(e,t)=>An(e,"stash/apply",t),Hs=(e,t)=>An(e,"stash/pop",t),pd=(e,t)=>An(e,"stash/drop",t);async function hd(e,t){const r=await f(y(`${m}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to checkout branch")}return r.json()}async function md(e,t,r){const n=await f(y(`${m}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create branch")}return n.json()}async function yd(e,t,r){const n=await f(y(`${m}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:r})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to rename branch")}return n.json()}async function gd(e,t={}){const r=await f(y(`${m}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Failed to get git log: ${n.error||r.statusText}`)}return r.json()}async function wd(e,t){const r=await f(y(`${m}/commit-files`,e,{hash:t}));if(!r.ok)throw new Error(`Failed to get commit files: ${r.statusText}`);return r.json()}async function Mf(e,t,r,n){const o=await f(y(`${m}/commit-file-diff`,e,{hash:t,path:r,binary:n?"true":void 0}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function bd(){const e=await f(y(`${m}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Sd(e){const t=await f(y(`${m}/identities`,void 0),{method:"POST",headers:{"Content-Type":"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 create git identity")}return t.json()}async function Td(e,t){const r=await f(y(`${m}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to update git identity")}return r.json()}async function Ed(e){const t=await f(y(`${m}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to delete git identity")}}async function vd(e){if(!e)return null;const t=await f(y(`${m}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const r=await t.json();return r?{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}:null}async function kd(e){if(!e)return!1;const t=await f(y(`${m}/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 Rf(){const e=await f(y(`${m}/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 Ad(e,t){const r=await f(y(`${m}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to set git identity")}return r.json()}async function Of(){const e=await f(y(`${m}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function If(e,t){if(!e)return null;const r=await f(y(`${m}/remote-url`,e,{remote:t}));return r.ok?(await r.json()).url??null:null}async function Pd(e){const t=await f(y(`${m}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Dd(e,t){const r=await f(y(`${m}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to rebase")}return r.json()}async function Cd(e){const t=await f(y(`${m}/rebase/abort`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to abort rebase")}return t.json()}async function Md(e,t){const r=await f(y(`${m}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to merge")}return r.json()}async function Rd(e,t){const r=await f(y(`${m}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to checkout commit")}return r.json()}async function Od(e,t){const r=await f(y(`${m}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to cherry-pick")}return r.json()}async function Id(e,t){const r=await f(y(`${m}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to revert commit")}return r.json()}async function _d(e,t,r,n){const o=await f(y(`${m}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:r,force:n})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to reset")}return o.json()}async function Fd(e){const t=await f(y(`${m}/merge/abort`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to abort merge")}return t.json()}async function xd(e){const t=await f(y(`${m}/rebase/continue`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to continue rebase")}return t.json()}async function Ld(e){const t=await f(y(`${m}/merge/continue`,e),{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to continue merge")}return t.json()}async function Nd(e,t){return await js(e,{message:t?.message}),{success:!0}}async function Bd(e){return await Hs(e,{ref:"stash@{0}"}),{success:!0}}async function Ud(e){const t=await f(y(`${m}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function jd(e,t){const r=await f(`${m}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!r.ok)throw new Error(`Failed to validate worktree directory: ${r.statusText}`);return r.json()}async function Hd(e){const t=await f(`${m}/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 zd=()=>({checkIsGitRepository:Hl,getGitStatus:zl,getGitDiff:Gl,getGitFileDiff:$l,revertGitFile:Wl,stageGitFile:ql,stageGitFiles:Bs,unstageGitFile:Kl,unstageGitFiles:Us,stageGitHunk:Vl,unstageGitHunk:Jl,revertGitHunk:Yl,isLinkedWorktree:Ql,getGitBranches:Xl,deleteGitBranch:Zl,deleteRemoteBranch:ed,removeRemote:td,generateCommitMessage:rd,generatePullRequestDescription:nd,listGitWorktrees:yo,validateGitWorktree:go,createGitWorktree:wo,deleteGitWorktree:bo,validateWorktreeDirectory:jd,canonicalizeWorktreeState:Hd,createGitCommit(e,t,r){return id(e,t,r)},gitPush:ad,gitPull:cd,gitFetch:ld,listGitStashes:dd,countGitStashFiles:ud,stashGitChanges:js,applyGitStash:fd,popGitStash:Hs,dropGitStash:pd,checkoutBranch:hd,createBranch:md,renameBranch:yd,getGitLog(e,t){return gd(e,t)},getCommitFiles:wd,getCurrentGitIdentity:vd,hasLocalIdentity:kd,setGitIdentity:Ad,getGitIdentities:bd,createGitIdentity:Sd,updateGitIdentity:Td,deleteGitIdentity:Ed,getRemotes:Pd,rebase:Dd,abortRebase:Cd,continueRebase:xd,merge:Md,abortMerge:Fd,continueMerge:Ld,checkoutCommit:Rd,cherryPick:Od,revertCommit:Id,resetToCommit:_d,stash:Nd,stashPop:Bd,getConflictDetails:Ud,worktree:{list:yo,validate:go,bootstrapStatus:od,preview:sd,create:wo,remove:bo}}),W=e=>e.replace(/\\/g,"/"),Gd=(e,t)=>{const r=W(t?.directory||t?.path||e),n=Array.isArray(t?.entries)?t.entries:[];return{directory:r,entries:n.filter(o=>!!(o&&typeof o.name=="string"&&typeof o.path=="string")).map(o=>({name:o.name,path:W(o.path),isDirectory:!!o.isDirectory}))}},de=(e,t)=>{const r=t||e?.();return r?{"x-opencode-directory":r}:void 0},$d=({getDirectory:e})=>({async listDirectory(t,r){const n=W(t),o=new URLSearchParams;n&&o.set("path",n),r?.respectGitignore&&o.set("respectGitignore","true");const s=await f("/api/fs/list",{query:o,headers:de(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to list directory")}const i=await s.json();return Gd(n,i)},async search(t){const r=new URLSearchParams,n=W(t.directory);n&&r.set("directory",n),r.set("query",t.query),r.set("dirs","false"),r.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&r.set("limit",String(t.maxResults));const o=await f("/api/find/file",{query:r,headers:de(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:W(`${n}/${a}`),preview:[W(a)]}))},async createDirectory(t){const r=W(t),n=await f("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...de(e)},body:JSON.stringify({path:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to create directory")}const o=await n.json();return{success:!!o?.success,path:typeof o?.path=="string"?W(o.path):r}},async statFile(t,r){const n=W(t),o=new URLSearchParams({path:n});r?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&o.set("outsideFileGrant",r.outsideFileGrant);const s=await f("/api/fs/stat",{query:o,headers:de(e,r?.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"?W(i.path):n,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,r){const n=W(t),o=new URLSearchParams({path:n});r?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),r?.outsideFileGrant&&o.set("outsideFileGrant",r.outsideFileGrant),r?.optional&&o.set("optional","true");const s=await f("/api/fs/read",{query:o,cache:r?.optional?"no-store":"default",headers:de(e,r?.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:n}},async writeFile(t,r){const n=W(t),o=await f("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...de(e)},body:JSON.stringify({path:n,content:r})});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"?W(s.path):n}},async delete(t){const r=W(t),n=await f("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...de(e)},body:JSON.stringify({path:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await n.json().catch(()=>({}))).success}},async rename(t,r){const n=await f("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...de(e)},body:JSON.stringify({oldPath:t,newPath:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to rename file")}const o=await n.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?W(o.path):r}},async revealPath(t){const r=await f("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...de(e)},body:JSON.stringify({path:W(t)})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await r.json().catch(()=>({}))).success}},async downloadFile(t){const r=W(t),n=await f("/api/fs/raw",{query:{path:r,download:!0},headers:de(e)});if(!n.ok)throw new Error(`Download failed (${n.status})`);const o=await n.blob(),s=URL.createObjectURL(o),i=document.createElement("a");i.href=s,i.download=r.split("/").pop()||"file",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(s),100)}}),So="/api/config/settings",Wd="/api/config/reload",To=e=>!e||typeof e!="object"?{}:e,qd=()=>({async load(){const e=await f(So,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:To(await e.json().catch(()=>({}))),source:"web"}},async save(e){const t=await f(So,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"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 save settings")}return To(await t.json().catch(()=>({})))},async restartOpenCode(){const e=await f(Wd,{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}}}),Kd=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),Vd=1500,on=5e3,Jd="openchamber-notification-claim:",ut=new Map,Yd=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Qd=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).join("|")},Xd=e=>{for(const[t,r]of ut)e-r>on&&ut.delete(t)},Zd=e=>{const t=Qd(e);if(!t)return!0;const r=Date.now();Xd(r);const n=ut.get(t)??0;if(r-n<on)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${Jd}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&r-s<on)return ut.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(r))}}catch{}return ut.set(t,r),!0},zs=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(r=>{setTimeout(()=>r(null),Vd)})])??e}catch{return e}},eu=async e=>{const t=await zs();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(r){return console.warn("Failed to send notification via service worker",r),!1}},tu=async()=>{const e=await zs();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},ru=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(!Yd()&&await tu()||!Zd(e))return!0;try{return await eu(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},nu=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(r){return console.warn("Failed to send native notification (desktop)",r),!1}},ou=()=>({async notifyAgentCompletion(e){return await nu(e)||await ru(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),su=()=>({async getAvailableTools(){const e=await f("/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(r=>typeof r=="string"&&r!=="invalid").sort()}}),$e=async(e,t)=>{try{const r=await f(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return r.ok?await r.json():null}catch{return null}},iu=()=>({async getVapidPublicKey(){return $e("/api/push/vapid-public-key")},async subscribe(e){return $e("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return $e("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return $e("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return $e("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return $e("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),j=async e=>await e.json().catch(()=>null),au=({urls:e})=>({async authStatus(){const t=await f("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to load GitHub status");return r},async authStart(){const t=await f("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),r=await j(t);if(!t.ok||!r||!("deviceCode"in r))throw new Error(r?.error||t.statusText||"Failed to start GitHub auth");return r},async authComplete(t){const r=await f("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to complete GitHub auth");return n},async authDisconnect(){const t=await f("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok)throw new Error(r?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!r?.removed}},async authActivate(t){const r=await f("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to activate GitHub account");return n},async authSetGhCliDisabled(t){const r=await f("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to update gh CLI setting");return{disabled:!!n.disabled}},async me(){const t=await f("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),r=await j(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to fetch GitHub user");return r},async prStatus(t,r,n,o){const s=new URLSearchParams({directory:t,branch:r,...n?{remote:n}:{},...o?.force?{force:"true"}:{}}),i=await f(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await j(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const r=await f("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to create PR");return n},async prUpdate(t){const r=await f("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to update PR");return n},async prMerge(t){const r=await f("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to merge PR");return n},async prReady(t){const r=await f("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to mark PR ready");return n},async repoUpstream(t){const r=await f(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),n=await j(r);if(!r.ok||!n)throw new Error(n?.error||r.statusText||"Failed to detect upstream repo");return n},async repoBranches(t,r){const n=await f(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(r)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await j(n);if(!n.ok||!o)throw new Error(o?.error||n.statusText||"Failed to fetch repo branches");return o.branches??[]},async prsList(t,r){const n=r?.page??1,o=new URLSearchParams({directory:t,page:String(n)});r?.query&&o.set("query",r.query);const s=await f(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull requests");return i},async prContext(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.includeDiff&&o.set("diff","1"),n?.includeCheckDetails&&o.set("checkDetails","1"),n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await f(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull request context");return i},async issuesList(t,r){const n=r?.page??1,o=new URLSearchParams({directory:t,page:String(n)});r?.query&&o.set("query",r.query);const s=await f(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issues");return i},async issueGet(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await f(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue");return i},async issueComments(t,r,n){const o=new URLSearchParams({directory:t,number:String(r)});n?.sourceRepo?.owner&&n.sourceRepo.repo&&(o.set("owner",n.sourceRepo.owner),o.set("repo",n.sourceRepo.repo));const s=await f(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await j(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}}),Te=async e=>await e.json().catch(()=>null),cu=()=>({async listClients(){const e=await f("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 f("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),r=await Te(t);if(!t.ok||!r?.client||typeof r.token!="string")throw new Error(r?.error||t.statusText||"Failed to create remote client token");return r},async createPairingSession(e={}){const t=await f("/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}:{}})}),r=await Te(t);if(!t.ok||typeof r?.pairing?.secret!="string"||!r?.server)throw new Error(r?.error||t.statusText||"Failed to create pairing session");return r},async listPendingPairings(){const e=await f("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 f("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await Te(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 f(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),r=await Te(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to cancel pairing");return{cancelled:r.cancelled===!0}},async revokeClient(e){const t=await f(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),r=await Te(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to revoke remote client");return r},async purgeRevokedClients(){const e=await f("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await Te(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),lu=()=>({api:(...e)=>X().api(...e),authenticatedAsset:(...e)=>X().authenticatedAsset(...e),auth:(...e)=>X().auth(...e),health:(...e)=>X().health(...e),rawFile:(...e)=>X().rawFile(...e),sse:(...e)=>X().sse(...e),websocket:(...e)=>X().websocket(...e)}),du=(e={})=>{const t=e.urls??dn();ia(t);const r=lu();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Nl(),git:zd(),files:$d({getDirectory:()=>rn.getState().currentDirectory}),settings:qd(),permissions:Kd(),notifications:ou(),github:au({urls:r}),push:iu(),clientAuth:cu(),tools:su()}},Eo=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}};let Gs=Promise.resolve();const _f=()=>Gs,Ff=()=>{const e=typeof window.__OPENCHAMBER_API_BASE_URL__=="string"?window.__OPENCHAMBER_API_BASE_URL__.trim():"",t=typeof window.__OPENCHAMBER_CLIENT_TOKEN__=="string"?window.__OPENCHAMBER_CLIENT_TOKEN__.trim():"",r=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__.trim():"",n=Zo({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});wa({apiBaseUrl:e,runtimeKey:Eo(e,r)?"local":null}),zo(t||null),Go(window.__OPENCHAMBER_RUNTIME_HEADERS__||null),cn(e||void 0).catch(()=>{}),r&&!Eo(e,r)&&Object.keys(ar()).length>0&&Jo(r).catch(()=>{}),ga();const o=window.__OPENCHAMBER_RELAY_HOST_ID__;return Gs=Promise.race([Ha(typeof o=="string"&&o?o:void 0).catch(()=>{}),new Promise(s=>{window.setTimeout(s,1e4)})]),du({urls:n})};export{Sf as $,tf as A,_l as B,Rl as C,et as D,dr as E,cs as F,Ku as G,Fa as H,qu as I,H as J,$o as K,Cu as L,xl as M,st as N,Ou as O,fs as P,sf as Q,Pc as R,af as S,al as T,zu as U,hu as V,mu as W,Mu as X,ju as Y,Uu as Z,bf as _,vt as a,md as a$,wf as a0,ie as a1,Zu as a2,va as a3,Ea as a4,yu as a5,gf as a6,of as a7,gu as a8,wu as a9,vu as aA,Au as aB,Du as aC,Ru as aD,_u as aE,Fu as aF,kf as aG,Tu as aH,cc as aI,cl as aJ,ef as aK,od as aL,Rs as aM,is as aN,ir as aO,Sl as aP,Fd as aQ,Cd as aR,fd as aS,Hd as aT,Hl as aU,hd as aV,Rd as aW,Od as aX,Ld as aY,xd as aZ,ud as a_,Da as aa,Nu as ab,xu as ac,Lu as ad,Et as ae,xa as af,Wu as ag,Ju as ah,Ae as ai,$u as aj,ls as ak,Yu as al,Bu as am,Lc as an,Ic as ao,nf as ap,hc as aq,wc as ar,mc as as,bc as at,Fc as au,ur as av,Su as aw,Eu as ax,ku as ay,Pu as az,X as b,It as b$,id as b0,Sd as b1,wo as b2,Zl as b3,Ed as b4,bo as b5,ed as b6,Of as b7,pd as b8,Mf as b9,yd as bA,_d as bB,Pf as bC,Df as bD,Id as bE,Wl as bF,Yl as bG,Ad as bH,ql as bI,Bs as bJ,Vl as bK,Nd as bL,js as bM,Bd as bN,Kl as bO,Us as bP,Jl as bQ,Td as bR,jd as bS,Y as bT,rf as bU,pc as bV,Xu as bW,Qu as bX,Vu as bY,ja as bZ,ar as b_,wd as ba,Ud as bb,vd as bc,Xl as bd,Cf as be,Gl as bf,$l as bg,bd as bh,gd as bi,zl as bj,Rf as bk,If as bl,Pd as bm,go as bn,yo as bo,ld as bp,cd as bq,ad as br,kd as bs,Ql as bt,dd as bu,Md as bv,Hs as bw,sd as bx,Dd as by,td as bz,Ff as c,Rr as c0,cf as c1,df as c2,hf as c3,uf as c4,lf as c5,ff as c6,Ms as c7,pf as c8,Tf as c9,Ef as ca,Iu as cb,vf as cc,yc as cd,gc as ce,Af as cf,mn as d,rn as e,ke as f,_f as g,f as h,fu as i,pu as j,Lo as k,cr as l,bu as m,ba as n,ve as o,yf as p,mf as q,cn as r,Gr as s,fe as t,ue as u,ss as v,Q as w,Gu as x,Hu as y,Ca as z};