@openchamber/web 1.22.1 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/bin/cli.js +4 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-BI-TY1UG.js} +1 -1
  6. package/dist/assets/{DiffView-CNnDxRmO.js → DiffView-cOmByCaX.js} +3 -3
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-BwSnDlNy.js} +1 -1
  8. package/dist/assets/FilesView-DRRy_6oZ.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-B7YCg1YM.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-CjzNsiIU.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BYlE0YrW.js} +1 -1
  12. package/dist/assets/{MarkdownImageGallery-DffjmciG.js → MarkdownImageGallery-DlTF-wua.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-CqgeZRlP.js +12 -0
  14. package/dist/assets/{OnboardingScreen-CTZe6HZn.js → OnboardingScreen-BsJU7oav.js} +1 -1
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CDNu968J.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BvwtCxW4.js → PierreDiffViewer-BoBsAanf.js} +1 -1
  17. package/dist/assets/{PlanView-C1qvAm7m.js → PlanView-Cxr8LQT1.js} +4 -4
  18. package/dist/assets/SettingsView-bsKpCZbB.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-B0rHQdw4.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-6zP8hwzX.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-Bvwh4Y31.js} +2 -2
  22. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-aaIfrRxl.js} +1 -1
  23. package/dist/assets/{WalkthroughView-D-HFgdmM.js → WalkthroughView-baZ0ssy9.js} +2 -2
  24. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-DfgllYQc.js} +2 -2
  25. package/dist/assets/{contextPanelEmbeddedChat-CV-DwAiX.js → contextPanelEmbeddedChat-prHos-tt.js} +1 -1
  26. package/dist/assets/{de-Cv_4FoXm.js → de-hknQLFxa.js} +2 -2
  27. package/dist/assets/{es-BIWNEbnS.js → es-C_bD3kvW.js} +2 -2
  28. package/dist/assets/{fr-SD3OfMHJ.js → fr-BVF-C2Nu.js} +2 -2
  29. package/dist/assets/index-B0aX0JeI.js +39 -0
  30. package/dist/assets/{index-DLiD86ge.js → index-DUwZ2cWA.js} +1 -1
  31. package/dist/assets/index-Dl3xbAB_.css +1 -0
  32. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-COIS9Df5.js} +1 -1
  33. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-D7LEG-KY.js} +1 -1
  34. package/dist/assets/{ja-D7I9HofF.js → ja-B2G5hD59.js} +2 -2
  35. package/dist/assets/{ko-BsVJM_PQ.js → ko-D6OrOdZ3.js} +2 -2
  36. package/dist/assets/main-BBuBZzoi.js +930 -0
  37. package/dist/assets/{main-DCB4JgVe.js → main-CwIEELQq.js} +2 -2
  38. package/dist/assets/{markdownCore-BoQVG5-a.js → markdownCore-BE_Hhps5.js} +2 -2
  39. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CeXAoWiF.js} +2 -2
  40. package/dist/assets/{mobile-DZV_sfX7.js → mobile-ilq39yLQ.js} +2 -2
  41. package/dist/assets/{patchFileDiff-Chmiz6hq.js → patchFileDiff-DLky6SYr.js} +5 -5
  42. package/dist/assets/{pl-XR9Bs8Be.js → pl-CVroZXt1.js} +2 -2
  43. package/dist/assets/{pt-BR-Due4be8g.js → pt-BR-eH3onaIW.js} +2 -2
  44. package/dist/assets/{renderElectronMiniChatApp-8tXADjfl.js → renderElectronMiniChatApp-BsywqmJT.js} +2 -2
  45. package/dist/assets/{renderMobileApp-Cji7Hma5.js → renderMobileApp-CDun1795.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-DebJIo5U.js +17 -0
  47. package/dist/assets/{scheduledTasksApi-9e-UX6im.js → scheduledTasksApi-B0tChXQC.js} +1 -1
  48. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-DJSXdcG4.js} +1 -1
  49. package/dist/assets/tr-BvtU2tXS.js +7 -0
  50. package/dist/assets/{uk-COYh2BaN.js → uk-nu36iqFz.js} +2 -2
  51. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-Bb1Zihd2.js} +134 -131
  52. package/dist/assets/useInlineCommentController-B8dQWRpH.js +2 -0
  53. package/dist/assets/{useRootScrollLock-KzOUytpn.js → useRootScrollLock-DrJ8gE-x.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-CNjvbb69.js} +2 -2
  55. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  56. package/dist/assets/{web-components-B6QgbmTo.js → web-components-C06MmTcR.js} +1 -1
  57. package/dist/assets/{zh-CN-Cjk6lzhc.js → zh-CN-BClBzZ64.js} +2 -2
  58. package/dist/assets/{zh-TW-Dk0dOg03.js → zh-TW-CXtSqJHF.js} +2 -2
  59. package/dist/index.html +5 -5
  60. package/dist/mini-chat.html +4 -4
  61. package/dist/mobile.html +4 -4
  62. package/package.json +3 -3
  63. package/server/index.js +7 -1
  64. package/server/lib/changelog/update-notes.js +82 -0
  65. package/server/lib/changelog/update-notes.test.js +59 -0
  66. package/server/lib/fs/DOCUMENTATION.md +2 -0
  67. package/server/lib/fs/routes.js +32 -21
  68. package/server/lib/fs/routes.test.js +77 -0
  69. package/server/lib/git/service.js +10 -0
  70. package/server/lib/git/service.test.js +18 -0
  71. package/server/lib/message-queue/DOCUMENTATION.md +17 -7
  72. package/server/lib/message-queue/runtime.js +59 -7
  73. package/server/lib/message-queue/runtime.test.js +59 -3
  74. package/server/lib/opencode/DOCUMENTATION.md +8 -4
  75. package/server/lib/opencode/config-paths.test.js +116 -0
  76. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  77. package/server/lib/opencode/input-history-scope.js +14 -0
  78. package/server/lib/opencode/plugins.js +2 -2
  79. package/server/lib/opencode/providers.js +44 -2
  80. package/server/lib/opencode/providers.test.js +131 -4
  81. package/server/lib/opencode/routes.js +4 -4
  82. package/server/lib/opencode/server-startup-runtime.js +1 -1
  83. package/server/lib/opencode/settings-helpers.js +28 -0
  84. package/server/lib/opencode/settings-helpers.test.js +177 -0
  85. package/server/lib/opencode/shared.js +4 -1
  86. package/server/lib/opencode/skill-routes.js +2 -1
  87. package/server/lib/opencode/snippets.js +1 -2
  88. package/server/lib/package-manager.js +3 -28
  89. package/server/lib/quota/utils/auth.js +1 -1
  90. package/server/lib/relay/host-client.test.js +9 -1
  91. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  92. package/server/lib/session-goal/runtime.js +76 -11
  93. package/server/lib/session-goal/runtime.test.js +426 -0
  94. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  95. package/server/lib/skills-catalog/install.js +3 -2
  96. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  97. package/server/lib/terminal/runtime.js +150 -19
  98. package/server/lib/terminal/runtime.test.js +553 -26
  99. package/server/lib/terminal/shells.js +17 -0
  100. package/server/lib/terminal/shells.test.js +32 -1
  101. package/server/lib/walkthrough/routes.test.js +26 -5
  102. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  103. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  104. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  105. package/dist/assets/index-CHUT_bDS.css +0 -1
  106. package/dist/assets/index-DDInLQDd.js +0 -40
  107. package/dist/assets/main-De8Z5w49.js +0 -928
  108. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  109. package/dist/assets/tr-DBJcAv4y.js +0 -7
  110. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  111. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
@@ -1,40 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CEam9pDc.js","assets/vendor-react-BUCujlKS.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
- import{_ as wo}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as St,d as fn,p as nr}from"./vendor-zustand-BAGL70zf.js";import{o as U,n as ce,s as k,d as mi,_ as Fr,l as pe,a as rn}from"./vendor-zod-DVWEh-IS.js";import{c as mc}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as yi,R as Un}from"./vendor-react-BUCujlKS.js";const Qt=1,yc="openchamber-relay-v1",gi=1,wi=12,Xt=1+wi,on=64*1024,sn=5,an=128,bi=0,Si=1,jt=4,gc=1+jt,jr=on-sn-gc,R={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},wc=new Set(Object.values(R)),bc=e=>wc.has(e),ht={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},Ne=globalThis.crypto.subtle,Ti={name:"ECDH",namedCurve:"P-256"},Ei=16,gr=32,Sc=16,Ur=4,ki=8;class Xe extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const Tc=()=>Ne.generateKey(Ti,!0,["deriveBits"]),Ec=async e=>{const t=await Ne.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},kc=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new Xe("invalid ECDH public key JWK");try{return await Ne.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},Ti,!0,[])}catch{throw new Xe("invalid ECDH public key JWK")}},vc=()=>{const e=new Uint8Array(Ei);return globalThis.crypto.getRandomValues(e),e},Pc=async(e,t,n)=>{if(n.length!==Ei)throw new Xe("invalid handshake nonce length");const r=await Ne.deriveBits({name:"ECDH",public:t},e,256),o=await Ne.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await Ne.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(yc)},o,gr*2*8)),i=(a,c)=>Ne.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"])}},Ac=(e,t,n)=>{for(let r=ki-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Mc=(e,t)=>{let n=0n;for(let r=0;r<ki;r+=1)n=n<<8n|BigInt(e[t+r]);return n},Cc=e=>{const t=new Uint8Array(Ur);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>on)throw new Xe("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(wi);o.set(t,0),Ac(o,Ur,n);const s=new Uint8Array(await Ne.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(Xt+s.length);return i[0]=gi,i.set(o,1),i.set(s,Xt),i}}},Dc=e=>{let t=0n;return{async decrypt(n){if(n.length<Xt+Sc)throw new Xe("encrypted frame too short");if(n[0]!==gi)throw new Xe("unsupported encrypted frame version");const r=n.slice(1,Xt),o=Mc(r,Ur);if(o<=t)throw new Xe("frame counter regression");let s;try{s=await Ne.decrypt({name:"AES-GCM",iv:r},e,n.slice(Xt))}catch{throw new Xe("frame decryption failed")}return t=o,new Uint8Array(s)}}},gn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Rc=e=>{let t="";for(let n=0;n<e.length;n+=3){const r=e[n],o=n+1<e.length?e[n+1]:void 0,s=n+2<e.length?e[n+2]:void 0;t+=gn[r>>2],t+=gn[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=gn[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=gn[s&63])}return t},es=e=>{let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const n=t;if(n.v!==Qt)return null;const r=n.batch===!0;return n.t==="ready"?{t:"ready",v:Qt,batch:r}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:Qt,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r}:null},Ic=e=>({type:"fail",closeCode:ht.ChannelFailure,reason:e}),Oc=async(e,t={})=>{const n=t.batch!==!1,r=await kc(e),o=await Tc(),s=vc(),i={t:"hello",v:Qt,clientPubJwk:await Ec(o.publicKey),nonce:Rc(s),...n?{batch:!0}:{}};let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return es(c)?.t==="ready"?{type:"ignore"}:Ic("plaintext frame on established channel");const l=es(c);if(l?.t!=="ready")return{type:"ignore"};const d=await Pc(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,channel:{encryptor:Cc(d.clientToHost),decryptor:Dc(d.hostToClient)}}}}},vi=4294967295;class ee extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Pe=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>vi)throw new ee("invalid stream id");if(n.length>jr)throw new ee("tunnel payload exceeds maximum size");const o=new Uint8Array(sn+n.length);return o[0]=r?e|an:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,sn),o},xc=e=>{if(e.length<sn)throw new ee("tunnel frame too short");const t=e[0],n=(t&an)!==0,r=t&~an;if(!bc(r))throw new ee(`unknown tunnel frame type ${r}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:o,payload:e.slice(sn),hasMoreFragments:n}},_c=new TextEncoder,Lc=new TextDecoder,wn=e=>_c.encode(JSON.stringify(e)),bn=(e,t)=>{let n;try{n=JSON.parse(Lc.decode(e))}catch{throw new ee("malformed JSON tunnel payload")}if(!t(n))throw new ee("unexpected JSON tunnel payload shape");return n},Pi=(e,t=jr)=>{if(t<=0||t>jr)throw new ee("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},ts=(e,t,n)=>{const r=Pi(n);return r.map((o,s)=>Pe(e,t,o,s<r.length-1))},Fc=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,o=t.get(r);if(!n.hasMoreFragments&&!o)return n.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ee("fragmented message exceeds maximum size");if(s.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:s,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},jc=e=>{if(e.length===0)throw new ee("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=bi,s.set(o,1),s.length>on)throw new ee("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=jt+o.length;if(t>on)throw new ee("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Si;let r=1;for(const o of e)n[r]=o.length>>>24&255,n[r+1]=o.length>>>16&255,n[r+2]=o.length>>>8&255,n[r+3]=o.length&255,r+=jt,n.set(o,r),r+=o.length;return n},Uc=e=>{if(e.length<1)throw new ee("empty batch plaintext");const t=e[0];if(t===bi)return[e.slice(1)];if(t!==Si)throw new ee(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+jt>e.length)throw new ee("truncated batch frame length");const o=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=jt,r+o>e.length)throw new ee("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ee("empty frame batch");return n},Nc=new Set([R.HttpBody,R.WsText,R.WsBinary]),Ai=150,Bc=24*1024,Hc=32,zc=e=>{const t=e.windowMs??Ai,n=e.maxBatchBytes??Bc,r=e.maxBatchFrames??Hc,o=e.now??(()=>Date.now()),s=e.setTimer??((g,y)=>setTimeout(g,y)),i=e.clearTimer??(g=>clearTimeout(g));let a=[],c=0,l=null,d=0,u=!1;const f=()=>{l!==null&&(i(l),l=null)},m=()=>{if(f(),a.length===0)return;const g=a;a=[],c=0,d=o(),e.sendBatch(jc(g))};return{enqueue:g=>{if(u)return;const y=g[0]&~an;if(!Nc.has(y)){a.push(g),m();return}const S=o();if(a.length===0&&S-d>=t){a.push(g),m();return}const E=jt+g.length;if(a.length>0&&1+c+E>on&&m(),a.push(g),c+=E,c>=n||a.length>=r){m();return}l===null&&(l=s(m,t))},flush:m,dispose(){u=!0,f(),a=[],c=0}}},$c=()=>{let e=1;return{next(){if(e>vi)throw new ee("stream id space exhausted");const t=e;return e+=2,t}}},rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gc=e=>rr(e)&&Object.values(e).every(t=>typeof t=="string"),Wc=e=>rr(e)&&typeof e.status=="number"&&Gc(e.headers),ns=e=>rr(e)&&typeof e.reason=="string",qc=e=>rr(e)&&typeof e.code=="number"&&typeof e.reason=="string",Mi=/^[a-z][a-z\d+.-]*:\/\//i,bo="http://tunnel.invalid",Kc=e=>{try{const t=Mi.test(e)?new URL(e):new URL(e,bo);return`${t.pathname}${t.search}`}catch{return e}},Sn=e=>({async*[Symbol.asyncIterator](){yield e}}),Vc=e=>({async*[Symbol.asyncIterator](){const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)return;r&&(yield r)}}finally{t.releaseLock()}}}),Jc=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},Yc=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:Vc(e)};if(typeof e=="string")return{body:Sn(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Sn(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Sn(Jc(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Sn(r),contentType:n}},Qc=async(e,t)=>{let n;const r=new Headers;let o="GET",s=null,i;e instanceof Request?(n=e.url,o=e.method,e.headers.forEach((u,f)=>r.set(f,u)),i=e.signal,s=e.body):n=e.toString(),t&&(t.method&&(o=t.method),t.headers&&new Headers(t.headers).forEach((u,f)=>r.set(f,u)),t.body!==void 0&&(s=t.body),t.signal&&(i=t.signal));const a=Mi.test(n)?new URL(n):new URL(n,bo),{body:c,contentType:l}=await Yc(s);l&&!r.has("content-type")&&r.set("content-type",l);const d={};return r.forEach((u,f)=>{d[f]=u}),{method:o.toUpperCase(),path:a.pathname,query:a.search.startsWith("?")?a.search.slice(1):a.search,headers:d,body:c,signal:i}},Ci="__openchamberAmbiguousTransport",Di=e=>(Object.defineProperty(e,Ci,{value:!0,enumerable:!1,configurable:!0}),e),Xc=e=>!e||typeof e!="object"?!1:e[Ci]===!0,Tn=new Uint8Array(0),Zc=new TextEncoder,el=new TextDecoder,be=e=>e instanceof Error?e:new Error(String(e)),En=()=>new DOMException("The operation was aborted.","AbortError"),tl=e=>{e.binaryType="arraybuffer";const t={get readyState(){return e.readyState},send(n){e.send(n)},close(n,r){e.close(n,r)},onopen:null,onmessage:null,onclose:null,onerror:null};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>t.onmessage?.({data:n.data}),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),e.onerror=()=>t.onerror?.(),t},nl=e=>{const t={get readyState(){return e.readyState},get binaryType(){return e.binaryType},set binaryType(n){n&&(e.binaryType=n)},onopen:null,onmessage:null,onerror:null,onclose:null,send(n){e.send(n)},close(n,r){e.close(n,r)}};return e.onopen=()=>t.onopen?.(),e.onmessage=n=>{const r=n.data;(typeof r=="string"||r instanceof ArrayBuffer)&&t.onmessage?.({data:r})},e.onerror=()=>t.onerror?.(),e.onclose=n=>t.onclose?.({code:n.code,reason:n.reason}),t},rs=0,wr=1,os=2,ss=3,rl=new Set([ht.AuthFailed,ht.DuplicateClient,ht.LimitExceeded]),ol={[ht.AuthFailed]:"relay authentication failed",[ht.DuplicateClient]:"relay connection replaced by another client",[ht.LimitExceeded]:"relay connection limit reached"},is=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},So=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??Ai,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(T=>tl(new WebSocket(T)));let u=!1,f={state:"idle"};const m=new Set;let p=null,g=null,y=null,S=0,E=0,P=null,C=[],Q=!1;const we=T=>{if(!(f.state===T.state&&f.lastError===T.lastError)){f=T;for(const I of m)try{I(f)}catch{}}},Wt=T=>{const I=C;C=[];for(const v of I)v.reject(T)},fr=T=>{const I=C;C=[];for(const v of I)v.resolve(T)},Yo=(T,I)=>{T.dead=!0;const v=Array.from(T.streams.values());T.streams.clear();for(const A of v)try{A.fail(I)}catch{}},pr=()=>{P!==null&&(clearTimeout(P),P=null)},hr=()=>{u||P===null||is()||(pr(),mr(),yr())},Qo=()=>{typeof document<"u"&&document.visibilityState==="visible"&&hr()},lc=()=>{Q||typeof window>"u"||(Q=!0,window.addEventListener("online",hr),typeof document<"u"&&document.addEventListener("visibilitychange",Qo))},mr=()=>{!Q||typeof window>"u"||(Q=!1,window.removeEventListener("online",hr),typeof document<"u"&&document.removeEventListener("visibilitychange",Qo))},Xo=()=>{if(u||P!==null)return;const T=Math.max(0,E-1),I=a*2**Math.min(T,10),v=is()?l:c,A=Math.min(v,I);lc(),P=setTimeout(()=>{P=null,mr(),yr()},A)},dc=()=>{const T=new URL(e.relayUrl);return T.searchParams.set("v",String(Qt)),T.searchParams.set("role","client"),T.searchParams.set("serverId",e.serverId),e.grant&&T.searchParams.set("grant",e.grant),T.toString()},yr=async()=>{if(u)return;pr(),S+=1;const T=S;we({state:E>0?"reconnecting":"connecting",lastError:f.lastError});let I;try{I=await Oc(e.hostEncPubJwk,{batch:i})}catch(_){if(T!==S||u)return;ie(T,be(_),!0);return}if(T!==S||u)return;let v;try{v=d(dc())}catch(_){ie(T,be(_));return}g=v;let A=!1,M=null,O=null,de=null,X=null,D=Promise.resolve(),x=null,z=null,Oe=!1,W=null,Z=Date.now();const te=()=>{M!==null&&(clearInterval(M),M=null),O!==null&&(clearTimeout(O),O=null),de!==null&&(clearInterval(de),de=null),X!==null&&(clearTimeout(X),X=null),W!==null&&(W.dispose(),W=null)};y=te;function H(_,N=!1,F=!1){if(!(A||T!==S)){A=!0,te(),x&&(p=null,Yo(x,new Error(`relay tunnel reset: ${_.message}`))),Wt(_);try{v.close()}catch{}if(g===v&&(g=null),!u){if(E+=1,F){we({state:"error",lastError:_.message});return}we({state:N?"error":"reconnecting",lastError:_.message}),Xo()}}}const ot=()=>{try{v.send(I.helloText)}catch{}},$=(_,N)=>{z=_,Oe=N,M!==null&&(clearInterval(M),M=null),O!==null&&(clearTimeout(O),O=null);const F=new Map,q=$c(),st=Fc();let ye=Promise.resolve();const xe=Pt=>{ye=ye.then(async()=>{if(vt.dead)return;const yn=await _.encryptor.encrypt(Pt);v.send(yn)}).catch(()=>{})},it=N?zc({windowMs:s,sendBatch:xe}):null;W=it;const vt={streams:F,assembler:st,nextStreamId:()=>q.next(),dead:!1,send(Pt){if(vt.dead)return;const yn=Pt[0]&~an;yn!==R.Ping&&yn!==R.Pong&&(Z=Date.now()),it?it.enqueue(Pt):xe(Pt)}};x=vt,p=vt,E=0,Z=Date.now(),we({state:"connected"}),fr(vt),de=setInterval(()=>{Date.now()-Z<r||(vt.send(Pe(R.Ping,0,Tn)),X===null&&(X=setTimeout(()=>{X=null,H(new Error("relay keepalive timeout"))},o)))},r)},He=(_,N)=>{let F;try{F=xc(N)}catch(ye){H(be(ye));return}if(X!==null&&(clearTimeout(X),X=null),F.frameType===R.Ping){_.send(Pe(R.Pong,F.streamId,Tn));return}if(F.frameType===R.Pong)return;Z=Date.now();let q=F.payload;if(F.frameType===R.WsText||F.frameType===R.WsBinary){let ye;try{ye=_.assembler.push(F)}catch(xe){H(be(xe));return}if(ye===null)return;q=ye}else if(F.hasMoreFragments){H(new Error("unexpected fragmented tunnel frame"));return}const st=_.streams.get(F.streamId);st&&st.handleFrame(F.frameType,q)};v.onopen=()=>{A||T!==S||(ot(),M=setInterval(ot,t))},v.onmessage=_=>{if(A||T!==S)return;const N=_.data;if(typeof N=="string"){D=D.then(async()=>{if(A||T!==S)return;const q=await I.handleText(N);if(q.type==="established"){if(z)return;$(q.channel,q.batch)}else q.type==="fail"&&H(new Error(`relay handshake failed: ${q.reason}`))}).catch(q=>{H(be(q))});return}const F=N instanceof ArrayBuffer?new Uint8Array(N):N instanceof Uint8Array?N:null;F&&(D=D.then(async()=>{if(A||T!==S)return;const q=x,st=z;if(!q||!st){H(new Error("encrypted frame before handshake completed"));return}let ye;try{ye=await st.decryptor.decrypt(F)}catch(xe){H(be(xe));return}if(Oe){let xe;try{xe=Uc(ye)}catch(it){H(be(it));return}for(const it of xe){if(A||T!==S||q.dead)return;He(q,it)}return}He(q,ye)}).catch(q=>{H(be(q))}))},v.onclose=_=>{const N=rl.has(_.code);H(new Error(ol[_.code]??`relay socket closed (code ${_.code})`),N,N)},v.onerror=()=>{},O=setTimeout(()=>{O=null,H(new Error("relay handshake timeout"),!0)},n);function ie(_,N,F=!1){_!==S||u||(Wt(N),E+=1,we({state:F?"error":"reconnecting",lastError:N.message}),Xo())}},Zo=T=>u?Promise.reject(new Error("relay tunnel closed")):T?.aborted?Promise.reject(En()):p&&!p.dead?Promise.resolve(p):new Promise((I,v)=>{let A=null;const M={resolve(O){A&&T&&T.removeEventListener("abort",A),I(O)},reject(O){A&&T&&T.removeEventListener("abort",A),v(O)}};T&&(A=()=>{C=C.filter(O=>O!==M),v(En())},T.addEventListener("abort",A,{once:!0})),C.push(M)}),uc=async(T,I)=>{const v=await Qc(T,I),A=v.signal;if(A?.aborted)throw En();const M=await Zo(A),O=M.nextStreamId();return await new Promise((de,X)=>{let D=!1,x=!1,z=null,Oe=null;const W=()=>{M.streams.delete(O),M.assembler.dropStream(O),Oe&&A&&A.removeEventListener("abort",Oe)},Z=$=>{if(!x){if(x=!0,W(),!D){X($);return}try{z?.error($)}catch{}}},te=$=>{M.dead||M.send(Pe(R.StreamAbort,O,wn({reason:$})))},H=$=>Di(new Error($));Oe=()=>{te("aborted"),Z(En())},M.streams.set(O,{handleFrame($,He){if($===R.HttpResponse){if(D||x)return;let ie;try{ie=bn(He,Wc)}catch(F){te("malformed response head"),Z(H(be(F).message));return}const _=ie.status===204||ie.status===205||ie.status===304;let N=null;_||(N=new ReadableStream({start(F){z=F},cancel(){x||(x=!0,W(),te("response body cancelled"))}})),D=!0,de(new Response(N,{status:ie.status,headers:ie.headers})),_&&(x=!0,W());return}if($===R.HttpBody){if(!D||x)return;try{z?.enqueue(He)}catch{}return}if($===R.StreamEnd){if(x)return;if(!D){Z(H("tunnel stream ended before response head"));return}x=!0,W();try{z?.close()}catch{}return}if($===R.StreamAbort){let ie="stream aborted by host";try{ie=bn(He,ns).reason}catch{}Z(H(ie))}},fail($){Z(H($.message))}}),A&&A.addEventListener("abort",Oe,{once:!0});const ot={method:v.method,path:v.path,query:v.query,headers:v.headers,hasBody:v.body!==null};M.send(Pe(R.HttpRequest,O,wn(ot))),(async()=>{try{let $=!1;if(v.body)for await(const He of v.body){if(x||M.dead)return;for(const ie of Pi(He))M.send(Pe(R.HttpBody,O,ie)),$=!0}!x&&!M.dead&&(v.body&&!$&&M.send(Pe(R.HttpBody,O,Tn)),M.send(Pe(R.StreamEnd,O,Tn)))}catch($){te("request body failed"),Z(H(be($).message))}})()})},fc=T=>{const I=T.indexOf("?");return I===-1?{path:T,query:""}:{path:T.slice(0,I),query:T.slice(I+1)}},pc=(T,I)=>{let v=rs,A=null,M=0,O=!1;const de={get readyState(){return v},onopen:null,onmessage:null,onerror:null,onclose:null,send(D){if(v!==wr||!A||A.dead)throw new Error("relay tunnel socket is not open");if(typeof D=="string"){for(const z of ts(R.WsText,M,Zc.encode(D)))A.send(z);return}const x=D instanceof ArrayBuffer?new Uint8Array(D.slice(0)):(()=>{const z=new Uint8Array(D.byteLength);return z.set(new Uint8Array(D.buffer,D.byteOffset,D.byteLength)),z})();for(const z of ts(R.WsBinary,M,x))A.send(z)},close(D=1e3,x=""){v===ss||v===os||(v===wr&&A&&!A.dead&&(v=os,A.send(Pe(R.WsClose,M,wn({code:D,reason:x})))),X(D,x))}},X=(D,x,z=!1)=>{if(!O){if(O=!0,A&&(A.streams.delete(M),A.assembler.dropStream(M)),v=ss,z)try{de.onerror?.()}catch{}try{de.onclose?.({code:D,reason:x})}catch{}}};return(async()=>{let D;try{D=await Zo()}catch(W){X(1006,be(W).message,!0);return}if(O)return;A=D,M=D.nextStreamId(),D.streams.set(M,{handleFrame(W,Z){if(W===R.WsOpened){if(v===rs){v=wr;try{de.onopen?.()}catch{}}return}if(W===R.WsText){try{de.onmessage?.({data:el.decode(Z)})}catch{}return}if(W===R.WsBinary){const te=new ArrayBuffer(Z.byteLength);new Uint8Array(te).set(Z);try{de.onmessage?.({data:te})}catch{}return}if(W===R.WsClose){let te=1e3,H="";try{const ot=bn(Z,qc);te=ot.code,H=ot.reason}catch{}X(te,H);return}if(W===R.StreamAbort){let te="stream aborted";try{te=bn(Z,ns).reason}catch{}X(1006,te,!0)}},fail(W){X(1012,W.message,!0)}});const{path:x,query:z}=fc(T),Oe=I&&I.length>0?{path:x,query:z,protocols:I}:{path:x,query:z};D.send(Pe(R.WsOpen,M,wn(Oe)))})(),de},hc=()=>{if(u)return;u=!0,S+=1,pr(),mr(),y?.(),y=null;const T=p;p=null;const I=new Error("relay tunnel closed");T&&Yo(T,I),Wt(I);try{g?.close()}catch{}g=null,we({state:"idle"})};return yr(),{fetch:uc,openWebSocket:pc,getStatus:()=>f,subscribeStatus(T){return m.add(T),()=>{m.delete(T)}},close:hc}};let me=null,Be=null;const sl=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),or=()=>me,Cm=()=>!me||!Be?null:{relayUrl:Be.relayUrl,serverId:Be.serverId,hostEncPubJwk:{...Be.hostEncPubJwk}},Dm=()=>me!==null,il=e=>(me&&Be&&sl(Be,e)||(me?.close(),Be=e,me=So(e)),me),Rm=(e,t)=>{me!==t&&(me?.close(),Be=e,me=t)},al=()=>{me?.close(),me=null,Be=null};let Ri=()=>null,Ii="",Nn={},yt="",cn=0,dt=null,Lt="",ln=0,gt="",ut=null,Ye="",_n=0,Ln=0;const To=1e4,cl=e=>e.toLowerCase()==="authorization",Oi=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!cl(o)&&(t[o]=s)}return t},ll=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},sr=e=>typeof e!="string"?"":e.trim(),dl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_CLIENT_TOKEN__;return sr(e)},ul=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},xi=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():ul();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},Eo=e=>{try{return new URL(e).origin}catch{return""}},_i=()=>{Lt="",ln=0,gt="",ut=null,Ye="",_n+=1},pn=()=>{yt="",cn=0,_i()},Li=()=>{Ln+=1,dt=null,pn(),ko()},Fi=e=>{const t=sr(e);Ii=t,Li(),Ri=()=>t?{type:"bearer",token:t}:null},ji=e=>{const t=Oi(e);ll(Nn,t)||(Nn=t,Li())},ir=()=>{if(Object.keys(Nn).length>0)return Nn;if(typeof window>"u")return{};const e=window.__OPENCHAMBER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Oi(e):{}},Ui=()=>Ii||dl(),fl=(e,t)=>{const n=sr(e);if(!n||typeof t!="number"||!Number.isFinite(t)){pn();return}const r=yt;yt=n,cn=t,r&&r!==n&&gl()},Ni=()=>!yt||cn<=Date.now()+To?(pn(),""):yt,Bi=e=>{const t=Eo(e);return!t||gt!==t?"":!Lt||ln<=Date.now()+To?(Lt="",ln=0,gt="",""):Lt},pl=()=>{const e=Ni();return!e&&(Ui()||typeof window<"u")&&ar().catch(()=>{}),e},hl=e=>{const t=e?Bi(e):"";return!t&&e&&typeof window<"u"&&$i(e).catch(()=>{}),t},Hi=async()=>{const e=await Ri(),t=e?.type==="bearer"?sr(e.token):Ui();return t?{type:"bearer",token:t}:null},zi=e=>{if(dt)return dt;const t=Ln,r=(async()=>{const o=await Hi(),s=new Headers;for(const[u,f]of Object.entries(ir()))s.set(u,f);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(xi(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===Ln&&pn(),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!==Ln)throw new Error("Runtime URL auth token response is stale");if(fl(l,d),!yt)throw new Error("Runtime URL auth token response was invalid");return yt})().finally(()=>{dt===r&&(dt=null)});return dt=r,dt},ml=e=>{const t=Eo(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(ut&&Ye===t)return ut;const n=_n,o=(async()=>{const s=await fetch(xi(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===_n&&t===Ye&&(Lt="",ln=0,gt=""),new Error(`Failed to mint local runtime URL auth token (${s.status})`);const i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!a||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(n!==_n||t!==Ye)throw new Error("Local runtime URL auth token response is stale");return Lt=a,ln=c,gt=t,a})().finally(()=>{ut===o&&(ut=null,Ye="")});return ut=o,Ye=t,ut},ar=async e=>{const t=Ni();return t||zi(e)},$i=async e=>{const t=Eo(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Bi(t);return n||((gt&&gt!==t||Ye&&Ye!==t)&&_i(),ml(t))};let _t=0,Zt=null,Gi=null;const Nr=new Set,yl=5e3,gl=()=>{for(const e of Nr)try{e()}catch{}},Wi=()=>{Zt!==null&&(clearTimeout(Zt),Zt=null)},ko=()=>{if(Wi(),_t<=0||typeof window>"u")return;const e=cn-To-yl,t=cn>0?Math.max(0,e-Date.now()):0;Zt=setTimeout(()=>{Zt=null,!(_t<=0)&&zi(Gi).catch(()=>{}).finally(()=>{ko()})},t)},Im=e=>{typeof e=="string"&&e.trim()&&(Gi=e.trim()),_t+=1,ko();let t=!1;return()=>{t||(t=!0,_t=Math.max(0,_t-1),_t===0&&Wi())}},Om=e=>(Nr.add(e),()=>{Nr.delete(e)}),wl=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(ir()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await Hi();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},Bn=St(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),bl=15e3,Sl=5*6e4;let Br=0,br=!1;const Tl=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),El=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!Tl(t)},qi=async()=>{if(!br){br=!0;try{const{runtimeFetch:e}=await wo(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>Hl);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Bn.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=Bn.getState();n==="expired"&&r()}}catch{}finally{br=!1}}},kl=(e,t)=>{if(t!==401||Bn.getState().state==="expired"||!El(e))return;const n=Date.now();n-Br<bl||(Br=n,qi())};let as=!1;const xm=()=>{if(as)return;as=!0;let e=Date.now();const t=()=>{if(Bn.getState().state!=="ok")return;const n=Date.now();n-e<Sl||(e=n,Br=n,qi())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},Hn=/^[a-z][a-z\d+.-]*:\/\//i,vl=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},zn=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Pl=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return zn(e)},Al=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return zn(e)},Ml=()=>Object.keys(ir()).length>0,Cl=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Hr=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},Dl=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Hr({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},cs=(e,t,n)=>{if(Hn.test(t)){const s=new URL(t);return Hr(s,n),s.toString()}const r=vl(t);if(!e)return Dl(r,n);const o=new URL(r,`${e}/`);return Hr(o,n),o.toString()},Sr=e=>{const t=pl();if(!t)return e;const n=Hn.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),Hn.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},Ki=(e,t)=>{const n=Hn.test(e)?new URL(e):new URL(e,Cl(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},ls=(e,t,n)=>{if(!Ml())return null;const r=Al();if(!r)return null;try{const o=new URL(`/api/openchamber/realtime-proxy/${e==="sse"?"sse":"ws"}`,`${r}/`);o.searchParams.set("url",t);const s=hl(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",Ki(o.toString(),n)):o.toString()}catch{return null}},vo=(e={})=>{const t=zn(e.apiBaseUrl),n=zn(e.realtimeBaseUrl),r=()=>t||Pl(),o=()=>n||r(),s=(a,c)=>cs(r(),a,c),i=(a,c)=>cs(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 ls("sse",l,e)||l},websocket:(a,c)=>{const l=Ki(Sr(i(a,c)),e);return ls("ws",l,e)||l}}};let $n=vo();const le=()=>$n,Rl=e=>{$n=e},Vi=e=>($n=vo(e),$n),wt=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",Il=()=>typeof window>"u"?"":window.location.origin||"",Po=e=>{if(typeof window>"u")return!1;const t=Il();if(t&&e.origin===t)return!0;try{const n=new URL(window.location.href||t);return e.protocol===n.protocol&&e.host===n.host}catch{return!1}},Ao=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Ol=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),Ve=(e,t)=>{try{Ol(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","openchamber")}catch{}return t},Mo=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},Fn=e=>{try{const t=le().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:wt(e.pathname)}catch{return!1}},Tr=e=>{if(wt(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return Po(t)&&wt(t.pathname)}catch{return!1}},xl=(e,t)=>{try{const n=new URL(e);if(!Po(n))return e;const r=et(`${n.pathname}${n.search}`,t);return!Ao(r)&&(n.protocol==="http:"||n.protocol==="https:")?(Mo(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},et=(e,t)=>e==="/health"?le().health(t):e.startsWith("/auth/")||e==="/auth"?le().auth(e,t):wt(e)?le().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?xl(e,t):e,_l=e=>{const t=e instanceof Request?e.url:e.toString();if(!Ao(t))return wt(t);try{return Fn(new URL(t))}catch{return!1}},Ji=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Ll=(e,t)=>!Ji(t),zr=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const n=[];let r=!1,o=!1;for(const[s,i]of t)Ll(s,i)?(n.push([s,encodeURIComponent(i)]),r=!0,s.toLowerCase()==="x-opencode-directory"&&(o=!0)):n.push([s,i]);return o&&n.push(["x-opencode-directory-encoding","uri"]),r?n:void 0},_e=async(e,t,n=!0)=>{const r=new Headers(zr(e)??e);return t&&new Headers(zr(t)??t).forEach((o,s)=>r.set(s,o)),n?wl(r):r},Fl=(e,t)=>{if(!t)return e;const n=new URL(e,bo);return Mo(n,t),`${n.pathname}${n.search}`},Yi=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!Ao(n))return wt(n)?Fl(n,t):null;try{const r=new URL(n);return!Po(r)||!wt(r.pathname)?null:(Mo(r,t),`${r.pathname}${r.search}`)}catch{return null}},jl=async(e,t,n)=>{const r=or();if(!r)return null;const o=Yi(e,n);if(o===null)return null;const s=e instanceof Request?e.headers:void 0,i=await _e(s,t.headers,!0);return e instanceof Request?r.fetch(e,{...t,headers:i}):r.fetch(o,{...t,headers:i})},Ul=(e,t)=>{if(typeof e=="string")return et(e,t);if(e instanceof URL)return et(e.toString(),t);const n=et(e.url,t);return n===e.url?e:new Request(n,e)},Nl=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,kn=new Map,Bl=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!Nl.test(t)?null:`GET ${t}`,h=async(e,t={})=>{const{query:n,...r}=t,o=or(),s=o?Yi(e,n):null;let i,a,c;if(o&&s!==null){const p=e instanceof Request?e.headers:void 0,g=await _e(p,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:g}):()=>o.fetch(s,{...r,headers:g}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const p=Ul(e,n),g=p instanceof Request?p.headers:void 0,y=await _e(g,r.headers,_l(p)),S=p instanceof Request?p.url:p instanceof URL?p.toString():String(p);Ve(S,y),i=p instanceof Request?()=>fetch(new Request(p,{...r,headers:y})):()=>fetch(p,{...r,headers:y}),a=S,c=String(r.method??(p instanceof Request?p.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(p=>(kl(a,p.status),p));const d=r.signal!=null||e instanceof Request,u=Bl(c,a,d);if(!u)return i();const f=kn.get(u);if(f)return f.then(p=>p.clone());const m=i();return kn.set(u,m),m.then(()=>kn.delete(u),()=>kn.delete(u)),m.then(p=>p.clone())};let ds=!1;const Qi=()=>{if(ds||typeof window>"u")return;ds=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await jl(t,n??{});if(r)return r;if(typeof t=="string"){if(!Tr(t)){try{const i=new URL(t);if(Fn(i)){const a=await _e(void 0,n?.headers);return Ve(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await _e(void 0,n?.headers),s=et(t);return Ve(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!Tr(o)){if(Fn(t)){const a=await _e(void 0,n?.headers);return Ve(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await _e(void 0,n?.headers),i=et(o);return Ve(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!Tr(t.url)){try{const a=new URL(t.url);if(Fn(a)){const c=await _e(t.headers,n?.headers);return Ve(a.toString(),c),e(new Request(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await _e(t.headers,n?.headers),s=et(t.url);Ve(s,o);const i=s===t.url?t:new Request(s,t);return e(new Request(i,{...n,headers:o}))}return e(t,n)}},Hl=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:Ve,buildRuntimeFetchUrl:et,installRuntimeFetchBridge:Qi,isLatin1Safe:Ji,runtimeFetch:h,sanitizeHeadersForBrowser:zr},Symbol.toStringTag,{value:"Module"})),$r="openchamber:runtime-endpoint-changed",Gr="openchamber:runtime-endpoint-will-change";let Ut="",dn="";const Er=(e,t,n)=>{try{e[t]=n}catch{}},Co=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"}`}},zl="mobile-disconnected",$l="url:default",Xi=e=>e===""||e===$l||e===zl,Zi=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_API_BASE_URL__;return typeof e=="string"?e.trim():""},ea=()=>{if(typeof window>"u")return"";const e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},ta=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},cr=()=>Ut||Zi();let kr="",us=null,fs,ps;const hs=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},L=()=>{if(dn)return dn;const e=hs("__OPENCHAMBER_API_BASE_URL__"),t=hs("__OPENCHAMBER_LOCAL_ORIGIN__");if(us===Ut&&fs===e&&ps===t)return kr;const n=cr();return kr=ta(n,ea())?"local":Co(n),us=Ut,fs=e,ps=t,kr},Gl=(e={})=>{if(Ut||dn)return;const t=e.apiBaseUrl?.trim()||Zi();t&&(Ut=t,dn=e.runtimeKey?.trim()||(ta(t,ea())?"local":Co(t)))},Gn=e=>{const t=e.apiBaseUrl.trim(),n=cr(),r=L(),o=e.runtimeKey?.trim()||Co(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Gr,{detail:s})),Ut=t,dn=o,typeof window<"u"){const i=window;Er(i,"__OPENCHAMBER_API_BASE_URL__",t),Er(i,"__OPENCHAMBER_CLIENT_TOKEN__",e.clientToken||void 0),Er(i,"__OPENCHAMBER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}Vi({apiBaseUrl:t,realtimeBaseUrl:t}),ji(e.requestHeaders||null),Fi(e.clientToken||null),e.relay?il(e.relay):al(),ar(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent($r,{detail:s}))},Wl=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Gr,t),()=>window.removeEventListener(Gr,t)},na=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener($r,t),()=>window.removeEventListener($r,t)},ql=["local","remote",null],Kl=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function ra(e){if(!e||typeof e!="object")return{valid:!1};const t=e,n=t.localAvailable===!1?{localAvailable:!1}:{},r=t.target,o=t.status;if(r!==null&&(typeof r!="string"||!ql.includes(r)))return{valid:!1};if(typeof o!="string"||!Kl.includes(o))return{valid:!1};if(r==="remote"||r==="local"){if(o==="ok"&&r==="local")return{valid:!0,outcome:{target:"local",status:"ok",...n}};if(o==="ok"&&r==="remote")return typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"ok",hostId:t.hostId,url:t.url,...n}};if(o==="unreachable")return r==="local"?{valid:!0,outcome:{target:"local",status:"unreachable",...n}}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"unreachable",hostId:t.hostId,url:t.url,...n}};if(o==="incompatible"||o==="wrong-service")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"||typeof t.url!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:o,hostId:t.hostId,url:t.url,...n}};if(o==="missing")return r!=="remote"?{valid:!1}:typeof t.hostId!="string"?{valid:!1}:{valid:!0,outcome:{target:"remote",status:"missing",hostId:t.hostId,...n}}}if(r===null){if(o==="not-configured")return{valid:!0,outcome:{target:null,status:"not-configured",...n}};if(o==="missing")return{valid:!1}}return{valid:!1}}function _m(e){if(!e.isDesktopShell)return null;const t=e.bootOutcome;if(!t)return null;const n=t.localAvailable===!1?{localAvailable:!1}:{};if(t.status==="ok"){if(t.target==="local")return{screen:"main",...n};if(t.target==="remote")return{screen:"main",hostId:t.hostId,url:t.url,...n}}if(t.target===null&&t.status==="not-configured")return{screen:"chooser",...n};if(t.target==="local"&&t.status==="unreachable")return{screen:"chooser",...n};if(t.target==="remote"){if(t.status==="unreachable")return{screen:"recovery",variant:"remote-unreachable",hostId:t.hostId,url:t.url,...n};if(t.status==="incompatible")return{screen:"recovery",variant:"remote-incompatible",hostId:t.hostId,url:t.url,...n};if(t.status==="wrong-service")return{screen:"recovery",variant:"remote-wrong-service",hostId:t.hostId,url:t.url,...n};if(t.status==="missing")return{screen:"recovery",variant:"remote-missing",hostId:t.hostId,...n}}return null}function Lm(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function Fm(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function oa(){if(Vl()!=="valid")return null;const t=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__,n=ra(t);return n.valid?n.outcome:null}function Vl(){if(typeof window>"u")return"not-injected";const e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":ra(e).valid?"valid":"malformed"}let Wr=null;const jm=e=>{Wr=e},lr=()=>Wr||(typeof window>"u"?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),sa=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,Jl=(e=sa())=>!!e,Yl=()=>typeof window>"u"?null:window.__OPENCHAMBER_ELECTRON__??null,zt=()=>typeof window>"u"?null:window.__OPENCHAMBER_DESKTOP__??null,Tt=()=>Yl()?.runtime==="electron",Ql=()=>{if(typeof window>"u")return null;const e=window.__OPENCHAMBER_PLATFORM__;return typeof e=="string"?e:null},Xl="right",Um=()=>{if(!Tt())return!1;const e=Ql();return e==="win32"||e==="linux"},Nm=e=>e==="left"?"left":Xl,Bm=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],oe=()=>typeof zt()?.invoke=="function",$t=()=>Tt()&&oe(),G=async(e,t)=>{const n=zt();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},Hm=async()=>{if(!$t()||!se())return null;try{const e=await G("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}},zm=async e=>{if(!$t()||!se())return null;try{const t=await G("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}},$m=async()=>{if(!$t()||!se())return null;try{const e=await G("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}},Gm=async e=>{if(!$t()||!se())return null;try{const t=await G("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}},Wm=async()=>{if(!$t()||!se())return null;try{const e=await G("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}},qm=async e=>{if(!$t()||!se())return null;try{const t=await G("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}},ms=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}}},Zl=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),qt=e=>{const t=Zl(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},se=()=>{if(typeof window>"u"||!rt())return!1;if(L()==="local")return!0;const e=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",t=vr(e),n=vr(cr());if(!n&&t&&oa()?.target==="local")return!0;if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&qt(t.hostname)&&qt(n.hostname)}const r=vr(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&qt(t.hostname)&&qt(r.hostname)}const o=ms(e),s=ms(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&qt(r.hostname))},rt=()=>typeof window>"u"?!1:Tt(),Km=async()=>{if(!rt())return!1;try{return!!await G("desktop_focus_window")}catch{return!1}},ed=()=>rt()&&oe()&&se(),Vm=async()=>{if(!rt())return!1;try{return await G("desktop_start_window_drag"),!0}catch{return!1}},Ie=()=>Jl()?!0:lr()?.runtime?.isVSCode===!0,Jm=()=>{const t=lr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Ie()},Ym=(e,t=rt())=>e==="web"&&!t,ia=async()=>{if(typeof window<"u"){const e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},Qm=async e=>{if(ed())try{const t=await zt()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},td=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),nd=U({path:k().min(1),outsideFileGrant:k().min(1),expiresAt:ce().finite()}),Xm=async e=>{if(oe()&&se())try{const t=await zt()?.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(!td(t))return{success:!1,error:"File selection cancelled"};const n=typeof t.path=="string"?t.path:"";return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant=="string"?t.outsideFileGrant:void 0}:{success:!1,error:"File selection cancelled"}}catch(t){return console.warn("Failed to request file access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native file picker not available"}},Zm=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!oe()||!se())return{success:!1,error:"Native file access not available"};try{const n=await zt()?.grantFileAccess?.(t),r=nd.safeParse(n);return r.success?{success:!0,...r.data}:{success:!1,error:"File access was not granted"}}catch(n){return console.warn("Failed to request existing file access",n),{success:!1,error:n instanceof Error?n.message:String(n)}}},ey=async e=>({success:!0}),ty=async e=>({success:!0}),ny=async()=>oe()?await G("desktop_check_for_updates"):null,ry=async e=>{if(!oe())return!1;const t=zt();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("openchamber:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:o});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(r=d),typeof u=="number"&&(o=u),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await G("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(n)try{const s=n();s instanceof Promise&&await s}catch{}}},oy=async()=>oe()?(await G("desktop_restart"),!0):!1,sy=async()=>{if(!oe())return!1;try{return await G("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},iy=async()=>{if(!oe()||!se())return null;try{const e=await G("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}},rd=async(e,t)=>{if(!oe()||!se())return!1;const n=e?.trim();if(!n)return!1;try{return await G("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},ay=async e=>{if(!oe()||!se())return!1;const t=e?.trim();if(!t)return!1;try{return await G("desktop_reveal_path",{path:t}),!0}catch{return rd(t)}},cy=async(e,t)=>{if(!oe()||!se())return null;const n=e?.trim();if(!n)return null;try{const r=await G("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},ly=async(e,t,n)=>{if(!oe()||!se())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await G("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},dy=async(e,t,n)=>{if(!oe()||!se())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await G("desktop_open_file_in_app",{filePath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},uy=async(e,t)=>{if(!oe()||!se())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await G("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=r;return o.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(o.apps)?{apps:o.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Ft=16384,Wn=globalThis,od=e=>{if(Wn.Buffer)return Wn.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.slice(r,r+32768));return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},aa=e=>{try{if(Wn.Buffer)return Wn.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}},sd=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:(n.hash="",n.toString().replace(/\/+$/g,""))}catch{return null}},id=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="ws:"&&n.protocol!=="wss:"?null:(n.hash="",n.toString())}catch{return null}},ys=e=>typeof e=="string"&&e.length>0,ad=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!ys(t.x)||!ys(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},cd=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ld=e=>{if(!e||typeof e!="object")return null;const t=e,n=cd(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=sd(t.url);return r?n===void 0?{type:t.type,url:r}:{type:t.type,url:r,priority:n}:null}if(t.type==="relay"){const r=id(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=ad(t.hostEncPubJwk);if(!s)return null;const i=typeof t.grant=="string"&&t.grant.trim()?t.grant.trim():void 0;return{type:"relay",relayUrl:r,serverId:o,hostEncPubJwk:s,...i?{grant:i}:{},...n===void 0?{}:{priority:n}}}return null},Do=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.v!==2)return null;const n=typeof t.pairingId=="string"?t.pairingId.trim():"",r=typeof t.secret=="string"?t.secret.trim():"";if(!n||!r)return null;const o=Array.isArray(t.candidates)?t.candidates.map(ld).filter(c=>!!c):[];if(o.length===0)return null;const s=typeof t.expiresAt=="string"&&t.expiresAt.trim()?t.expiresAt.trim():void 0;if(s){const c=Date.parse(s);if(!Number.isFinite(c)||c<=Date.now())return null}const i=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0,a=typeof t.fingerprint=="string"&&t.fingerprint.trim()?t.fingerprint.trim():void 0;return{v:2,pairingId:n,secret:r,...i?{label:i}:{},...a?{fingerprint:a}:{},...s?{expiresAt:s}:{},candidates:o}},fy=e=>({v:2,pairingId:e.pairingId.trim(),secret:e.secret.trim(),...e.label?.trim()?{label:e.label.trim()}:{},...e.fingerprint?.trim()?{fingerprint:e.fingerprint.trim()}:{},...e.expiresAt?.trim()?{expiresAt:e.expiresAt.trim()}:{},candidates:e.candidates}),py=e=>{const t=Do(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",od(JSON.stringify(t))),`openchamber://connect?${n.toString()}`},dd=e=>{const t=e.trim();if(!t||t.length>Ft)return null;try{const n=new URL(t);if(n.protocol!=="openchamber:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>Ft)return null;const o=aa(r);return!o||o.length>Ft?null:Do(JSON.parse(o))}catch{return null}},hy=e=>{const t=e.trim();if(!t||t.length>Ft)return null;const n=t.indexOf("?");if(n===-1||!/^openchamber:\/\/connect\/?$/i.test(t.slice(0,n)))return null;let r=null,o=null;for(const i of t.slice(n+1).split("&")){const a=i.indexOf("=");if(a===-1)continue;const c=i.slice(0,a),l=i.slice(a+1);c==="v"?r=l:c==="p"&&(o=l)}if(r!=="2"||!o||o.length>Ft)return null;const s=aa(o);if(!s||s.length>Ft)return null;try{return Do(JSON.parse(s))}catch{return null}},Nt=e=>typeof e=="object"&&e!==null,ud=e=>e.trim().toLowerCase()==="authorization",fd=e=>{if(!Nt(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=typeof r=="string"?r.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||ud(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},pd=e=>`relay://${e}`,hd=e=>{if(!Nt(e))return null;const t=ne(e,"relayUrl")||ne(e,"relay_url"),n=ne(e,"serverId")||ne(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!Nt(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},md=()=>{if(typeof navigator>"u")return;const e=navigator.userAgent;if(/Macintosh|Mac OS X/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux"},my=async(e,t)=>{const n=dd(e);if(!n)throw new Error("invalid-connect-link");const r=await Sd().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:md(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=async y=>{if(!y.ok)return null;const S=await y.json().catch(()=>null);return(typeof S?.clientToken=="string"?S.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((y,S)=>(y.type==="relay"?1:0)-(S.type==="relay"?1:0));for(const y of a){if(y.type==="relay"){const E=So({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const P=await s(await E.fetch("/api/client-auth/pairing/redeem",o));if(P){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:P};break}}catch{}finally{E.close()}continue}const S=re(y.url);if(S)try{const E=await s(await fetch(`${S}/api/client-auth/pairing/redeem`,o));if(E){i={directUrl:S,token:E};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(y=>y.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=n.candidates.filter(y=>y.type!=="relay").map(y=>re(y.url)).find(y=>!!y),u=i.directUrl||d,f=u||(l?pd(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const m=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&re(y.apiUrl||y.url)===f),p=m?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),g={...m||{},id:p,label:n.label||m?.label||ca(f),url:f,apiUrl:u,clientToken:i.token,...l?{relay:l}:{}};return{hostId:p,hosts:m?t.map(y=>y.id===p?g:y):[g,...t]}},yd=/^(t|.*(?:token|auth|secret|api).*)$/i,re=e=>{const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},yy=e=>{const t=re(e);if(!t)return null;try{const n=new URL(t);if((n.pathname.replace(/\/+$/,"")||"/")==="/connect"&&n.searchParams.has("t"))return{persistedUrl:n.origin,redeemUrl:n.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},ca=e=>{const t=re(e);if(!t)return e;try{const n=new URL(t);(n.username||n.password)&&(n.username="",n.password="");const r=Array.from(new Set(Array.from(n.searchParams.keys())));for(const o of r)yd.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},vn=(e,t)=>{const n=re(e),r=re(t);if(!n||!r)return!1;try{const o=new URL(n),s=new URL(r);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},ne=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},gs=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},gd=e=>{if(!Nt(e))return null;const t=ne(e,"id"),n=ne(e,"label"),r=ne(e,"url"),o=ne(e,"apiUrl")||ne(e,"api_url"),s=ne(e,"clientToken")||ne(e,"client_token"),i=fd(e.requestHeaders),a=hd(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},en=e=>re(e.apiUrl||e.url)||e.apiUrl||e.url,Et=()=>oe()?(e,t)=>G(e,t):null,Ro=async()=>{const e=Et();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!Nt(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(gd).filter(a=>!!a):[],o=ne(t,"defaultHostId")||ne(t,"default_host_id")||ne(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ne(t,"localOrigin")||ne(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},wd=async e=>{const t=Et();if(!t)return;const n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:n})},bd=async()=>{const e=Et();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Sd=async()=>{const e=Et();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},Td=8e3,Ed=15e3,kd=400,vd=async(e,t,n,r)=>{const o=new AbortController,s=window.setTimeout(()=>o.abort(),n);try{return await e.fetch(t,{...r,signal:o.signal})}finally{window.clearTimeout(s)}},ws=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await vd(e,t,Math.min(Td,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,kd))}}},Pd=async(e,t)=>{const n=So({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+Ed;let s=!1;try{if(!(await ws(n,"/health",o)).ok)return{status:"unreachable",latencyMs:0};const a=new Headers({Accept:"application/json"});for(const[d,u]of Object.entries(t?.requestHeaders||{}))d.toLowerCase()!=="authorization"&&a.set(d,u);const c=t?.clientToken?.trim();c&&a.set("Authorization",`Bearer ${c}`);const l=await ws(n,"/auth/session",o,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(s=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...s?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{s||n.close()}},Io=async(e,t)=>{const n=Et();if(!n)return{status:"unreachable",latencyMs:0};const r=await n("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!Nt(r))return{status:"unreachable",latencyMs:0};const o=r.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=gs(r,"latencyMs")??gs(r,"latency_ms")??0;return{status:s,latencyMs:i}},gy=async(e,t)=>{const n=Et();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},wy=async e=>{const t=Et();t&&await t("desktop_new_window_for_host",{hostId:e})},Ze="local",Ad=e=>({id:Ze,label:"Local",url:e||la()}),la=()=>typeof window>"u"?"":window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Md=e=>e.id===Ze?"local":`host:${e.id}`,by=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(d=>d.id===Ze)?.url||la(),r=cr(),o=re(n)||n,s=re(t)||t,i=L(),a=e.find(d=>d.relay&&Md(d)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&vn(r,n))return{id:Ze,label:"Local",url:o};const c=e.find(d=>r?vn(r,en(d)):!1);if(c)return{id:c.id,label:c.label,url:re(en(c))||en(c)};if(t&&vn(t,n))return{id:Ze,label:"Local",url:o};const l=e.find(d=>t?vn(t,d.url):!1);return l?{id:l.id,label:l.label,url:re(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:Ze,label:"Local",url:o}:{id:"custom",label:ca(s||"Instance"),url:s}},qn=new Map;let da=0;const Kn=new Map;let qr=0,ua={byHostId:{},isProbing:!1};const Kr=new Set,Vn=()=>{ua={byHostId:Object.fromEntries(qn),isProbing:qr>0};for(const e of Kr)try{e()}catch{}},Sy=e=>(Kr.add(e),()=>{Kr.delete(e)}),Ty=()=>ua,fa=(e,t)=>{qn.set(e,t),Vn()},Ey=(e,t)=>{Kn.set(e,++da),fa(e,t)},Cd=e=>{const t=new Set([Ze,...e]);let n=!1;for(const r of Array.from(qn.keys()))t.has(r)||(qn.delete(r),Kn.delete(r),n=!0);n&&Vn()},Dd=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Rd=async()=>Tt()?bd().catch(()=>""):"",Id=async(e,t)=>{const n=e.id===Ze?t:e.clientToken||"",r=async()=>{const i=await Pd(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const o=re(Tt()?en(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await Io(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Dd(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},Od=async e=>{if(!rt())return;const t=++da;for(const n of e)Kn.set(n.id,t);qr+=1,Vn();try{const n=await Rd();await Promise.all(e.map(async r=>{const o=await Id(r,n);Kn.get(r.id)===t&&fa(r.id,o)}))}finally{qr-=1,Vn()}};let bs=!1;const xd=async()=>{if(bs||!rt())return;bs=!0;const e=await Ro().catch(()=>null);e&&(Cd(e.hosts.map(t=>t.id)),await Od([Ad(e.localOrigin),...e.hosts]))},_d=5e3,Ld=1500;let Pr=!1;const Fd=async e=>{if(!Tt()||Pr)return;const t=`host:${e}`;if(L()===t){Pr=!0;try{const n=await Ro().catch(()=>null),r=n?.hosts.find(u=>u.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?re(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await h("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const u of a){if(!u||typeof u!="object")continue;const f=u;if(f.type!=="lan"||typeof f.url!="string")continue;const m=re(f.url);m&&!c.includes(m)&&c.push(m)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await wd({hosts:n.hosts.map(u=>u.id===e?{...u,apiUrl:l}:u),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const d=await Io(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(d.status==="unreachable"||d.status==="wrong-service"||d.status==="incompatible"||L()!==t)return;Gn({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{Pr=!1}}},jd=e=>{typeof window>"u"||window.setTimeout(()=>{Fd(e).catch(()=>{})},_d)},Ud=async e=>{if(!Tt())return;const t=await Ro().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(u=>u.id===n);if(!r?.relay)return;const o=`host:${r.id}`;if(L()===o)return;const s=u=>{Gn({apiBaseUrl:u,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{Gn({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),jd(r.id)},a=r.apiUrl?re(en(r)):null;if(!a){i();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",l=Io(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),d=await Promise.race([l,new Promise(u=>setTimeout(()=>u(null),Ld))]);if(d){if(c(d)){s(a);return}i();return}i(),l.then(u=>{c(u)&&L()===o&&s(a)})};class tt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const ky=e=>e instanceof tt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Vr=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},Ss=500,pa=()=>{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}},vy=()=>pa(),Te=(e,t)=>{if(!pa())return;const n=typeof performance<"u"?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>Ss&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-Ss)},Nd=()=>{const e=typeof window<"u"?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("loadAgents")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory")||r.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=Nd);const Py=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Te(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return Te(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw Te(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},Bd=3,Hd=3e4,zd=32e3,$d=3600*1e3,Gd=600*1e3,Wd=200,qd=new Set([429,502,503,504]),je=new Map,Oo=e=>JSON.stringify([L(),e]);function Kd(){const e=Date.now();for(const[t,n]of je){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>$d&&je.delete(t)}}typeof setInterval<"u"&&setInterval(Kd,Gd).unref?.();function Vd(e){const t=Oo(e);let n=je.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Hd},je.set(t,n);je.size>Wd;){const r=je.keys().next().value;if(!r)break;je.delete(r)}return n}function Jd(e){e&&je.delete(Oo(e))}function Ts(e,t){if(!e)return;const n=Vd(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Yd(t)&&n.consecutiveErrors>=Bd&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Yd(e){return e!==void 0&&qd.has(e)}function Qd(e){const t=je.get(Oo(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,zd*4),!1):!0:!1}function Xd(e){if(!(!e||!Qd(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const Es="/api",Zd=1e4,eu=4e3;function pt(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}const ks=e=>{if(e instanceof tt)return e.reason==="not-found"||e.reason==="not-directory";if(e&&typeof e=="object"){const t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return!0}return/\bENOENT\b|\bENOTDIR\b|no such file or directory/i.test(pt(e))};function ae(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${pt(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function At(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${pt(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const tu=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,vs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nu=14;let Ps=0,Ar=0;const ru=e=>{const t=new Uint8Array(e);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let r=0;r<e;r+=1)t[r]=Math.floor(Math.random()*256);let n="";for(let r=0;r<e;r+=1)n+=vs[t[r]%vs.length];return n},As=e=>{const t=Date.now();t!==Ps&&(Ps=t,Ar=0),Ar+=1;const n=BigInt(t)*BigInt(4096)+BigInt(Ar),r=new Uint8Array(6);for(let s=0;s<6;s+=1)r[s]=Number(n>>BigInt(40-8*s)&BigInt(255));const o=Array.from(r,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${ru(nu)}`},Ms=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(tu.test(t)||typeof window>"u")return t;const n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),t}},Cs=()=>{try{return le().api("/api")}catch{return null}},ha=e=>{const t=typeof AbortSignal<"u"?AbortSignal:void 0;if(typeof t?.timeout=="function")return{signal:t.timeout(e),cleanup:()=>{}};const n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},ou=3e4,su=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),Mr=e=>{const t=e.requestTimeoutMs??ou;return mc({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(su(n)||o==="POST")return h(n,r);const s=ha(t),i=r?.signal,a=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let c,l=null;if(i&&a)c=AbortSignal.any([i,s.signal]);else if(i){const d=new AbortController,u=()=>d.abort(i.reason),f=()=>d.abort(s.signal.reason);i.aborted?u():s.signal.aborted?f():(i.addEventListener("abort",u,{once:!0}),s.signal.addEventListener("abort",f,{once:!0}),l=()=>{i.removeEventListener("abort",u),s.signal.removeEventListener("abort",f)}),c=d.signal}else c=s.signal;try{return await h(n,{...r,signal:c})}catch(d){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):d}finally{l?.(),s.cleanup()}}})},Mt=e=>e.replace(/\\/g,"/"),Ds=400,Rs=()=>{const e=lr();return e&&e.runtime?.isDesktop&&e.files?e.files:null};class iu{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=Es){const r=Cs()||t;this.baseUrl=Ms(r),this.client=Mr({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==L())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=Cs(),n=Ms(t||Es);n!==this.baseUrl&&(this.baseUrl=n,this.client=Mr({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear())}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",o=this.scopedClients.get(r);if(o)return o;const s=Mr({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,s),s}normalizeCandidatePath(t){if(typeof t!="string")return null;const n=t.trim();if(!n)return null;const r=n.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(r.length>1?r.replace(/\/+$/,""):r)||null}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const s=n[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:s,username:void 0}}const r=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&Te("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:n??null}),this.currentDirectory=n}getDirectory(){return this.currentDirectory}async withDirectory(t,n){const r=async()=>{if(t==null)return n();const s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,n=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(n(s.directory),n(s.worktree),n(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>n(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(t);return this.deriveHomeDirectory(r)}async probeDirectory(t){return await this.getDirectoryAvailability(t)==="available"}async getDirectoryAvailability(t){const n=this.normalizeCandidatePath(t);if(!n)return"unknown";try{const r=await this.client.path.get({directory:n});return r.error?ks(r.error)?"missing":"unknown":(typeof r.data?.directory=="string"?r.data.directory.trim():"")?"available":"unknown"}catch(r){return ks(r)?"missing":"unknown"}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.create({...r?{directory:r}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return ae(o,"session.create")}async getSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...r?{directory:r}:{}});return ae(o,"session.get")}async deleteSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...r?{directory:r}:{}});return At(o,"session.delete")===!0}async updateSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s={...n.title!==void 0?{title:n.title}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},...n.time?.archived!==void 0&&n.time.archived!==null?{time:{archived:n.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return ae(i,"session.update")}async getSessionMessages(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.messages({sessionID:t,...o?{directory:o}:{},...typeof n=="number"?{limit:n}:{}});return ae(s,"session.messages")}async getSessionTodos(t){try{const n=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(n.error)return[];const r=n.data;return!r||!Array.isArray(r)?[]:r}catch{return[]}}shouldNormalizeToTextPlain(t){if(!t)return!1;const n=t.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(t){if(!t)return!1;const n=t.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(t){try{const n=(await wo(async()=>{const{default:u}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:u}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const o=t.url.substring(r+1),s=atob(o),i=new Uint8Array(s.length);for(let u=0;u<s.length;u++)i[u]=s.charCodeAt(u);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((u,f)=>{const m=new FileReader;m.onload=()=>u(m.result),m.onerror=f,m.readAsDataURL(c)});let d=t.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const o=t.url.substring(5,r),s=t.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toNormalizedFilePartInput(t){const n=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??As("msg"),r=[];if(t.prefaceText&&t.prefaceText.trim()&&r.push({type:"text",text:t.prefaceText,synthetic:t.prefaceTextSynthetic!==!1}),t.text&&t.text.trim()){const l={type:"text",text:t.text};r.push(l)}if(t.files&&t.files.length>0)for(const l of t.files){const d=await this.toNormalizedFilePartInput(l);r.push(d)}if(t.additionalParts&&t.additionalParts.length>0)for(const l of t.additionalParts){if(l.text&&l.text.trim()){const d={type:"text",text:l.text};l.synthetic&&(d.synthetic=!0),l.metadata&&(d.metadata=l.metadata),r.push(d)}if(l.files&&l.files.length>0)for(const d of l.files){const u=await this.toNormalizedFilePartInput(d);r.push(u)}}if(t.agentMentions&&t.agentMentions.length>0)for(const l of t.agentMentions)l?.name&&r.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(r.length===0)throw new Error("Message must have at least one part (text or file)");const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;t.format&&console.info("[git-generation][browser] send structured message",{sessionId:t.id,providerID:t.providerID,modelID:t.modelID,agent:t.agent,variant:t.variant,directory:o,baseUrl:this.baseUrl,formatType:t.format.type}),Xd(t.providerID),this.assertRuntimeUnchanged(t.runtimeKey);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:n,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:r});if(l.response instanceof Response)s=l.response;else if(l.error){const d=l.response?.status;if(!d){const u=new Error(`Message send transport failure: ${pt(l.error)}`);throw Xc(l.error)?Di(u):u}s=new Response(JSON.stringify(l.error),{status:d})}else s=new Response(JSON.stringify(l.data??!0),{status:200})}catch(l){throw Ts(t.providerID),l}if(s.ok)return Jd(t.providerID),n;let i="";try{i=await s.text()}catch{}const a=i&&i.trim().length>0?`: ${i.trim()}`:"",c=new Error(`Failed to send message (${s.status})${a}`);throw c.status=s.status,Ts(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??As("msg"),r=[];if(t.files&&t.files.length>0)for(const i of t.files)r.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;this.assertRuntimeUnchanged(t.runtimeKey);const s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...r.length>0?{parts:r}:{},messageID:n});return At(s,"session.command"),n}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,r=await this.client.session.shell({sessionID:t.sessionId,...n?{directory:n}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return ae(r,"session.shell")}async revertSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:n,partID:r});return ae(i,"session.revert")}async summarizeSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:n,modelID:r});return At(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return ae(n,"session.unrevert")}async forkSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:n});return ae(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const n=typeof t=="string"?t.trim():"",r=await this.client.session.status(n?{directory:n}:void 0);return r.error||!r.data||typeof r.data!="object"?null:r.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const t=await h("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async listToolIds(t){try{const n=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,n,r){const o=this.normalizeCandidatePath(r?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:n,...r?.message?{message:r.message}:{}});return At(s,"permission.reply")===!0}async createPermission(t,n,r,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:n,resources:r,...o?.id?{id:o.id}:{},...o?.save?{save:o.save}:{},...o?.metadata?{metadata:o.metadata}:{},...o?.source?{source:o.source}:{},...o?.agent?{agent:o.agent}:{}});if(s.error!==void 0)return null;const i=s.data?.data;return i===void 0?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(t,n,r){try{const s=await(r?this.getScopedSdkClient(r):this.client).v2.session.permission.get({sessionID:t,requestID:n});if(s.error===void 0){const i=s.data?.data;if(i!==void 0)return{state:"ok",permission:i}}return s.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${pt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}async replyToQuestion(t,n,r){const o=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n],s=this.normalizeCandidatePath(r)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return At(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return At(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${pt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configCache.get(r);if(o&&o.expiresAt>Date.now())return Te("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return Te("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{Te("opencodeClient.getConfig:start",{directory:n??null});const c=typeof performance<"u"?performance.now():Date.now(),d=await(n?this.getScopedApiClient(n):this.client).config.get();if(!d.data)throw new Error("Failed to get config");const u=typeof performance<"u"?performance.now():Date.now();return Te("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(u-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:d.data,expiresAt:Date.now()+Zd}),d.data})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async updateConfig(t){const n=await this.client.config.update({config:t}),r=ae(n,"global.config.update");return this.clearConfigCache(),r}async updateConfigPartial(t){const n=await this.getConfig(),r=t(n);return await this.updateConfig(r)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configProvidersInFlight.get(r);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(n?{directory:n}:void 0);return ae(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.delete(r)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.listAgentsInFlight.get(r);if(o)return o;const s=(async()=>{const i=n?{directory:n}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await h("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${pt(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(r,s);try{return await s}finally{this.listAgentsInFlight.delete(r)}}async readFile(t){try{const n=await this.client.file.read({path:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(ae(n,"file.read"))}catch{return`// Content of ${t}
3
- // This would be loaded from the server`}}async listFiles(t){try{const n=t||this.currentDirectory||"/",r=await this.client.file.list({path:n,...this.currentDirectory?{directory:this.currentDirectory}:{}}),o=ae(r,"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(ae(t,"command.list")||[]).map(r=>({name:r.name,description:r.description,agent:r.agent,model:r.model,source:r.source}))}async listCommandsWithDetails(t){const n=this.normalizeCandidatePath(t??null)??this.currentDirectory,r=await this.client.command.list(n?{directory:n}:void 0);return(ae(r,"command.list")||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,source:s.source,template:s.template}))}async listSkillsWithDetails(){try{const n=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(n))return[];const r=[];for(const o of n){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),r.push(a)}return r}catch{return[]}}async getCommandDetails(t){try{const n=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(n.data){const r=n.data.find(o=>o.name===t);if(r)return{name:r.name,template:r.template,description:r.description,agent:r.agent,model:r.model}}return null}catch{return null}}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;Te("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=ha(eu),o=await h(n,{signal:r.signal}).finally(r.cleanup);if(Te("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return Te("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=Rs();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await h(`${this.baseUrl}/opencode/directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,create:!0})});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create project directory"}));throw new Error(l.error||"Failed to create project directory")}return{success:!0,path:(await a.json()).path}}const o={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await h(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const n=await h(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(r.error||"Failed to clone repository")}return await n.json()}async listLocalDirectory(t,n){const o=`${typeof t=="string"?Mt(t.trim()):""}|${n?.respectGitignore?"1":"0"}`,s=Date.now(),i=this.listDirectoryCache.get(o);if(i&&i.expiresAt>s)return i.entries;const a=this.listDirectoryInFlight.get(o);if(a)return a;const l=(async()=>{const d=Rs();try{if(d){const y=await d.listDirectory(t||"",n);if(!y||!Array.isArray(y.entries))throw new tt("Directory listing returned an invalid response",{reason:"invalid-response"});const S=y.entries.map(E=>({name:E.name,path:Mt(E.path),isDirectory:!!E.isDirectory,isFile:!E.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:S,expiresAt:Date.now()+Ds}),S}const u=new URLSearchParams;t&&t.trim().length>0&&u.set("path",t),n?.respectGitignore&&u.set("respectGitignore","true");const f=u.toString(),m=await h(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!m.ok){const y=await m.json().catch(()=>({})),S=typeof y.error=="string"?y.error:"Failed to list directory";throw new tt(S,{reason:Vr(y.reason),status:m.status})}const p=await m.json();if(!p||!Array.isArray(p.entries))throw new tt("Directory listing returned an invalid response",{reason:"invalid-response"});const g=p.entries;return this.listDirectoryCache.set(o,{entries:g,expiresAt:Date.now()+Ds}),g}catch(u){throw console.error("Failed to list directory contents:",u),u}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?Mt(r):null,s=r?this.getScopedApiClient(r):this.client;try{const i=await s.find.files({query:t,limit:typeof n?.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0,dirs:n?.dirs===!1||n?.type==="file"?"false":"true",type:n?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const l=Mt(c),d=l.split("/").filter(Boolean).pop()||l,u=Mt(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=L();if(!t||t==="local"){const n=await ia();if(n)return n}try{const n=await h(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const n=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",n,"with path:",t);try{const r=await h(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await r.json().catch(()=>null);if(!r.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const De=new iu,ma=["session","repository","usage","subagents","tasks","mcp","pinned","contextSources"],Ay={session:"chat.workStatus.section.session",repository:"chat.workStatus.section.project",usage:"chat.workStatus.section.usage",subagents:"chat.workStatus.section.subagents",tasks:"chat.workStatus.section.tasks",mcp:"chat.workStatus.section.mcp",pinned:"chat.workStatus.section.pinned",contextSources:"chat.workStatus.section.contextBreakdown"},au=new Set(ma),cu=e=>typeof e=="string"&&au.has(e),My=(e,t)=>!e?.includes(t),Cy=e=>e!=null&&ma.every(t=>e.includes(t)),Dy=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),ya=e=>{if(!Array.isArray(e))return[];const t=new Set;for(const n of e)cu(n)&&t.add(n);return[...t]},lu=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const s of n)r+=String.fromCharCode(s);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let Cr=null,Dr=null,Rr=null;const Is=new Set;let Os=!1;const ga=e=>{if(Is.add(e),Os||typeof window>"u")return;Os=!0;const t=()=>{for(const n of Is)n()};try{window.addEventListener("pagehide",t,{capture:!0}),window.addEventListener("beforeunload",t,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t()}),document.addEventListener("freeze",t))}catch{}},du=(e,t)=>{let n;try{n=e()}catch{return}const r=new Map,o=new Set;let s;const i=()=>{if(s=void 0,r.size===0&&o.size===0)return;const c=Array.from(r.entries()),l=Array.from(o);r.clear(),o.clear();for(const[d,u]of c)try{n.setItem(d,JSON.stringify(u,t?.replacer))}catch(f){console.error("Failed to persist deferred storage value",f),!r.has(d)&&!o.has(d)&&r.set(d,u)}for(const d of l)try{n.removeItem(d)}catch(u){console.error("Failed to remove deferred storage value",u),r.has(d)||o.add(d)}},a=()=>{s===void 0&&(s=setTimeout(i,0))};return ga(i),{getItem:c=>{if(r.has(c))return r.get(c)??null;if(o.has(c))return null;const l=u=>{if(u===null)return null;try{return JSON.parse(u,t?.reviver)}catch{try{n.removeItem(c)}catch{}return null}},d=n.getItem(c);return d instanceof Promise?d.then(l):l(d)},setItem:(c,l)=>{r.set(c,l),o.delete(c),a()},removeItem:c=>{r.delete(c),o.add(c),a()}}},xo=e=>du(()=>Sa(),e),uu=e=>{const t=new Map,n=new Set;let r;const o=()=>{if(r=void 0,t.size===0&&n.size===0)return;const i=Array.from(t.entries()),a=Array.from(n);t.clear(),n.clear();for(const[c,l]of i)try{e.setItem(c,l)}catch(d){console.error("Failed to persist deferred storage value",d),!t.has(c)&&!n.has(c)&&t.set(c,l)}for(const c of a)try{e.removeItem(c)}catch(l){console.error("Failed to remove deferred storage value",l),t.has(c)||n.add(c)}},s=()=>{r===void 0&&(r=setTimeout(o,0))};return ga(o),{getItem:i=>t.has(i)?t.get(i)??null:n.has(i)?null:e.getItem(i),setItem:(i,a)=>{t.set(i,a),n.delete(i),s()},removeItem:i=>{t.delete(i),n.add(i),s()},clear:()=>{t.clear(),n.clear(),r!==void 0&&(clearTimeout(r),r=void 0),e.clear()},key:i=>e.key(i),get length(){return e.length}}},wa=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},_o=()=>{const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()},key:t=>Array.from(e.keys())[t]??null,get length(){return e.size}}},ba=e=>{const t=_o(),n=new Set,r=new Set,o=l=>{if(r.has(l))return null;if(n.has(l))return t.getItem(l);try{return e.getItem(l)}catch{return null}},s=(l,d)=>{try{e.setItem(l,d),t.removeItem(l),n.delete(l),r.delete(l);return}catch{try{e.removeItem(l)}catch{}}t.setItem(l,d),n.add(l),r.delete(l)},i=l=>{try{e.removeItem(l),r.delete(l)}catch{r.add(l)}t.removeItem(l),n.delete(l)},a=()=>{const l=[];try{for(let d=0;d<e.length;d+=1){const u=e.key(d);u&&l.push(u)}}catch{}try{e.clear(),r.clear()}catch{for(const d of l)r.add(d)}t.clear(),n.clear()},c=()=>{const l=new Set;try{for(let d=0;d<e.length;d+=1){const u=e.key(d);u&&!r.has(u)&&!n.has(u)&&l.add(u)}}catch{}for(const d of n)l.add(d);return[...l]};return{getItem:o,setItem:s,removeItem:i,clear:a,key:l=>c()[l]??null,get length(){return c().length}}},fu=()=>{const e=wa("localStorage");return e?ba(e):_o()},Sa=()=>(Cr||(Cr=fu()),Cr),hn=()=>(Rr||(Rr=uu(Sa())),Rr),pu=()=>{const e=wa("sessionStorage");return e?ba(e):_o()},Ry=()=>(Dr||(Dr=pu()),Dr),hu={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem",settingsPageTitle:"1.125rem"},Iy={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem",settingsPageTitle:"1.0625rem"};function xs(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Pn={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)"}}},Ir={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Pn.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ir.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Pn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ir.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Pn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Ir.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Pn.tool.inline})},mu=[{id:"inter",label:"Inter",description:"Modern UI sans with excellent readability at small sizes.",stack:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Inter",packageName:"@fontsource/inter",filePrefix:"inter",weights:[400,500,600]}},{id:"fixel",label:"Fixel Text",description:"Humanist geometric sans-serif with full Ukrainian support.",stack:'"Fixel Text", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Fixel Text",weights:[400,500,600],urls:{400:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Regular.woff2",500:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-Medium.woff2",600:"https://cdn.jsdelivr.net/gh/MacPaw/Fixel@f6ee910e98add47e830db87f1a754130506c11a2/fonts/webfonts/FixelText-SemiBold.woff2"}}},{id:"geist-sans",label:"Geist Sans",description:"Crisp sans-serif with a technical interface feel.",stack:'"Geist Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Geist Sans",packageName:"@fontsource/geist-sans",filePrefix:"geist-sans",weights:[400,500,600]}},{id:"atkinson-hyperlegible",label:"Atkinson Hyperlegible",description:"Accessibility-focused sans-serif optimized for character distinction.",stack:'"Atkinson Hyperlegible", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Atkinson Hyperlegible",packageName:"@fontsource/atkinson-hyperlegible",filePrefix:"atkinson-hyperlegible",weights:[400,700]}},{id:"source-sans-3",label:"Source Sans 3",description:"Adobe sans-serif tuned for clean, readable interfaces.",stack:'"Source Sans 3", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Source Sans 3",packageName:"@fontsource/source-sans-3",filePrefix:"source-sans-3",weights:[400,500,600]}},{id:"roboto",label:"Roboto",description:"Familiar Material-style sans-serif with broad UI usage.",stack:'"Roboto", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Roboto",packageName:"@fontsource/roboto",filePrefix:"roboto",weights:[400,500,600]}},{id:"noto-sans",label:"Noto Sans",description:"Readable sans-serif with strong international coverage.",stack:'"Noto Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Noto Sans",packageName:"@fontsource/noto-sans",filePrefix:"noto-sans",weights:[400,500,600]}},{id:"dm-sans",label:"DM Sans",description:"Modern product UI sans-serif with friendly proportions.",stack:'"DM Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"DM Sans",packageName:"@fontsource/dm-sans",filePrefix:"dm-sans",weights:[400,500,600]}},{id:"manrope",label:"Manrope",description:"Polished geometric sans-serif for modern app interfaces.",stack:'"Manrope", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',source:{family:"Manrope",packageName:"@fontsource/manrope",filePrefix:"manrope",weights:[400,500,600]}},{id:"system",label:"System",description:"Native operating system interface font.",stack:'"SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'}],yu=[{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'}],Ta=e=>Object.fromEntries(e.map(t=>[t.id,t])),gu=Ta(mu),wu=Ta(yu),bu="system",Su="system-mono",Ea=e=>typeof e=="string"&&e in gu,ka=e=>typeof e=="string"&&e in wu,Jr="openchamber.mobileKeyboardMode",Tu='meta[name="viewport"]',_s="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Oy=()=>!0;function dr(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const Eu=e=>dr(e)==="resize-content"?`${_s}, interactive-widget=resizes-content`:_s,ku=()=>{if(typeof window>"u")return"resize-content";try{return dr(localStorage.getItem(Jr))}catch{return"resize-content"}},va=e=>{const t=dr(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(Jr):localStorage.setItem(Jr,t)}catch{}return t},xy=e=>{const t=va(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Tu);if(n instanceof HTMLMetaElement){const r=Eu(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},Ae=20,vu=8,Ls=4096,Pu=2160*60*6e4,j=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",s=/^[A-Za-z]:\/$/.test(r);return!o&&!s&&(r=r.replace(/\/+$/,"")),r},Je=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,Qe=(e,t)=>{const n=j(t),r=j(e);if(!n||!r)return!1;const o=Je(n),s=Je(r);return s===o||s.startsWith(`${o}/`)},Kt=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=j(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(m=>typeof m=="string").map(m=>j(m)).filter(m=>m.length<=Ls&&Qe(m,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(m=>typeof m=="string").map(m=>j(m)).filter(m=>m.length<=Ls&&Qe(m,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?j(i.selectedPath):null,d=l&&Qe(l,s)?l:a[0]??null,u=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-u>Pu)continue;const f=n[s];if(f){const m=Array.from(new Set([...f.openPaths,...a])),p=Array.from(new Set([...f.expandedPaths,...c])),g=f.selectedPath??d??m[0]??null;n[s]={openPaths:m,selectedPath:g,expandedPaths:p,touchedAt:Math.max(f.touchedAt,u)};continue}n[s]={openPaths:a,selectedPath:d,expandedPaths:c,touchedAt:u}}return Me(n,Ae)},Me=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},Ct=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Au=St()(fn(nr((e,t)=>({byRoot:{},activeRuntimeKey:L(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:Kt(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:Kt(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=j((n||"").trim()),i=j((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!Qe(i,s)||e(a=>{const c=a.byRoot[s],l=Ct(c),d=l.openPaths.includes(i),u=d?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&d&&c.selectedPath===f)return a;const m={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:f}};return{byRoot:Me(m,Ae)}})},removeOpenPath:(n,r)=>{const o=j((n||"").trim()),s=j((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=Je(s),l=p=>Je(p)===c,d=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!d)return i;const u=a.openPaths.filter(p=>!l(p)),f=d?u[0]??null:a.selectedPath,m={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Ae)}})},removeOpenPathsByPrefix:(n,r)=>{const o=j((n||"").trim()),s=j((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=Je(s),l=c.endsWith("/")?c:`${c}/`,d=p=>{const g=Je(p);return g===c||g.startsWith(l)},u=a.openPaths.filter(p=>!d(p));if(u.length===a.openPaths.length)return i;const f=a.selectedPath&&d(a.selectedPath)?u[0]??null:a.selectedPath,m={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:Me(m,Ae)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=j((n||"").trim()),s=j((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=Je(s),l=c.endsWith("/")?c:`${c}/`,d=a.expandedPaths.filter(f=>{const m=Je(f);return m!==c&&!m.startsWith(l)});if(d.length===a.expandedPaths.length)return i;const u={...i.byRoot,[o]:{...a,expandedPaths:d,touchedAt:Date.now()}};return{byRoot:Me(u,Ae)}})},setSelectedPath:(n,r,o)=>{const s=j((n||"").trim()),i=r?j(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!Qe(i,s)||e(a=>{const c=a.byRoot[s],l=Ct(c),d=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&d===c.openPaths)return a;const u={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:i}};return{byRoot:Me(u,Ae)}})},ensureSelectedPath:n=>{const r=j((n||"").trim());if(!r)return;const o=t().byRoot[r];if(!o||o.selectedPath)return;const s=o.openPaths[0]??null;s&&t().setSelectedPath(r,s)},toggleExpandedPath:(n,r)=>{const o=j((n||"").trim()),s=j((r||"").trim());!o||!s||!Qe(s,o)||e(i=>{const a=i.byRoot[o],c=Ct(a),d=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===d&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:d}};return{byRoot:Me(u,Ae)}})},collapseAllExpandedPaths:n=>{const r=j((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...Ct(s),expandedPaths:[]}};return{byRoot:Me(i,Ae)}})},expandPath:(n,r)=>{const o=j((n||"").trim()),s=j((r||"").trim());!o||!s||!Qe(s,o)||e(i=>{const a=i.byRoot[o],c=Ct(a);if(c.expandedPaths.includes(s)&&a)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:Me(d,Ae)}})},expandPaths:(n,r)=>{const o=j((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>j((i||"").trim())).filter(i=>i&&Qe(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=Ct(a),l=new Set(c.expandedPaths),d=s.filter(f=>!l.has(f));if(d.length===0)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...d]}};return{byRoot:Me(u,Ae)}})}}),{name:"files-view-tabs-store",version:3,storage:xo(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:L(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:Kt(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,vu).map(([r,o])=>[r,{byRoot:Kt(o.byRoot),updatedAt:o.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:n}},merge:(e,t)=>{const n=e&&typeof e=="object"?e:{},r=n.runtimeSnapshots&&typeof n.runtimeSnapshots=="object"?n.runtimeSnapshots:{},o=L();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:Kt(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),Pa=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",Mu=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},_y=()=>{if(typeof window>"u"||!Pa()||Cu()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},Cu=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Ie()?"vscode":rt()?"desktop":"web"},Aa="ask",Fs=e=>e==="attach"||e==="inline"||e==="ask"?e:Aa;function js(e){return e==="vim"?"vim":"default"}const Ue="all";function Us(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Ns(e){return e==="me"||e==="any"?e:"any"}function Ma(e){return typeof e!="string"?Ue:e.trim()||Ue}function Bs(e,t){const n=L();if(Xi(n))return e;const r={...e};return t===Ue?delete r[n]:r[n]=t,r}function Du(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e)){if(!n.trim()||typeof r!="string")continue;const o=Ma(r);o!==Ue&&(t[n]=o)}return t}function Hs(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const An={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}"}},ze={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},Mn=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,Ru=e=>{if(!e||typeof e!="object")return!1;const t=e;return Mn(t.completion,An.completion)&&Mn(t.error,An.error)&&Mn(t.question,An.question)&&Mn(t.subtask,An.subtask)},Iu=380,Ou=380,xu=1400,Ca=12,zs=120,Vt=280;let $s=0;const Ly=e=>J(e),J=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},Da=e=>Number.isFinite(e)?Math.min(xu,Math.max(Ou,Math.round(e))):Iu,Jn=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Yn=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>zs?t.slice(0,zs):t:null},Lo=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Ra=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.id=="string"?t.id.trim():"",r=typeof t.path=="string"?t.path.trim():"";return n&&r?{id:n,path:r}:null},_u=(e,t)=>(e==="file"||e==="browser")&&t||e,Ia=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return _u(e,t)},Oa=(e,t)=>t===e?e:`${e}:${t}`,xa=e=>{const t=Jn(e.targetPath),n=Ia(e.mode,t,e.dedupeKey);return{id:Oa(e.mode,n),mode:e.mode,targetPath:t,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Ra(e.projectPlanRef),dedupeKey:n,label:Yn(e.label),sessionTitleFallback:Yn(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Lo(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},_a=(e,t,n)=>{const r=new Map;for(const i of e)r.set(i.mode,(r.get(i.mode)??0)+1);const o=[...r.entries()].filter(([,i])=>i>t);if(o.length===0)return e;const s=new Set;for(const[i,a]of o){const l=[...e.filter(d=>d.mode===i)].sort((d,u)=>d.touchedAt-u.touchedAt).filter(d=>d.id!==n);for(const d of l.slice(0,a-t))s.add(d.id)}return s.size===0?e:e.filter(i=>!s.has(i.id))},La=e=>{if(!Array.isArray(e))return[];const t=Ie(),n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o;if(s.mode!=="diff"&&s.mode!=="walkthrough"&&s.mode!=="file"&&s.mode!=="context"&&s.mode!=="plan"&&s.mode!=="chat"&&s.mode!=="browser"&&s.mode!=="git"&&s.mode!=="pr"&&s.mode!=="linear"&&s.mode!=="notes"&&s.mode!=="terminal"||t&&s.mode==="browser")continue;const i=Jn(typeof s.targetPath=="string"?s.targetPath:null),a=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,c=Ra(s.projectPlanRef);if(s.mode==="plan"&&a!==null!=(c!==null))continue;const l=Ia(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),d=Oa(s.mode,l);!d||r.has(d)||(r.add(d),n.push({id:d,mode:s.mode,targetPath:i,projectPlanId:a,projectPlanRef:c,dedupeKey:l,label:Yn(typeof s.label=="string"?s.label:null),sessionTitleFallback:Yn(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:Lo(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},Bt=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,at=e=>{if(e){const t=La(e.tabs),n=Bt(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},touchedAt:Date.now()}},Lu=(e,t,n)=>{const r=n?.reveal!==!1,o=xa(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(d=>!(d.mode==="file"&&!d.targetPath)):e.tabs,i=s.findIndex(d=>d.id===o.id),a=i===-1?[...s,o]:s.map((d,u)=>u===i?{...d,mode:o.mode,targetPath:o.targetPath||d.targetPath,projectPlanId:o.projectPlanId??d.projectPlanId,projectPlanRef:o.projectPlanRef??d.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||d.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:d),c=r?o.id:e.activeTabId??o.id,l=_a(a,Ca,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:Bt(l,c),touchedAt:Date.now()}},Fu=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),o=e.tabs.filter(l=>!n.has(l.id));if(o.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:o,activeTabId:Bt(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?o.filter(l=>l.mode===i):[],c=a.length>0?a.reduce((l,d)=>d.touchedAt>=l.touchedAt?d:l):null;return{...e,tabs:o,activeTabId:c?.id??Bt(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},ju=(e,t,n)=>{if(t===n)return e;const r=e.tabs.findIndex(a=>a.id===t),o=e.tabs.findIndex(a=>a.id===n);if(r===-1||o===-1)return e;const s=[...e.tabs],[i]=s.splice(r,1);return i?(s.splice(o,0,i),{...e,tabs:s,touchedAt:Date.now()}):e},Uu=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),Or=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=J(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=La(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=[xa({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=Bt(a,c),d=_a(a,Ca,l),u={};if(i.widthByMode&&typeof i.widthByMode=="object")for(const[f,m]of Object.entries(i.widthByMode))(f==="diff"||f==="file"||f==="context"||f==="plan"||f==="chat"||f==="browser"||f==="git"||f==="pr"||f==="linear"||f==="notes"||f==="terminal")&&typeof m=="number"&&Number.isFinite(m)&&(u[f]=Da(m));n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:Bt(d,l),widthByMode:u,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},ct=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},he=St()(fn(nr((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:Vt,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,showOpenCodeRestartConfirm:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:bu,monoFont:Su,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:ku(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Ue,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...ze.completion},error:{...ze.error},question:{...ze.question},subtask:{...ze.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!Mu(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:Aa,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>{const r=!n.isSidebarOpen;return r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:Vt}:{isSidebarOpen:r}})},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==Vt?{isSidebarOpen:n,sidebarWidth:Vt}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:Vt}:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((o,s)=>typeof o=="string"&&o.trim()!==""&&n.indexOf(o)===s):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>({contextEditorTreeVisible:!n.contextEditorTreeVisible}))},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(n)))})},openContextSurface:(n,r)=>{const o=J((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],a=i?.tabs??[],c=a.find(d=>d.id===i?.activeTabId)??null;if(i?.isOpen&&c?.mode===r){s.closeContextPanel(o);return}const l=a.filter(d=>d.mode===r);if(l.length>0){const d=l.reduce((u,f)=>f.touchedAt>=u.touchedAt?f:u);s.setActiveContextPanelTab(o,d.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=J((n||"").trim());s&&e(i=>{const a=i.contextPanelByDirectory[s],c=at(a),l={...i.contextPanelByDirectory,[s]:Lu(c,r,o)};return{contextPanelByDirectory:ct(l,20)}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=J((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Lo(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=J((n||"").trim()),s=Jn(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=J((n||"").trim()),a=Jn(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=J((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=J((n||"").trim()),s=(r||"").trim();!o||!s||Ie()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=J((n||"").trim());!r||Ie()||($s+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${$s}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=J((n||"").trim());if(!s||Ie())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(s,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},o)},setContextPanelTabTargetPath:(n,r,o)=>{const s=J((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:Uu(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=J((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=at(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:ct(l,20)}})},reorderContextPanelTabs:(n,r,o)=>{const s=J((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],d=at(l);if(!d.tabs.some(m=>m.id===i)||!d.tabs.some(m=>m.id===a))return c;const u=ju(d,i,a);if(u.tabs===d.tabs)return c;const f={...c.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:ct(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=J((n||"").trim()),s=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!o||s.length===0)return;const i=s.map(a=>t().contextPanelByDirectory[o]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[o],l=at(c);if(!l.tabs.some(u=>s.includes(u.id)))return a;const d={...a.contextPanelByDirectory,[o]:Fu(l,s)};return{contextPanelByDirectory:ct(d,20)}});for(const a of i)a.mode==="file"&&a.targetPath&&Au.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=J((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...at(s),isOpen:!1}};return{contextPanelByDirectory:ct(i,20)}})},toggleContextPanelExpanded:n=>{const r=J((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=at(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:ct(a,20)}})},setContextPanelWidth:(n,r,o)=>{const s=J((n||"").trim());s&&e(i=>{const a=i.contextPanelByDirectory[s],c=at(a),l={...i.contextPanelByDirectory,[s]:{...c,widthByMode:{...c.widthByMode,[r]:Da(o)}}};return{contextPanelByDirectory:ct(l,20)}})},setNotesPanelHeight:n=>{e({notesPanelHeight:n})},setWorkStatusSectionExpanded:(n,r)=>{e(o=>o.workStatusExpandedSections[n]===r?o:{workStatusExpandedSections:{...o.workStatusExpandedSections,[n]:r}})},setWorkStatusScrollTop:n=>{e({workStatusScrollTop:Math.max(0,n)})},setWorkStatusPanelEnabled:n=>{e({workStatusPanelEnabled:n})},setWorkStatusPanelVisible:n=>{e(r=>r.workStatusPanelVisible===n?r:{workStatusPanelVisible:n})},setWorkStatusPanelFits:n=>{e(r=>r.workStatusPanelFits===n?r:n?{workStatusPanelFits:!0,workStatusOverlayOpen:!1}:{workStatusPanelFits:!1})},setWorkStatusOverlayOpen:n=>{e(r=>r.workStatusOverlayOpen===n?r:{workStatusOverlayOpen:n})},setWorkStatusSectionVisible:(n,r)=>{e(o=>{const s=o.workStatusHiddenSections,i=s.includes(n);return r===!i?o:{workStatusHiddenSections:r?s.filter(a=>a!==n):[...s,n]}})},setWorkStatusHiddenSections:n=>{e({workStatusHiddenSections:[...new Set(n)]})},setContextRailSurfaceVisible:(n,r)=>{e(o=>{const s=o.contextRailHiddenSurfaces,i=s.includes(n);return r===!i?o:{contextRailHiddenSurfaces:r?s.filter(a=>a!==n):[...s,n]}})},setContextRailHiddenSurfaces:n=>{e({contextRailHiddenSurfaces:[...new Set(n)]})},setSessionSwitcherOpen:n=>{t().isSessionSwitcherOpen!==n&&e({isSessionSwitcherOpen:n})},setSessionDropdownOpen:n=>{t().isSessionDropdownOpen!==n&&e({isSessionDropdownOpen:n})},setPendingDiffFile:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:n?r:!1,pendingDiffScope:n?o:null})},setPendingFileNavigation:n=>{e({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{e({pendingFileFocusPath:n})},navigateToDiff:(n,r=!1,o=null)=>{e({pendingDiffFile:n,pendingDiffStaged:r,pendingDiffScope:o})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=t();return n&&e({pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null}),n},setIsMobile:n=>{e({isMobile:n})},toggleCommandPalette:()=>{e(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{e({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{e(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{e({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{e({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{e({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{e({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{e({isSessionCreateDialogOpen:n})},setScheduledTasksDialogOpen:n=>{e(n?{isScheduledTasksDialogOpen:!0,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{isScheduledTasksDialogOpen:!1})},setArchivePageOpen:n=>{e(n?{isArchivePageOpen:!0,isScheduledTasksDialogOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1}:{isArchivePageOpen:!1})},setWorktreesPageProjectId:n=>{e(n?{worktreesPageProjectId:n,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,isMultiRunLauncherOpen:!1}:{worktreesPageProjectId:null})},closeMainSurfaces:()=>{const n=t();!n.isScheduledTasksDialogOpen&&!n.isArchivePageOpen&&!n.worktreesPageProjectId&&!n.isMultiRunLauncherOpen||e({isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:""})},setSettingsDialogOpen:n=>{e(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setNewWorktreeDialogOpen:n=>{e({isNewWorktreeDialogOpen:n})},setModelSelectorOpen:n=>{e({isModelSelectorOpen:n})},setSidebarSection:n=>{e({sidebarSection:n})},setSettingsPage:n=>{e({settingsPage:n})},setSettingsProjectPath:n=>{const r=n?.trim();e({settingsProjectPath:r||null})},setSettingsProjectsSelectedId:n=>{e({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{e({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{e({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{e({showReasoningTraces:n})},setStreamingAutoFollowEnabled:n=>{e({streamingAutoFollowEnabled:n})},setSessionRecapEnabled:n=>{e({sessionRecapEnabled:n})},setSessionSuggestionEnabled:n=>{e({sessionSuggestionEnabled:n})},setSessionGoalEnabled:n=>{e({sessionGoalEnabled:n})},setSessionGoalDefaultBudgetEnabled:n=>{e({sessionGoalDefaultBudgetEnabled:n})},setSessionGoalDefaultBudget:n=>{e({sessionGoalDefaultBudget:n})},setCollapsibleThinkingBlocks:n=>{e({collapsibleThinkingBlocks:n})},setChatRenderMode:n=>{e({chatRenderMode:n})},setActivityRenderMode:n=>{e({activityRenderMode:n})},setShowDeletionDialog:n=>{e({showDeletionDialog:n})},setShowOpenCodeRestartConfirm:n=>{e({showOpenCodeRestartConfirm:n})},setAutoDeleteEnabled:n=>{e({autoDeleteEnabled:n})},setAutoSaveEnabled:n=>{e({autoSaveEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));e({autoDeleteAfterDays:r})},setSessionRetentionAction:n=>{e({sessionRetentionAction:n})},setAutoDeleteLastRunAt:n=>{e({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));e({messageLimit:r})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));e({fontSize:r}),t().applyTypography()},setGlobalDraftStarters:n=>{e({globalDraftStarters:n})},setDraftStartersVisible:n=>{e({draftStartersVisible:n})},setTerminalFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(52,r));e({terminalFontSize:o})},setTerminalShell:n=>{e({terminalShell:n})},setTerminalLoginShells:n=>{e({terminalLoginShells:[...new Set(n)]})},setEditorFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(32,r));e({editorFontSize:o})},setUiFont:n=>{e({uiFont:n})},setMonoFont:n=>{e({monoFont:n})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));e({padding:r}),t().applyPadding()},setCornerRadius:n=>{e({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=t(),r=document.documentElement,o=n/100,s=Object.entries(hu);if(o===1){for(const[i]of s)r.style.removeProperty(xs(i));return}for(const[i,a]of s){const c=parseFloat(a);Number.isFinite(c)&&r.style.setProperty(xs(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,o=n/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);r.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{e({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{e(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{e({diffWrapLines:n})},setWalkthroughTocWidth:n=>{e({walkthroughTocWidth:Math.round(n)})},setGitChangesViewMode:n=>{e({gitChangesViewMode:n})},setLinearIssueListStatus:n=>{e({linearIssueListStatus:Us(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Ns(n)})},setLinearIssueListTeamId:n=>{const r=Ma(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Bs(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=L();e(r=>({linearIssueListTeamId:Xi(n)?Ue:r.linearIssueListTeamIdByRuntime[n]??Ue}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:Hs(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Ue,linearIssueListTeamIdByRuntime:Bs(n.linearIssueListTeamIdByRuntime,Ue),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},reorderFavoriteModel:(n,r,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===r),c=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const o=n.filter(i=>typeof i=="string"&&i.length>0),s=r.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?r:{providerOrder:o}})},toggleHiddenModel:(n,r)=>{e(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},hideAllModels:(n,r)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...s]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const o=Array.from(new Set(n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...o]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},addRecentModel:(n,r)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...s].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>{if(o.recentAgents.includes(r))return o;const s=o.recentAgents;return{recentAgents:[r,...s].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const s=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";e(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const u=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null}:{}}))},openMultiRunLauncher:()=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(o=>({agentMemoryViewedAt:r>(o.agentMemoryViewedAt[n]??0)?{...o.agentMemoryViewedAt,[n]:r}:o.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:Fs(n)})},setWideChatLayoutEnabled:n=>{e({wideChatLayoutEnabled:n})},setCodeBlockLineWrap:n=>{e({codeBlockLineWrap:n})},setShowToolFileIcons:n=>{e({showToolFileIcons:n})},setShowTurnChangedFiles:n=>{e({showTurnChangedFiles:n})},setShowExpandedBashTools:n=>{e({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{e({showExpandedEditTools:n})},setTimeFormatPreference:n=>{e({timeFormatPreference:n})},setWeekStartPreference:n=>{e({weekStartPreference:n})},setDesktopWindowControlsPosition:n=>{e({desktopWindowControlsPosition:n==="left"?"left":"right"})},setDesktopWindowControlsStyle:n=>{e({desktopWindowControlsStyle:n==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:n=>{e({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{e({userMessageRenderingMode:n})},setCollapsibleUserMessages:n=>{e({collapsibleUserMessages:n})},setStickyUserHeader:n=>{e({stickyUserHeader:n})},setPromptNavigatorEnabled:n=>{e({promptNavigatorEnabled:n})},setShowSplitAssistantMessageActions:n=>{e({showSplitAssistantMessageActions:n})},setAllowPromptingSubagentSessions:n=>{e({allowPromptingSubagentSessions:n})},setReportUsage:n=>{e({reportUsage:n})},viewPagerPage:"center",setViewPagerPage:n=>{e({viewPagerPage:n}),e({isSessionSwitcherOpen:n==="left"})},setShortcutOverride:(n,r)=>{e(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:js(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:xo(),version:19,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const o of Object.values(r)){if(!o||typeof o!="object")continue;const s=o,i=s.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(s.tabs))continue;const a=new Set,c=[];for(const l of s.tabs){if(!l||typeof l!="object")continue;const d=l;if(d.mode!=="preview"){typeof d.id=="string"&&a.add(d.id),c.push(d);continue}const u=typeof d.targetPath=="string"?d.targetPath:"",f=typeof d.dedupeKey=="string"&&d.dedupeKey.trim()?d.dedupeKey.trim():u||"browser",m=f==="browser"?"browser":`browser:${f}`;a.has(m)||(a.add(m),c.push({...d,mode:"browser",id:m,dedupeKey:f}))}if(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(d=>typeof d.id=="string");s.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const o=localStorage.getItem("openchamber:files:auto-save-enabled");o!==null&&(r=o!=="false",localStorage.removeItem("openchamber:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&Ru(n.notificationTemplates)&&(n.notificationTemplates={completion:{...ze.completion},error:{...ze.error},question:{...ze.question},subtask:{...ze.subtask}}),t<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,s=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof s=="number"&&!r.has(s)&&(n.messageLimit=s),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=Or(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[s,i]of Object.entries(r))typeof s=="string"&&typeof i=="string"&&(o[s]=i);n.shortcutOverrides=o}return t<6&&(n.contextPanelByDirectory=Or(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=Or(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Us(n.linearIssueListStatus),n.linearIssueListAssignee=Ns(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=Du(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=Hs(n.linearIssueListPriority),n.fileEditorKeymap=js(n.fileEditorKeymap),n.largeTextPasteBehavior=Fs(n.largeTextPasteBehavior),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,showOpenCodeRestartConfirm:e.showOpenCodeRestartConfirm,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Nu=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Bu=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
4
- `).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const o=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:o,endLine:Math.max(o,Math.floor(e.endLine)),text:r}},Hu=(e,t)=>{const n=t.map(Bu).filter(s=>s!==null);if(n.length===0)return e;const o=["<terminal_context>",...n.flatMap((s,i)=>[`- ${s.terminalLabel} lines ${s.startLine}-${s.endLine}:`,...s.text.split(`
5
- `).map((a,c)=>` ${s.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
6
- `);return e.trim()?`${e.trim()}
7
-
8
- ${o}`:o},Fy=e=>{const t=Nu.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const o of(t[1]??"").split(`
9
- `)){const s=/^- (.+) lines (\d+)-(\d+):$/.exec(o);if(s){r&&n.push(r),r={terminalLabel:s[1],startLine:Number(s[2]),endLine:Number(s[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(o);r&&i&&(r.text+=`${r.text?`
10
- `:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},Fo="openchamberContext";function zu(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
11
- \`\`\`${e.language}
12
- ${e.code}
13
- \`\`\`
14
-
15
- ${e.text}`}case"terminal":return Hu("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
16
-
17
- ${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
18
-
19
- ${e.body}${e.text?`
20
-
21
- ${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
22
- `).map(r=>`> ${r}`).join(`
23
- `);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
24
- ${n}${e.text?`
25
-
26
- ${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
27
- ${e.quote.split(`
28
- `).map(n=>`> ${n}`).join(`
29
- `)}${e.text?`
30
-
31
- ${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
32
- \`\`\`
33
- ${e.output}
34
- \`\`\`${e.text?`
35
-
36
- ${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":return""}}function jy(e,t){return{text:t??zu(e),synthetic:!0,metadata:{[Fo]:e}}}function Uy(e){switch(e.source){case"terminal":return{kind:"terminal",terminalId:e.terminalId??"",terminalLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,output:e.code};case"preview-annotation":return{kind:"browser-annotation",pageUrl:e.fileLabel,prompt:e.code,text:e.text};case"pr-comment":return{kind:"pr-comment",label:e.fileLabel,body:e.code,text:e.text};case"pr-check":return{kind:"pr-check",label:e.fileLabel,output:e.code,text:e.text};case"file-quote":{const t={kind:"file-quote",fileLabel:e.fileLabel,quote:e.code,text:e.text};return e.startLine>0&&e.endLine>0&&(t.startLine=e.startLine,t.endLine=e.endLine),t}case"chat-quote":{const t={kind:"chat-quote",quote:e.code,text:e.text};return e.fileLabel&&(t.messageId=e.fileLabel),t}case"diff":case"file":case"plan":{const t={kind:"code-comment",source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,language:e.language,code:e.code,text:e.text};return e.source==="diff"&&e.side&&(t.side=e.side),t}}}const Fa=mi("kind",[U({kind:pe("code-comment"),source:Fr(["diff","file","plan"]),fileLabel:k(),startLine:ce(),endLine:ce(),side:Fr(["original","modified"]).optional(),language:k(),code:k(),text:k()}),U({kind:pe("terminal"),terminalId:k(),terminalLabel:k(),startLine:ce(),endLine:ce(),output:k()}),U({kind:pe("browser-annotation"),pageUrl:k(),prompt:k(),text:k()}),U({kind:pe("pr-comment"),label:k(),body:k(),text:k()}),U({kind:pe("pr-check"),label:k(),output:k(),text:k()}),U({kind:pe("file-quote"),fileLabel:k(),startLine:ce().optional(),endLine:ce().optional(),quote:k(),text:k()}),U({kind:pe("chat-quote"),messageId:k().optional(),quote:k(),text:k()}),U({kind:pe("github-issue"),number:ce().int().positive(),title:k(),url:k()}),U({kind:pe("github-pr"),number:ce().int().positive(),title:k(),url:k()}),U({kind:pe("linear-issue"),identifier:k().min(1),title:k(),url:k()})]),$u=U({[Fo]:Fa});function Gu(e){if(e.type!=="text")return null;const t=Fa.safeParse(e.metadata?.[Fo]);return t.success?t.data:null}function Ny(e){return e.some(t=>Gu(t)!==null)}function By(e){switch(e.kind){case"code-comment":{const t={source:e.source,fileLabel:e.fileLabel,startLine:e.startLine,endLine:e.endLine,code:e.code,language:e.language,text:e.text};return e.side&&(t.side=e.side),t}case"terminal":return{source:"terminal",fileLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,code:e.output,language:"",text:"",terminalId:e.terminalId};case"browser-annotation":return{source:"preview-annotation",fileLabel:e.pageUrl,startLine:0,endLine:0,code:e.prompt,language:"",text:e.text};case"pr-comment":return{source:"pr-comment",fileLabel:e.label,startLine:0,endLine:0,code:e.body,language:"",text:e.text};case"pr-check":return{source:"pr-check",fileLabel:e.label,startLine:0,endLine:0,code:e.output,language:"",text:e.text};case"file-quote":return{source:"file-quote",fileLabel:e.fileLabel,startLine:e.startLine??0,endLine:e.endLine??0,code:e.quote,language:"",text:e.text};case"chat-quote":return{source:"chat-quote",fileLabel:e.messageId??"",startLine:0,endLine:0,code:e.quote,language:"",text:e.text};case"github-issue":case"github-pr":case"linear-issue":return null}}const ja=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(o,s)=>s.toUpperCase()+":");return n==="/"?"/":(n.length>1?n.replace(/\/+$/,""):n)||null},jo="queue",Uo=e=>e==="steer"||e==="queue",No=(e,t)=>e==="immediate"?"steer":Uo(e)?e:t===!1?"steer":t===!0?"queue":jo,qe=()=>!Ie(),Gs=50,Yr=(e,t,n=L())=>{const r=ja(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},ge=e=>`${e.runtimeKey}
37
- ${e.directory}
38
- ${e.sessionId}`,Dt=e=>{const[t,n,...r]=e.split(`
39
- `);return Yr(r.join(`
40
- `),n,t)},Wu=U({providerID:k().min(1),modelID:k().min(1),agent:k().optional(),variant:k().optional()}),qu=U({id:k(),filename:k(),mimeType:k(),size:ce(),source:Fr(["local","server","vscode"]),serverPath:k().optional(),dataUrl:k().optional()}),Ku=mi("kind",[U({kind:pe("context"),text:k(),metadata:$u,instructions:k().optional()}),U({kind:pe("instruction"),text:k()}),U({kind:pe("synthetic"),text:k()})]),Bo=U({id:k().min(1),createdAt:ce(),content:k(),text:k(),agentMention:k().optional(),attachments:rn(qu),context:rn(Ku).optional(),sendConfig:Wu}),Ho=U({sessionId:k().min(1),directory:k(),items:rn(Bo),sendingId:k().nullable()}),Ws=U({revision:ce(),sessions:rn(Ho)}),tn=U({revision:ce(),session:Ho}),Vu=tn.extend({item:Bo}),Ju=tn.extend({items:rn(Bo)}),Yu=e=>{const t=e.indexOf(",");if(!e.startsWith("data:")||t===-1)return null;const n=e.slice(5,t),r=e.slice(t+1);try{if(n.endsWith(";base64")){const i=atob(r),a=new ArrayBuffer(i.length),c=new Uint8Array(a);for(let l=0;l<i.length;l+=1)c[l]=i.charCodeAt(l);return a}const o=new TextEncoder().encode(decodeURIComponent(r)),s=new ArrayBuffer(o.byteLength);return new Uint8Array(s).set(o),s}catch{return null}},Qu=e=>{const t=e.dataUrl??"",n=t?Yu(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},Cn=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(Qu)),e.context&&(t.context=e.context),t},Xu=e=>{const t={id:e.id,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source,dataUrl:e.dataUrl};return e.serverPath&&(t.serverPath=e.serverPath),t},qs=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(r=>!!r.dataUrl).map(Xu),context:e.context??[],sendConfig:t};return e.agentMention&&(n.agentMention=e.agentMention),n},lt=async(e,t,n)=>{const r=await h(t,n);if(!r.ok){const s=new Error(`Message queue request failed (${r.status})`);throw s.status=r.status,s}const o=e.safeParse(await r.json());if(!o.success)throw new Error("Invalid message queue response");return o.data},$e=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},Ge=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,Dn=new Set,Rt=new Map;let xr=0;const Ks=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),Zu=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:Ks(n.queuedMessages??{}),quarantinedLegacyMessages:Ks({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:No(n.followUpBehavior,n.queueModeEnabled??null)}},Ke=(e,t)=>{const{[t]:n,...r}=e;return r},Rn=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(o=>o.id!==n);return r.length===0?{queuedMessages:Ke(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},Ua=St()(fn(nr((e,t)=>{const n=(s,i,a)=>{if(a!==L())return;const c=Yr(s.sessionId,s.directory,a);if(!c)return;const l=ge(c);(Rt.get(l)??-1)>i||(Rt.set(l,i),e(d=>{const u=s.items.map(Cn),f=u.length>0?{...d.queuedMessages,[l]:u}:Ke(d.queuedMessages,l),m=s.sendingId?{...d.sendingIds,[l]:[s.sendingId]}:Ke(d.sendingIds,l);return{queuedMessages:f,sendingIds:m}}))},r=async s=>{try{const i=await lt(Ws,"/api/message-queue"),a=i.sessions.find(c=>c.sessionId===s.sessionId)??{sessionId:s.sessionId,directory:s.directory,items:[],sendingId:null};n(a,i.revision,s.runtimeKey)}catch{}},o=async(s,i,a)=>{try{const c=await lt(tn,i,a);n(c.session,c.revision,s.runtimeKey)}catch(c){console.warn("[queue] server update failed:",c),await r(s)}};return{queuedMessages:{},quarantinedLegacyMessages:{},followUpBehavior:jo,sendingIds:{},addToQueue:async(s,i)=>{const a=ge(s),c=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,l={id:c,content:i.content,text:i.text??i.content,createdAt:Date.now(),sendConfig:i.sendConfig};if(i.agentMention&&(l.agentMention=i.agentMention),i.attachments&&i.attachments.length>0&&(l.attachments=i.attachments),i.context&&i.context.length>0&&(l.context=i.context),e(d=>{const u=d.queuedMessages[a]??[],f={...d.queuedMessages,[a]:[...u,l].slice(-20)},m=Object.keys(f);if(m.length>Gs){m.sort((p,g)=>(f[p]?.[0]?.createdAt??0)-(f[g]?.[0]?.createdAt??0));for(const p of m.slice(0,m.length-Gs))delete f[p]}return{queuedMessages:f}}),!!qe()){if(!i.sendConfig)throw e(d=>Rn(d,a,c)),new Error("A queued message needs a provider and model to be delivered later.");try{const d=await lt(tn,`${Ge(s.sessionId)}/items`,$e("POST",{directory:s.directory,item:qs(i,i.sendConfig)}));e(u=>Rn(u,a,c)),n(d.session,d.revision,s.runtimeKey)}catch(d){throw e(u=>Rn(u,a,c)),d}}},removeFromQueue:(s,i)=>{const a=ge(s);e(c=>Rn(c,a,i)),qe()&&o(s,`${Ge(s.sessionId)}/items/${encodeURIComponent(i)}`,$e("DELETE"))},reorderQueue:(s,i,a)=>{if(i===a)return;const c=ge(s),l=t().queuedMessages[c];if(!l)return;const d=l.findIndex(p=>p.id===i),u=l.findIndex(p=>p.id===a);if(d===-1||u===-1)return;const f=l.slice(),[m]=f.splice(d,1);if(f.splice(u,0,m),e(p=>({queuedMessages:{...p.queuedMessages,[c]:f}})),qe()){const p=f.map(g=>g.id);o(s,`${Ge(s.sessionId)}/order`,$e("PUT",{itemIds:p}))}},popToInput:async(s,i)=>{const[a]=await t().takeForSend(s,i);return a??null},takeForSend:async(s,i)=>{const a=ge(s);if(qe()){if(i){const m=await lt(Vu,`${Ge(s.sessionId)}/items/${encodeURIComponent(i)}/take`,$e("POST"));return n(m.session,m.revision,s.runtimeKey),[Cn(m.item)]}const f=await lt(Ju,`${Ge(s.sessionId)}/take`,$e("POST"));return n(f.session,f.revision,s.runtimeKey),f.items.map(Cn)}const c=t(),l=c.sendingIds[a]??[],d=(c.queuedMessages[a]??[]).filter(f=>(i?f.id===i:!0)&&!l.includes(f.id));if(d.length===0)return[];const u=new Set(d.map(f=>f.id));return e(f=>{const m=(f.queuedMessages[a]??[]).filter(p=>!u.has(p.id));return m.length===0?{queuedMessages:Ke(f.queuedMessages,a)}:{queuedMessages:{...f.queuedMessages,[a]:m}}}),d},clearQueue:s=>{const i=ge(s);e(a=>{const c=a.sendingIds[i]??[],l=(a.queuedMessages[i]??[]).filter(d=>c.includes(d.id));return l.length>0?{queuedMessages:{...a.queuedMessages,[i]:l}}:{queuedMessages:Ke(a.queuedMessages,i)}}),qe()&&o(s,Ge(s.sessionId),$e("DELETE"))},forgetQueue:s=>{const i=ge(s);Rt.delete(i),e(a=>({queuedMessages:Ke(a.queuedMessages,i),sendingIds:Ke(a.sendingIds,i)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(s,i)=>{const a=ge(s);e(c=>{const l=c.sendingIds[a]??[];return l.includes(i)?c:{sendingIds:{...c.sendingIds,[a]:[...l,i]}}})},clearSending:(s,i)=>{const a=ge(s);e(c=>{const l=c.sendingIds[a];if(!l||!l.includes(i))return c;const d=l.filter(u=>u!==i);return d.length===0?{sendingIds:Ke(c.sendingIds,a)}:{sendingIds:{...c.sendingIds,[a]:d}}})},getSendableQueue:s=>{const i=ge(s),a=t(),c=a.queuedMessages[i]??[],l=a.sendingIds[i];return!l||l.length===0?c:c.filter(d=>!l.includes(d.id))},setFollowUpBehavior:s=>{e({followUpBehavior:s}),Ce({followUpBehavior:s})},getQueueForTarget:s=>t().queuedMessages[ge(s)]??[],hydrate:async()=>{if(!qe())return;const s=L(),i=++xr,a=()=>i===xr&&s===L(),c=Object.entries(t().queuedMessages).map(([d,u])=>({target:Dt(d),queue:u})).filter(d=>d.target!==null&&d.target.runtimeKey===s&&!Dn.has(s));for(const{target:d,queue:u}of c)for(const f of u)if(f.sendConfig){try{await lt(tn,`${Ge(d.sessionId)}/items`,$e("POST",{directory:d.directory,item:qs(f,f.sendConfig)}))}catch(m){console.warn("[queue] failed to migrate a locally queued message to the server:",m)}if(!a())return}const l=await lt(Ws,"/api/message-queue");a()&&(Dn.add(s),e(d=>{const u={},f={};for(const[m,p]of Object.entries(d.queuedMessages))Dt(m)?.runtimeKey!==s&&(u[m]=p);for(const[m,p]of Object.entries(d.sendingIds))Dt(m)?.runtimeKey!==s&&(f[m]=p);for(const m of l.sessions){const p=Yr(m.sessionId,m.directory,s);if(!p)continue;const g=ge(p);if((Rt.get(g)??-1)>l.revision){d.queuedMessages[g]&&(u[g]=d.queuedMessages[g]),d.sendingIds[g]&&(f[g]=d.sendingIds[g]);continue}Rt.set(g,l.revision),m.items.length>0&&(u[g]=m.items.map(Cn)),m.sendingId&&(f[g]=[m.sendingId])}return{queuedMessages:u,sendingIds:f}}))},applyServerSession:n,setServerHold:async(s,i)=>{if(!qe())return;const a=await h(`${Ge(s)}/hold`,$e("PUT",{held:i}));if(!a.ok)throw new Error(`Message queue hold request failed (${a.status})`)},resetForRuntimeSwitch:s=>{xr+=1,!(!s||!Dn.has(s))&&e(i=>{const a={},c={};for(const[l,d]of Object.entries(i.queuedMessages))Dt(l)?.runtimeKey===s?Rt.delete(l):a[l]=d;for(const[l,d]of Object.entries(i.sendingIds))Dt(l)?.runtimeKey!==s&&(c[l]=d);return{queuedMessages:a,sendingIds:c}})}}},{name:"message-queue-store",version:3,storage:xo(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Dt(t)?.runtimeKey;return!n||!Dn.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:Zu}),{name:"message-queue-store"})),ef=U({properties:U({revision:ce(),session:Ho})}),Hy=(e,t)=>{if(!qe())return;const n=ef.safeParse(e);if(!n.success)return;const{session:r,revision:o}=n.data.properties;Ua.getState().applyServerSession(r,o,t)},Na="directoryTreeShowHidden",Qr="directory-show-hidden-change",Vs=()=>{if(typeof window>"u")return!0;try{const e=hn().getItem(Na);return e===null?!0:e==="true"}catch{return!0}},tf=()=>{typeof window>"u"||window.dispatchEvent(new Event(Qr))},nf=(e,t={})=>{if(!(typeof window>"u")){try{hn().setItem(Na,e?"true":"false"),tf()}catch{}t.persist!==!1&&Ce({directoryShowHidden:e})}},zy=()=>{const e=yi.c(2),[t,n]=Un.useState(Vs);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Vs())};return window.addEventListener("storage",s),window.addEventListener(Qr,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Qr,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),Un.useEffect(r,o),t},Ba="filesViewShowGitignored",Xr="files-view-show-gitignored-change",Js=()=>{if(typeof window>"u")return!1;try{return hn().getItem(Ba)==="true"}catch{return!1}},rf=()=>{typeof window>"u"||window.dispatchEvent(new Event(Xr))},of=(e,t={})=>{if(!(typeof window>"u")){try{hn().setItem(Ba,e?"true":"false"),rf()}catch{}t.persist!==!1&&Ce({filesViewShowGitignored:e})}},$y=()=>{const e=yi.c(2),[t,n]=Un.useState(Js);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(Js())};return window.addEventListener("storage",s),window.addEventListener(Xr,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Xr,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),Un.useEffect(r,o),t},sf=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},af=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},cf=e=>{const t=he.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},lf=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=af(t);return sf(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},Ha=[{name:"explore",icon:"compass-3",labelKey:"chat.draftPresets.explore.label",command:"/explore"},{name:"catch-up",icon:"history",labelKey:"chat.draftPresets.catchup.label",command:"/catch-up"},{name:"weigh",icon:"scales-3",labelKey:"chat.draftPresets.weigh.label",command:"/weigh"},{name:"plan-feature",icon:"survey",labelKey:"chat.draftPresets.plan.label",command:"/plan-feature"},{name:"craft-goal",icon:"target",labelKey:"chat.draftPresets.craftGoal.label",command:"/craft-goal"},{name:"schedule-task",icon:"calendar-schedule",labelKey:"chat.draftPresets.scheduleTask.label",command:"/schedule-task"},{name:"debug",icon:"bug",labelKey:"chat.draftPresets.debug.label",command:"/debug"},{name:"review",icon:"search-eye",labelKey:"chat.draftPresets.review.label",command:"/workspace-review"}],df=new Map(Ha.map(e=>[e.name,e])),Gy=e=>df.get(e),Wy=Ha.map(e=>({type:"command",name:e.name})),qy="terminal-box",Ky="book-open",Vy=e=>`${e.type}:${e.name}`,Jy=(e,t)=>e.type===t.type&&e.name===t.name,Yy=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},za=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=o.type==="command"||o.type==="skill"?o.type:null,i=typeof o.name=="string"?o.name.trim():"";if(!s||!i)continue;const a=`${s}:${i}`;n.has(a)||(n.add(a),t.push({type:s,name:i}))}return t},uf=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Qn=e=>e==="auto"||typeof e=="string"&&uf.includes(e),ff=[{id:"finder",label:"Finder",appName:"Finder"},{id:"terminal",label:"Terminal",appName:"Terminal"},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"vscode-insiders",label:"VS Code Insiders",appName:"Visual Studio Code - Insiders"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"kiro",label:"Kiro",appName:"Kiro"},{id:"antigravity",label:"Antigravity",appName:"Antigravity"},{id:"trae",label:"Trae",appName:"Trae"}],pf="finder",Qy=new Set(["finder","terminal"]),hf=e=>{if(typeof window>"u")return e;const t=window.__OPENCHAMBER_PLATFORM__;if(e.id==="finder"){if(t==="win32")return{...e,label:"Explorer",appName:"File Explorer"};if(t==="linux")return{...e,label:"File Manager"}}return e},Xy=e=>{if(!e)return null;const t=ff.find(n=>n.id===e)??null;return t?hf(t):null},mf=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,n},Zr=St()(nr(e=>({projectDisplayMode:"all",singleProjectId:null,setProjectDisplayMode:t=>e({projectDisplayMode:t}),setSingleProjectId:t=>e({singleProjectId:t}),sessionGroupingMode:"by-worktree",setSessionGroupingMode:t=>e({sessionGroupingMode:t}),stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,projectSortOrder:"manual",setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions})),setProjectSortOrder:t=>e({projectSortOrder:t})}),{name:"session-display-mode",version:5,migrate:mf})),yf=e=>{if(!(typeof window>"u")&&!(typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Ys="openchamber.settingsMirror.v2.index",gf="openchamber.settingsMirror.v2:",wf=5,Qs=e=>`${gf}${encodeURIComponent(e)}`,It=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},bf=(e,t)=>{const n={themeId:e.themeId,themeVariant:e.themeVariant,lightThemeId:e.lightThemeId,darkThemeId:e.darkThemeId,useSystemTheme:e.useSystemTheme,lastDirectory:e.lastDirectory,homeDirectory:e.homeDirectory,projects:e.projects,activeProjectId:e.activeProjectId,sidebarProjectDisplayMode:e.sidebarProjectDisplayMode,sidebarSessionGroupingMode:e.sidebarSessionGroupingMode,sidebarProjectSortOrder:e.sidebarProjectSortOrder,sidebarShowRecentSection:e.sidebarShowRecentSection,pinnedDirectories:e.pinnedDirectories,gitmojiEnabled:e.gitmojiEnabled,directoryShowHidden:e.directoryShowHidden,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode,openCodeUpdateToastDismissedVersion:e.openCodeUpdateToastDismissedVersion,dictationEnabled:e.dictationEnabled,sttProvider:e.sttProvider,sttServerUrl:e.sttServerUrl,sttModel:e.sttModel,sttLocalModel:e.sttLocalModel,sttLanguage:e.sttLanguage};localStorage.setItem(Qs(t),JSON.stringify(n));let r=[];try{const s=JSON.parse(localStorage.getItem(Ys)??"[]");Array.isArray(s)&&(r=s.filter(i=>typeof i=="string"))}catch{r=[]}const o=[t,...r.filter(s=>s!==t)].slice(0,wf);for(const s of r)o.includes(s)||localStorage.removeItem(Qs(s));localStorage.setItem(Ys,JSON.stringify(o))},Sf=e=>{if(!(typeof window>"u")){if(bf(e,L()),It("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),yf(e.homeDirectory)):localStorage.removeItem("homeDirectory"),Array.isArray(e.projects)&&e.projects.length>0?localStorage.setItem("projects",JSON.stringify(e.projects)):localStorage.removeItem("projects"),e.activeProjectId?localStorage.setItem("activeProjectId",e.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(e.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(e.projects)&&e.projects.length>0){const t=e.projects.filter(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0);t.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(t)):localStorage.removeItem("oc.sessions.projectCollapse")}else localStorage.removeItem("oc.sessions.projectCollapse");if(typeof e.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(e.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof e.directoryShowHidden=="boolean"?localStorage.setItem("directoryTreeShowHidden",e.directoryShowHidden?"true":"false"):localStorage.removeItem("directoryTreeShowHidden"),typeof e.filesViewShowGitignored=="boolean"?localStorage.setItem("filesViewShowGitignored",e.filesViewShowGitignored?"true":"false"):localStorage.removeItem("filesViewShowGitignored"),It("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("openchamber.pwaName",t):localStorage.removeItem("openchamber.pwaName")}else localStorage.removeItem("openchamber.pwaName");if(va(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion=="string"){const t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem("opencode-update-toast-dismissed-version",t):localStorage.removeItem("opencode-update-toast-dismissed-version")}else localStorage.removeItem("opencode-update-toast-dismissed-version");typeof e.dictationEnabled=="boolean"?localStorage.setItem("dictationEnabled",String(e.dictationEnabled)):localStorage.removeItem("dictationEnabled"),e.sttProvider==="local"||e.sttProvider==="openai-compatible"?localStorage.setItem("sttProvider",e.sttProvider):localStorage.removeItem("sttProvider"),It("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),It("sttModel",typeof e.sttModel=="string"?e.sttModel:null),It("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),It("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},eo=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let to="idle",In=null;const no=new Set,Zy=()=>to,eg=e=>(no.add(e),()=>no.delete(e)),tg=e=>{Le(e)},Le=e=>{In&&(clearTimeout(In),In=null);const t=e==="saved"?"idle":e;t!==to&&(to=t,no.forEach(n=>n())),t==="error"&&(In=setTimeout(()=>Le("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("openchamber:settings-save-state",{detail:e}))},Tf=e=>{if(!Array.isArray(e))return;const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",a=typeof o.source=="string"?o.source.trim():"",c=typeof o.subpath=="string"?o.subpath.trim():"",l=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";if(!s||!i||!a||n.has(s))continue;n.add(s);const d={id:s,label:i,source:a};c&&(d.subpath=c),l&&(d.gitIdentityId=l),t.push(d)}return t},Ef=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=typeof n=="string"?n.trim():"",s=typeof r=="string"?r.trim():"";!o||!s||(t[o]=s)}return t},kf=(e,t)=>{const n=Object.entries(e),r=Object.entries(t);return n.length!==r.length?!1:n.every(([o,s])=>t[o]===s)},_r=(e,t)=>e.length===t.length&&e.every((n,r)=>n.providerID===t[r]?.providerID&&n.modelID===t[r]?.modelID),ro=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),oo=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.length>0)))},vf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!n||!Array.isArray(r))continue;const o=oo(r);o&&o.length>0&&(t[n]=o.slice(0,5))}return Object.keys(t).length>0?t:void 0},Pf=(e,t)=>{const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>Array.isArray(t[r])&&ro(e[r],t[r]))},Af=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Mf=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&Af.test(t)?t.toLowerCase():null},Cf=e=>{if(!Array.isArray(e))return;const t=[],n=new Set,r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.path=="string"?s.path.trim():"";if(!i)continue;const a=i==="/"?i:i.replace(/\\/g,"/").replace(/\/+$/,"");if(!a)continue;const c=lu(a);if(!c||n.has(c)||r.has(a))continue;n.add(c),r.add(a);const l={id:c,path:a};if(typeof s.label=="string"&&s.label.trim().length>0&&(l.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(l.icon=s.icon.trim()),s.iconImage===null)l.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,u=typeof d.mime=="string"?d.mime.trim():"",f=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,m=d.source==="custom"||d.source==="auto"?d.source:null;u&&f>0&&m&&(l.iconImage={mime:u,updatedAt:f,source:m})}if(typeof s.color=="string"&&s.color.trim().length>0&&(l.color=s.color.trim()),s.iconBackground===null)l.iconBackground=null;else{const d=Mf(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},Df=e=>{if(!Array.isArray(e))return;const t=[],n=new Set,r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.name=="string"?s.name.trim():"",c=typeof s.hostname=="string"?s.hostname.trim().toLowerCase():"";!i||!a||!c||n.has(i)||r.has(c)||(n.add(i),r.add(c),t.push({id:i,name:a,hostname:c}))}return t},Rf=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n={};for(const[r,o]of Object.entries(t)){const s=r.trim(),i=typeof o=="string"?o.trim():"";!s||!i||(n[s]=i)}return Object.keys(n).length>0?n:void 0},Lr=(e,t)=>{if(!Array.isArray(e))return;const n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=typeof s.providerID=="string"?s.providerID.trim():"",a=typeof s.modelID=="string"?s.modelID.trim():"";if(!i||!a)continue;const c=`${i}/${a}`;if(!r.has(c)&&(r.add(c),n.push({providerID:i,modelID:a}),n.length>=t))break}return n},$a=()=>{const e=he.persist;if(e&&typeof e=="object")return e},Ga=()=>lr()?.settings??null,If=e=>{const t=he.getInitialState();return{openInAppId:pf,showReasoningTraces:t.showReasoningTraces,streamingAutoFollowEnabled:t.streamingAutoFollowEnabled,workStatusPanelEnabled:t.workStatusPanelEnabled,workStatusHiddenSections:t.workStatusHiddenSections,sessionRecapEnabled:t.sessionRecapEnabled,sessionSuggestionEnabled:t.sessionSuggestionEnabled,sessionGoalEnabled:t.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:t.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:t.sessionGoalDefaultBudget,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,autoDeleteEnabled:t.autoDeleteEnabled,autoSaveEnabled:t.autoSaveEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,followUpBehavior:jo,showDeletionDialog:t.showDeletionDialog,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,inputSpellcheckEnabled:t.inputSpellcheckEnabled,showOpenCodeUpdateNotifications:t.showOpenCodeUpdateNotifications,agentControlToolEnabled:t.agentControlToolEnabled,agentWebToolEnabled:t.agentWebToolEnabled,agentMemoryToolEnabled:t.agentMemoryToolEnabled,showToolFileIcons:t.showToolFileIcons,codeBlockLineWrap:t.codeBlockLineWrap,showTurnChangedFiles:t.showTurnChangedFiles,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,timeFormatPreference:t.timeFormatPreference,weekStartPreference:t.weekStartPreference,desktopWindowControlsPosition:t.desktopWindowControlsPosition,desktopWindowControlsStyle:t.desktopWindowControlsStyle,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,collapsibleUserMessages:t.collapsibleUserMessages,messageStreamTransport:"auto",stickyUserHeader:t.stickyUserHeader,promptNavigatorEnabled:t.promptNavigatorEnabled,wideChatLayoutEnabled:t.wideChatLayoutEnabled,showSplitAssistantMessageActions:t.showSplitAssistantMessageActions,draftStartersVisible:t.draftStartersVisible,reportUsage:t.reportUsage,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,terminalShell:t.terminalShell,terminalLoginShells:t.terminalLoginShells,editorFontSize:t.editorFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,inputBarOffset:t.inputBarOffset,shortcutOverrides:t.shortcutOverrides,mobileKeyboardMode:"resize-content",favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,gitChangesViewMode:t.gitChangesViewMode,directoryShowHidden:!0,filesViewShowGitignored:!1,dictationEnabled:!0,sttProvider:"local",sttServerUrl:"http://localhost:8001/v1",sttModel:"deepdml/faster-whisper-large-v3-turbo-ct2",sttLocalModel:"parakeet-tdt-0.6b-v2-int8",sttLanguage:"",...e}},so=e=>{const t=he.getState(),n=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,r=typeof window<"u"?window.__zustand_config_store__??null:null,o=Ua.getState();if(typeof e.workStatusPanelEnabled=="boolean"&&e.workStatusPanelEnabled!==t.workStatusPanelEnabled&&t.setWorkStatusPanelEnabled(e.workStatusPanelEnabled),Array.isArray(e.workStatusHiddenSections)){const a=ya(e.workStatusHiddenSections);a.join("\0")!==t.workStatusHiddenSections.join("\0")&&t.setWorkStatusHiddenSections(a)}if(typeof e.showReasoningTraces=="boolean"&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.streamingAutoFollowEnabled=="boolean"&&e.streamingAutoFollowEnabled!==t.streamingAutoFollowEnabled&&t.setStreamingAutoFollowEnabled(e.streamingAutoFollowEnabled),typeof e.sessionRecapEnabled=="boolean"&&e.sessionRecapEnabled!==t.sessionRecapEnabled&&t.setSessionRecapEnabled(e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&e.sessionSuggestionEnabled!==t.sessionSuggestionEnabled&&t.setSessionSuggestionEnabled(e.sessionSuggestionEnabled),typeof e.sessionGoalEnabled=="boolean"&&e.sessionGoalEnabled!==t.sessionGoalEnabled&&t.setSessionGoalEnabled(e.sessionGoalEnabled),typeof e.sessionGoalDefaultBudgetEnabled=="boolean"&&e.sessionGoalDefaultBudgetEnabled!==t.sessionGoalDefaultBudgetEnabled&&t.setSessionGoalDefaultBudgetEnabled(e.sessionGoalDefaultBudgetEnabled),typeof e.sessionGoalDefaultBudget=="number"&&Number.isFinite(e.sessionGoalDefaultBudget)&&e.sessionGoalDefaultBudget!==t.sessionGoalDefaultBudget&&t.setSessionGoalDefaultBudget(e.sessionGoalDefaultBudget),typeof e.collapsibleThinkingBlocks=="boolean"&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoSaveEnabled=="boolean"&&e.autoSaveEnabled!==t.autoSaveEnabled&&t.setAutoSaveEnabled(e.autoSaveEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)){const a=Math.max(1,Math.min(365,e.autoDeleteAfterDays));a!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(a)}(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let s=null;if(Uo(e.followUpBehavior)?s=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(s=No(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.agentControlToolEnabled=="boolean"&&e.agentControlToolEnabled!==t.agentControlToolEnabled&&t.setAgentControlToolEnabled(e.agentControlToolEnabled),typeof e.agentWebToolEnabled=="boolean"&&e.agentWebToolEnabled!==t.agentWebToolEnabled&&t.setAgentWebToolEnabled(e.agentWebToolEnabled),typeof e.agentMemoryToolEnabled=="boolean"&&e.agentMemoryToolEnabled!==t.agentMemoryToolEnabled&&t.setAgentMemoryToolEnabled(e.agentMemoryToolEnabled),typeof e.agentMemoryFeatureAvailable=="boolean"&&e.agentMemoryFeatureAvailable!==t.agentMemoryFeatureAvailable&&t.setAgentMemoryFeatureAvailable(e.agentMemoryFeatureAvailable),typeof e.showToolFileIcons=="boolean"&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap=="boolean"&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles=="boolean"&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&e.showExpandedEditTools!==t.showExpandedEditTools&&t.setShowExpandedEditTools(e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.desktopWindowControlsPosition=="string"){const a=e.desktopWindowControlsPosition==="left"?"left":e.desktopWindowControlsPosition==="right"||e.desktopWindowControlsPosition==="auto"?"right":null;a&&a!==t.desktopWindowControlsPosition&&t.setDesktopWindowControlsPosition(a)}if(typeof e.desktopWindowControlsStyle=="string"){const a=e.desktopWindowControlsStyle==="traffic-lights"?"traffic-lights":e.desktopWindowControlsStyle==="classic"?"classic":null;a&&a!==t.desktopWindowControlsStyle&&t.setDesktopWindowControlsStyle(a)}if(typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&n&&e.messageStreamTransport!==n.settingsMessageStreamTransport&&n.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.stickyUserHeader=="boolean"&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.promptNavigatorEnabled=="boolean"&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.wideChatLayoutEnabled=="boolean"&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.reportUsage=="boolean"&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){let a=za(e.draftStarters);if(e.draftStartersCraftGoalAdded!==!0&&!a.some(c=>c.type==="command"&&c.name==="craft-goal")){const c=a.findIndex(d=>d.type==="command"&&d.name==="plan-feature"),l=c>=0?c+1:a.length;a=[...a.slice(0,l),{type:"command",name:"craft-goal"},...a.slice(l)]}if(e.draftStartersScheduleTaskAdded!==!0&&!a.some(c=>c.type==="command"&&c.name==="schedule-task")){const c=a.findIndex(d=>d.type==="command"&&d.name==="craft-goal"),l=c>=0?c+1:a.length;a=[...a.slice(0,l),{type:"command",name:"schedule-task"},...a.slice(l)]}JSON.stringify(t.globalDraftStarters)!==JSON.stringify(a)&&t.setGlobalDraftStarters(a),(e.draftStartersCraftGoalAdded!==!0||e.draftStartersScheduleTaskAdded!==!0)&&(e.draftStarters=a,e.draftStartersCraftGoalAdded=!0,e.draftStartersScheduleTaskAdded=!0)}else e.draftStartersCraftGoalAdded!==!0&&(e.draftStartersCraftGoalAdded=!0),e.draftStartersScheduleTaskAdded!==!0&&(e.draftStartersScheduleTaskAdded=!0);if(typeof e.draftStartersVisible=="boolean"&&e.draftStartersVisible!==t.draftStartersVisible&&t.setDraftStartersVisible(e.draftStartersVisible),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),Qn(e.terminalShell)&&e.terminalShell!==t.terminalShell&&t.setTerminalShell(e.terminalShell),Array.isArray(e.terminalLoginShells)&&(e.terminalLoginShells.length!==t.terminalLoginShells.length||e.terminalLoginShells.some((a,c)=>a!==t.terminalLoginShells[c]))&&t.setTerminalLoginShells(e.terminalLoginShells),typeof e.editorFontSize=="number"&&Number.isFinite(e.editorFontSize)&&e.editorFontSize!==t.editorFontSize&&t.setEditorFontSize(e.editorFontSize),Ea(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),ka(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&&!kf(e.shortcutOverrides,t.shortcutOverrides)&&he.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode=="string"){const a=dr(e.mobileKeyboardMode,t.mobileKeyboardMode);a!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(a)}if(r&&n){const a={};typeof e.dictationEnabled=="boolean"&&e.dictationEnabled!==n.dictationEnabled&&(a.dictationEnabled=e.dictationEnabled),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&e.sttProvider!==n.sttProvider&&(a.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&e.sttServerUrl!==n.sttServerUrl&&(a.sttServerUrl=e.sttServerUrl),typeof e.sttModel=="string"&&e.sttModel!==n.sttModel&&(a.sttModel=e.sttModel),typeof e.sttLocalModel=="string"&&e.sttLocalModel!==n.sttLocalModel&&(a.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage=="string"&&e.sttLanguage!==n.sttLanguage&&(a.sttLanguage=e.sttLanguage),Object.keys(a).length>0&&r.setState(a)}if(Array.isArray(e.favoriteModels)){const a=t.favoriteModels,c=e.favoriteModels;_r(a,c)||he.setState({favoriteModels:c})}if(Array.isArray(e.hiddenModels)){const a=t.hiddenModels,c=e.hiddenModels;_r(a,c)||he.setState({hiddenModels:c})}if(Array.isArray(e.collapsedModelProviders)){const a=t.collapsedModelProviders,c=e.collapsedModelProviders;ro(a,c)||he.setState({collapsedModelProviders:c})}if(Array.isArray(e.recentModels)){const a=t.recentModels,c=e.recentModels;_r(a,c)||he.setState({recentModels:c})}if(Array.isArray(e.recentAgents)){const a=t.recentAgents,c=e.recentAgents;ro(a,c)||he.setState({recentAgents:c})}if(e.recentEfforts&&typeof e.recentEfforts=="object"){const a=t.recentEfforts,c=e.recentEfforts;Pf(a,c)||he.setState({recentEfforts:c})}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"&&nf(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored=="boolean"&&of(e.filesViewShowGitignored,{persist:!1});const i={};(e.sidebarProjectDisplayMode==="all"||e.sidebarProjectDisplayMode==="single")&&(i.projectDisplayMode=e.sidebarProjectDisplayMode),(e.sidebarSessionGroupingMode==="by-worktree"||e.sidebarSessionGroupingMode==="flat")&&(i.sessionGroupingMode=e.sidebarSessionGroupingMode),(e.sidebarProjectSortOrder==="manual"||e.sidebarProjectSortOrder==="a-z"||e.sidebarProjectSortOrder==="z-a"||e.sidebarProjectSortOrder==="date-added"||e.sidebarProjectSortOrder==="recent")&&(i.projectSortOrder=e.sidebarProjectSortOrder),typeof e.sidebarShowRecentSection=="boolean"&&(i.showRecentSection=e.sidebarShowRecentSection),Object.keys(i).length>0&&Zr.setState(i)},io=e=>{if(!e||typeof e!="object")return null;const t=e,n={};if(typeof t.themeId=="string"&&t.themeId.length>0&&(n.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(n.useSystemTheme=t.useSystemTheme),typeof t.themeVariant=="string"&&(t.themeVariant==="light"||t.themeVariant==="dark")&&(n.themeVariant=t.themeVariant),typeof t.lightThemeId=="string"&&t.lightThemeId.length>0&&(n.lightThemeId=t.lightThemeId),typeof t.darkThemeId=="string"&&t.darkThemeId.length>0&&(n.darkThemeId=t.darkThemeId),typeof t.lastDirectory=="string"&&t.lastDirectory.length>0&&(n.lastDirectory=t.lastDirectory),typeof t.homeDirectory=="string"&&t.homeDirectory.length>0&&(n.homeDirectory=t.homeDirectory),typeof t.opencodeBinary=="string"){const p=t.opencodeBinary.trim();n.opencodeBinary=p.length>0?p:void 0}typeof t.desktopLanAccessEnabled=="boolean"&&(n.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled=="boolean"&&(n.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled=="boolean"&&(n.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled),typeof t.desktopMacMenuBarEnabled=="boolean"&&(n.desktopMacMenuBarEnabled=t.desktopMacMenuBarEnabled);const r=Cf(t.projects);if(r&&(n.projects=r),typeof t.activeProjectId=="string"&&t.activeProjectId.length>0&&(n.activeProjectId=t.activeProjectId),(t.sidebarProjectDisplayMode==="all"||t.sidebarProjectDisplayMode==="single")&&(n.sidebarProjectDisplayMode=t.sidebarProjectDisplayMode),(t.sidebarSessionGroupingMode==="by-worktree"||t.sidebarSessionGroupingMode==="flat")&&(n.sidebarSessionGroupingMode=t.sidebarSessionGroupingMode),(t.sidebarProjectSortOrder==="manual"||t.sidebarProjectSortOrder==="a-z"||t.sidebarProjectSortOrder==="z-a"||t.sidebarProjectSortOrder==="date-added"||t.sidebarProjectSortOrder==="recent")&&(n.sidebarProjectSortOrder=t.sidebarProjectSortOrder),typeof t.sidebarShowRecentSection=="boolean"&&(n.sidebarShowRecentSection=t.sidebarShowRecentSection),Array.isArray(t.securityScopedBookmarks)&&(n.securityScopedBookmarks=t.securityScopedBookmarks.filter(p=>typeof p=="string"&&p.length>0)),Array.isArray(t.pinnedDirectories)&&(n.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(p=>typeof p=="string"&&p.length>0)))),Array.isArray(t.draftStarters)&&(n.draftStarters=za(t.draftStarters)),typeof t.draftStartersVisible=="boolean"&&(n.draftStartersVisible=t.draftStartersVisible),typeof t.draftStartersCraftGoalAdded=="boolean"&&(n.draftStartersCraftGoalAdded=t.draftStartersCraftGoalAdded),typeof t.draftStartersScheduleTaskAdded=="boolean"&&(n.draftStartersScheduleTaskAdded=t.draftStartersScheduleTaskAdded),typeof t.workStatusPanelEnabled=="boolean"&&(n.workStatusPanelEnabled=t.workStatusPanelEnabled),Array.isArray(t.workStatusHiddenSections)&&(n.workStatusHiddenSections=ya(t.workStatusHiddenSections)),typeof t.showReasoningTraces=="boolean"&&(n.showReasoningTraces=t.showReasoningTraces),typeof t.streamingAutoFollowEnabled=="boolean"&&(n.streamingAutoFollowEnabled=t.streamingAutoFollowEnabled),typeof t.sessionRecapEnabled=="boolean"&&(n.sessionRecapEnabled=t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&(n.sessionSuggestionEnabled=t.sessionSuggestionEnabled),typeof t.sessionGoalEnabled=="boolean"&&(n.sessionGoalEnabled=t.sessionGoalEnabled),typeof t.sessionGoalDefaultBudgetEnabled=="boolean"&&(n.sessionGoalDefaultBudgetEnabled=t.sessionGoalDefaultBudgetEnabled),typeof t.sessionGoalDefaultBudget=="number"&&Number.isFinite(t.sessionGoalDefaultBudget)&&t.sessionGoalDefaultBudget>0&&(n.sessionGoalDefaultBudget=Math.floor(t.sessionGoalDefaultBudget)),typeof t.collapsibleThinkingBlocks=="boolean"&&(n.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&(n.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoSaveEnabled=="boolean"&&(n.autoSaveEnabled=t.autoSaveEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)&&(n.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&(n.sessionRetentionAction=t.sessionRetentionAction),typeof t.tunnelProvider=="string"){const p=t.tunnelProvider.trim().toLowerCase();p.length>0&&(n.tunnelProvider=p)}if(typeof t.tunnelMode=="string"){const p=t.tunnelMode.trim().toLowerCase();(p==="quick"||p==="managed-remote"||p==="managed-local")&&(n.tunnelMode=p)}if(t.tunnelBootstrapTtlMs===null?n.tunnelBootstrapTtlMs=null:typeof t.tunnelBootstrapTtlMs=="number"&&Number.isFinite(t.tunnelBootstrapTtlMs)&&(n.tunnelBootstrapTtlMs=t.tunnelBootstrapTtlMs),typeof t.tunnelSessionTtlMs=="number"&&Number.isFinite(t.tunnelSessionTtlMs)&&(n.tunnelSessionTtlMs=t.tunnelSessionTtlMs),t.managedLocalTunnelConfigPath===null)n.managedLocalTunnelConfigPath=null;else if(typeof t.managedLocalTunnelConfigPath=="string"){const p=t.managedLocalTunnelConfigPath.trim();n.managedLocalTunnelConfigPath=p.length>0?p:null}typeof t.managedRemoteTunnelHostname=="string"&&(n.managedRemoteTunnelHostname=t.managedRemoteTunnelHostname.trim()),t.managedRemoteTunnelToken===null?n.managedRemoteTunnelToken=null:typeof t.managedRemoteTunnelToken=="string"&&(n.managedRemoteTunnelToken=t.managedRemoteTunnelToken.trim());const o=Df(t.managedRemoteTunnelPresets);if(o&&(n.managedRemoteTunnelPresets=o),typeof t.managedRemoteTunnelSelectedPresetId=="string"){const p=t.managedRemoteTunnelSelectedPresetId.trim();n.managedRemoteTunnelSelectedPresetId=p.length>0?p:void 0}const s=Rf(t.managedRemoteTunnelPresetTokens);if(s&&(n.managedRemoteTunnelPresetTokens=s),typeof t.defaultModel=="string"&&t.defaultModel.length>0&&(n.defaultModel=t.defaultModel),typeof t.defaultVariant=="string"&&t.defaultVariant.length>0&&(n.defaultVariant=t.defaultVariant),typeof t.defaultAgent=="string"&&t.defaultAgent.length>0&&(n.defaultAgent=t.defaultAgent),typeof t.smallModelUseDefault=="boolean"&&(n.smallModelUseDefault=t.smallModelUseDefault),typeof t.smallModelOverride=="string"&&t.smallModelOverride.length>0&&(n.smallModelOverride=t.smallModelOverride),typeof t.walkthroughModelOverride=="string"&&t.walkthroughModelOverride.length>0&&(n.walkthroughModelOverride=t.walkthroughModelOverride),typeof t.autoCreateWorktree=="boolean"&&(n.autoCreateWorktree=t.autoCreateWorktree),typeof t.gitmojiEnabled=="boolean"&&(n.gitmojiEnabled=t.gitmojiEnabled),Uo(t.followUpBehavior)?n.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(n.followUpBehavior=No(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog=="boolean"&&(n.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&(n.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&(n.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&(n.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&(n.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&(n.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&(n.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"){const p=t.notificationTemplates,g=C=>{const Q=p[C];if(!Q||typeof Q!="object")return;const we=Q,Wt=typeof we.title=="string"?we.title:"",fr=typeof we.message=="string"?we.message:"";return{title:Wt,message:fr}},y=g("completion"),S=g("error"),E=g("question"),P=g("subtask");(y||S||E||P)&&(n.notificationTemplates={completion:y??{title:"Task Complete",message:"Your task has finished."},error:S??{title:"Error Occurred",message:"An error occurred while processing your task."},question:E??{title:"Input Needed",message:"Please provide input to continue."},subtask:P??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof t.summarizeLastMessage=="boolean"&&(n.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&(n.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&(n.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&(n.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),(t.usageDisplayMode==="usage"||t.usageDisplayMode==="remaining")&&(n.usageDisplayMode=t.usageDisplayMode),Array.isArray(t.usageDropdownProviders)&&(n.usageDropdownProviders=t.usageDropdownProviders.filter(p=>typeof p=="string"&&p.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels=="object"){const p={};for(const[g,y]of Object.entries(t.usageSelectedModels))Array.isArray(y)&&(p[g]=y.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(n.usageSelectedModels=p)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies=="object"){const p={};for(const[g,y]of Object.entries(t.usageCollapsedFamilies))Array.isArray(y)&&(p[g]=y.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(n.usageCollapsedFamilies=p)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies=="object"){const p={};for(const[g,y]of Object.entries(t.usageExpandedFamilies))Array.isArray(y)&&(p[g]=y.filter(S=>typeof S=="string"));Object.keys(p).length>0&&(n.usageExpandedFamilies=p)}if(t.usageModelGroups&&typeof t.usageModelGroups=="object"){const p={};for(const[g,y]of Object.entries(t.usageModelGroups))if(y&&typeof y=="object"){const S=y,E={};Array.isArray(S.customGroups)&&(E.customGroups=S.customGroups.filter(P=>P&&typeof P=="object").map(P=>({id:String(P.id??""),label:String(P.label??""),models:Array.isArray(P.models)?P.models.filter(C=>typeof C=="string"):[],order:typeof P.order=="number"?P.order:0}))),S.modelAssignments&&typeof S.modelAssignments=="object"&&(E.modelAssignments=Object.fromEntries(Object.entries(S.modelAssignments).filter(([,P])=>typeof P=="string").map(([P,C])=>[P,String(C)]))),S.renamedGroups&&typeof S.renamedGroups=="object"&&(E.renamedGroups=Object.fromEntries(Object.entries(S.renamedGroups).filter(([,P])=>typeof P=="string").map(([P,C])=>[P,String(C)]))),Object.keys(E).length>0&&(p[g]=E)}Object.keys(p).length>0&&(n.usageModelGroups=p)}typeof t.inputSpellcheckEnabled=="boolean"&&(n.inputSpellcheckEnabled=t.inputSpellcheckEnabled),typeof t.showOpenCodeUpdateNotifications=="boolean"&&(n.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.agentControlToolEnabled=="boolean"&&(n.agentControlToolEnabled=t.agentControlToolEnabled),typeof t.agentWebToolEnabled=="boolean"&&(n.agentWebToolEnabled=t.agentWebToolEnabled),typeof t.agentMemoryToolEnabled=="boolean"&&(n.agentMemoryToolEnabled=t.agentMemoryToolEnabled),typeof t.openCodeUpdateToastDismissedVersion=="string"&&(n.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons=="boolean"&&(n.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap=="boolean"&&(n.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles=="boolean"&&(n.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&(n.showExpandedBashTools=t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&(n.showExpandedEditTools=t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&(n.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&(n.weekStartPreference=t.weekStartPreference),typeof t.desktopWindowControlsPosition=="string"&&(t.desktopWindowControlsPosition==="left"?n.desktopWindowControlsPosition="left":(t.desktopWindowControlsPosition==="right"||t.desktopWindowControlsPosition==="auto")&&(n.desktopWindowControlsPosition="right")),typeof t.desktopWindowControlsStyle=="string"&&(t.desktopWindowControlsStyle==="classic"||t.desktopWindowControlsStyle==="traffic-lights")&&(n.desktopWindowControlsStyle=t.desktopWindowControlsStyle),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&(n.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&(n.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&(n.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&(n.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&(n.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&(n.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader=="boolean"&&(n.stickyUserHeader=t.stickyUserHeader),typeof t.promptNavigatorEnabled=="boolean"&&(n.promptNavigatorEnabled=t.promptNavigatorEnabled),typeof t.wideChatLayoutEnabled=="boolean"&&(n.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&(n.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&(n.fontSize=t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&(n.terminalFontSize=t.terminalFontSize),Qn(t.terminalShell)&&(n.terminalShell=t.terminalShell),Array.isArray(t.terminalLoginShells)&&(n.terminalLoginShells=[...new Set(t.terminalLoginShells.filter(Qn))]),typeof t.editorFontSize=="number"&&Number.isFinite(t.editorFontSize)&&(n.editorFontSize=t.editorFontSize),Ea(t.uiFont)&&(n.uiFont=t.uiFont),ka(t.monoFont)&&(n.monoFont=t.monoFont),typeof t.padding=="number"&&Number.isFinite(t.padding)&&(n.padding=t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&(n.cornerRadius=t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&(n.inputBarOffset=t.inputBarOffset);const i=Ef(t.shortcutOverrides);i&&(n.shortcutOverrides=i),typeof t.mobileKeyboardMode=="string"&&(t.mobileKeyboardMode==="native"||t.mobileKeyboardMode==="resize-content")&&(n.mobileKeyboardMode=t.mobileKeyboardMode);const a=Lr(t.favoriteModels,64);a&&(n.favoriteModels=a);const c=Lr(t.hiddenModels,1024);c&&(n.hiddenModels=c);const l=oo(t.collapsedModelProviders);l&&(n.collapsedModelProviders=l);const d=Lr(t.recentModels,16);d&&(n.recentModels=d);const u=oo(t.recentAgents);u&&(n.recentAgents=u);const f=vf(t.recentEfforts);if(f&&(n.recentEfforts=f),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&(n.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&(n.gitChangesViewMode=t.gitChangesViewMode),typeof t.directoryShowHidden=="boolean"&&(n.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored=="boolean"&&(n.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&(n.openInAppId=t.openInAppId),typeof t.pwaAppName=="string"){const p=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);n.pwaAppName=p.length>0?p:""}const m=Tf(t.skillCatalogs);return m&&(n.skillCatalogs=m),typeof t.reportUsage=="boolean"&&(n.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt=="string"&&(n.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled=="boolean"&&(n.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset=="string"&&(t.responseStylePreset==="concise"||t.responseStylePreset==="detailed"||t.responseStylePreset==="mentor"||t.responseStylePreset==="pushback"||t.responseStylePreset==="noFiller"||t.responseStylePreset==="matchEnergy"||t.responseStylePreset==="warmPeer"||t.responseStylePreset==="custom")&&(n.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions=="string"&&(n.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled=="boolean"&&(n.dictationEnabled=t.dictationEnabled),t.sttProvider==="local"||t.sttProvider==="openai-compatible"?n.sttProvider=t.sttProvider:t.sttProvider==="server"?n.sttProvider="openai-compatible":(t.sttProvider==="browser"||t.sttProvider==="wasm")&&(n.sttProvider="local"),typeof t.sttServerUrl=="string"&&(n.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel=="string"&&(n.sttModel=t.sttModel.trim()),typeof t.sttLocalModel=="string"&&(n.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage=="string"&&(n.sttLanguage=t.sttLanguage.trim()),n};class Of{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(o=>o.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const o of this.mutations)o.revision<=n.revision||(r={...r,...o.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let zo=0,Fe=null,ft=null,nt=null,mt=null,ke=null,ao=[],Xs=!1,Xn=0;const Re=new Of,xf=2e3,_f=200,$o=()=>({runtimeKey:L(),generation:zo}),co=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,Y=e=>e.generation===zo&&e.runtimeKey===L(),Jt=()=>{nt&&(ke&&(clearTimeout(ke),ke=null),Zn({keepalive:!0}))},Go=()=>{if(!(Xs||typeof window>"u")){Xs=!0,Wl(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ke&&clearTimeout(ke),nt&&Zn())}),na(e=>{e.runtimeKey!==e.previousRuntimeKey&&(zo+=1,Re.reset(),Xn=0,Fe=null,ft=null)});try{window.addEventListener("pagehide",Jt,{capture:!0}),window.addEventListener("beforeunload",Jt,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Jt()}),document.addEventListener("freeze",Jt)),Pa()&&wo(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||Jt()})).catch(()=>{})}catch{}}},Lf=async(e=$o())=>{if(Go(),Fe&&co(Fe.context,e)&&Date.now()-Fe.at<xf)return Fe.value;if(ft&&co(ft.context,e))return ft.promise;const t={context:e,promise:(async()=>{const n=Ga();if(n)try{const r=await n.load();if(!Y(e))return null;const o=io(r.settings);return Fe={value:o,at:Date.now(),context:e},o}catch(r){if(!Y(e))return null;console.warn("Failed to load shared settings from runtime settings API:",r)}if(!Y(e))return null;try{const r=await h("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!Y(e)||!r.ok)return null;const o=await r.json().catch(()=>null);if(!Y(e))return null;const s=io(o);return Fe={value:s,at:Date.now(),context:e},s}catch(r){return Y(e)&&console.warn("Failed to load shared settings from server:",r),null}})()};return ft=t,t.promise.finally(()=>{ft===t&&(ft=null)}),t.promise},ng=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Go();const r=$o(),o=Re.begin(),s=[$a(),Zr.persist],i=d=>!d?.hasHydrated||d.hasHydrated()||!d.onFinishHydration?Promise.resolve():new Promise(u=>{let f=!1;const m=()=>{f||(f=!0,u())},p=d.onFinishHydration(()=>{p?.(),m()});d.hasHydrated?.()&&m()}),a=()=>Promise.all(s.map(i)).then(()=>{}),c=d=>!nt||!mt||!Y(mt)?d:{...d,...nt},l=async d=>{if(!Y(r))return;let u=c(Re.reconcile(d,o));if(await a(),!Y(r))return;u=c(Re.reconcile(d,o));const f=u.draftStartersCraftGoalAdded!==!0||u.draftStartersScheduleTaskAdded!==!0,m=typeof u.autoSaveEnabled!="boolean",p=u.sidebarProjectDisplayMode===void 0,g=u.sidebarSessionGroupingMode===void 0,y=u.sidebarProjectSortOrder===void 0,S=u.sidebarShowRecentSection===void 0,E=If(u);try{Sf(u)}catch(Q){console.warn("persistToLocalStorage failed:",Q)}m&&(E.autoSaveEnabled=he.getState().autoSaveEnabled);const P=Zr.getState();p&&(E.sidebarProjectDisplayMode=P.projectDisplayMode),g&&(E.sidebarSessionGroupingMode=P.sessionGroupingMode),y&&(E.sidebarProjectSortOrder=P.projectSortOrder),S&&(E.sidebarShowRecentSection=P.showRecentSection),u.draftStarters===void 0&&he.setState({globalDraftStarters:null});try{so(E)}catch(Q){console.warn("applyDesktopUiPreferences failed:",Q)}const C={};f&&(E.draftStarters&&(C.draftStarters=E.draftStarters),C.draftStartersCraftGoalAdded=!0,C.draftStartersScheduleTaskAdded=!0),m&&(C.autoSaveEnabled=E.autoSaveEnabled),p&&(C.sidebarProjectDisplayMode=E.sidebarProjectDisplayMode),g&&(C.sidebarSessionGroupingMode=E.sidebarSessionGroupingMode),y&&(C.sidebarProjectSortOrder=E.sidebarProjectSortOrder),S&&(C.sidebarShowRecentSection=E.sidebarShowRecentSection),!(Object.keys(C).length>0&&(await Ce(C),!Y(r)))&&eo(E,t,n)};try{const d=await Lf(r);d&&Y(r)&&await l(d)}catch(d){console.warn("Failed to synchronise settings:",d)}finally{Re.finish(o)}};async function Zn({keepalive:e=!1}={}){const t=nt,n=mt,r=Xn,o=ao;nt=null,mt=null,Xn=0,ke=null,ao=[];try{if(!t||!n||Object.keys(t).length===0||!Y(n)){Le("saved");return}const s=Re.begin(r);try{const i=Ga();if(i)try{const a=await i.save(t);if(!Y(n))return;if(a){const c=Re.reconcile(a,s);so(c),eo(c,!1),Fe=null}Le(a?"saved":"error");return}catch(a){if(!Y(n))return;console.warn("Failed to update settings via runtime settings API:",a)}if(!Y(n))return;try{const a=await h("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t),keepalive:e});if(!Y(n))return;if(!a.ok){console.warn("Failed to update shared settings via API:",a.status,a.statusText),Le("error");return}const c=io(await a.json().catch(()=>null));if(!Y(n))return;if(c){const l=Re.reconcile(c,s);so(l),eo(l,!1),Le("saved"),Fe=null}else Le("error")}catch(a){Y(n)&&(console.warn("Failed to update shared settings via API:",a),Le("error"))}}finally{Re.finish(s)}}finally{o.forEach(s=>s())}}const Ce=async e=>{if(typeof window>"u")return;Go();const t=$o();mt&&!co(mt,t)&&(ke&&clearTimeout(ke),Zn()),nt={...nt??{},...e},mt=t,Xn=Re.record(e),Le("saving"),ke&&clearTimeout(ke);const n=new Promise(r=>{ao.push(r)});return ke=setTimeout(()=>{Zn()},_f),n},rg=async()=>{if(typeof window>"u")return;const e=$a();try{const t=await lf();if(!t)return;const n=()=>cf(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){const r=e.onFinishHydration(()=>{r?.(),n()})}}catch(t){console.warn("Failed to load appearance preferences:",t)}},Ff=3e4,jf=40,Uf=60,Nf=(e,t,n,r,o,s,i)=>{const a=t.trim(),c=n.trim().toLowerCase();return JSON.stringify([e,a,c,r,o,s,i])},Zs=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},Bf=St()(fn((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,o=Uf,s){if(!n||n.trim().length===0)return[];const i=n.trim(),a=L(),c=typeof r=="string"?r.trim():"",l=!!s?.includeHidden,d=s?.respectGitignore??!0,u=s?.type==="directory"?"directory":"file",f=Nf(a,i,c,o,l,d,u),m=Date.now(),p=t().cache[f];if(p&&m-p.timestamp<Ff)return p.files;const g=t().inFlight[f];if(g)return g;const y=De.searchFiles(c,{directory:i,limit:o,includeHidden:l,respectGitignore:d,dirs:u!=="file",type:u}).then(S=>(e(E=>{if(E.inFlight[f]!==y)return E;const P={...E.cache,[f]:{files:S,timestamp:Date.now()}},C=E.cacheKeys.filter(Q=>Q!==f);for(C.push(f);C.length>jf;){const Q=C.shift();Q&&delete P[Q]}return{cache:P,cacheKeys:C}}),S)).finally(()=>{e(S=>{if(S.inFlight[f]!==y)return S;const E={...S.inFlight};return delete E[f],{inFlight:E}})});return e(S=>({inFlight:{...S.inFlight,[f]:y}})),y},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(o=>{const s={...o.cache},i=o.cacheKeys.filter(l=>Zs(l,r)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!Zs(l,r)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),Hf=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},lo="openchamber_stream_perf",zf=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(lo)==="1"}catch{return!1}};let kt=zf();const ei=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),$f=()=>{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},Wa=e=>Array.from(e.entries()).map(([t,n])=>({metric:t,count:n.count,avg:n.count>0?Number((n.total/n.count).toFixed(3)):0,max:Number(n.max.toFixed(3)),total:Number(n.total.toFixed(3)),last:Number(n.last.toFixed(3))})).sort((t,n)=>n.total-t.total||n.count-t.count),Wo=(e,t)=>{const n=$f();if(!n)return;const r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},Gf=e=>{if(kt=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(lo,"1"),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(lo),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()}))},qf=()=>{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:Wa(e.counters)}},og=()=>{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,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:Wa(e.counters)}},sg=(e,t=1)=>{Wo(e,t)},ig=(e,t)=>{Wo(e,t)},ag=e=>{!kt||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`openchamber.${e}`)},cg=(e,t)=>{if(!kt)return t();const n=ei();try{return t()}finally{Wo(e,ei()-n)}};typeof window<"u"&&(window.__openchamberStreamPerformance={setEnabled:Gf,reset:Wf,getSnapshot:qf});var Kf={};let ve=null,ti=0;const Ee=hn(),ni=Ee.getItem("lastDirectory"),Vf=typeof ni=="string"&&ni.length>0,On=e=>{try{Bf.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},Ht=e=>{const t=e.trim();if(!t)return t;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(r,o)=>o.toUpperCase()+":");return n.length>1?n.replace(/\/+$/,""):n},Jf=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},jn=(e,t)=>{const n=Jf(e,t);return Ht(n)},Yf=()=>{const e=Ee.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Ht(e);return t.length>0?t:null},Qf=()=>{const e=Ee.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=Ht(e);return t.length>0?t:null},Xf=()=>{if(typeof process>"u")return null;const e=Kf,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=Ht(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=Ht(n);return r.length>0?r:null}return null},er=()=>{if(typeof window<"u"){if(ve)return ve;const t=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(t&&t.length>0)return ve=t,Ee.setItem("homeDirectory",t),t;const n=Yf();if(n&&!Ie())return ve=n,n}const e=Xf();return e||"/"},Zf=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/");if(n.length>1){const r=n.replace(/\/+$/,"");if(r&&r.length>0)return r==="/"?null:r}return n==="/"||n.length===0?null:n},ep=e=>(ve=e,typeof window<"u"&&Ee.setItem("homeDirectory",e),Ce({homeDirectory:e}),e),uo=async()=>{const e=r=>{const o=Zf(r);return o?ep(o):null};try{const r=await De.getFilesystemHome(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await De.getSystemInfo(),o=e(r?.homeDirectory);if(o)return o}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await ia(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=er(),n=e(t);return n||t},tp=()=>{if(!Ie())return null;const e=sa()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=Ht(e);return t.length>0?t:null},un=tp()||er(),tr=(()=>{const e=Qf();return e&&!Ie()?jn(e,un):un})();tr&&De.setDirectory(tr);const np=!!(un&&un!=="/"),fo=St()(fn((e,t)=>({currentDirectory:tr,directoryHistory:[tr],historyIndex:0,homeDirectory:un,hasPersistedDirectory:Vf,isHomeReady:np,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const o=ve||t().homeDirectory||Ee.getItem("homeDirectory"),s=jn(n,o);Hf()&&console.log("[DirectoryStore] setDirectory called with path:",s),De.setDirectory(s),On(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return Ee.setItem("lastDirectory",s),Ce({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,o=n.directoryHistory[r];De.setDirectory(o),On(),Ee.setItem("lastDirectory",o),Ce({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,o=n.directoryHistory[r];De.setDirectory(o),On(),Ee.setItem("lastDirectory",o),Ce({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),o=ve||t().homeDirectory||er();if(n===o||n==="/")return;const s=n.endsWith("/")?n.slice(0,-1):n,i=s.lastIndexOf("/");if(i===-1){const a=ve||er();r(a)}else r(i===0?"/":s.substring(0,i))},goHome:async()=>{const n=ve||t().homeDirectory||await uo();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),o=n;ve=o;const s=r.homeDirectory!==o,i=Ee.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!s&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof o=="string"&&o!==""&&o!=="/",d=r.currentDirectory?jn(r.currentDirectory,o):r.currentDirectory,u=r.directoryHistory.map(g=>jn(g,o)),f=u.some((g,y)=>g!==r.directoryHistory[y]),m=!!(d&&d!==r.currentDirectory),p={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(p.currentDirectory=o,p.directoryHistory=[o],p.historyIndex=0,p.isSwitchingDirectory=!1):(m||f)&&(p.currentDirectory=d,p.directoryHistory=u,p.historyIndex=Math.min(r.historyIndex,u.length-1),p.isSwitchingDirectory=!1),e(()=>p),(c||m)&&l){const g=c?o:d;De.setDirectory(g),On(),Ee.setItem("lastDirectory",g),Ce({lastDirectory:g})}Ce({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(uo().then(e=>{fo.getState().synchronizeHomeDirectory(e)}),na(()=>{ve=null;const e=++ti;uo().then(t=>{e===ti&&fo.getState().synchronizeHomeDirectory(t)})}));const rp=(e,t)=>{const n=or();return n?n.openWebSocket(Kc(e),t):nl(new WebSocket(e))},qa=1,ri=512*1024,op=0,Ot=1,sp=15e3,qo=new TextEncoder,Ka=new TextDecoder,ip=e=>{const t=qo.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=qa,n.set(t,1),n},ap=async e=>{let t;if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(e instanceof Uint8Array)t=e;else if(typeof Blob<"u"&&e instanceof Blob)t=new Uint8Array(await e.arrayBuffer());else if(typeof e=="string")t=qo.encode(e);else return null;t[0]===qa&&(t=t.subarray(1));try{return JSON.parse(Ka.decode(t))}catch{return null}},ur=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},cp=e=>{const t=qo.encode(e);if(t.byteLength<=ri)return e;let n=t.byteLength-ri;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return Ka.decode(t.subarray(n))};class Va{constructor(t={refreshAuth:ar,openSocket:()=>rp(le().websocket("/api/terminal/ws")),clearUrlAuthToken:pn}){this.dependencies=t}socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},o=this.subscribers.get(t)??new Set,s=o.size===0;o.add(r),this.subscribers.set(t,o);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data:i.history,status:i.status,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend}));const a=this.socket?.readyState===Ot;return this.ensureConnected().then(()=>{const c=this.subscribers.get(t);s&&a&&c===o&&c.size>0&&this.send({t:"attach",v:3,s:t})}).catch(c=>{o.has(r)&&(n.onError?.(c,!1),this.scheduleReconnect())}),()=>{const c=this.subscribers.get(t);if(c?.delete(r),c?.size===0&&(this.subscribers.delete(t),this.projections.delete(t),this.send({t:"detach",v:3,s:t})),this.subscribers.size===0){if(this.cancelReconnect(),this.failures=0,this.socket?.readyState===Ot){this.scheduleIdleClose();return}this.generation+=1,this.opening=null,this.closeSocket()}}}async write(t,n){if(n&&(await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n})&&(this.closeSocket(),await this.ensureConnected(),!this.send({t:"write",v:3,s:t,d:n}))))throw new Error("Terminal connection is unavailable")}dispose(){this.disposed=!0,this.generation+=1,this.opening=null,this.subscribers.clear(),this.projections.clear(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.cancelIdleClose(),this.wakeCleanup?.(),this.wakeCleanup=null,this.closeSocket()}forget(t){this.projections.delete(t)}async ensureConnected(){if(this.disposed)throw new Error("Terminal runtime changed");if(this.socket?.readyState===Ot)return;if(this.opening)return await this.opening,this.socket?.readyState===Ot?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,o)=>{let s=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,d=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},u=m=>{s||(s=!0,clearTimeout(f),m?o(m):r())},f=setTimeout(()=>{d(),c?.close(),u(new Error("Terminal connection timed out"))},1e4);try{const m=this.dependencies.openSocket();c=m,m.binaryType="arraybuffer",this.socket=m,m.onopen=()=>{if(!l()){m.close(),u(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const p of this.subscribers.keys())this.send({t:"attach",v:3,s:p});this.startKeepalive(),u()},m.onmessage=p=>{this.handleMessage(p.data)},m.onerror=()=>{const p=l();p&&d(),u(new Error("Terminal WebSocket failed")),p&&this.subscribers.size>0&&this.scheduleReconnect()},m.onclose=()=>{const p=l();p&&(this.stopKeepalive(),d()),this.socket===m&&(this.socket=null),u(new Error("Terminal WebSocket closed")),p&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(m){u(m instanceof Error?m:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}async handleMessage(t){const n=await ap(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const s=new Error(typeof n.message=="string"?n.message:"Terminal error");typeof n.code=="string"&&(s.code=n.code);const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(s,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const s={sequence:typeof n.q=="number"?n.q:0,history:typeof n.history=="string"?n.history:"",status:n.status,exitCode:typeof n.exitCode=="number"?n.exitCode:void 0,signal:typeof n.signal=="number"?n.signal:null,runtime:n.runtime,ptyBackend:typeof n.ptyBackend=="string"?n.ptyBackend:void 0};this.projections.set(n.s,s);for(const i of r)i.lastSequence=s.sequence,i.handlers.onEvent({type:"snapshot",sequence:s.sequence,data:s.history,status:s.status,exitCode:s.exitCode,signal:s.signal,runtime:s.runtime,ptyBackend:s.ptyBackend});return}if(typeof n.q!="number")return;const o=this.projections.get(n.s);o&&n.q>o.sequence&&(n.t==="output"?this.projections.set(n.s,{...o,sequence:n.q,history:cp(o.history+(typeof n.r=="string"?n.r:typeof n.d=="string"?n.d:""))}):n.t==="exit"?this.projections.set(n.s,{...o,sequence:n.q,status:"exited",exitCode:typeof n.exitCode=="number"?n.exitCode:void 0,signal:typeof n.signal=="number"?n.signal:null}):n.t==="restarted"&&this.projections.set(n.s,{...o,sequence:n.q,history:typeof n.history=="string"?n.history:"",status:"running",exitCode:void 0,signal:null}));for(const s of r)n.q<=s.lastSequence||(s.lastSequence=n.q,n.t==="output"?s.handlers.onEvent({type:"data",sequence:n.q,data:typeof n.d=="string"?n.d:"",replayData:typeof n.r=="string"?n.r:void 0}):n.t==="exit"?s.handlers.onEvent({type:"exit",sequence:n.q,exitCode:typeof n.exitCode=="number"?n.exitCode:void 0,signal:typeof n.signal=="number"?n.signal:null}):n.t==="restarted"&&s.handlers.onEvent({type:"snapshot",sequence:n.q,data:typeof n.history=="string"?n.history:"",status:"running"}))}send(t){if(!this.socket||this.socket.readyState!==Ot)return!1;try{return this.socket.send(ip(t)),!0}catch{return!1}}scheduleReconnect(){if(this.reconnectTimer||this.disposed||this.subscribers.size===0)return;this.failures+=1;const n=typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine?6e4:Math.min(500*2**Math.min(this.failures-1,10),8e3);for(const o of this.subscribers.values())for(const s of o)s.handlers.onEvent({type:"reconnecting",attempt:this.failures,maxAttempts:Number.POSITIVE_INFINITY});const r=()=>{typeof document<"u"&&document.visibilityState==="hidden"||typeof navigator<"u"&&!navigator.onLine||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null,this.ensureConnected().catch(()=>this.scheduleReconnect()))};typeof window<"u"&&window.addEventListener("online",r),typeof document<"u"&&document.addEventListener("visibilitychange",r),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",r),typeof document<"u"&&document.removeEventListener("visibilitychange",r)},this.reconnectTimer=setTimeout(r,n)}scheduleIdleClose(){this.idleCloseTimer||this.disposed||(this.idleCloseTimer=setTimeout(()=>{this.idleCloseTimer=null,!(this.disposed||this.subscribers.size>0)&&(this.generation+=1,this.opening=null,this.closeSocket())},sp))}cancelIdleClose(){this.idleCloseTimer&&(clearTimeout(this.idleCloseTimer),this.idleCloseTimer=null)}startKeepalive(){this.stopKeepalive(),this.keepaliveTimer=setInterval(()=>this.send({t:"ping",v:3}),45e3)}stopKeepalive(){this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null}cancelReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wakeCleanup?.(),this.wakeCleanup=null}closeSocket(){this.stopKeepalive();const t=this.socket;this.socket=null,t&&(t.readyState===op||t.readyState===Ot)&&t.close()}}let bt=new Va;async function lp(e){const t=await h("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await ur(t,"Failed to create terminal session");return t.json()}async function dp(e){const t=await h(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await ur(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=n&&typeof n=="object"&&"sessions"in n?n.sessions:null;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const o=[];for(const s of r){if(typeof s!="object"||s===null)continue;const i=s;typeof i.sessionId!="string"||typeof i.cwd!="string"||i.status!=="running"&&i.status!=="exited"||o.push({sessionId:i.sessionId,cwd:i.cwd,status:i.status,createdAt:typeof i.createdAt=="number"?i.createdAt:null})}return o}async function up(e){e.length!==0&&await Gt("/api/terminal/touch","POST",{sessionIds:e})}async function fp(){const e=await h("/api/terminal/shells");if(!e.ok)throw await ur(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Qn(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function pp(e,t,n){return bt.subscribe(e,{onEvent:t,onError:n})}async function hp(e,t){await bt.write(e,t)}async function Gt(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const o=await h(e,r);if(!o.ok)throw await ur(o,"Terminal command failed");return o}async function mp(e,t,n){await Gt(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n})}async function yp(e,t){await Gt(`/api/terminal/${e}/appearance`,"POST",t)}async function gp(e){await Gt(`/api/terminal/${e}`,"DELETE"),bt.forget(e)}async function wp(e,t){return(await Gt(`/api/terminal/${e}/restart`,"POST",t)).json()}async function bp(e){const n=await(await Gt("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&bt.forget(r);else e.sessionId&&bt.forget(e.sessionId)}function lg(){bt.dispose(),bt=new Va}const Sp=()=>({async listShells(){return fp()},async listSessions(e){return dp(e)},async touchSessions(e){await up(e)},async createSession(e){return lp(e)},connect(e,t){const n=pp(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await hp(e,t)},async resize(e){await mp(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await yp(e,t)},async close(e){await gp(e)},async restartSession(e,t){return wp(e,{cwd:t.cwd??"",cols:t.cols,rows:t.rows,themeMode:t.themeMode,terminalBackground:t.terminalBackground,terminalForeground:t.terminalForeground,shell:t.shell,loginShell:t.loginShell})},async forceKill(e){await bp(e)}}),po=new Set,Tp=e=>(po.add(e),()=>{po.delete(e)}),Ep=e=>{for(const t of po)t(e)},w="/api/git",kp=1200,vp=5e3,ho=new Map,Yt=new Map,Ja=new Map,oi=new Map,xn=new Map,Ya=e=>e.trim(),Ko=(e,t)=>JSON.stringify([e,Ya(t)]),Qa=(e,t,n)=>JSON.stringify([e,Ya(t),n??"full"]),mo=(e,t)=>Ja.get(Ko(e,t))??0,Xa=(e,t)=>{const n=Ko(e,t);Ja.set(n,mo(e,t)+1);for(const r of[void 0,"light"]){const o=Qa(e,t,r);ho.delete(o),Yt.delete(o)}};Tp(e=>{Xa(L(),e)});const mn=e=>{Ep(e)},B=async(e,t)=>{const n=await t.json();return mn(e),n};function b(e,t,n){const r={...n};return t&&(r.directory=t),le().api(e,r)}async function Pp(e){const t=Ko(L(),e),n=Date.now(),r=oi.get(t);if(r&&r.expiresAt>n)return r.value;const o=xn.get(t);if(o)return o;const s=(async()=>{const i=await h(b(`${w}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return oi.set(t,{value:c,expiresAt:Date.now()+vp}),c})();xn.set(t,s);try{return await s}finally{xn.get(t)===s&&xn.delete(t)}}class Ap extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function dg(e){const t=await h("/api/fs/git-dirs",{query:{path:e}});if(t.status===501)throw new Ap;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>ja(r?.path??null)).filter(r=>r!==null)}async function Mp(e,t){const n=t?.mode,r=L();t?.fresh&&Xa(r,e);const o=Qa(r,e,n),s=Date.now(),i=ho.get(o);if(i&&i.expiresAt>s)return i.value;const a=Yt.get(o);if(a)return a;const c=(async()=>{const l=mo(r,e),d=await h(b(`${w}/status`,e,n?{mode:n}:void 0));if(!d.ok)throw new Error(`Failed to get git status: ${d.statusText}`);const u=await d.json();return mo(r,e)===l&&ho.set(o,{value:u,expiresAt:Date.now()+kp}),u})();Yt.set(o,c);try{return await c}finally{Yt.get(o)===c&&Yt.delete(o)}}async function ug(e){const t=await h(b(`${w}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function fg(e){const t=await h(b(`${w}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function pg(e,t){const n=await h(b(`${w}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function Cp(e,t){const{path:n,staged:r,contextLines:o}=t;if(!n)throw new Error("path is required to fetch git diff");const s=await h(b(`${w}/diff`,e,{path:n,staged:r?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function Dp(e,t){const{base:n,head:r,path:o,contextLines:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const i=await h(b(`${w}/range-diff`,e,{base:n,head:r,path:o||void 0,context:s}));if(!i.ok)throw new Error(`Failed to get git range diff: ${i.statusText}`);return i.json()}async function Rp(e,t){const{base:n,head:r}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await h(b(`${w}/range-files`,e,{base:n,head:r}));if(!o.ok)throw new Error(`Failed to get git range files: ${o.statusText}`);const s=await o.json();return Array.isArray(s.files)?s.files.filter(i=>{if(!i||typeof i!="object")return!1;const a=i;return typeof a.path=="string"&&typeof a.status=="string"}):[]}async function Ip(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await h(b(`${w}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function Op(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const o=await h(b(`${w}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function xp(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await h(b(`${w}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert git changes")}mn(e)}async function _p(e,t){await Za(e,[t])}async function Za(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await h(b(`${w}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stage git changes")}mn(e)}async function Lp(e,t){await ec(e,[t])}async function ec(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await h(b(`${w}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to unstage git changes")}mn(e)}async function Fp(e,t,n){await Vo(e,t,n,"stage")}async function jp(e,t,n){await Vo(e,t,n,"unstage")}async function Up(e,t,n){await Vo(e,t,n,"discard")}async function Vo(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const o=await h(b(`${w}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to apply git hunk")}mn(e)}async function Np(e){if(!e)return!1;const t=await h(b(`${w}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Bp(e){const t=await h(b(`${w}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function Hp(e,t){const n=await h(b(`${w}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function zp(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await h(b(`${w}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return B(e,n)}async function $p(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await h(b(`${w}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return B(e,n)}async function Gp(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await h(b(`${w}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to remove remote")}return B(e,r)}async function Wp(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const o=await h(b(`${w}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const s=await o.json();if(!s?.message||typeof s.message!="object")throw new Error("Malformed commit generation response");const i=typeof s.message.subject=="string"&&s.message.subject.trim().length>0?s.message.subject.trim():"",a=Array.isArray(s.message.highlights)?s.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function qp(e,t){const{base:n,head:r,context:o,zenModel:s,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};o?.trim()&&(c.context=o.trim()),s&&(c.zenModel=s),i&&(c.providerId=i),a&&(c.modelId=a);const l=await h(b(`${w}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const m=await l.json().catch(()=>({error:l.statusText}));throw new Error(m.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",f=typeof d?.body=="string"?d.body:"";if(!u&&!f)throw new Error("Malformed PR description response");return{title:u,body:f}}async function si(e){const t=await h(b(`${w}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function ii(e,t){const n=await h(b(`${w}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function Kp(e){const t=await h(b(`${w}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function Vp(e,t){const n=await h(b(`${w}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function ai(e,t){const n=await h(b(`${w}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function ci(e,t){const n=await h(b(`${w}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}async function Jp(e,t,n={}){const r=await h(b(`${w}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create commit")}return B(e,r)}async function Yp(e,t={}){const n=await h(b(`${w}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to push")}return B(e,n)}async function Qp(e,t={}){const n=await h(b(`${w}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return B(e,n)}async function Xp(e,t={}){const n=await h(b(`${w}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return B(e,n)}async function Zp(e){const t=await h(b(`${w}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function eh(e,t){const n=await h(b(`${w}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function tc(e,t={}){const n=await h(b(`${w}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return B(e,n)}const Jo=async(e,t,n)=>{const r=await h(b(`${w}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||`Failed to ${t}`)}return B(e,r)},th=(e,t)=>Jo(e,"stash/apply",t),nc=(e,t)=>Jo(e,"stash/pop",t),nh=(e,t)=>Jo(e,"stash/drop",t);async function rh(e,t){const n=await h(b(`${w}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return B(e,n)}async function oh(e,t,n){const r=await h(b(`${w}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create branch")}return B(e,r)}async function sh(e,t,n){const r=await h(b(`${w}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename branch")}return B(e,r)}async function ih(e,t={}){const n=await h(b(`${w}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return n.json()}async function ah(e,t){const n=await h(b(`${w}/commit-files`,e,{hash:t}));if(!n.ok)throw new Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function hg(e,t,n,r){const o=await h(b(`${w}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function ch(){const e=await h(b(`${w}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function lh(e){const t=await h(b(`${w}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to create git identity")}return t.json()}async function dh(e,t){const n=await h(b(`${w}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function uh(e){const t=await h(b(`${w}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function fh(e){if(!e)return null;const t=await h(b(`${w}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function ph(e){if(!e)return!1;const t=await h(b(`${w}/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 mg(){const e=await h(b(`${w}/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 hh(e,t){const n=await h(b(`${w}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function yg(){const e=await h(b(`${w}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function gg(e,t){if(!e)return null;const n=await h(b(`${w}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function mh(e){const t=await h(b(`${w}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function yh(e,t){const n=await h(b(`${w}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return B(e,n)}async function gh(e){const t=await h(b(`${w}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return B(e,t)}async function wh(e,t){const n=await h(b(`${w}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return B(e,n)}async function bh(e,t){const n=await h(b(`${w}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return B(e,n)}async function Sh(e,t){const n=await h(b(`${w}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return B(e,n)}async function Th(e,t){const n=await h(b(`${w}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return B(e,n)}async function Eh(e,t,n,r){const o=await h(b(`${w}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to reset")}return B(e,o)}async function kh(e){const t=await h(b(`${w}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return B(e,t)}async function vh(e){const t=await h(b(`${w}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return B(e,t)}async function Ph(e){const t=await h(b(`${w}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return B(e,t)}async function Ah(e,t){return await tc(e,{message:t?.message}),{success:!0}}async function Mh(e){return await nc(e,{ref:"stash@{0}"}),{success:!0}}async function Ch(e){const t=await h(b(`${w}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function Dh(e,t){const n=await h(`${w}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function Rh(e){const t=await h(`${w}/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 Ih=()=>({checkIsGitRepository:Pp,getGitStatus:Mp,getGitDiff:Cp,getGitFileDiff:Op,getGitRangeDiff:Dp,getGitRangeFiles:Rp,getBranchBase:Ip,revertGitFile:xp,stageGitFile:_p,stageGitFiles:Za,unstageGitFile:Lp,unstageGitFiles:ec,stageGitHunk:Fp,unstageGitHunk:jp,revertGitHunk:Up,isLinkedWorktree:Np,getGitBranches:Bp,getGitUnpushedBranchCounts:Hp,deleteGitBranch:zp,deleteRemoteBranch:$p,removeRemote:Gp,generateCommitMessage:Wp,generatePullRequestDescription:qp,listGitWorktrees:si,validateGitWorktree:ii,createGitWorktree:ai,deleteGitWorktree:ci,validateWorktreeDirectory:Dh,canonicalizeWorktreeState:Rh,createGitCommit(e,t,n){return Jp(e,t,n)},gitPush:Yp,gitPull:Qp,gitFetch:Xp,listGitStashes:Zp,countGitStashFiles:eh,stashGitChanges:tc,applyGitStash:th,popGitStash:nc,dropGitStash:nh,checkoutBranch:rh,createBranch:oh,renameBranch:sh,getGitLog(e,t){return ih(e,t)},getCommitFiles:ah,getCurrentGitIdentity:fh,hasLocalIdentity:ph,setGitIdentity:hh,getGitIdentities:ch,createGitIdentity:lh,updateGitIdentity:dh,deleteGitIdentity:uh,getRemotes:mh,rebase:yh,abortRebase:gh,continueRebase:vh,merge:wh,abortMerge:kh,continueMerge:Ph,checkoutCommit:bh,cherryPick:Sh,revertCommit:Th,resetToCommit:Eh,stash:Ah,stashPop:Mh,getConflictDetails:Ch,worktree:{list:si,validate:ii,bootstrapStatus:Kp,preview:Vp,create:ai,remove:ci}}),V=e=>e.replace(/\\/g,"/"),Oh=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new tt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:V(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:V(r.path),isDirectory:!!r.isDirectory}))}},Se=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},xh=({getDirectory:e})=>({async listDirectory(t,n){const r=V(t),o=new URLSearchParams;r&&o.set("path",r),n?.respectGitignore&&o.set("respectGitignore","true");const s=await h("/api/fs/list",{query:o,headers:Se(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new tt(a.error||"Failed to list directory",{reason:Vr(a.reason),status:s.status})}const i=await s.json();return Oh(r,i)},async search(t){const n=new URLSearchParams,r=V(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const o=await h("/api/find/file",{query:n,headers:Se(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:V(`${r}/${a}`),preview:[V(a)]}))},async createDirectory(t){const n=V(t),r=await h("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Se(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create directory")}const o=await r.json();return{success:!!o?.success,path:typeof o?.path=="string"?V(o.path):n}},async statFile(t,n){const r=V(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant);const s=await h("/api/fs/stat",{query:o,headers:Se(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await s.json().catch(()=>({}));return{path:typeof i.path=="string"?V(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=V(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&o.set("optional","true");const s=await h("/api/fs/read",{query:o,cache:n?.optional?"no-store":"default",headers:Se(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await s.text(),path:r}},async writeFile(t,n){const r=V(t),o=await h("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Se(e)},body:JSON.stringify({path:r,content:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to write file")}const s=await o.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?V(s.path):r}},async uploadFile(t,n,r){const o=V(t),s=await h("/api/fs/upload",{method:"POST",query:{path:o,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Se(e,r?.directory)},body:n});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new tt(a.error||"Failed to upload file",{reason:Vr(a.reason),status:s.status})}const i=await s.json().catch(()=>({}));return{success:!!i.success,path:i.path?V(i.path):o}},async delete(t){const n=V(t),r=await h("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Se(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await h("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...Se(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename file")}const o=await r.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?V(o.path):n}},async revealPath(t){const n=await h("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Se(e)},body:JSON.stringify({path:V(t)})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=V(t),r=await h("/api/fs/raw",{query:{path:n,download:!0},headers:Se(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const o=await r.blob(),s=n.split("/").pop()||"file",i=window.Capacitor,a=new File([o],s,{type:o.type||"application/octet-stream"});if(i?.isNativePlatform?.()===!0&&navigator.canShare?.({files:[a]})){await navigator.share({files:[a]});return}const c=URL.createObjectURL(o),l=document.createElement("a");l.href=c,l.download=s,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),100)}}),li="/api/config/settings",_h="/api/config/reload",di=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},Lh=()=>({async load(){const e=await h(li,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:di(await e.json()),source:"web"}},async save(e){const t=await h(li,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to save settings")}return di(await t.json())},async restartOpenCode(){const e=await h(_h,{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}}}),Fh=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),jh=1500,yo=5e3,Uh="openchamber-notification-claim:",nn=new Map,Nh=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Bh=e=>{const t=typeof e?.tag=="string"?e.tag.trim():"";return t||[e?.sessionId,e?.kind,e?.title,e?.body].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim()).join("|")},Hh=e=>{for(const[t,n]of nn)e-n>yo&&nn.delete(t)},zh=e=>{const t=Bh(e);if(!t)return!0;const n=Date.now();Hh(n);const r=nn.get(t)??0;if(n-r<yo)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${Uh}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<yo)return nn.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return nn.set(t,n),!0},rc=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{setTimeout(()=>n(null),jh)})])??e}catch{return e}},$h=async e=>{const t=await rc();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},Gh=async()=>{const e=await rc();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},Wh=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(!Nh()&&await Gh()||!zh(e))return!0;try{return await $h(e)||new Notification(e?.title??"OpenChamber",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},qh=async e=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},Kh=()=>({async notifyAgentCompletion(e){return await qh(e)||await Wh(e)},canNotify:()=>typeof window<"u"&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),Vh=()=>({async getAvailableTools(){const e=await h("/api/experimental/tool/ids");if(!e.ok)throw new Error(`Tools API returned ${e.status} ${e.statusText}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Tools API returned invalid data format");return t.filter(n=>typeof n=="string"&&n!=="invalid").sort()}}),xt=async(e,t)=>{try{const n=await h(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},Jh=()=>({async getVapidPublicKey(){return xt("/api/push/vapid-public-key")},async subscribe(e){return xt("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return xt("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return xt("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return xt("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return xt("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),K=async e=>await e.json().catch(()=>null),Yh=({urls:e})=>({async authStatus(){const t=await h("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await K(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await h("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await K(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await h("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await h("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await K(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await h("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await h("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await h("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await K(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,o){const s=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...o?.force?{force:"true"}:{}}),i=await h(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await K(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const n=await h("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await h("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await h("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await h("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await h(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await K(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await h(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await K(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to fetch repo branches");return o.branches??[]},async prsList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await h(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await K(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&o.set("diff","1"),r?.includeCheckDetails&&o.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await h(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await K(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await h(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await K(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await h(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await K(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await h(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await K(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}});async function ue(e){try{return await e.json()}catch{return null}}function fe(e,t){return e?.error?.trim()||t}function oc(e){return Number.isFinite(e)?e??null:null}function sc(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function ic(e){const t=e?.id?.trim();return t?{id:t,name:e?.name?.trim()||null,displayName:e?.displayName?.trim()||null,email:e?.email?.trim()||null,avatarUrl:e?.avatarUrl?.trim()||null}:null}function Qh(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function Xh(e){const t=e?.id?.trim();if(!t)return null;const n=e?.authorizedAt;return{id:t,name:e?.name?.trim()||null,urlKey:e?.urlKey?.trim()||null,current:e?.current===!0,user:ic(e?.user),authorizedAt:oc(n)}}function ui(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(Xh).filter(n=>n!=null):[];return{connected:e.connected,user:ic(e.user),organization:Qh(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function Zh(e){const t=e?.authorizationUrl?.trim(),n=e?.expiresIn,r=e?.scope?.trim();return!t||!Number.isFinite(n)||n==null||!r?null:{authorizationUrl:t,expiresIn:n,scope:r}}function em(e){const t=e?.id?.trim()||null,n=e?.name?.trim()||null,r=e?.type?.trim()||null;return!t&&!n&&!r?null:{id:t,name:n,type:r}}function tm(e){const t=e?.id?.trim(),n=e?.name?.trim();if(!t||!n)return null;const r=e?.position;return{id:t,name:n,type:e?.type?.trim()||null,position:oc(r)??0}}function nm(e){const t=e?.name?.trim()||null,n=e?.displayName?.trim()||null,r=e?.avatarUrl?.trim()||null;return!t&&!n&&!r?null:{name:t,displayName:n,avatarUrl:r}}function rm(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();return!t||!n||!r?null:{id:t,key:n,name:r}}function om(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function sm(e){const t=e?.trim();if(!t)return null;const n=t.startsWith("#")?t.slice(1):t;return/^[0-9A-Fa-f]{6}$/.test(n)?`#${n.toLowerCase()}`:null}function im(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:sm(e.color)}}function am(e){return Array.isArray(e)?e.map(im).filter(t=>t!=null):[]}function ac(e){if(!e)return null;const t=e?.id?.trim(),n=e?.identifier?.trim(),r=e?.title?.trim(),o=e?.url?.trim();return!t||!n||!r||!o?null:{id:t,identifier:n,title:r,url:o,state:em(e.state),assignee:nm(e.assignee),team:rm(e.team),priority:om(e.priority),labels:am(e.labels)}}function cm(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:sc(n)??"",createdAt:e?.createdAt?.trim()||null,user:e?.user?{name:e.user.name?.trim()||null,displayName:e.user.displayName?.trim()||null,avatarUrl:e.user.avatarUrl?.trim()||null}:null}}function cc(e){const t=ac(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(cm).filter(o=>o!=null):[],r=e?.description;return{...t,description:sc(r),comments:n}}function lm(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(ac).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function dm(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:cc(e.issue)}}function um(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(tm).filter(n=>n!=null):[]}}function fm(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:cc(e.issue)}}function pm(e){const t=e?.id?.trim(),n=e?.key?.trim(),r=e?.name?.trim();if(!t||!n||!r)return null;const o=e?.projectPath?.trim()||null;return{id:t,key:n,name:r,projectPath:o}}function fi(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};const t=Array.isArray(e.teams)?e.teams.map(pm).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const hm=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function mm(e){return hm.find(t=>t===e)??null}function pi(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function ym(e){if(e?.connected!==!0&&e?.connected!==!1)return null;if(e.connected===!1)return{connected:!1};if(e.posted===!0)return{connected:!0,posted:!0,commentId:e.commentId?.trim()||null};const t=mm(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const gm=()=>({async authStatus(){const e=await h("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await ue(e),n=ui(t);if(!e.ok||!n)throw new Error(fe(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await h("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await ue(t),r=Zh(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await h("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await ue(e);if(!e.ok)throw new Error(fe(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await h("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await ue(t),r=ui(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),o=e?.status?.trim(),s=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),o&&t.set("status",o),s&&t.set("assignee",s),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",d=await h(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),u=await ue(d),f=lm(u);if(!d.ok||!f)throw new Error(fe(u,d.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await h(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await ue(n),o=dm(r);if(!n.ok||!o)throw new Error(fe(r,n.statusText||"Failed to load Linear issue"));return o},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await h(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await ue(n),o=um(r);if(!n.ok||!o)throw new Error(fe(r,n.statusText||"Failed to load Linear workflow states"));return o},async issueUpdate(e){const t=await h("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await ue(t),r=fm(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await h("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await ue(e),n=fi(t);if(!e.ok||!n)throw new Error(fe(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await h("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await ue(t),r=fi(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await h("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await ue(t),r=ym(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await h("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await ue(e),n=pi(t);if(!e.ok||!n)throw new Error(fe(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await h("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await ue(t),r=pi(n);if(!t.ok||!r)throw new Error(fe(n,t.statusText||"Failed to save Linear preferences"));return r}}),We=async e=>await e.json().catch(()=>null),wm=()=>({async listClients(){const e=await h("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await We(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 h("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await We(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await h("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),n=await We(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await h("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await We(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 h("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await We(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 h(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await We(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await h(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await We(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await h("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await We(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),bm=()=>({api:(...e)=>le().api(...e),authenticatedAsset:(...e)=>le().authenticatedAsset(...e),auth:(...e)=>le().auth(...e),health:(...e)=>le().health(...e),rawFile:(...e)=>le().rawFile(...e),sse:(...e)=>le().sse(...e),websocket:(...e)=>le().websocket(...e)}),Sm=(e={})=>{const t=e.urls??vo();Rl(t);const n=bm();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Sp(),git:Ih(),files:xh({getDirectory:()=>fo.getState().currentDirectory}),settings:Lh(),permissions:Fh(),notifications:Kh(),github:Yh({urls:n}),linear:gm(),push:Jh(),clientAuth:wm(),tools:Vh()}},Tm=3e3,hi=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Em=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__OPENCHAMBER_API_BASE_URL__),clientToken:e(window.__OPENCHAMBER_CLIENT_TOKEN__),localOrigin:e(window.__OPENCHAMBER_LOCAL_ORIGIN__),runtimeHeaders:window.__OPENCHAMBER_RUNTIME_HEADERS__,relayHostId:e(window.__OPENCHAMBER_RELAY_HOST_ID__)}};let go=Promise.resolve();const wg=()=>go,bg=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:o,relayHostId:s,relay:i}=e??Em(),a=e?null:oa(),c=s||(a?.target==="remote"?a.hostId:""),l=Vi({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return Gl({apiBaseUrl:t,runtimeKey:hi(t,r)?"local":c?`host:${c}`:null}),Fi(n||null),ji(o||null),i&&Gn({apiBaseUrl:t,clientToken:n||null,requestHeaders:o||null,runtimeKey:s?`host:${s}`:null,relay:i}),De.reconnectToRuntimeBaseUrl(),ar(t||void 0).catch(()=>{}),r&&!hi(t,r)&&Object.keys(ir()).length>0&&$i(r).catch(()=>{}),Qi(),go=i?Promise.resolve():Promise.race([Ud(s||void 0).catch(()=>{}),new Promise(d=>{window.setTimeout(d,1e4)})]).then(()=>{De.reconnectToRuntimeBaseUrl()}),go.then(()=>{window.setTimeout(()=>{xd().catch(()=>{})},Tm)}),Sm({urls:l})};export{xo as $,se as A,ly as B,rd as C,pf as D,cy as E,Ie as F,ay as G,ja as H,sg as I,$t as J,Ro as K,la as L,zl as M,by as N,ff as O,Ad as P,Ze as Q,ca as R,G as S,Ui as T,Vm as U,Ym as V,zy as W,$y as X,Bf as Y,ky as Z,le as _,L as a,gh as a$,or as a0,ar as a1,rp as a2,ir as a3,Cm as a4,Ly as a5,Jm as a6,Ce as a7,Zr as a8,ag as a9,wu as aA,Su as aB,lg as aC,Ua as aD,Um as aE,Nm as aF,Bm as aG,Jl as aH,sa as aI,lu as aJ,Hf as aK,Py as aL,Sa as aM,Gu as aN,Ep as aO,Yr as aP,qe as aQ,Wl as aR,Xc as aS,By as aT,Di as aU,Kp as aV,za as aW,ia as aX,pn as aY,Hy as aZ,kh as a_,ed as aa,Qm as ab,qf as ac,og as ad,Wf as ae,vn as af,en as ag,Ry as ah,Te as ai,vy as aj,Vl as ak,oa as al,_m as am,Gf as an,xy as ao,Lm as ap,Fm as aq,sy as ar,oy as as,ny as at,ry as au,Tt as av,tg as aw,ey as ax,ty as ay,Xm as az,Cu as b,Mh as b$,th as b0,Rh as b1,Pp as b2,rh as b3,bh as b4,Sh as b5,Ph as b6,vh as b7,eh as b8,oh as b9,mh as bA,ii as bB,si as bC,Xp as bD,Qp as bE,Yp as bF,ph as bG,Np as bH,Zp as bI,wh as bJ,nc as bK,Vp as bL,yh as bM,Gp as bN,sh as bO,Eh as bP,ug as bQ,fg as bR,Th as bS,xp as bT,Up as bU,hh as bV,_p as bW,Za as bX,Fp as bY,Ah as bZ,tc as b_,Jp as ba,lh as bb,ai as bc,zp as bd,uh as be,ci as bf,$p as bg,yg as bh,nh as bi,Ip as bj,hg as bk,ah as bl,Ch as bm,fh as bn,Bp as bo,pg as bp,Cp as bq,Op as br,ch as bs,ih as bt,Dp as bu,Rp as bv,Mp as bw,Hp as bx,mg as by,gg as bz,bg as c,iy as c$,Lp as c0,ec as c1,jp as c2,dh as c3,Dh as c4,oe as c5,Iy as c6,hu as c7,Xi as c8,_y as c9,qy as cA,Yy as cB,Ky as cC,Wy as cD,Vy as cE,Ha as cF,Jy as cG,jy as cH,Uy as cI,Fo as cJ,cg as cK,Km as cL,Cy as cM,ma as cN,Ay as cO,My as cP,Dy as cQ,Ny as cR,Dt as cS,gu as cT,bu as cU,eg as cV,Zy as cW,Sd as cX,pd as cY,fy as cZ,py as c_,Sy as ca,Ty as cb,re as cc,wd as cd,Cd as ce,Od as cf,Md as cg,Io as ch,Pd as ci,Ey as cj,yy as ck,wy as cl,gy as cm,bd as cn,jd as co,xm as cp,Fy as cq,Pn as cr,Ir as cs,ig as ct,dg as cu,Ap as cv,Tp as cw,Zm as cx,ge as cy,Gy as cz,hn as d,of as d0,Oy as d1,mu as d2,yu as d3,Qn as d4,nf as d5,dr as d6,Mu as d7,Hm as d8,$m as d9,Wm as da,zm as db,Gm as dc,qm as dd,Xy as de,uy as df,Qy as dg,hf as dh,Im as di,Om as dj,dy as dk,my as dl,Ue as dm,cr as e,Dm as f,wg as g,Rm as h,Pa as i,So as j,Ve as k,hy as l,fo as m,Au as n,lr as o,dd as p,Bn as q,h as r,Gn as s,jm as t,he as u,na as v,De as w,rg as x,ng as y,rt as z};