@aiworker/web 1.22.2 → 1.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +7 -0
- package/dist/assets/{CodeMirrorCommentWidgets-CSICpWQD.js → CodeMirrorCommentWidgets-teB3HmBT.js} +1 -1
- package/dist/assets/DiffView-DC9RX3MF.js +4 -0
- package/dist/assets/{DirtyBranchSwitchDialog-C22HdWj4.js → DirtyBranchSwitchDialog-DwPkzXsS.js} +1 -1
- package/dist/assets/FilesView-BFZkuu4O.js +13 -0
- package/dist/assets/{GitView-VQQkYuUw.js → GitView-B_x52MHY.js} +4 -4
- package/dist/assets/{JsonTreeView-6lrhwD3q.js → JsonTreeView-cmAzUTiw.js} +1 -1
- package/dist/assets/{LinearIssuesView-Ba6Q9569.js → LinearIssuesView-Dehh5afm.js} +1 -1
- package/dist/assets/MarkdownImageGallery-DgNOqqhE.js +1 -0
- package/dist/assets/MarkdownRendererImpl-DusmMZ_p.js +12 -0
- package/dist/assets/OnboardingScreen-B8fm1H4m.js +1 -0
- package/dist/assets/{PatchDiff-BzcZPlOq.js → PatchDiff-BVr7gJU0.js} +1 -1
- package/dist/assets/PierreDiffViewer-DzLt-nel.js +161 -0
- package/dist/assets/PlanView-BmQUYT_z.js +5 -0
- package/dist/assets/SettingsView-ChWmAcZT.js +28 -0
- package/dist/assets/{SettingsWindow-DDQYaKWQ.js → SettingsWindow-Dy3M6ZB9.js} +1 -1
- package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
- package/dist/assets/{ToolOutputDialog-iYF8Y2bz.js → ToolOutputDialog-cTl_eLIH.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-CdjbOVMM.js → ToolPartDiffPreview-C_3iYNJQ.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-fFFm2QgH.js → VirtualizedFileDiff-CAWthkoy.js} +4 -4
- package/dist/assets/WalkthroughView-C7AHOpCA.js +4 -0
- package/dist/assets/{computeVirtualFileMetrics-CzgLum_K.js → computeVirtualFileMetrics-BkiDSlTW.js} +2 -2
- package/dist/assets/contextPanelEmbeddedChat-BdA6bdky.js +1 -0
- package/dist/assets/de-DJsQr-p7.js +10 -0
- package/dist/assets/es-BuYMlA9g.js +16 -0
- package/dist/assets/fr-ePDay33C.js +14 -0
- package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
- package/dist/assets/index-BD8ILbxF.js +40 -0
- package/dist/assets/{index-Bl3LSbjn.js → index-n6O3hklM.js} +1 -1
- package/dist/assets/index-zhgg-SDz.css +1 -0
- package/dist/assets/{isDiffPlainText-Dx-dB_8l.js → isDiffPlainText-GMdPz-71.js} +1 -1
- package/dist/assets/{isFilePlainText-CWFPwmnU.js → isFilePlainText-BVuH1zH9.js} +1 -1
- package/dist/assets/ja-BzR9xOY_.js +16 -0
- package/dist/assets/ko-BEjHAm14.js +16 -0
- package/dist/assets/main-BydQ1tr_.js +930 -0
- package/dist/assets/{main-DnBAoktx.js → main-D3ZDQglc.js} +2 -2
- package/dist/assets/markdownCore-Cb2MdZnV.js +5 -0
- package/dist/assets/{miniChat-BKyvLseN.js → miniChat-d01k801U.js} +2 -2
- package/dist/assets/{mobile-DKjeFgMN.js → mobile-D7VV-Ufz.js} +2 -2
- package/dist/assets/patchFileDiff-CdztVMz0.js +13 -0
- package/dist/assets/pl-rQmpxNIF.js +16 -0
- package/dist/assets/pt-BR-CorbsSW-.js +16 -0
- package/dist/assets/renderElectronMiniChatApp-BGG9UIlh.js +2 -0
- package/dist/assets/renderMobileApp-BRP3J1iv.js +25 -0
- package/dist/assets/runtimeEndpointReset-BhT_-c52.js +41 -0
- package/dist/assets/scheduledTasksApi-BEuUF_cj.js +1 -0
- package/dist/assets/{shikiHighlight-TEQCmzW8.js → shikiHighlight-BzXUjlby.js} +1 -1
- package/dist/assets/surface-COKb77Ua.js +1 -0
- package/dist/assets/tr-CoAMXPtI.js +7 -0
- package/dist/assets/uk-YlAX0rRU.js +16 -0
- package/dist/assets/{useAppFontEffects-D7sNpuL2.js → useAppFontEffects-Cwyhjfl5.js} +141 -140
- package/dist/assets/useGitComparison-BCZVefdE.js +1 -0
- package/dist/assets/useInlineCommentController-DDkpBEU8.js +2 -0
- package/dist/assets/useRootScrollLock-CwjoWuC4.js +1 -0
- package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-BY_5qla_.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-Dp3KMRQG.js → vendor-codemirror-language-data-Cb1YnICj.js} +2 -2
- package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
- package/dist/assets/vendor-zod-B6551dwG.js +39 -0
- package/dist/assets/{web-components-_mNEMjFY.js → web-components-LV3vjTxy.js} +1 -1
- package/dist/assets/zh-CN-DDYg0Jl7.js +16 -0
- package/dist/assets/zh-TW-CQKaCayr.js +16 -0
- package/dist/index.html +5 -43
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -3
- package/server/index.d.ts +15 -0
- package/server/index.js +48 -22
- package/server/lib/agent-memory/runtime.js +7 -2
- package/server/lib/agent-memory/runtime.test.js +22 -0
- package/server/lib/data-dir-migration.js +40 -0
- package/server/lib/data-dir-migration.test.js +59 -0
- package/server/lib/event-stream/DOCUMENTATION.md +3 -0
- package/server/lib/event-stream/global-hub.js +29 -4
- package/server/lib/event-stream/global-hub.test.js +22 -0
- package/server/lib/event-stream/global-ws-bridge.js +15 -18
- package/server/lib/event-stream/protocol.js +21 -7
- package/server/lib/event-stream/runtime.js +9 -6
- package/server/lib/event-stream/runtime.test.js +72 -12
- package/server/lib/fs/DOCUMENTATION.md +3 -0
- package/server/lib/fs/routes.js +31 -0
- package/server/lib/fs/routes.test.js +110 -1
- package/server/lib/git/DOCUMENTATION.md +39 -6
- package/server/lib/git/routes.js +45 -12
- package/server/lib/git/routes.test.js +78 -0
- package/server/lib/git/service.js +343 -202
- package/server/lib/git/service.test.js +496 -25
- package/server/lib/github/DOCUMENTATION.md +5 -0
- package/server/lib/github/routes.js +2 -2
- package/server/lib/inherited-env.js +16 -9
- package/server/lib/inherited-env.test.js +8 -9
- package/server/lib/message-queue/DOCUMENTATION.md +11 -1
- package/server/lib/message-queue/runtime.js +13 -0
- package/server/lib/message-queue/runtime.test.js +31 -1
- package/server/lib/network-defaults.js +23 -0
- package/server/lib/network-defaults.test.js +52 -0
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/emitter-runtime.js +4 -3
- package/server/lib/opencode/DOCUMENTATION.md +35 -5
- package/server/lib/opencode/bootstrap-runtime.js +2 -0
- package/server/lib/opencode/env-runtime.js +5 -1
- package/server/lib/opencode/env-runtime.test.js +72 -0
- package/server/lib/opencode/feature-routes-runtime.js +17 -1
- package/server/lib/opencode/lifecycle.js +4 -3
- package/server/lib/opencode/lifecycle.test.js +29 -0
- package/server/lib/opencode/managed-plugin-config.js +1 -1
- package/server/lib/opencode/openchamber-routes.js +64 -4
- package/server/lib/opencode/openchamber-routes.test.js +128 -1
- package/server/lib/opencode/proxy.js +33 -0
- package/server/lib/opencode/routes.js +5 -3
- package/server/lib/opencode/settings-files.js +214 -0
- package/server/lib/opencode/settings-helpers.js +88 -41
- package/server/lib/opencode/settings-helpers.test.js +176 -1
- package/server/lib/opencode/settings-registry.json +750 -0
- package/server/lib/opencode/settings-runtime.js +175 -27
- package/server/lib/opencode/settings-runtime.test.js +321 -7
- package/server/lib/project-context/DOCUMENTATION.md +38 -4
- package/server/lib/project-context/routes.http.test.js +18 -0
- package/server/lib/project-context/routes.js +15 -0
- package/server/lib/project-context/runtime.js +256 -25
- package/server/lib/project-context/runtime.test.js +160 -3
- package/server/lib/projects/DOCUMENTATION.md +77 -0
- package/server/lib/projects/project-config.js +179 -17
- package/server/lib/projects/project-config.test.js +97 -0
- package/server/lib/projects/project-id.js +43 -0
- package/server/lib/projects/project-setup.js +409 -0
- package/server/lib/projects/project-setup.test.js +557 -0
- package/server/lib/projects/routes.js +59 -0
- package/server/lib/quota/DOCUMENTATION.md +31 -1
- package/server/lib/quota/providers/cline-pass.js +125 -0
- package/server/lib/quota/providers/cline-pass.test.js +103 -0
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/neuralwatt.js +3 -6
- package/server/lib/quota/providers/neuralwatt.test.js +7 -7
- package/server/lib/quota/providers/ollama-cloud.js +31 -0
- package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
- package/server/lib/quota/providers/opencode-go.js +1 -1
- package/server/lib/quota/providers/opencode-go.test.js +26 -1
- package/server/lib/quota/providers/openrouter.js +119 -24
- package/server/lib/quota/providers/openrouter.test.js +330 -0
- package/server/lib/relay/DOCUMENTATION.md +75 -0
- package/server/lib/relay/cross-compat.test.js +26 -0
- package/server/lib/relay/downstream-scheduler.js +154 -0
- package/server/lib/relay/downstream-scheduler.test.js +162 -0
- package/server/lib/relay/e2ee.js +10 -8
- package/server/lib/relay/flow-control.test.js +177 -0
- package/server/lib/relay/host-client.js +44 -8
- package/server/lib/relay/host-client.test.js +14 -0
- package/server/lib/relay/tunnel-codec.js +9 -0
- package/server/lib/relay/tunnel-host.js +66 -17
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
- package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
- package/server/lib/scheduled-tasks/runtime.js +12 -2
- package/server/lib/scheduled-tasks/runtime.test.js +53 -0
- package/server/lib/session-assist/DOCUMENTATION.md +131 -66
- package/server/lib/session-assist/context.js +127 -0
- package/server/lib/session-assist/context.test.js +132 -0
- package/server/lib/session-assist/prompt.js +54 -0
- package/server/lib/session-assist/runtime.js +117 -267
- package/server/lib/session-assist/runtime.test.js +203 -0
- package/server/lib/session-goal/runtime.js +4 -9
- package/server/lib/small-model/DOCUMENTATION.md +3 -2
- package/server/lib/small-model/call.js +9 -4
- package/server/lib/small-model/call.test.js +29 -0
- package/server/lib/small-model/index.js +5 -10
- package/server/lib/small-model/runtime-providers.js +15 -7
- package/server/lib/small-model/runtime-providers.test.js +7 -1
- package/server/lib/terminal/DOCUMENTATION.md +4 -4
- package/server/lib/terminal/runtime.js +11 -6
- package/server/lib/terminal/runtime.test.js +20 -13
- package/server/lib/walkthrough/DOCUMENTATION.md +49 -20
- package/server/lib/walkthrough/model-settings.js +8 -12
- package/server/lib/walkthrough/pr-source.test.js +21 -0
- package/server/lib/walkthrough/prompt.js +3 -1
- package/server/lib/walkthrough/pull-request.js +7 -4
- package/server/lib/walkthrough/pull-request.test.js +16 -0
- package/server/lib/walkthrough/routes.js +19 -0
- package/server/lib/walkthrough/routes.test.js +26 -0
- package/server/lib/walkthrough/sources.js +36 -4
- package/server/opencode-worktree-readiness.test.js +130 -0
- package/dist/assets/DiffView-hDBKesA_.js +0 -4
- package/dist/assets/FilesView-CdWzeOp9.js +0 -17
- package/dist/assets/MarkdownImageGallery-Czv_mhvS.js +0 -1
- package/dist/assets/MarkdownRendererImpl-BrMcswiy.js +0 -12
- package/dist/assets/OnboardingScreen-ChxQoAkx.js +0 -1
- package/dist/assets/PierreDiffViewer-BchBtZlp.js +0 -157
- package/dist/assets/PlanView-DyDt_nZ_.js +0 -5
- package/dist/assets/SettingsView-BKf5xBsP.js +0 -28
- package/dist/assets/WalkthroughView-DOeCsMju.js +0 -4
- package/dist/assets/contextPanelEmbeddedChat-C0ZLAepL.js +0 -1
- package/dist/assets/de-B5JaA3SA.js +0 -10
- package/dist/assets/es-EPIH88ii.js +0 -16
- package/dist/assets/fr-CAMfxUdZ.js +0 -14
- package/dist/assets/index-DF5kMP-i.js +0 -39
- package/dist/assets/index-Dl3xbAB_.css +0 -1
- package/dist/assets/ja-CifOE1VN.js +0 -16
- package/dist/assets/ko-BBDyAyYQ.js +0 -16
- package/dist/assets/main-MhSaOZoB.js +0 -930
- package/dist/assets/markdownCore-BrBwOOMn.js +0 -3
- package/dist/assets/patchFileDiff-o8ms1me8.js +0 -10
- package/dist/assets/pl-DgEHYfFM.js +0 -16
- package/dist/assets/pt-BR-DuWHojUw.js +0 -16
- package/dist/assets/renderElectronMiniChatApp-CDgBwwCS.js +0 -2
- package/dist/assets/renderMobileApp-DJIKIK1r.js +0 -25
- package/dist/assets/runtimeEndpointReset-CYJ9O_xX.js +0 -17
- package/dist/assets/scheduledTasksApi-D8yamh1b.js +0 -1
- package/dist/assets/tr-D5m2yIWL.js +0 -7
- package/dist/assets/uk-D_q60oog.js +0 -16
- package/dist/assets/useInlineCommentController-Brz_cLcQ.js +0 -2
- package/dist/assets/useRootScrollLock-lXEnWlaU.js +0 -1
- package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
- package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
- package/dist/assets/vendor-zod-CK21ihK-.js +0 -39
- package/dist/assets/zh-CN-D8QvsVeg.js +0 -16
- package/dist/assets/zh-TW-B9t7rQQO.js +0 -16
- package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
- package/server/lib/mcp-reconnect/runtime.js +0 -122
- package/server/lib/mcp-reconnect/runtime.test.js +0 -140
|
@@ -1,39 +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 ls}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ze,d as an,p as Un,a as Ml}from"./vendor-zustand-BAGL70zf.js";import{o as P,n as C,s as w,l as F,r as Rl,u as Ea,a as Xe,b as ds,t as Js,d as Ur,_ as mt,c as xl}from"./vendor-zod-CK21ihK-.js";import{c as Cl}from"./vendor-opencode-sdk-BJ73u-bH.js";import{f as Aa,R as wr}from"./vendor-react-BUCujlKS.js";const vn=1,Dl="openchamber-relay-v1",Pa=1,Ia=12,En=1+Ia,xn=64*1024,Cn=5,Dn=128,Ma=0,Ra=1,tn=4,Ol=1+tn,Ao=xn-Cn-Ol,L={HttpRequest:1,HttpBody:2,HttpResponse:3,StreamEnd:4,StreamAbort:5,WsOpen:6,WsOpened:7,WsText:8,WsBinary:9,WsClose:10,Ping:11,Pong:12},Ll=new Set(Object.values(L)),_l=e=>Ll.has(e),Mt={DuplicateClient:4002,AuthFailed:4010,LimitExceeded:4029,ChannelFailure:1011},Ye=globalThis.crypto.subtle,xa={name:"ECDH",namedCurve:"P-256"},Ca=16,Qr=32,Fl=16,Po=4,Da=8;class ft extends Error{constructor(t){super(t),this.name="RelayCryptoError"}}const jl=()=>Ye.generateKey(xa,!0,["deriveBits"]),Ul=async e=>{const t=await Ye.exportKey("jwk",e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y}},Nl=async e=>{if(e.kty!=="EC"||e.crv!=="P-256"||typeof e.x!="string"||typeof e.y!="string")throw new ft("invalid ECDH public key JWK");try{return await Ye.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y,ext:!0},xa,!0,[])}catch{throw new ft("invalid ECDH public key JWK")}},Bl=()=>{const e=new Uint8Array(Ca);return globalThis.crypto.getRandomValues(e),e},Hl=async(e,t,n)=>{if(n.length!==Ca)throw new ft("invalid handshake nonce length");const r=await Ye.deriveBits({name:"ECDH",public:t},e,256),o=await Ye.importKey("raw",r,"HKDF",!1,["deriveBits"]),s=new Uint8Array(await Ye.deriveBits({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Dl)},o,Qr*2*8)),i=(a,c)=>Ye.importKey("raw",a,{name:"AES-GCM"},!1,c);return{clientToHost:await i(s.slice(0,Qr),["encrypt","decrypt"]),hostToClient:await i(s.slice(Qr),["encrypt","decrypt"])}},zl=(e,t,n)=>{for(let r=Da-1;r>=0;r-=1)e[t+r]=Number(n&0xffn),n>>=8n},Wl=(e,t)=>{let n=0n;for(let r=0;r<Da;r+=1)n=n<<8n|BigInt(e[t+r]);return n},$l=e=>{const t=new Uint8Array(Po);globalThis.crypto.getRandomValues(t);let n=0n;return{async encrypt(r){if(r.length>xn)throw new ft("plaintext frame exceeds maximum size");n+=1n;const o=new Uint8Array(Ia);o.set(t,0),zl(o,Po,n);const s=new Uint8Array(await Ye.encrypt({name:"AES-GCM",iv:o},e,r)),i=new Uint8Array(En+s.length);return i[0]=Pa,i.set(o,1),i.set(s,En),i}}},Gl=e=>{let t=0n;return{async decrypt(n){if(n.length<En+Fl)throw new ft("encrypted frame too short");if(n[0]!==Pa)throw new ft("unsupported encrypted frame version");const r=n.slice(1,En),o=Wl(r,Po);if(o<=t)throw new ft("frame counter regression");let s;try{s=await Ye.decrypt({name:"AES-GCM",iv:r},e,n.slice(En))}catch{throw new ft("frame decryption failed")}return t=o,new Uint8Array(s)}}},Kn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Kl=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+=Kn[r>>2],t+=Kn[(r&3)<<4|(o??0)>>4],o!==void 0&&(t+=Kn[(o&15)<<2|(s??0)>>6]),s!==void 0&&(t+=Kn[s&63])}return t},Ys=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!==vn)return null;const r=n.batch===!0;return n.t==="ready"?{t:"ready",v:vn,batch:r}:n.t==="hello"&&typeof n.nonce=="string"&&typeof n.clientPubJwk=="object"&&n.clientPubJwk!==null?{t:"hello",v:vn,clientPubJwk:n.clientPubJwk,nonce:n.nonce,batch:r}:null},ql=e=>({type:"fail",closeCode:Mt.ChannelFailure,reason:e}),Vl=async(e,t={})=>{const n=t.batch!==!1,r=await Nl(e),o=await jl(),s=Bl(),i={t:"hello",v:vn,clientPubJwk:await Ul(o.publicKey),nonce:Kl(s),...n?{batch:!0}:{}};let a=!1;return{helloText:JSON.stringify(i),get established(){return a},async handleText(c){if(a)return Ys(c)?.t==="ready"?{type:"ignore"}:ql("plaintext frame on established channel");const l=Ys(c);if(l?.t!=="ready")return{type:"ignore"};const d=await Hl(o.privateKey,r,s);return a=!0,{type:"established",batch:n&&l.batch===!0,channel:{encryptor:$l(d.clientToHost),decryptor:Gl(d.hostToClient)}}}}},Oa=4294967295;class ie extends Error{constructor(t){super(t),this.name="TunnelCodecError"}}const Oe=(e,t,n,r=!1)=>{if(!Number.isInteger(t)||t<0||t>Oa)throw new ie("invalid stream id");if(n.length>Ao)throw new ie("tunnel payload exceeds maximum size");const o=new Uint8Array(Cn+n.length);return o[0]=r?e|Dn:e,o[1]=t>>>24&255,o[2]=t>>>16&255,o[3]=t>>>8&255,o[4]=t&255,o.set(n,Cn),o},Jl=e=>{if(e.length<Cn)throw new ie("tunnel frame too short");const t=e[0],n=(t&Dn)!==0,r=t&~Dn;if(!_l(r))throw new ie(`unknown tunnel frame type ${r}`);const o=(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0;return{frameType:r,streamId:o,payload:e.slice(Cn),hasMoreFragments:n}},Yl=new TextEncoder,Ql=new TextDecoder,qn=e=>Yl.encode(JSON.stringify(e)),Vn=(e,t)=>{let n;try{n=JSON.parse(Ql.decode(e))}catch{throw new ie("malformed JSON tunnel payload")}if(!t(n))throw new ie("unexpected JSON tunnel payload shape");return n},La=(e,t=Ao)=>{if(t<=0||t>Ao)throw new ie("invalid chunk size");if(e.length===0)return[new Uint8Array(0)];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},Qs=(e,t,n)=>{const r=La(n);return r.map((o,s)=>Oe(e,t,o,s<r.length-1))},Xl=(e=16*1024*1024)=>{const t=new Map;return{push(n){const r=`${n.streamId}:${n.frameType}`,o=t.get(r);if(!n.hasMoreFragments&&!o)return n.payload;const s=o?.chunks??[],i=(o?.totalBytes??0)+n.payload.length;if(i>e)throw t.delete(r),new ie("fragmented message exceeds maximum size");if(s.push(n.payload),n.hasMoreFragments)return t.set(r,{chunks:s,totalBytes:i}),null;t.delete(r);const a=new Uint8Array(i);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a},dropStream(n){for(const r of t.keys())r.startsWith(`${n}:`)&&t.delete(r)}}},Zl=e=>{if(e.length===0)throw new ie("cannot encode an empty frame batch");if(e.length===1){const o=e[0],s=new Uint8Array(1+o.length);if(s[0]=Ma,s.set(o,1),s.length>xn)throw new ie("frame batch exceeds maximum plaintext size");return s}let t=1;for(const o of e)t+=tn+o.length;if(t>xn)throw new ie("frame batch exceeds maximum plaintext size");const n=new Uint8Array(t);n[0]=Ra;let r=1;for(const o of e)n[r]=o.length>>>24&255,n[r+1]=o.length>>>16&255,n[r+2]=o.length>>>8&255,n[r+3]=o.length&255,r+=tn,n.set(o,r),r+=o.length;return n},ed=e=>{if(e.length<1)throw new ie("empty batch plaintext");const t=e[0];if(t===Ma)return[e.slice(1)];if(t!==Ra)throw new ie(`unknown batch container tag ${t}`);const n=[];let r=1;for(;r<e.length;){if(r+tn>e.length)throw new ie("truncated batch frame length");const o=(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0;if(r+=tn,r+o>e.length)throw new ie("truncated batch frame body");n.push(e.slice(r,r+o)),r+=o}if(n.length===0)throw new ie("empty frame batch");return n},td=new Set([L.HttpBody,L.WsText,L.WsBinary]),_a=150,nd=24*1024,rd=32,od=e=>{const t=e.windowMs??_a,n=e.maxBatchBytes??nd,r=e.maxBatchFrames??rd,o=e.now??(()=>Date.now()),s=e.setTimer??((g,y)=>setTimeout(g,y)),i=e.clearTimer??(g=>clearTimeout(g));let a=[],c=0,l=null,d=0,u=!1;const f=()=>{l!==null&&(i(l),l=null)},p=()=>{if(f(),a.length===0)return;const g=a;a=[],c=0,d=o(),e.sendBatch(Zl(g))};return{enqueue:g=>{if(u)return;const y=g[0]&~Dn;if(!td.has(y)){a.push(g),p();return}const b=o();if(a.length===0&&b-d>=t){a.push(g),p();return}const S=tn+g.length;if(a.length>0&&1+c+S>xn&&p(),a.push(g),c+=S,c>=n||a.length>=r){p();return}l===null&&(l=s(p,t))},flush:p,dispose(){u=!0,f(),a=[],c=0}}},sd=()=>{let e=1;return{next(){if(e>Oa)throw new ie("stream id space exhausted");const t=e;return e+=2,t}}},Nr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),id=e=>Nr(e)&&Object.values(e).every(t=>typeof t=="string"),ad=e=>Nr(e)&&typeof e.status=="number"&&id(e.headers),Xs=e=>Nr(e)&&typeof e.reason=="string",cd=e=>Nr(e)&&typeof e.code=="number"&&typeof e.reason=="string",Fa=/^[a-z][a-z\d+.-]*:\/\//i,us="http://tunnel.invalid",ld=e=>{try{const t=Fa.test(e)?new URL(e):new URL(e,us);return`${t.pathname}${t.search}`}catch{return e}},Jn=e=>({async*[Symbol.asyncIterator](){yield e}}),dd=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()}}}),ud=e=>{const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t},fd=async e=>{if(e==null)return{body:null};if(e instanceof ReadableStream)return{body:dd(e)};if(typeof e=="string")return{body:Jn(new TextEncoder().encode(e))};if(e instanceof ArrayBuffer)return{body:Jn(new Uint8Array(e.slice(0)))};if(ArrayBuffer.isView(e))return{body:Jn(ud(e))};const t=new Response(e),n=t.headers.get("content-type")??void 0,r=new Uint8Array(await t.arrayBuffer());return{body:Jn(r),contentType:n}},pd=async(e,t)=>{let n;const r=new Headers;let o="GET",s=null,i;e instanceof Request?(n=e.url,o=e.method,e.headers.forEach((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=Fa.test(n)?new URL(n):new URL(n,us),{body:c,contentType:l}=await fd(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}},ja="__aiworkerAmbiguousTransport",Ua=e=>(Object.defineProperty(e,ja,{value:!0,enumerable:!1,configurable:!0}),e),hd=e=>!e||typeof e!="object"?!1:e[ja]===!0,Yn=new Uint8Array(0),md=new TextEncoder,yd=new TextDecoder,Ee=e=>e instanceof Error?e:new Error(String(e)),Qn=()=>new DOMException("The operation was aborted.","AbortError"),gd=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},wd=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},Zs=0,Xr=1,ei=2,ti=3,bd=new Set([Mt.AuthFailed,Mt.DuplicateClient,Mt.LimitExceeded]),Sd={[Mt.AuthFailed]:"relay authentication failed",[Mt.DuplicateClient]:"relay connection replaced by another client",[Mt.LimitExceeded]:"relay connection limit reached"},ni=()=>{const e=typeof navigator<"u"&&navigator.onLine===!1,t=typeof document<"u"&&document.visibilityState==="hidden";return e||t},fs=e=>{const t=e.helloRetryMs??1e3,n=e.helloTimeoutMs??3e4,r=e.pingIntervalMs??3e4,o=e.pingTimeoutMs??15e3,s=e.batchWindowMs??_a,i=e.batch!==!1,a=e.reconnectBaseDelayMs??1e3,c=e.reconnectMaxDelayMs??3e4,l=e.hiddenOrOfflineMaxDelayMs??6e4,d=e.createWireSocket??(v=>gd(new WebSocket(v)));let u=!1,f={state:"idle"};const p=new Set;let h=null,g=null,y=null,b=0,S=0,E=null,M=[],W=!1;const A=v=>{if(!(f.state===v.state&&f.lastError===v.lastError)){f=v;for(const _ of p)try{_(f)}catch{}}},fe=v=>{const _=M;M=[];for(const I of _)I.reject(v)},Q=v=>{const _=M;M=[];for(const I of _)I.resolve(v)},zn=(v,_)=>{v.dead=!0;const I=Array.from(v.streams.values());v.streams.clear();for(const x of I)try{x.fail(_)}catch{}},pe=()=>{E!==null&&(clearTimeout(E),E=null)},fn=()=>{u||E===null||ni()||(pe(),R(),Nt())},Wn=()=>{typeof document<"u"&&document.visibilityState==="visible"&&fn()},Ut=()=>{W||typeof window>"u"||(W=!0,window.addEventListener("online",fn),typeof document<"u"&&document.addEventListener("visibilitychange",Wn))},R=()=>{!W||typeof window>"u"||(W=!1,window.removeEventListener("online",fn),typeof document<"u"&&document.removeEventListener("visibilitychange",Wn))},He=()=>{if(u||E!==null)return;const v=Math.max(0,S-1),_=a*2**Math.min(v,10),I=ni()?l:c,x=Math.min(I,_);Ut(),E=setTimeout(()=>{E=null,R(),Nt()},x)},pn=()=>{const v=new URL(e.relayUrl);return v.searchParams.set("v",String(vn)),v.searchParams.set("role","client"),v.searchParams.set("serverId",e.serverId),e.grant&&v.searchParams.set("grant",e.grant),v.toString()},Nt=async()=>{if(u)return;pe(),b+=1;const v=b;A({state:S>0?"reconnecting":"connecting",lastError:f.lastError});let _;try{_=await Vl(e.hostEncPubJwk,{batch:i})}catch(N){if(v!==b||u)return;he(v,Ee(N),!0);return}if(v!==b||u)return;let I;try{I=d(pn())}catch(N){he(v,Ee(N));return}g=I;let x=!1,D=null,j=null,ge=null,oe=null,O=Promise.resolve(),U=null,V=null,ze=!1,X=null,se=Date.now();const ae=()=>{D!==null&&(clearInterval(D),D=null),j!==null&&(clearTimeout(j),j=null),ge!==null&&(clearInterval(ge),ge=null),oe!==null&&(clearTimeout(oe),oe=null),X!==null&&(X.dispose(),X=null)};y=ae;function q(N,$=!1,H=!1){if(!(x||v!==b)){x=!0,ae(),U&&(h=null,zn(U,new Error(`relay tunnel reset: ${N.message}`))),fe(N);try{I.close()}catch{}if(g===I&&(g=null),!u){if(S+=1,H){A({state:"error",lastError:N.message});return}A({state:$?"error":"reconnecting",lastError:N.message}),He()}}}const wt=()=>{try{I.send(_.helloText)}catch{}},J=(N,$)=>{V=N,ze=$,D!==null&&(clearInterval(D),D=null),j!==null&&(clearTimeout(j),j=null);const H=new Map,Z=sd(),bt=Xl();let ke=Promise.resolve();const We=Ht=>{ke=ke.then(async()=>{if(Bt.dead)return;const Gn=await N.encryptor.encrypt(Ht);I.send(Gn)}).catch(()=>{})},St=$?od({windowMs:s,sendBatch:We}):null;X=St;const Bt={streams:H,assembler:bt,nextStreamId:()=>Z.next(),dead:!1,send(Ht){if(Bt.dead)return;const Gn=Ht[0]&~Dn;Gn!==L.Ping&&Gn!==L.Pong&&(se=Date.now()),St?St.enqueue(Ht):We(Ht)}};U=Bt,h=Bt,S=0,se=Date.now(),A({state:"connected"}),Q(Bt),ge=setInterval(()=>{Date.now()-se<r||(Bt.send(Oe(L.Ping,0,Yn)),oe===null&&(oe=setTimeout(()=>{oe=null,q(new Error("relay keepalive timeout"))},o)))},r)},tt=(N,$)=>{let H;try{H=Jl($)}catch(ke){q(Ee(ke));return}if(oe!==null&&(clearTimeout(oe),oe=null),H.frameType===L.Ping){N.send(Oe(L.Pong,H.streamId,Yn));return}if(H.frameType===L.Pong)return;se=Date.now();let Z=H.payload;if(H.frameType===L.WsText||H.frameType===L.WsBinary){let ke;try{ke=N.assembler.push(H)}catch(We){q(Ee(We));return}if(ke===null)return;Z=ke}else if(H.hasMoreFragments){q(new Error("unexpected fragmented tunnel frame"));return}const bt=N.streams.get(H.streamId);bt&&bt.handleFrame(H.frameType,Z)};I.onopen=()=>{x||v!==b||(wt(),D=setInterval(wt,t))},I.onmessage=N=>{if(x||v!==b)return;const $=N.data;if(typeof $=="string"){O=O.then(async()=>{if(x||v!==b)return;const Z=await _.handleText($);if(Z.type==="established"){if(V)return;J(Z.channel,Z.batch)}else Z.type==="fail"&&q(new Error(`relay handshake failed: ${Z.reason}`))}).catch(Z=>{q(Ee(Z))});return}const H=$ instanceof ArrayBuffer?new Uint8Array($):$ instanceof Uint8Array?$:null;H&&(O=O.then(async()=>{if(x||v!==b)return;const Z=U,bt=V;if(!Z||!bt){q(new Error("encrypted frame before handshake completed"));return}let ke;try{ke=await bt.decryptor.decrypt(H)}catch(We){q(Ee(We));return}if(ze){let We;try{We=ed(ke)}catch(St){q(Ee(St));return}for(const St of We){if(x||v!==b||Z.dead)return;tt(Z,St)}return}tt(Z,ke)}).catch(Z=>{q(Ee(Z))}))},I.onclose=N=>{const $=bd.has(N.code);q(new Error(Sd[N.code]??`relay socket closed (code ${N.code})`),$,$)},I.onerror=()=>{},j=setTimeout(()=>{j=null,q(new Error("relay handshake timeout"),!0)},n);function he(N,$,H=!1){N!==b||u||(fe($),S+=1,A({state:H?"error":"reconnecting",lastError:$.message}),He())}},$n=v=>u?Promise.reject(new Error("relay tunnel closed")):v?.aborted?Promise.reject(Qn()):h&&!h.dead?Promise.resolve(h):new Promise((_,I)=>{let x=null;const D={resolve(j){x&&v&&v.removeEventListener("abort",x),_(j)},reject(j){x&&v&&v.removeEventListener("abort",x),I(j)}};v&&(x=()=>{M=M.filter(j=>j!==D),I(Qn())},v.addEventListener("abort",x,{once:!0})),M.push(D)}),Jr=async(v,_)=>{const I=await pd(v,_),x=I.signal;if(x?.aborted)throw Qn();const D=await $n(x),j=D.nextStreamId();return await new Promise((ge,oe)=>{let O=!1,U=!1,V=null,ze=null;const X=()=>{D.streams.delete(j),D.assembler.dropStream(j),ze&&x&&x.removeEventListener("abort",ze)},se=J=>{if(!U){if(U=!0,X(),!O){oe(J);return}try{V?.error(J)}catch{}}},ae=J=>{D.dead||D.send(Oe(L.StreamAbort,j,qn({reason:J})))},q=J=>Ua(new Error(J));ze=()=>{ae("aborted"),se(Qn())},D.streams.set(j,{handleFrame(J,tt){if(J===L.HttpResponse){if(O||U)return;let he;try{he=Vn(tt,ad)}catch(H){ae("malformed response head"),se(q(Ee(H).message));return}const N=he.status===204||he.status===205||he.status===304;let $=null;N||($=new ReadableStream({start(H){V=H},cancel(){U||(U=!0,X(),ae("response body cancelled"))}})),O=!0,ge(new Response($,{status:he.status,headers:he.headers})),N&&(U=!0,X());return}if(J===L.HttpBody){if(!O||U)return;try{V?.enqueue(tt)}catch{}return}if(J===L.StreamEnd){if(U)return;if(!O){se(q("tunnel stream ended before response head"));return}U=!0,X();try{V?.close()}catch{}return}if(J===L.StreamAbort){let he="stream aborted by host";try{he=Vn(tt,Xs).reason}catch{}se(q(he))}},fail(J){se(q(J.message))}}),x&&x.addEventListener("abort",ze,{once:!0});const wt={method:I.method,path:I.path,query:I.query,headers:I.headers,hasBody:I.body!==null};D.send(Oe(L.HttpRequest,j,qn(wt))),(async()=>{try{let J=!1;if(I.body)for await(const tt of I.body){if(U||D.dead)return;for(const he of La(tt))D.send(Oe(L.HttpBody,j,he)),J=!0}!U&&!D.dead&&(I.body&&!J&&D.send(Oe(L.HttpBody,j,Yn)),D.send(Oe(L.StreamEnd,j,Yn)))}catch(J){ae("request body failed"),se(q(Ee(J).message))}})()})},et=v=>{const _=v.indexOf("?");return _===-1?{path:v,query:""}:{path:v.slice(0,_),query:v.slice(_+1)}},Yr=(v,_)=>{let I=Zs,x=null,D=0,j=!1;const ge={get readyState(){return I},onopen:null,onmessage:null,onerror:null,onclose:null,send(O){if(I!==Xr||!x||x.dead)throw new Error("relay tunnel socket is not open");if(typeof O=="string"){for(const V of Qs(L.WsText,D,md.encode(O)))x.send(V);return}const U=O instanceof ArrayBuffer?new Uint8Array(O.slice(0)):(()=>{const V=new Uint8Array(O.byteLength);return V.set(new Uint8Array(O.buffer,O.byteOffset,O.byteLength)),V})();for(const V of Qs(L.WsBinary,D,U))x.send(V)},close(O=1e3,U=""){I===ti||I===ei||(I===Xr&&x&&!x.dead&&(I=ei,x.send(Oe(L.WsClose,D,qn({code:O,reason:U})))),oe(O,U))}},oe=(O,U,V=!1)=>{if(!j){if(j=!0,x&&(x.streams.delete(D),x.assembler.dropStream(D)),I=ti,V)try{ge.onerror?.()}catch{}try{ge.onclose?.({code:O,reason:U})}catch{}}};return(async()=>{let O;try{O=await $n()}catch(X){oe(1006,Ee(X).message,!0);return}if(j)return;x=O,D=O.nextStreamId(),O.streams.set(D,{handleFrame(X,se){if(X===L.WsOpened){if(I===Zs){I=Xr;try{ge.onopen?.()}catch{}}return}if(X===L.WsText){try{ge.onmessage?.({data:yd.decode(se)})}catch{}return}if(X===L.WsBinary){const ae=new ArrayBuffer(se.byteLength);new Uint8Array(ae).set(se);try{ge.onmessage?.({data:ae})}catch{}return}if(X===L.WsClose){let ae=1e3,q="";try{const wt=Vn(se,cd);ae=wt.code,q=wt.reason}catch{}oe(ae,q);return}if(X===L.StreamAbort){let ae="stream aborted";try{ae=Vn(se,Xs).reason}catch{}oe(1006,ae,!0)}},fail(X){oe(1012,X.message,!0)}});const{path:U,query:V}=et(v),ze=_&&_.length>0?{path:U,query:V,protocols:_}:{path:U,query:V};O.send(Oe(L.WsOpen,D,qn(ze)))})(),ge},Il=()=>{if(u)return;u=!0,b+=1,pe(),R(),y?.(),y=null;const v=h;h=null;const _=new Error("relay tunnel closed");v&&zn(v,_),fe(_);try{g?.close()}catch{}g=null,A({state:"idle"})};return Nt(),{fetch:Jr,openWebSocket:Yr,getStatus:()=>f,subscribeStatus(v){return p.add(v),()=>{p.delete(v)}},close:Il}};let Te=null,Qe=null;const Td=(e,t)=>e.relayUrl===t.relayUrl&&e.serverId===t.serverId&&e.grant===t.grant&&JSON.stringify(e.hostEncPubJwk)===JSON.stringify(t.hostEncPubJwk),Br=()=>Te,Fg=()=>!Te||!Qe?null:{relayUrl:Qe.relayUrl,serverId:Qe.serverId,hostEncPubJwk:{...Qe.hostEncPubJwk}},jg=()=>Te!==null,kd=e=>(Te&&Qe&&Td(Qe,e)||(Te?.close(),Qe=e,Te=fs(e)),Te),Ug=(e,t)=>{Te!==t&&(Te?.close(),Qe=e,Te=t)},vd=()=>{Te?.close(),Te=null,Qe=null};let Na=()=>null,Ba="",br={},Ct="",On=0,Et=null,Zt="",Ln=0,Dt="",At=null,dt="",ur=0,fr=0;const ps=1e4,Ed=e=>e.toLowerCase()==="authorization",Ha=e=>{const t={};for(const[n,r]of Object.entries(e||{})){const o=n.trim(),s=r.trim();o&&s&&!Ed(o)&&(t[o]=s)}return t},Ad=(e,t)=>{const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([r,o])=>t[r]===o)},Hr=e=>typeof e!="string"?"":e.trim(),Pd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_CLIENT_TOKEN__;return Hr(e)},Id=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return typeof e=="string"?e.trim():""},za=(e,t)=>{const n=typeof e=="string"&&e.trim()?e.trim():Id();if(!n)return t;try{return new URL(t,`${n.replace(/\/+$/,"")}/`).toString()}catch{return t}},hs=e=>{try{return new URL(e).origin}catch{return""}},Wa=()=>{Zt="",Ln=0,Dt="",At=null,dt="",ur+=1},Nn=()=>{Ct="",On=0,Wa()},$a=()=>{fr+=1,Et=null,Nn(),ms()},Ga=e=>{const t=Hr(e);Ba=t,$a(),Na=()=>t?{type:"bearer",token:t}:null},Ka=e=>{const t=Ha(e);Ad(br,t)||(br=t,$a())},zr=()=>{if(Object.keys(br).length>0)return br;if(typeof window>"u")return{};const e=window.__AIWORKER_RUNTIME_HEADERS__;return e&&typeof e=="object"?Ha(e):{}},qa=()=>Ba||Pd(),Md=(e,t)=>{const n=Hr(e);if(!n||typeof t!="number"||!Number.isFinite(t)){Nn();return}const r=Ct;Ct=n,On=t,r&&r!==n&&Od()},Va=()=>!Ct||On<=Date.now()+ps?(Nn(),""):Ct,Ja=e=>{const t=hs(e);return!t||Dt!==t?"":!Zt||Ln<=Date.now()+ps?(Zt="",Ln=0,Dt="",""):Zt},Rd=()=>{const e=Va();return!e&&(qa()||typeof window<"u")&&Wr().catch(()=>{}),e},xd=e=>{const t=e?Ja(e):"";return!t&&e&&typeof window<"u"&&Xa(e).catch(()=>{}),t},Ya=async()=>{const e=await Na(),t=e?.type==="bearer"?Hr(e.token):qa();return t?{type:"bearer",token:t}:null},Qa=e=>{if(Et)return Et;const t=fr,r=(async()=>{const o=await Ya(),s=new Headers;for(const[u,f]of Object.entries(zr()))s.set(u,f);o?.type==="bearer"&&s.set("Authorization",`Bearer ${o.token}`);const i=Br(),a=i?await i.fetch("/auth/url-token",{method:"POST",headers:s}):await fetch(za(e,"/auth/url-token"),{method:"POST",headers:s,credentials:"include"});if(!a.ok)throw t===fr&&Nn(),new Error(`Failed to mint runtime URL auth token (${a.status})`);const c=await a.json().catch(()=>null),l=typeof c?.token=="string"?c.token.trim():"",d=typeof c?.expiresAt=="number"?c.expiresAt:0;if(t!==fr)throw new Error("Runtime URL auth token response is stale");if(Md(l,d),!Ct)throw new Error("Runtime URL auth token response was invalid");return Ct})().finally(()=>{Et===r&&(Et=null)});return Et=r,Et},Cd=e=>{const t=hs(e);if(!t)return Promise.reject(new Error("Local runtime URL auth origin was invalid"));if(At&&dt===t)return At;const n=ur,o=(async()=>{const s=await fetch(za(t,"/auth/url-token"),{method:"POST",credentials:"include"});if(!s.ok)throw n===ur&&t===dt&&(Zt="",Ln=0,Dt=""),new Error(`Failed to mint local runtime URL auth token (${s.status})`);const i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token.trim():"",c=typeof i?.expiresAt=="number"?i.expiresAt:0;if(!a||!Number.isFinite(c))throw new Error("Local runtime URL auth token response was invalid");if(n!==ur||t!==dt)throw new Error("Local runtime URL auth token response is stale");return Zt=a,Ln=c,Dt=t,a})().finally(()=>{At===o&&(At=null,dt="")});return At=o,dt=t,At},Wr=async e=>{const t=Va();return t||Qa(e)},Xa=async e=>{const t=hs(e);if(!t)throw new Error("Local runtime URL auth origin was invalid");const n=Ja(t);return n||((Dt&&Dt!==t||dt&&dt!==t)&&Wa(),Cd(t))};let Jt=0,An=null,Za=null;const Io=new Set,Dd=5e3,Od=()=>{for(const e of Io)try{e()}catch{}},ec=()=>{An!==null&&(clearTimeout(An),An=null)},ms=()=>{if(ec(),Jt<=0||typeof window>"u")return;const e=On-ps-Dd,t=On>0?Math.max(0,e-Date.now()):0;An=setTimeout(()=>{An=null,!(Jt<=0)&&Qa(Za).catch(()=>{}).finally(()=>{ms()})},t)},Ng=e=>{typeof e=="string"&&e.trim()&&(Za=e.trim()),Jt+=1,ms();let t=!1;return()=>{t||(t=!0,Jt=Math.max(0,Jt-1),Jt===0&&ec())}},Bg=e=>(Io.add(e),()=>{Io.delete(e)}),Ld=async e=>{const t=new Headers(e);for(const[r,o]of Object.entries(zr()))t.has(r)||t.set(r,o);if(t.has("Authorization"))return t;const n=await Ya();return n?.type==="bearer"&&t.set("Authorization",`Bearer ${n.token}`),t},Sr=Ze(e=>({state:"ok",markExpired:()=>e(t=>t.state==="expired"?t:{state:"expired"}),markReauthenticating:()=>e({state:"reauthenticating"}),markAuthenticated:()=>e({state:"ok"})})),_d=15e3,Fd=5*6e4;let Mo=0,Zr=!1;const jd=e=>e.includes("/auth/session")||e.includes("/api/client-auth/"),Ud=e=>{const t=e.startsWith("/")?e:(()=>{try{return new URL(e).pathname}catch{return""}})();return!t.startsWith("/api/")&&!t.startsWith("/auth/")?!1:!jd(t)},tc=async()=>{if(!Zr){Zr=!0;try{const{runtimeFetch:e}=await ls(async()=>{const{runtimeFetch:n}=await Promise.resolve().then(()=>ru);return{runtimeFetch:n}},void 0),t=await e("/auth/session",{credentials:"include"});if(t.status===401){Sr.getState().markExpired();return}if(t.ok){const{state:n,markAuthenticated:r}=Sr.getState();n==="expired"&&r()}}catch{}finally{Zr=!1}}},Nd=(e,t)=>{if(t!==401||Sr.getState().state==="expired"||!Ud(e))return;const n=Date.now();n-Mo<_d||(Mo=n,tc())};let ri=!1;const Hg=()=>{if(ri)return;ri=!0;let e=Date.now();const t=()=>{if(Sr.getState().state!=="ok")return;const n=Date.now();n-e<Fd||(e=n,Mo=n,tc())};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t)},Tr=/^[a-z][a-z\d+.-]*:\/\//i,Bd=e=>{const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:"/"},kr=e=>typeof e!="string"?"":e.trim().replace(/\/+$/,""),Hd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return kr(e)},zd=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_LOCAL_ORIGIN__;return kr(e)},Wd=()=>Object.keys(zr()).length>0,$d=e=>{const t=e.currentHref?.();return t||(typeof window<"u"?window.location.href||window.location.origin:"")},Ro=(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))},Gd=(e,t)=>{if(!t)return e;const n=new URLSearchParams;Ro({searchParams:n},t);const r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e},oi=(e,t,n)=>{if(Tr.test(t)){const s=new URL(t);return Ro(s,n),s.toString()}const r=Bd(t);if(!e)return Gd(r,n);const o=new URL(r,`${e}/`);return Ro(o,n),o.toString()},eo=e=>{const t=Rd();if(!t)return e;const n=Tr.test(e)?new URL(e):new URL(e,"http://openchamber.local");return n.searchParams.set("oc_url_token",t),Tr.test(e)?n.toString():`${n.pathname}${n.search}${n.hash}`},nc=(e,t)=>{const n=Tr.test(e)?new URL(e):new URL(e,$d(t));return n.protocol==="ws:"||n.protocol==="wss:"||(n.protocol=n.protocol==="https:"?"wss:":"ws:"),n.toString()},si=(e,t,n)=>{if(!Wd())return null;const r=zd();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=xd(r);return s&&o.searchParams.set("oc_url_token",s),e==="ws"?(o.protocol=o.protocol==="https:"?"wss:":"ws:",nc(o.toString(),n)):o.toString()}catch{return null}},ys=(e={})=>{const t=kr(e.apiBaseUrl),n=kr(e.realtimeBaseUrl),r=()=>t||Hd(),o=()=>n||r(),s=(a,c)=>oi(r(),a,c),i=(a,c)=>oi(o(),a,c);return{api:s,authenticatedAsset:(a,c)=>eo(s(a,c)),auth:s,health:a=>s("/health",a),rawFile:(a,c)=>s("/api/fs/raw",{path:a,download:c?.download===!0?!0:void 0,allowOutsideWorkspace:c?.allowOutsideWorkspace===!0?!0:void 0,outsideFileGrant:c?.outsideFileGrant}),sse:(a,c)=>{const l=eo(i(a,c));return si("sse",l,e)||l},websocket:(a,c)=>{const l=nc(eo(i(a,c)),e);return si("ws",l,e)||l}}};let vr=ys();const ye=()=>vr,Kd=e=>{vr=e},rc=e=>(vr=ys(e),vr),Ot=e=>e.startsWith("/api/")||e==="/api"||e.startsWith("/auth/")||e==="/auth"||e==="/health",qd=()=>typeof window>"u"?"":window.location.origin||"",gs=e=>{if(typeof window>"u")return!1;const t=qd();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}},ws=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),Vd=e=>/(^|\.)ngrok(?:-free)?\.(?:app|dev|io)$/i.test(e),at=(e,t)=>{try{Vd(new URL(e).hostname)&&!t.has("ngrok-skip-browser-warning")&&t.set("ngrok-skip-browser-warning","aiworker")}catch{}return t},bs=(e,t)=>{if(!t)return;const n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(const[r,o]of n)o!=null&&e.searchParams.set(r,String(o))},pr=e=>{try{const t=ye().api("/api");if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;const n=new URL(t);return e.origin!==n.origin?!1:Ot(e.pathname)}catch{return!1}},to=e=>{if(Ot(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{const t=new URL(e);return gs(t)&&Ot(t.pathname)}catch{return!1}},Jd=(e,t)=>{try{const n=new URL(e);if(!gs(n))return e;const r=ht(`${n.pathname}${n.search}`,t);return!ws(r)&&(n.protocol==="http:"||n.protocol==="https:")?(bs(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},ht=(e,t)=>e==="/health"?ye().health(t):e.startsWith("/auth/")||e==="/auth"?ye().auth(e,t):Ot(e)?ye().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?Jd(e,t):e,Yd=e=>{const t=e instanceof Request?e.url:e.toString();if(!ws(t))return Ot(t);try{return pr(new URL(t))}catch{return!1}},oc=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Qd=(e,t)=>!oc(t),xo=e=>{if(!e)return;const t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;const n=[];let r=!1,o=!1;for(const[s,i]of t)Qd(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(xo(e)??e);return t&&new Headers(xo(t)??t).forEach((o,s)=>r.set(s,o)),n?Ld(r):r},Xd=(e,t)=>{if(!t)return e;const n=new URL(e,us);return bs(n,t),`${n.pathname}${n.search}`},sc=(e,t)=>{const n=e instanceof Request?e.url:e.toString();if(!ws(n))return Ot(n)?Xd(n,t):null;try{const r=new URL(n);return!gs(r)||!Ot(r.pathname)?null:(bs(r,t),`${r.pathname}${r.search}`)}catch{return null}},Zd=async(e,t,n)=>{const r=Br();if(!r)return null;const o=sc(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})},ic="half",Co=(e,t={})=>{const n={...t,duplex:ic};return new Request(e,n)},ac=(e,t)=>{const n={method:e.method,headers:e.headers,body:e.body,signal:e.signal,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,duplex:ic};return new Request(t,n)},eu=(e,t)=>{if(typeof e=="string")return ht(e,t);if(e instanceof URL)return ht(e.toString(),t);const n=ht(e.url,t);return n===e.url?e:ac(e,n)},tu=/\/api\/(config|path|app\/agents|agent|project|command)(\b|\/|\?|$)/,Xn=new Map,nu=(e,t,n)=>n||e!=="GET"||t.includes("/event")||!tu.test(t)?null:`GET ${t}`,m=async(e,t={})=>{const{query:n,...r}=t,o=Br(),s=o?sc(e,n):null;let i,a,c;if(o&&s!==null){const h=e instanceof Request?e.headers:void 0,g=await $e(h,r.headers,!0);i=e instanceof Request?()=>o.fetch(e,{...r,headers:g}):()=>o.fetch(s,{...r,headers:g}),a=s,c=String(r.method??(e instanceof Request?e.method:"GET")).toUpperCase()}else{const h=eu(e,n),g=h instanceof Request?h.headers:void 0,y=await $e(g,r.headers,Yd(h)),b=h instanceof Request?h.url:h instanceof URL?h.toString():String(h);at(b,y),i=h instanceof Request?()=>fetch(Co(h,{...r,headers:y})):()=>fetch(h,{...r,headers:y}),a=b,c=String(r.method??(h instanceof Request?h.method:"GET")).toUpperCase()}const l=i;i=()=>l().then(h=>(Nd(a,h.status),h));const d=r.signal!=null||e instanceof Request,u=nu(c,a,d);if(!u)return i();const f=Xn.get(u);if(f)return f.then(h=>h.clone());const p=i();return Xn.set(u,p),p.then(()=>Xn.delete(u),()=>Xn.delete(u)),p.then(h=>h.clone())};let ii=!1;const cc=()=>{if(ii||typeof window>"u")return;ii=!0;const e=window.fetch.bind(window);window.fetch=async(t,n)=>{const r=await Zd(t,n??{});if(r)return r;if(typeof t=="string"){if(!to(t)){try{const i=new URL(t);if(pr(i)){const a=await $e(void 0,n?.headers);return at(i.toString(),a),e(t,{...n,headers:a})}}catch{}return e(t,n)}const o=await $e(void 0,n?.headers),s=ht(t);return at(s,o),e(s,{...n,headers:o})}if(t instanceof URL){const o=t.toString();if(!to(o)){if(pr(t)){const a=await $e(void 0,n?.headers);return at(t.toString(),a),e(t,{...n,headers:a})}return e(t,n)}const s=await $e(void 0,n?.headers),i=ht(o);return at(i,s),e(i,{...n,headers:s})}if(t instanceof Request){if(!to(t.url)){try{const a=new URL(t.url);if(pr(a)){const c=await $e(t.headers,n?.headers);return at(a.toString(),c),e(Co(t,{...n,headers:c}))}}catch{}return e(t,n)}const o=await $e(t.headers,n?.headers),s=ht(t.url);at(s,o);const i=s===t.url?t:ac(t,s);return e(Co(i,{...n,headers:o}))}return e(t,n)}},ru=Object.freeze(Object.defineProperty({__proto__:null,addRuntimeProxyHeaders:at,buildRuntimeFetchUrl:ht,installRuntimeFetchBridge:cc,isLatin1Safe:oc,runtimeFetch:m,sanitizeHeadersForBrowser:xo},Symbol.toStringTag,{value:"Module"})),Do="aiworker:runtime-endpoint-changed",Oo="aiworker:runtime-endpoint-will-change";let nn="",_n="";const no=(e,t,n)=>{try{e[t]=n}catch{}},Ss=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"}`}},ou="mobile-disconnected",su="url:default",lc=e=>e===""||e===su||e===ou,dc=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_API_BASE_URL__;return typeof e=="string"?e.trim():""},uc=()=>{if(typeof window>"u")return"";const e=window.__AIWORKER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},fc=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},$r=()=>nn||dc();let ro="",ai=null,ci,li;const di=e=>{if(typeof window>"u")return;const t=window[e];return typeof t=="string"?t:void 0},B=()=>{if(_n)return _n;const e=di("__AIWORKER_API_BASE_URL__"),t=di("__AIWORKER_LOCAL_ORIGIN__");if(ai===nn&&ci===e&&li===t)return ro;const n=$r();return ro=fc(n,uc())?"local":Ss(n),ai=nn,ci=e,li=t,ro},iu=(e={})=>{if(nn||_n)return;const t=e.apiBaseUrl?.trim()||dc();t&&(nn=t,_n=e.runtimeKey?.trim()||(fc(t,uc())?"local":Ss(t)))},Er=e=>{const t=e.apiBaseUrl.trim(),n=$r(),r=B(),o=e.runtimeKey?.trim()||Ss(t),s={apiBaseUrl:t,previousApiBaseUrl:n,runtimeKey:o,previousRuntimeKey:r};if(typeof window<"u"&&window.dispatchEvent(new CustomEvent(Oo,{detail:s})),nn=t,_n=o,typeof window<"u"){const i=window;no(i,"__AIWORKER_API_BASE_URL__",t),no(i,"__AIWORKER_CLIENT_TOKEN__",e.clientToken||void 0),no(i,"__AIWORKER_RUNTIME_HEADERS__",e.requestHeaders||void 0)}rc({apiBaseUrl:t,realtimeBaseUrl:t}),Ka(e.requestHeaders||null),Ga(e.clientToken||null),e.relay?kd(e.relay):vd(),Wr(t).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Do,{detail:s}))},au=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Oo,t),()=>window.removeEventListener(Oo,t)},pc=e=>{if(typeof window>"u")return()=>{};const t=n=>{e(n.detail)};return window.addEventListener(Do,t),()=>window.removeEventListener(Do,t)},cu=["local","remote",null],lu=["ok","not-configured","unreachable","incompatible","wrong-service","missing"];function hc(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"||!cu.includes(r)))return{valid:!1};if(typeof o!="string"||!lu.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 zg(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 Wg(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1?!0:e.isInitialized:!1:e.isInitialized}function $g(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function mc(){if(du()!=="valid")return null;const t=window.__AIWORKER_DESKTOP_BOOT_OUTCOME__,n=hc(t);return n.valid?n.outcome:null}function du(){if(typeof window>"u")return"not-injected";const e=window.__AIWORKER_DESKTOP_BOOT_OUTCOME__;return e==null?"not-injected":hc(e).valid?"valid":"malformed"}let Lo=null;const Gg=e=>{Lo=e},Gr=()=>Lo||(typeof window>"u"?null:window.__AIWORKER_RUNTIME_APIS__??null),yc=()=>typeof window>"u"?null:window.__VSCODE_CONFIG__??null,uu=(e=yc())=>!!e,fu=()=>typeof window>"u"?null:window.__AIWORKER_ELECTRON__??null,cn=()=>typeof window>"u"?null:window.__AIWORKER_DESKTOP__??null,_t=()=>fu()?.runtime==="electron",pu=()=>{if(typeof window>"u")return null;const e=window.__AIWORKER_PLATFORM__;return typeof e=="string"?e:null},hu="right",Kg=()=>{if(!_t())return!1;const e=pu();return e==="win32"||e==="linux"},qg=e=>e==="left"?"left":hu,Vg=e=>e==="left"?["close","minimize","maximize"]:["minimize","maximize","close"],de=()=>typeof cn()?.invoke=="function",ln=()=>_t()&&de(),Y=async(e,t)=>{const n=cn();return typeof n?.invoke!="function"?null:n.invoke(e,t??{})},Jg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_launch_at_login");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get launch at login status",e),null}},Yg=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_launch_at_login",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set launch at login status",t),null}},Qg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_minimize_to_tray");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"?null:e}catch(e){return console.warn("Failed to get minimize to tray status",e),null}},Xg=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_minimize_to_tray",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"?null:t}catch(t){return console.warn("Failed to set minimize to tray status",t),null}},Zg=async()=>{if(!ln()||!ue())return null;try{const e=await Y("desktop_get_keep_awake");return!e||typeof e.supported!="boolean"||typeof e.enabled!="boolean"||typeof e.active!="boolean"?null:e}catch(e){return console.warn("Failed to get keep awake status",e),null}},ew=async e=>{if(!ln()||!ue())return null;try{const t=await Y("desktop_set_keep_awake",{enabled:e});return!t||typeof t.supported!="boolean"||typeof t.enabled!="boolean"||typeof t.active!="boolean"?null:t}catch(t){return console.warn("Failed to set keep awake status",t),null}},ui=e=>{const t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith("/")?t:`${t}/`).origin}catch{return null}}},oo=e=>{const t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith("/")?t:`${t}/`)}catch{return null}}},mu=e=>e.replace(/^\[|\]$/g,"").toLowerCase(),hn=e=>{const t=mu(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},ue=()=>{if(typeof window>"u"||!gt())return!1;if(B()==="local")return!0;const e=typeof window.__AIWORKER_LOCAL_ORIGIN__=="string"?window.__AIWORKER_LOCAL_ORIGIN__:"",t=oo(e),n=oo($r());if(!n&&t&&mc()?.target==="local")return!0;if(t&&n){if(t.origin===n.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=n.port||(n.protocol==="https:"?"443":"80");return t.protocol===n.protocol&&i===a&&hn(t.hostname)&&hn(n.hostname)}const r=oo(window.location.origin);if(t&&r){if(t.origin===r.origin)return!0;const i=t.port||(t.protocol==="https:"?"443":"80"),a=r.port||(r.protocol==="https:"?"443":"80");return t.protocol===r.protocol&&i===a&&hn(t.hostname)&&hn(r.hostname)}const o=ui(e),s=ui(window.location.origin)||window.location.origin;return o&&s&&o===s?!0:!!(r&&hn(r.hostname))},gt=()=>typeof window>"u"?!1:_t(),tw=async()=>{if(!gt())return!1;try{return!!await Y("desktop_focus_window")}catch{return!1}},yu=()=>gt()&&de()&&ue(),nw=async()=>{if(!gt())return!1;try{return await Y("desktop_start_window_drag"),!0}catch{return!1}},Be=()=>uu()?!0:Gr()?.runtime?.isVSCode===!0,rw=()=>{const t=Gr()?.runtime?.platform;return t==="web"?!0:t==="desktop"||t==="vscode"?!1:!Be()},ow=(e,t=gt())=>e==="web"&&!t,gc=async()=>{if(typeof window<"u"){const e=window.__AIWORKER_HOME__;if(e&&e.length>0)return e}return null},sw=async e=>{if(yu())try{const t=await cn()?.openDialog?.({directory:!0,multiple:!1,title:"Select Working Directory",...e?{defaultPath:e}:{}});return!t||typeof t!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:t}}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}return{success:!1,error:"Native directory picker not available"}},gu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wu=P({path:w().min(1),outsideFileGrant:w().min(1),expiresAt:C().finite()}),iw=async e=>{if(de()&&ue())try{const t=await cn()?.openDialog?.({directory:!1,multiple:!1,title:"Select File",returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:"File selection cancelled"};if(typeof t=="string")return{success:!0,path:t};if(!gu(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"}},aw=async e=>{const t=typeof e=="string"?e.trim():"";if(!t)return{success:!1,error:"Path is required"};if(!de()||!ue())return{success:!1,error:"Native file access not available"};try{const n=await cn()?.grantFileAccess?.(t),r=wu.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)}}},cw=async e=>({success:!0}),lw=async e=>({success:!0}),dw=async()=>de()?await Y("desktop_check_for_updates"):null,uw=async e=>{if(!de())return!1;const t=cn();let n=null,r=0,o;try{return typeof e=="function"&&t?.listen&&(n=await t.listen("aiworker:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,c=typeof a.event=="string"?a.event:null,l=a.data&&typeof a.data=="object"?a.data:null;if(c==="Started"){r=0,o=typeof l?.contentLength=="number"?l.contentLength:void 0,e({downloaded:r,total:o});return}if(c==="Progress"){const d=l?.downloaded,u=l?.total;typeof d=="number"&&(r=d),typeof u=="number"&&(o=u),e({downloaded:r,total:o});return}c==="Finished"&&e({downloaded:r,total:o})})),await Y("desktop_download_and_install_update"),!0}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{if(n)try{const s=n();s instanceof Promise&&await s}catch{}}},fw=async()=>de()?(await Y("desktop_restart"),!0):!1,pw=async()=>{if(!de())return!1;try{return await Y("desktop_restart"),!0}catch(e){return console.warn("Failed to restart desktop app",e),!1}},hw=async()=>{if(!de()||!ue())return null;try{const e=await Y("desktop_get_lan_address");return typeof e=="string"&&e.trim().length>0?e.trim():null}catch(e){return console.warn("Failed to get desktop LAN address",e),null}},bu=async(e,t)=>{if(!de()||!ue())return!1;const n=e?.trim();if(!n)return!1;try{return await Y("desktop_open_path",{path:n,app:typeof t=="string"&&t.trim().length>0?t.trim():void 0}),!0}catch(r){return console.warn("Failed to open path",r),!1}},mw=async e=>{if(!de()||!ue())return!1;const t=e?.trim();if(!t)return!1;try{return await Y("desktop_reveal_path",{path:t}),!0}catch{return bu(t)}},yw=async(e,t)=>{if(!de()||!ue())return null;const n=e?.trim();if(!n)return null;try{const r=await Y("desktop_save_markdown_file",{defaultFileName:n,content:t});return typeof r=="string"&&r.trim().length>0?r:null}catch(r){return console.warn("Failed to save markdown file",r),null}},gw=async(e,t,n)=>{if(!de()||!ue())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await Y("desktop_open_in_app",{projectPath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open project in app",i),!1}},ww=async(e,t,n)=>{if(!de()||!ue())return!1;const r=e?.trim(),o=t?.trim(),s=n?.trim();if(!r||!o||!s)return!1;try{return await Y("desktop_open_file_in_app",{filePath:r,appId:o,appName:s}),!0}catch(i){return console.warn("Failed to open file in app",i),!1}},bw=async(e,t)=>{if(!de()||!ue())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const r=await Y("desktop_get_installed_apps",{apps:n,force:t===!0?!0:void 0});if(!r||typeof r!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const o=r;return o.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(o.apps)?{apps:o.apps.filter(i=>i&&typeof i=="object").map(i=>{const a=i;return{name:typeof a.name=="string"?a.name:"",iconDataUrl:typeof a.iconDataUrl=="string"?a.iconDataUrl:null}}).filter(i=>i.name.length>0),success:!0,hasCache:o.hasCache===!0,isCacheStale:o.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},en=16384,Ar=globalThis,Su=e=>{if(Ar.Buffer)return Ar.Buffer.from(e,"utf8").toString("base64url");const t=new TextEncoder().encode(e);let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.slice(r,r+32768));return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},wc=e=>{try{if(Ar.Buffer)return Ar.Buffer.from(e,"base64url").toString("utf8");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)r[o]=n.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}},Tu=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}},ku=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}},fi=e=>typeof e=="string"&&e.length>0,vu=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.kty!=="EC"||t.crv!=="P-256"||!fi(t.x)||!fi(t.y)?null:{kty:"EC",crv:"P-256",x:t.x,y:t.y}},Eu=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Au=e=>{if(!e||typeof e!="object")return null;const t=e,n=Eu(t.priority);if(t.type==="lan"||t.type==="tunnel"){const r=Tu(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=ku(t.relayUrl);if(!r)return null;const o=typeof t.serverId=="string"?t.serverId.trim():"";if(!o)return null;const s=vu(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},Ts=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(Au).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}},Sw=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}),Tw=e=>{const t=Ts(e);if(!t)throw new Error("Invalid pairing connection payload");const n=new URLSearchParams;return n.set("v","2"),n.set("p",Su(JSON.stringify(t))),`aiworker://connect?${n.toString()}`},Pu=e=>{const t=e.trim();if(!t||t.length>en)return null;try{const n=new URL(t);if(n.protocol!=="aiworker:"||n.hostname!=="connect"||n.searchParams.get("v")!=="2")return null;const r=n.searchParams.get("p")||"";if(!r||r.length>en)return null;const o=wc(r);return!o||o.length>en?null:Ts(JSON.parse(o))}catch{return null}},kw=e=>{const t=e.trim();if(!t||t.length>en)return null;const n=t.indexOf("?");if(n===-1||!/^aiworker:\/\/connect\/?$/i.test(t.slice(0,n)))return null;let r=null,o=null;for(const i of t.slice(n+1).split("&")){const a=i.indexOf("=");if(a===-1)continue;const c=i.slice(0,a),l=i.slice(a+1);c==="v"?r=l:c==="p"&&(o=l)}if(r!=="2"||!o||o.length>en)return null;const s=wc(o);if(!s||s.length>en)return null;try{return Ts(JSON.parse(s))}catch{return null}},rn=e=>typeof e=="object"&&e!==null,Iu=e=>e.trim().toLowerCase()==="authorization",Mu=e=>{if(!rn(e))return;const t={};for(const[n,r]of Object.entries(e)){const o=n.trim(),s=typeof r=="string"?r.trim():"";!o||!s||/[\r\n:]/.test(o)||/[\r\n]/.test(s)||Iu(o)||(t[o]=s)}return Object.keys(t).length>0?t:void 0},Ru=e=>`relay://${e}`,xu=e=>{if(!rn(e))return null;const t=ce(e,"relayUrl")||ce(e,"relay_url"),n=ce(e,"serverId")||ce(e,"server_id"),r=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!rn(r)?null:{relayUrl:t,serverId:n,hostEncPubJwk:r}},Cu=()=>{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"},vw=async(e,t)=>{const n=Pu(e);if(!n)throw new Error("invalid-connect-link");const r=await Fu().catch(()=>""),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pairingId:n.pairingId,secret:n.secret,clientLabel:n.label||"AiWorker Desktop",clientKind:"desktop",deviceName:"AiWorker Desktop",devicePlatform:Cu(),...r?{dedupeKey:`desktop:${r}`}:{}})},s=async y=>{if(!y.ok)return null;const b=await y.json().catch(()=>null);return(typeof b?.clientToken=="string"?b.clientToken.trim():"")||null};let i=null;const a=[...n.candidates].sort((y,b)=>(y.type==="relay"?1:0)-(b.type==="relay"?1:0));for(const y of a){if(y.type==="relay"){const S=fs({relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk,...y.grant?{grant:y.grant}:{}});try{const E=await s(await S.fetch("/api/client-auth/pairing/redeem",o));if(E){i={relay:{relayUrl:y.relayUrl,serverId:y.serverId,hostEncPubJwk:y.hostEncPubJwk},token:E};break}}catch{}finally{S.close()}continue}const b=le(y.url);if(b)try{const S=await s(await fetch(`${b}/api/client-auth/pairing/redeem`,o));if(S){i={directUrl:b,token:S};break}}catch{}}if(!i)throw new Error("pairing-redeem-failed");const c=n.candidates.find(y=>y.type==="relay"),l=i.relay||(c?{relayUrl:c.relayUrl,serverId:c.serverId,hostEncPubJwk:c.hostEncPubJwk}:void 0),d=n.candidates.filter(y=>y.type!=="relay").map(y=>le(y.url)).find(y=>!!y),u=i.directUrl||d,f=u||(l?Ru(l.serverId):null);if(!f)throw new Error("pairing-missing-transport");const p=t.find(y=>l?y.relay?.serverId===l.serverId:!y.relay&&le(y.apiUrl||y.url)===f),h=p?.id||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`),g={...p||{},id:h,label:n.label||p?.label||bc(f),url:f,apiUrl:u,clientToken:i.token,...l?{relay:l}:{}};return{hostId:h,hosts:p?t.map(y=>y.id===h?g:y):[g,...t]}},Du=/^(t|.*(?:token|auth|secret|api).*)$/i,le=e=>{const t=e.trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:t.split("#")[0]||null}catch{return null}},Ew=e=>{const t=le(e);if(!t)return null;try{const n=new URL(t);if((n.pathname.replace(/\/+$/,"")||"/")==="/connect"&&n.searchParams.has("t"))return{persistedUrl:n.origin,redeemUrl:n.toString(),kind:"tunnel-connect-link"}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:"normal-host"}},bc=e=>{const t=le(e);if(!t)return e;try{const n=new URL(t);(n.username||n.password)&&(n.username="",n.password="");const r=Array.from(new Set(Array.from(n.searchParams.keys())));for(const o of r)Du.test(o)&&n.searchParams.set(o,"[REDACTED]");return n.toString()}catch{return t}},Zn=(e,t)=>{const n=le(e),r=le(t);if(!n||!r)return!1;try{const o=new URL(n),s=new URL(r);if(o.origin!==s.origin||s.search&&o.search!==s.search)return!1;const i=s.pathname.length>1?s.pathname.replace(/\/+$/,""):s.pathname,a=o.pathname.length>1?o.pathname.replace(/\/+$/,""):o.pathname;return i==="/"?!0:a===i||a.startsWith(`${i}/`)}catch{return!1}},ce=(e,t)=>{const n=e[t];return typeof n=="string"?n:null},pi=(e,t)=>{const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null},Ou=e=>{if(!rn(e))return null;const t=ce(e,"id"),n=ce(e,"label"),r=ce(e,"url"),o=ce(e,"apiUrl")||ce(e,"api_url"),s=ce(e,"clientToken")||ce(e,"client_token"),i=Mu(e.requestHeaders),a=xu(e.relay);return!t||!n||!r?null:{id:t,label:n,url:r,...o?{apiUrl:o}:{},...s?{clientToken:s}:{},...i?{requestHeaders:i}:{},...a?{relay:a}:{}}},Pn=e=>le(e.apiUrl||e.url)||e.apiUrl||e.url,Ft=()=>de()?(e,t)=>Y(e,t):null,ks=async()=>{const e=Ft();if(!e)return{hosts:[],defaultHostId:"local",initialHostChoiceCompleted:!1};const t=await e("desktop_hosts_get");if(!rn(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};const n=t.hosts,r=Array.isArray(n)?n.map(Ou).filter(a=>!!a):[],o=ce(t,"defaultHostId")||ce(t,"default_host_id")||ce(t,"defaultHostID"),s=t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,i=ce(t,"localOrigin")||ce(t,"local_origin");return{hosts:r,defaultHostId:o,initialHostChoiceCompleted:s,localOrigin:i}},Lu=async e=>{const t=Ft();if(!t)return;const n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t("desktop_hosts_set",{input:n})},_u=async()=>{const e=Ft();if(!e)return"";const t=await e("desktop_local_client_token_get").catch(()=>null);return typeof t=="string"?t.trim():""},Fu=async()=>{const e=Ft();if(!e)return"";const t=await e("desktop_install_id_get").catch(()=>null);return typeof t=="string"?t.trim():""},ju=8e3,Uu=15e3,Nu=400,Bu=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)}},hi=async(e,t,n,r)=>{for(;;){const o=n-Date.now();if(o<=0)throw new Error("relay probe deadline exceeded");try{return await Bu(e,t,Math.min(ju,o),r)}catch(s){if(e.getStatus().state==="error"||Date.now()>=n)throw s;await new Promise(i=>window.setTimeout(i,Nu))}}},Hu=async(e,t)=>{const n=fs({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),r=Date.now(),o=r+Uu;let s=!1;try{if(!(await hi(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 hi(n,"/auth/session",o,{headers:a});return l.status===401||l.status===403?{status:"auth",latencyMs:Math.max(0,Date.now()-r)}:l.ok?(s=t?.keepTunnel===!0,{status:"ok",latencyMs:Math.max(0,Date.now()-r),...s?{tunnel:n}:{}}):{status:"unreachable",latencyMs:0}}catch{return{status:"unreachable",latencyMs:0}}finally{s||n.close()}},vs=async(e,t)=>{const n=Ft();if(!n)return{status:"unreachable",latencyMs:0};const r=await n("desktop_host_probe",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!rn(r))return{status:"unreachable",latencyMs:0};const o=r.status,s=o==="ok"||o==="auth"||o==="update-recommended"||o==="incompatible"||o==="wrong-service"||o==="unreachable"?o:"unreachable",i=pi(r,"latencyMs")??pi(r,"latency_ms")??0;return{status:s,latencyMs:i}},Aw=async(e,t)=>{const n=Ft();n&&await n("desktop_new_window_at_url",{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},Pw=async e=>{const t=Ft();t&&await t("desktop_new_window_for_host",{hostId:e})},pt="local",zu=e=>({id:pt,label:"Local",url:e||Sc()}),Sc=()=>typeof window>"u"?"":window.__AIWORKER_LOCAL_ORIGIN__||window.location.origin,Wu=e=>e.id===pt?"local":`host:${e.id}`,Iw=e=>{const t=typeof window>"u"?"":window.location.href,n=e.find(d=>d.id===pt)?.url||Sc(),r=$r(),o=le(n)||n,s=le(t)||t,i=B(),a=e.find(d=>d.relay&&Wu(d)===i);if(a)return{id:a.id,label:a.label,url:a.url};if(r&&Zn(r,n))return{id:pt,label:"Local",url:o};const c=e.find(d=>r?Zn(r,Pn(d)):!1);if(c)return{id:c.id,label:c.label,url:le(Pn(c))||Pn(c)};if(t&&Zn(t,n))return{id:pt,label:"Local",url:o};const l=e.find(d=>t?Zn(t,d.url):!1);return l?{id:l.id,label:l.label,url:le(l.url)||l.url}:t.startsWith("openchamber-ui://")?{id:pt,label:"Local",url:o}:{id:"custom",label:bc(s||"Instance"),url:s}},Pr=new Map;let Tc=0;const Ir=new Map;let _o=0,kc={byHostId:{},isProbing:!1};const Fo=new Set,Mr=()=>{kc={byHostId:Object.fromEntries(Pr),isProbing:_o>0};for(const e of Fo)try{e()}catch{}},Mw=e=>(Fo.add(e),()=>{Fo.delete(e)}),Rw=()=>kc,vc=(e,t)=>{Pr.set(e,t),Mr()},xw=(e,t)=>{Ir.set(e,++Tc),vc(e,t)},$u=e=>{const t=new Set([pt,...e]);let n=!1;for(const r of Array.from(Pr.keys()))t.has(r)||(Pr.delete(r),Ir.delete(r),n=!0);n&&Mr()},Gu=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",Ku=async()=>_t()?_u().catch(()=>""):"",qu=async(e,t)=>{const n=e.id===pt?t:e.clientToken||"",r=async()=>{const i=await Hu(e.relay,{clientToken:n,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0})),a={status:i.status,latencyMs:i.latencyMs};return i.status==="ok"&&(a.via="relay"),a};if(e.relay&&!e.apiUrl)return r();const o=le(_t()?Pn(e):e.url);if(!o)return{status:"unreachable",latencyMs:0};const s=await vs(o,{clientToken:n||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Gu(s.status)&&e.relay){const i=await r();if(i.status==="ok")return i}return{status:s.status,latencyMs:s.latencyMs}},Vu=async e=>{if(!gt())return;const t=++Tc;for(const n of e)Ir.set(n.id,t);_o+=1,Mr();try{const n=await Ku();await Promise.all(e.map(async r=>{const o=await qu(r,n);Ir.get(r.id)===t&&vc(r.id,o)}))}finally{_o-=1,Mr()}};let mi=!1;const Ju=async()=>{if(mi||!gt())return;mi=!0;const e=await ks().catch(()=>null);e&&($u(e.hosts.map(t=>t.id)),await Vu([zu(e.localOrigin),...e.hosts]))},Yu=5e3,Qu=1500;let so=!1;const Xu=async e=>{if(!_t()||so)return;const t=`host:${e}`;if(B()===t){so=!0;try{const n=await ks().catch(()=>null),r=n?.hosts.find(u=>u.id===e);if(!n||!r?.relay)return;const o=r.apiUrl?le(r.apiUrl):null;if(o&&o.startsWith("https://"))return;const s=await m("/api/client-auth/connection/candidates").catch(()=>null);if(!s?.ok)return;const i=await s.json().catch(()=>null);if(!i||i.serverId!==r.relay.serverId)return;const a=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const u of a){if(!u||typeof u!="object")continue;const f=u;if(f.type!=="lan"||typeof f.url!="string")continue;const p=le(f.url);p&&!c.includes(p)&&c.push(p)}if(c.length===0)return;const l=o&&c.includes(o)?o:c[0];l!==o&&await Lu({hosts:n.hosts.map(u=>u.id===e?{...u,apiUrl:l}:u),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{});const d=await vs(l,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0}));if(d.status==="unreachable"||d.status==="wrong-service"||d.status==="incompatible"||B()!==t)return;Er({apiBaseUrl:l,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:t})}finally{so=!1}}},Zu=e=>{typeof window>"u"||window.setTimeout(()=>{Xu(e).catch(()=>{})},Yu)},ef=async e=>{if(!_t())return;const t=await ks().catch(()=>null);if(!t)return;const n=e||(t.defaultHostId!=="local"?t.defaultHostId:null);if(!n)return;const r=t.hosts.find(u=>u.id===n);if(!r?.relay)return;const o=`host:${r.id}`;if(B()===o)return;const s=u=>{Er({apiBaseUrl:u,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})},i=()=>{Er({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:r.clientToken||null,runtimeKey:o,relay:r.relay??void 0}),Zu(r.id)},a=r.apiUrl?le(Pn(r)):null;if(!a){i();return}const c=u=>u.status!=="unreachable"&&u.status!=="wrong-service"&&u.status!=="incompatible",l=vs(a,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:"unreachable",latencyMs:0})),d=await Promise.race([l,new Promise(u=>setTimeout(()=>u(null),Qu))]);if(d){if(c(d)){s(a);return}i();return}i(),l.then(u=>{c(u)&&B()===o&&s(a)})};class Rt extends Error{reason;status;constructor(t,n={}){super(t),this.name="FilesystemError",this.reason=n.reason??"unknown",this.status=n.status}}const Cw=e=>e instanceof Rt||!!(e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"),Rr=e=>{switch(e){case"os-permission":case"already-exists":case"not-found":case"not-directory":case"invalid-response":return e;default:return"unknown"}},yi=500,Ec=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("AIWORKER_STARTUP_TRACE")==="1"}catch{return!1}},Dw=()=>Ec(),Ie=(e,t)=>{if(!Ec())return;const n=typeof performance<"u"?performance.now():Date.now();window.__AIWORKER_STARTUP_TRACE_START__??=n,window.__AIWORKER_STARTUP_TRACE__??=[],window.__AIWORKER_STARTUP_TRACE__.push({t:Math.round(n-window.__AIWORKER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__AIWORKER_STARTUP_TRACE__.length>yi&&window.__AIWORKER_STARTUP_TRACE__.splice(0,window.__AIWORKER_STARTUP_TRACE__.length-yi)},tf=()=>{const e=typeof window<"u"?window.__AIWORKER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("loadAgents")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory")||r.name.includes("opencodeClient:setDirectory"))};typeof window<"u"&&(window.__AIWORKER_STARTUP_TRACE_SUMMARY__=tf);const Ow=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();Ie(`${e}:start`,n);try{const o=await t(),s=typeof performance<"u"?performance.now():Date.now();return Ie(`${e}:end`,{durationMs:Math.round(s-r)}),o}catch(o){const s=typeof performance<"u"?performance.now():Date.now();throw Ie(`${e}:error`,{durationMs:Math.round(s-r),error:o instanceof Error?o.message:String(o)}),o}},nf=3,rf=3e4,of=32e3,sf=3600*1e3,af=600*1e3,cf=200,lf=new Set([429,502,503,504]),Ve=new Map,Es=e=>JSON.stringify([B(),e]);function df(){const e=Date.now();for(const[t,n]of Ve){const r=Math.max(n.lastErrorAt,n.circuitOpenAt);e-r>sf&&Ve.delete(t)}}typeof setInterval<"u"&&setInterval(df,af).unref?.();function uf(e){const t=Es(e);let n=Ve.get(t);if(!n)for(n={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:rf},Ve.set(t,n);Ve.size>cf;){const r=Ve.keys().next().value;if(!r)break;Ve.delete(r)}return n}function ff(e){e&&Ve.delete(Es(e))}function gi(e,t){if(!e)return;const n=uf(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),pf(t)&&n.consecutiveErrors>=nf&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function pf(e){return e!==void 0&&lf.has(e)}function hf(e){const t=Ve.get(Es(e));return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,of*4),!1):!0:!1}function mf(e){if(!(!e||!hf(e)))throw new Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}const wi="/api",yf=1e4,gf=4e3;function Yt(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object"&&"message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}const wf=P({reason:w().optional()});function Ae(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${Yt(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw new Error(`${t} failed: empty response`);return e.data}function zt(e,t){if(e.error){const n=e.response?.status,r=new Error(`${t} failed${n?` (${n})`:""}: ${Yt(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}const bf=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,bi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Sf=14;let Si=0,io=0;const Tf=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+=bi[t[r]%bi.length];return n},Ti=e=>{const t=Date.now();t!==Si&&(Si=t,io=0),io+=1;const n=BigInt(t)*BigInt(4096)+BigInt(io),r=new Uint8Array(6);for(let s=0;s<6;s+=1)r[s]=Number(n>>BigInt(40-8*s)&BigInt(255));const o=Array.from(r,s=>s.toString(16).padStart(2,"0")).join("");return`${e}_${o}${Tf(Sf)}`},ki=e=>{const t=typeof e=="string"&&e.trim().length>0?e.trim():"/api";if(bf.test(t)||typeof window>"u")return t;const n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),t}},vi=()=>{try{return ye().api("/api")}catch{return null}},Ac=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)}},kf=3e4,vf=e=>(typeof e=="string"?e:e instanceof URL?e.toString():e.url).includes("/event"),ao=e=>{const t=e.requestTimeoutMs??kf;return Cl({...e,fetch:async(n,r)=>{const o=String(r?.method??(n instanceof Request?n.method:"GET")).toUpperCase();if(vf(n)||o==="POST")return m(n,r);const s=Ac(t),i=r?.signal,a=typeof AbortSignal<"u"&&typeof AbortSignal.any=="function";let c,l=null;if(i&&a)c=AbortSignal.any([i,s.signal]);else if(i){const d=new AbortController,u=()=>d.abort(i.reason),f=()=>d.abort(s.signal.reason);i.aborted?u():s.signal.aborted?f():(i.addEventListener("abort",u,{once:!0}),s.signal.addEventListener("abort",f,{once:!0}),l=()=>{i.removeEventListener("abort",u),s.signal.removeEventListener("abort",f)}),c=d.signal}else c=s.signal;try{return await m(n,{...r,signal:c})}catch(d){throw s.signal.aborted&&!i?.aborted?new Error(`OpenCode request timed out after ${t}ms`):d}finally{l?.(),s.cleanup()}}})},Wt=e=>e.replace(/\\/g,"/"),Ei=400,Ai=()=>{const e=Gr();return e&&e.runtime?.isDesktop&&e.files?e.files:null},Pi=w().trim().regex(/^(?:\/|[A-Za-z]:[\\/]|\\\\)/),Ef=P({home:Pi,chatsRoot:Pi.optional()});class Af{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=wi){const r=vi()||t;this.baseUrl=ki(r),this.client=ao({baseUrl:this.baseUrl})}assertRuntimeUnchanged(t){if(t&&t!==B())throw new Error("Message was not sent because the runtime changed.")}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){const t=vi(),n=ki(t||wi);n!==this.baseUrl&&(this.baseUrl=n,this.client=ao({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear())}getSdkClient(){return this.client}getScopedSdkClient(t){return this.getScopedApiClient(t)}getScopedApiClient(t){const n=this.normalizeCandidatePath(t)??t,r=n||"",o=this.scopedClients.get(r);if(o)return o;const s=ao({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,s),s}normalizeCandidatePath(t){if(typeof t!="string")return null;const n=t.trim();if(!n)return null;const r=n.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(r.length>1?r.replace(/\/+$/,""):r)||null}deriveHomeDirectory(t){const n=t.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const s=n[1],a=t.slice(s.length+(t.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:s,username:void 0}}const r=t.startsWith("/"),o=t.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(t){const n=this.normalizeCandidatePath(t)??t;this.currentDirectory!==n&&Ie("opencodeClient:setDirectory",{previous:this.currentDirectory??null,next:n??null}),this.currentDirectory=n}getDirectory(){return this.currentDirectory}async withDirectory(t,n){const r=async()=>{if(t==null)return n();const s=this.currentDirectory,i=this.normalizeCandidatePath(t)??t;this.currentDirectory=i;try{return await n()}finally{this.currentDirectory===i&&(this.currentDirectory=s)}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const t=new Set,n=o=>{const s=this.normalizeCandidatePath(o);s&&t.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(n(s.directory),n(s.worktree),n(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!t.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!t.size)try{(await this.listSessions()).forEach(s=>n(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!t.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!t.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(t);return this.deriveHomeDirectory(r)}async probeDirectory(t){return await this.getDirectoryAvailability(t)==="available"}async getDirectoryAvailability(t){const n=this.normalizeCandidatePath(t);if(!n)return"unknown";try{const r=await m("/api/fs/list",{query:{path:n}});if(r.ok)return"available";const o=wf.safeParse(await r.json().catch(()=>null)).data,s=Rr(o?.reason);return s==="not-found"||s==="not-directory"?"missing":"unknown"}catch{return"unknown"}}async listSessions(){const t=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(t.data)?t.data:[]}async createSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.create({...r?{directory:r}:{},parentID:t?.parentID,title:t?.title,metadata:t?.metadata});return Ae(o,"session.create")}async getSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.get({sessionID:t,...r?{directory:r}:{}});return Ae(o,"session.get")}async deleteSession(t,n){const r=this.normalizeCandidatePath(n)??this.currentDirectory,o=await this.client.session.delete({sessionID:t,...r?{directory:r}:{}});return zt(o,"session.delete")===!0}async updateSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s={...n.title!==void 0?{title:n.title}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},...n.time?.archived!==void 0&&n.time.archived!==null?{time:{archived:n.time.archived}}:{}},i=await this.client.session.update({sessionID:t,...o?{directory:o}:{},...s});return Ae(i,"session.update")}async getSessionMessages(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.messages({sessionID:t,...o?{directory:o}:{},...typeof n=="number"?{limit:n}:{}});return Ae(s,"session.messages")}async getSessionTodos(t){try{const n=await this.client.session.todo({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(n.error)return[];const r=n.data;return!r||!Array.isArray(r)?[]:r}catch{return[]}}shouldNormalizeToTextPlain(t){if(!t)return!1;const n=t.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(t){if(!t)return!1;const n=t.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(t){try{const n=(await ls(async()=>{const{default:u}=await import("./vendor-heic2any-CEam9pDc.js").then(f=>f.h);return{default:u}},__vite__mapDeps([0,1,2]))).default,r=t.url.indexOf(",");if(r===-1)return t;const o=t.url.substring(r+1),s=atob(o),i=new Uint8Array(s.length);for(let u=0;u<s.length;u++)i[u]=s.charCodeAt(u);const a=new Blob([i],{type:t.mime}),c=await n({blob:a,toType:"image/jpeg",quality:.9}),l=await new Promise((u,f)=>{const p=new FileReader;p.onload=()=>u(p.result),p.onerror=f,p.readAsDataURL(c)});let d=t.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:l}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),t}}async normalizeFilePart(t){if(this.isHeicMime(t.mime))return this.convertHeicToJpeg(t);if(!this.shouldNormalizeToTextPlain(t.mime))return t;let n=t.url;if(t.url.startsWith("data:")){const r=t.url.indexOf(",");if(r!==-1){const o=t.url.substring(5,r),s=t.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:t.filename,url:n}}async toNormalizedFilePartInput(t){const n=await this.normalizeFilePart(t);return{...t.id?{id:t.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??Ti("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}),mf(t.providerID),this.assertRuntimeUnchanged(t.runtimeKey);let s;try{const l=await this.client.session.promptAsync({sessionID:t.id,...o?{directory:o}:{},model:{providerID:t.providerID,modelID:t.modelID},agent:t.agent,variant:t.variant,messageID:n,...t.delivery?{delivery:t.delivery}:{},...t.format?{format:t.format}:{},parts:r});if(l.response instanceof Response)s=l.response;else if(l.error){const d=l.response?.status;if(!d){const u=new Error(`Message send transport failure: ${Yt(l.error)}`);throw hd(l.error)?Ua(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 gi(t.providerID),l}if(s.ok)return ff(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,gi(t.providerID,s.status),c}async sendCommand(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=t.messageId??Ti("msg"),r=[];if(t.files&&t.files.length>0)for(const i of t.files)r.push(await this.toNormalizedFilePartInput(i));const o=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory;this.assertRuntimeUnchanged(t.runtimeKey);const s=await this.client.session.command({sessionID:t.id,...o?{directory:o}:{},command:t.command,arguments:t.arguments??"",model:`${t.providerID}/${t.modelID}`,agent:t.agent,variant:t.variant,...r.length>0?{parts:r}:{},messageID:n});return zt(s,"session.command"),n}async abortSession(t){return!!(await this.client.session.abort({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(t){this.assertRuntimeUnchanged(t.runtimeKey);const n=this.normalizeCandidatePath(t.directory??null)??this.currentDirectory,r=await this.client.session.shell({sessionID:t.sessionId,...n?{directory:n}:{},messageID:t.messageId,agent:t.agent,model:t.model,command:t.command});return Ae(r,"session.shell")}async revertSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.revert({sessionID:t,...s?{directory:s}:{},messageID:n,partID:r});return Ae(i,"session.revert")}async summarizeSession(t,n,r,o){const s=this.normalizeCandidatePath(o)??this.currentDirectory,i=await this.client.session.summarize({sessionID:t,...s?{directory:s}:{},providerID:n,modelID:r});return zt(i,"session.summarize")===!0}async unrevertSession(t){const n=await this.client.session.unrevert({sessionID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return Ae(n,"session.unrevert")}async forkSession(t,n,r){const o=this.normalizeCandidatePath(r)??this.currentDirectory,s=await this.client.session.fork({sessionID:t,...o?{directory:o}:{},messageID:n});return Ae(s,"session.fork")}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(t){try{const n=typeof t=="string"?t.trim():"",r=await this.client.session.status(n?{directory:n}:void 0);return r.error||!r.data||typeof r.data!="object"?null:r.data}catch{return null}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{const t=await m("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async listToolIds(t){try{const n=typeof t?.directory=="string"?t.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(t,n,r){const o=this.normalizeCandidatePath(r?.directory??null)??this.currentDirectory,s=await this.client.permission.reply({requestID:t,...o?{directory:o}:{},reply:n,...r?.message?{message:r.message}:{}});return zt(s,"permission.reply")===!0}async createPermission(t,n,r,o){try{const s=await this.client.v2.session.permission.create({sessionID:t,action:n,resources:r,...o?.id?{id:o.id}:{},...o?.save?{save:o.save}:{},...o?.metadata?{metadata:o.metadata}:{},...o?.source?{source:o.source}:{},...o?.agent?{agent:o.agent}:{}});if(s.error!==void 0)return null;const i=s.data?.data;return i===void 0?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(t,n,r){try{const s=await(r?this.getScopedSdkClient(r):this.client).v2.session.permission.get({sessionID:t,requestID:n});if(s.error===void 0){const i=s.data?.data;if(i!==void 0)return{state:"ok",permission:i}}return s.response?.status===404?{state:"resolved"}:{state:"unknown"}}catch{return{state:"unknown"}}}async listPendingPermissions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.permission.list(l?{directory:l}:void 0);if(d.error)throw new Error(`permission.list failed: ${Yt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}async replyToQuestion(t,n,r){const o=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n],s=this.normalizeCandidatePath(r)??this.currentDirectory,i=await this.client.question.reply({requestID:t,...s?{directory:s}:{},answers:o});return zt(i,"question.reply")===!0}async rejectQuestion(t){const n=await this.client.question.reject({requestID:t,...this.currentDirectory?{directory:this.currentDirectory}:{}});return zt(n,"question.reject")===!0}async listPendingQuestions(t){const n=[],r=async c=>{const l=typeof c=="string"?c.trim():"",d=await this.client.question.list(l?{directory:l}:void 0);if(d.error)throw new Error(`question.list failed: ${Yt(d.error)}`);return d.data||[]};n.push(r(null));const o=new Set;for(const c of t?.directories??[]){const l=this.normalizeCandidatePath(c??null);l&&o.add(l)}for(const c of o)n.push(r(c));const s=await Promise.all(n),i=[],a=new Set;for(const c of s)for(const l of c){if(!l||typeof l!="object")continue;const d=l.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(l))}return i}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}async getConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configCache.get(r);if(o&&o.expiresAt>Date.now())return Ie("opencodeClient.getConfig:cacheHit",{directory:n??null}),o.config;const s=this.configInFlight.get(r);if(s)return Ie("opencodeClient.getConfig:deduped",{directory:n??null}),s;const i=this.configCacheGeneration,a=(async()=>{Ie("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 Ie("opencodeClient.getConfig:end",{directory:n??null,durationMs:Math.round(u-c)}),i===this.configCacheGeneration&&this.configCache.set(r,{config:d.data,expiresAt:Date.now()+yf}),d.data})();this.configInFlight.set(r,a);try{return await a}finally{this.configInFlight.get(r)===a&&this.configInFlight.delete(r)}}async updateConfig(t){const n=await this.client.config.update({config:t}),r=Ae(n,"global.config.update");return this.clearConfigCache(),r}async updateConfigPartial(t){const n=await this.getConfig(),r=t(n);return await this.updateConfig(r)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.configProvidersInFlight.get(r);if(o)return o;const s=(async()=>{const i=await this.client.config.providers(n?{directory:n}:void 0);return Ae(i,"config.providers")})();this.configProvidersInFlight.set(r,s);try{return await s}finally{this.configProvidersInFlight.delete(r)}}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(t){const n=this.normalizeCandidatePath(t)??t??this.currentDirectory??void 0,r=n??"",o=this.listAgentsInFlight.get(r);if(o)return o;const s=(async()=>{const i=n?{directory:n}:void 0,a=await this.client.app.agents(i);if(!a.error&&Array.isArray(a.data)&&a.data.length>0)return a.data;const c=await m("/api/agent",{...n?{query:{directory:n}}:{}});if(!c.ok)throw a.error?new Error(`app.agents failed${a.response?.status?` (${a.response.status})`:""}: ${Yt(a.error)}`):new Error(`agent.list failed (${c.status})`);const l=await c.json().catch(()=>null);if(!Array.isArray(l))throw new Error("agent.list failed: invalid response");return l})();this.listAgentsInFlight.set(r,s);try{return await s}finally{this.listAgentsInFlight.delete(r)}}async listCommandsWithDetails(t){const n=this.normalizeCandidatePath(t??null)??this.currentDirectory,r=await this.client.command.list(n?{directory:n}:void 0);return(Ae(r,"command.list")||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,source:s.source,template:s.template}))}async checkHealth(){try{const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl,n=t==="/api"||t.endsWith("/api")?"/api/opencode/health":`${t}/opencode/health`;Ie("opencodeClient.checkHealth:url",{baseUrl:this.baseUrl,healthUrl:n});const r=Ac(gf),o=await m(n,{signal:r.signal}).finally(r.cleanup);if(Ie("opencodeClient.checkHealth:response",{status:o.status}),!o.ok)return!1;const s=await o.json();return Ie("opencodeClient.checkHealth:result",{healthy:s?.healthy}),s?.healthy===!0}catch{return!1}}async createDirectory(t,n){const r=Ai();if(r?.createDirectory)try{return await r.createDirectory(t)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"Failed to create directory")}if(n?.asProject){const a=await m(`${this.baseUrl}/opencode/directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,create:!0})});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create project directory"}));throw new Error(l.error||"Failed to create project directory")}return{success:!0,path:(await a.json()).path}}const o={path:t,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await m(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await s.json()}async cloneRepository(t){const n=await m(`${this.baseUrl}/fs/clone`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clone repository"}));throw new Error(r.error||"Failed to clone repository")}return await n.json()}async listLocalDirectory(t,n){const o=`${typeof t=="string"?Wt(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=Ai();try{if(d){const y=await d.listDirectory(t||"",n);if(!y||!Array.isArray(y.entries))throw new Rt("Directory listing returned an invalid response",{reason:"invalid-response"});const b=y.entries.map(S=>({name:S.name,path:Wt(S.path),isDirectory:!!S.isDirectory,isFile:!S.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:b,expiresAt:Date.now()+Ei}),b}const u=new URLSearchParams;t&&t.trim().length>0&&u.set("path",t),n?.respectGitignore&&u.set("respectGitignore","true");const f=u.toString(),p=await m(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!p.ok){const y=await p.json().catch(()=>({})),b=typeof y.error=="string"?y.error:"Failed to list directory";throw new Rt(b,{reason:Rr(y.reason),status:p.status})}const h=await p.json();if(!h||!Array.isArray(h.entries))throw new Rt("Directory listing returned an invalid response",{reason:"invalid-response"});const g=h.entries;return this.listDirectoryCache.set(o,{entries:g,expiresAt:Date.now()+Ei}),g}catch(u){throw console.error("Failed to list directory contents:",u),u}})().finally(()=>{this.listDirectoryInFlight.get(o)===l&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,l),l}async searchFiles(t,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?Wt(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=Wt(c),d=l.split("/").filter(Boolean).pop()||l,u=Wt(o?`${o}/${l}`:l);return{name:d,path:u,relativePath:l,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const t=B();if(!t||t==="local"){const n=await gc();if(n)return n}try{const n=await m(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async getFilesystemHomeInfo(){const t=await m(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to resolve the chats root (${t.status})`);return Ef.parse(await t.json())}async setOpenCodeWorkingDirectory(t){if(!t||typeof t!="string"||!t.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",t),null;const n=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",n,"with path:",t);try{const r=await m(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})}),o=await r.json().catch(()=>null);if(!r.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:t}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const Ue=new Af,Pc=["session","repository","usage","subagents","tasks","mcp","pinned","contextSources"],Lw={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"},Pf=new Set(Pc),If=e=>typeof e=="string"&&Pf.has(e),_w=(e,t)=>!e?.includes(t),Fw=e=>e!=null&&Pc.every(t=>e.includes(t)),jw=({visible:e,contentMounted:t,renderedSections:n,allSectionsHidden:r})=>({interactive:e&&(n>0||r),showEmptyState:t&&r}),Ic=e=>{if(!Array.isArray(e))return[];const t=new Set;for(const n of e)If(n)&&t.add(n);return[...t]},Mf=e=>{const t=e.replace(/\\/g,"/").replace(/\/+$/g,"").trim();if(!t)return"";const n=new TextEncoder().encode(t);let r="";for(const s of n)r+=String.fromCharCode(s);return`path_${typeof btoa=="function"?btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""):t.replace(/[^A-Za-z0-9._-]+/g,"_")}`};let co=null,lo=null,uo=null;const Ii=new Set;let Mi=!1;const Mc=e=>{if(Ii.add(e),Mi||typeof window>"u")return;Mi=!0;const t=()=>{for(const n of Ii)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{}},Rf=(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 Mc(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()}}},As=e=>Rf(()=>Cc(),e),xf=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 Mc(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}}},Rc=e=>{if(typeof window>"u")return null;try{return window[e]??null}catch{return null}},Ps=()=>{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}}},xc=e=>{const t=Ps(),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}}},Cf=()=>{const e=Rc("localStorage");return e?xc(e):Ps()},Cc=()=>(co||(co=Cf()),co),Bn=()=>(uo||(uo=xf(Cc())),uo),Df=()=>{const e=Rc("sessionStorage");return e?xc(e):Ps()},Of=()=>(lo||(lo=Df()),lo),Lf={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem",settingsPageTitle:"1.125rem"},Uw={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem",settingsPageTitle:"1.0625rem"};function Ri(e){return`--text-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const er={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},fo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...er.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:fo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...er.tool.inline})},_f=[{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'}],Ff=[{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'}],Dc=e=>Object.fromEntries(e.map(t=>[t.id,t])),jf=Dc(_f),Uf=Dc(Ff),Nf="system",Bf="system-mono",Oc=e=>typeof e=="string"&&e in jf,Lc=e=>typeof e=="string"&&e in Uf,jo="aiworker.mobileKeyboardMode",Hf='meta[name="viewport"]',xi="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover",Nw=()=>!0;function Kr(e,t="resize-content"){return e==="native"||e==="resize-content"?e:t}const zf=e=>Kr(e)==="resize-content"?`${xi}, interactive-widget=resizes-content`:xi,Wf=()=>{if(typeof window>"u")return"resize-content";try{return Kr(localStorage.getItem(jo))}catch{return"resize-content"}},_c=e=>{const t=Kr(e);if(typeof window<"u")try{t==="resize-content"?localStorage.removeItem(jo):localStorage.setItem(jo,t)}catch{}return t},Bw=e=>{const t=_c(e);if(typeof document>"u")return t;document.documentElement.setAttribute("data-oc-mobile-keyboard-mode",t);const n=document.querySelector(Hf);if(n instanceof HTMLMetaElement){const r=zf(t);n.getAttribute("content")!==r&&n.setAttribute("content",r)}return t},dn=e=>{if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(o,s)=>s.toUpperCase()+":");return n==="/"?"/":(n.length>1?n.replace(/\/+$/,""):n)||null},$f=e=>dn(e)??"",po=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Gf=new Set(["starting","running","stopping"]),Kf=e=>!!e?.tabs.some(t=>Qt(t.purpose)&&t.lifecycle!=="exited"),Uo=512*1024,qf=new TextEncoder,Vf=new TextDecoder,ho=e=>{const t=qf.encode(e);if(t.byteLength<=Uo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Uo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Vf.decode(r),byteLength:r.byteLength}},De=(e,t)=>`${e}\0${t}`,$t=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Jf="terminal-store";let Ci=!1,Di=0;const Yf=P({type:F("project-action"),actionId:w()}),bn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Di+=1,`tab-${Date.now().toString(36)}-${Di.toString(36)}`),mo=e=>typeof e=="object"&&e!==null,Qt=e=>e.type==="project-action",tr=(e,t)=>Qt(e.purpose)?t===void 0?!0:e.purpose.executionId===t:t==null,Qf=()=>bn().replace(/^tab-/,"exec-"),Oi=e=>e==="running"?"running":"exited",Xf=(e,t)=>({type:"project-action",actionId:e.actionId,executionId:t==="running"?e.executionId:null}),Zf=e=>{const t=new Map,n=[];for(const r of e){if(r.purpose?.type!=="project-action"){n.push(r);continue}const o=t.get(r.purpose.actionId);(!o||r.status==="running"&&o.status!=="running"||r.status===o.status&&((r.createdAt??0)>(o.createdAt??0)||r.createdAt===o.createdAt&&r.sessionId>o.sessionId))&&t.set(r.purpose.actionId,r)}return[...n,...t.values()]},yo={previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1},ep=e=>e.trim()||"Action",tp=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null},G=$f,xr=(e,t)=>`${e}\0${t}`,mn=(e,t,n,r)=>{e.set(xr(t,n),r)},Li=(e,t,n,r)=>{if(!r)return!1;const o=xr(t,n),s=e.actionMutationRevisions.get(o)??0,i=r.get(o)??0;return s>i},np=/^Terminal(?: (\d+))?$/,_i=e=>{let t=0;for(const n of e){const r=np.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},Hw=e=>e.purpose.type==="project-action"&&e.purpose.executionId!==null&&Gf.has(e.lifecycle),rp=e=>!!(e&&e.terminalSessionId!==null&&e.lifecycle==="running"),nr=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",purpose:{type:"terminal"},label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),go=e=>({tabs:[e],activeTabId:e.id}),me=(e,t)=>e.tabs.findIndex(n=>n.id===t);let wo=null,bo=null;const op=e=>{if(bo&&wo?.sessions===e.sessions&&wo.nextTabId===e.nextTabId)return bo;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt,purpose:o.purpose.type==="project-action"?{type:"project-action",actionId:o.purpose.actionId}:{type:"terminal"}}))}]),nextTabId:e.nextTabId};return wo={sessions:e.sessions,nextTabId:e.nextTabId},bo=t,t},sp=()=>{const e=Ml(()=>Of());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},hr=Ze()(an(Un((e,t)=>({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=G(n);r&&e(o=>{if(o.sessions.has(r))return o;const s=new Map(o.sessions),i=bn(),a=nr(i,"Terminal");return s.set(r,go(a)),{sessions:s,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=G(n);return t().sessions.get(r)},getActiveTab:n=>{const r=G(n),o=t().sessions.get(r);if(!o)return;const s=o.activeTabId;return s?o.tabs.find(i=>i.id===s)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(De(G(n),r))??po,matchesActionExecution:(n,r,o)=>{const s=t().sessions.get(G(n))?.tabs.find(i=>i.id===r);return!!(s&&Qt(s.purpose)&&s.purpose.executionId===o)},captureStartedActionMutationRevisions:n=>{const r=G(n),o=xr(r,""),s=new Map;for(const[i,a]of t().actionMutationRevisions.entries())i.startsWith(o)&&s.set(i,a);return s},createTab:n=>{const r=G(n);if(!r)return"tab-invalid";const o=bn();return e(s=>{const i=new Map(s.sessions),a=i.get(r),c=s.nextTabId+1,l=_i(a?.tabs??[]),d=nr(o,l);return a?i.set(r,{...a,tabs:[...a.tabs,d]}):i.set(r,go(d)),{sessions:i,nextTabId:c}}),o},reconcileServerSessions:(n,r,o)=>{const s=G(n);s&&e(i=>{const a=i.sessions.get(s);if(!a&&r.length===0)return i;const c=[...a?.tabs??[]];let l=i.buffers,d=!1,u=null;const f=new Set,p=new Set,h=c.length===1&&c[0].terminalSessionId===null&&c[0].lifecycle==="idle"&&c[0].purpose.type==="terminal"&&!i.buffers.has(De(s,c[0].id))?c[0]:null;h&&r.length>0&&(c.length=0);for(const A of Zf(r)){let fe=c.findIndex(R=>R.terminalSessionId===A.sessionId||R.id===A.sessionId);const Q=A.purpose,zn=Q?.type==="project-action"&&Li(i,s,Q.actionId,o?.startedActionMutationRevisions);if(Q?.type==="project-action"){f.add(Q.actionId);const R=c.findIndex(He=>Qt(He.purpose)&&He.purpose.actionId===Q.actionId);if(zn){R>=0&&p.add(c[R].id);continue}fe<0&&(fe=R)}const pe=Q?.type==="project-action"?Xf(Q,A.status):{type:"terminal"};if(fe>=0){const R=c[fe];let He=R.purpose.type==="project-action"||Q?.type==="project-action"?Oi(A.status):A.status;R.lifecycle==="stopping"&&A.status==="running"&&R.purpose.type==="project-action"&&pe.type==="project-action"&&R.purpose.executionId===pe.executionId&&(He="stopping");const pn=A.createdAt??R.createdAt,Nt=Q?.type==="project-action"&&(R.terminalSessionId!==A.sessionId||pe.type==="project-action"&&pe.executionId!==null&&(R.purpose.type!=="project-action"||R.purpose.executionId!==pe.executionId));if(Nt){const et=De(s,R.id);l=$t(l,Yr=>Yr===et)??l}const $n=Q?.type==="project-action"&&A.status==="running"&&(R.terminalSessionId!==A.sessionId||R.lifecycle!=="running"),Jr=R.purpose.type!==pe.type||R.purpose.type==="project-action"&&pe.type==="project-action"&&(R.purpose.actionId!==pe.actionId||R.purpose.executionId!==pe.executionId);if((R.terminalSessionId!==A.sessionId||R.lifecycle!==He||R.isConnecting!==!1||R.createdAt!==pn||Jr)&&(c[fe]={...R,terminalSessionId:A.sessionId,lifecycle:He,purpose:pe,isConnecting:!1,createdAt:pn},Nt&&Object.assign(c[fe],yo),d=!0),$n){const et={tabId:R.id,createdAt:pn,index:fe};(!u||et.createdAt>u.createdAt||et.createdAt===u.createdAt&&et.index>u.index)&&(u=et)}p.add(R.id);continue}const fn=Q?.type==="project-action"?ep(Q.actionId):h&&c.length===0?h.label:_i(c),Wn=Q?.type==="project-action"?"play":null,Ut={...nr(A.sessionId,fn),terminalSessionId:A.sessionId,lifecycle:Q?.type==="project-action"?Oi(A.status):A.status,purpose:pe,iconKey:Wn,createdAt:A.createdAt??Date.now()};if(c.push(Ut),d=!0,Q?.type==="project-action"&&A.status==="running"){const R={tabId:Ut.id,createdAt:Ut.createdAt,index:c.length-1};(!u||R.createdAt>u.createdAt||R.createdAt===u.createdAt&&R.index>u.index)&&(u=R)}p.add(Ut.id)}let g=d||!!(h&&r.length>0);const y=c.map(A=>!Qt(A.purpose)||f.has(A.purpose.actionId)||p.has(A.id)||A.lifecycle==="starting"||Li(i,s,A.purpose.actionId,o?.startedActionMutationRevisions)||A.lifecycle==="exited"&&!A.isConnecting?A:(g=!0,{...A,lifecycle:"exited",isConnecting:!1,purpose:{type:"project-action",actionId:A.purpose.actionId,executionId:null}})),b=a?.activeTabId??null,S=b&&y.some(A=>A.id===b)?b:y[0]?.id??null,E=S?y.find(A=>A.id===S):y[0],M=u&&!rp(E)?u.tabId:S;if(!g&&a&&M===a.activeTabId&&y.length===a.tabs.length&&y.every((A,fe)=>A===a.tabs[fe]))return i;const W=new Map(i.sessions);return W.set(s,{tabs:y,activeTabId:M}),{sessions:W,buffers:l}})},setActiveTab:(n,r)=>{const o=G(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);return!a||a.activeTabId===r||me(a,r)<0?s:(i.set(o,{...a,activeTabId:r}),{sessions:i})})},setTabLabel:(n,r,o)=>{const s=G(n),i=o.trim();i&&e(a=>{const c=new Map(a.sessions),l=c.get(s);if(!l)return a;const d=me(l,r);if(d<0||l.tabs[d]?.label===i)return a;const u=[...l.tabs];return u[d]={...u[d],label:i},c.set(s,{...l,tabs:u}),{sessions:c}})},setTabIconKey:(n,r,o)=>{const s=G(n);e(i=>{const a=new Map(i.sessions),c=a.get(s);if(!c)return i;const l=me(c,r);if(l<0)return i;const d=o?.trim()||null;if(c.tabs[l]?.iconKey===d)return i;const u=[...c.tabs];return u[l]={...u[l],iconKey:d},a.set(s,{...c,tabs:u}),{sessions:a}})},closeTab:(n,r)=>{const o=G(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=me(a,r);if(c<0)return s;const l=a.tabs[c].purpose;let d=s.actionMutationRevisions,u=s.nextActionMutationRevision;l.type==="project-action"&&(d=new Map(d),mn(d,o,l.actionId,u),u+=1);const f={actionMutationRevisions:d,nextActionMutationRevision:u},p=a.tabs.filter(S=>S.id!==r),h=De(o,r),g=s.buffers.has(h)?$t(s.buffers,S=>S===h):null;if(p.length===0){const S=bn(),E=nr(S,"Terminal");i.set(o,go(E));const M={sessions:i,nextTabId:s.nextTabId+1};return g&&(M.buffers=g),{...M,...f}}let y=a.activeTabId;a.activeTabId===r&&(y=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),i.set(o,{...a,tabs:p,activeTabId:y});const b={sessions:i};return g&&(b.buffers=g),{...b,...f}})},setTabPurpose:(n,r,o)=>{const s=G(n);e(i=>{const a=i.sessions.get(s);if(!a)return i;const c=me(a,r);if(c<0)return i;const l=a.tabs[c];if(JSON.stringify(l.purpose)===JSON.stringify(o))return i;const d=[...a.tabs],u=o.type==="project-action"&&o.executionId!==null&&(l.purpose.type!=="project-action"||l.purpose.executionId!==o.executionId);d[c]={...l,purpose:o},u&&Object.assign(d[c],yo);const f=De(s,r),p=u?$t(i.buffers,y=>y===f)??i.buffers:i.buffers,h=new Map(i.sessions);if(h.set(s,{...a,tabs:d}),o.type!=="project-action")return{sessions:h};const g=new Map(i.actionMutationRevisions);return mn(g,s,o.actionId,i.nextActionMutationRevision),{sessions:h,buffers:p,actionMutationRevisions:g,nextActionMutationRevision:i.nextActionMutationRevision+1}})},allocateActionExecution:(n,r,o)=>{const s=G(n),i=t().sessions.get(s);if(!i||me(i,r)<0)return null;const a=Qf();return e(c=>{const l=c.sessions.get(s);if(!l)return c;const d=me(l,r);if(d<0)return c;const u=[...l.tabs];u[d]={...u[d],purpose:{type:"project-action",actionId:o,executionId:a},lifecycle:"starting",terminalSessionId:null,...yo,isConnecting:!1};const f=new Map(c.sessions);f.set(s,{...l,tabs:u});const p=new Map(c.actionMutationRevisions);mn(p,s,o,c.nextActionMutationRevision);const h=De(s,r),g=$t(c.buffers,y=>y===h)??c.buffers;return{sessions:f,buffers:g,actionMutationRevisions:p,nextActionMutationRevision:c.nextActionMutationRevision+1}}),a},setTabSessionId:(n,r,o,s)=>{const i=G(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0)return a;const u=l.tabs[d];if(!tr(u,s?.expectedExecutionId))return a;const f=o!==null&&u.terminalSessionId!==o,p=o?"running":u.terminalSessionId?"exited":u.lifecycle,h={...u,terminalSessionId:o,lifecycle:p,isConnecting:!1},g=De(i,r),y=f&&a.buffers.has(g)?$t(a.buffers,E=>E===g):null,b=[...l.tabs];b[d]=h,c.set(i,{...l,tabs:b});const S={sessions:c,nextActionMutationRevision:a.nextActionMutationRevision};if(Qt(u.purpose)){const E=new Map(a.actionMutationRevisions);mn(E,i,u.purpose.actionId,a.nextActionMutationRevision),S.actionMutationRevisions=E,S.nextActionMutationRevision=a.nextActionMutationRevision+1}return y&&(S.buffers=y),S})},setTabLifecycle:(n,r,o,s)=>{const i=G(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0||!tr(l.tabs[d],s?.expectedExecutionId))return a;const u=l.tabs[d];if(u.lifecycle===o&&!u.isConnecting)return a;const f=[...l.tabs];if(f[d]={...u,lifecycle:o,isConnecting:!1},c.set(i,{...l,tabs:f}),u.purpose.type!=="project-action"||u.lifecycle===o)return{sessions:c};const p=new Map(a.actionMutationRevisions);return mn(p,i,u.purpose.actionId,a.nextActionMutationRevision),{sessions:c,actionMutationRevisions:p,nextActionMutationRevision:a.nextActionMutationRevision+1}})},setConnecting:(n,r,o,s)=>{const i=G(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0||!tr(l.tabs[d],s?.expectedExecutionId))return a;const u=[...l.tabs];return u[d]={...u[d],isConnecting:o},c.set(i,{...l,tabs:u}),{sessions:c}})},replaceBuffer:(n,r,o,s)=>{const i=G(n);e(a=>{const c=a.sessions.get(i);if(!c||me(c,r)<0)return a;const l=De(i,r),d=a.buffers.get(l)??po;if(d.lastSequence>s)return a;const u=ho(o);if(d.lastSequence===s&&d.byteLength===u.byteLength&&d.chunks.map(h=>h.data).join("")===u.text)return a;const f=a.nextChunkId,p=new Map(a.buffers);return p.set(l,{chunks:u.text?[{id:f,data:u.text,byteLength:u.byteLength}]:[],byteLength:u.byteLength,lastSequence:s}),{buffers:p,nextChunkId:u.text?f+1:f}})},appendToBuffer:(n,r,o,s,i)=>{if(!o)return;const a=G(n);e(c=>{const l=c.sessions.get(a);if(!l||me(l,r)<0)return c;const d=De(a,r),u=c.buffers.get(d)??po;if(s!==void 0&&s<=u.lastSequence)return c;const f=c.nextChunkId,p=ho(o),h=i!==void 0&&i!==o?ho(i).text:void 0,g={id:f,data:p.text,...h!==void 0?{replayData:h}:{},byteLength:p.byteLength},y=[...u.chunks,g];let b=u.byteLength+g.byteLength;for(;b>Uo&&y.length>1;){const E=y.shift();if(!E)break;b-=E.byteLength}const S=new Map(c.buffers);return S.set(d,{chunks:y,byteLength:b,lastSequence:s??u.lastSequence}),{buffers:S,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,s={})=>{const i=G(n);e(a=>{const c=new Map(a.sessions),l=c.get(i);if(!l)return a;const d=me(l,r);if(d<0)return a;const u=l.tabs[d];if(!tr(u,s.expectedExecutionId))return a;const f=s.autoOpened??u.previewAutoOpened,p=s.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===f&&u.previewUrlLocked===p)return a;const h=[...l.tabs];return h[d]={...u,previewUrl:o,previewAutoOpened:f,previewUrlLocked:p},c.set(i,{...l,tabs:h}),{sessions:c}})},markPreviewAutoOpened:(n,r)=>{const o=G(n);e(s=>{const i=new Map(s.sessions),a=i.get(o);if(!a)return s;const c=me(a,r);if(c<0)return s;const l=a.tabs[c];if(!l.previewUrl||l.previewAutoOpened)return s;const d=[...a.tabs];return d[c]={...l,previewAutoOpened:!0},i.set(o,{...a,tabs:d}),{sessions:i}})},removeDirectory:n=>{const r=G(n);e(o=>{const s=new Map(o.sessions);s.delete(r);const i=De(r,""),a=$t(o.buffers,u=>u.startsWith(i)),c=xr(r,"");let l;for(const u of o.actionMutationRevisions.keys())u.startsWith(c)&&(l??=new Map(o.actionMutationRevisions),l.delete(u));const d={sessions:s};return a&&(d.buffers=a),l&&(d.actionMutationRevisions=l),d})},clearAll:()=>{e({sessions:new Map,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:1})}}),{name:Jf,storage:sp(),partialize:op,merge:(e,t)=>{if(!mo(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const a of n){if(!Array.isArray(a)||a.length!==2)continue;const[c,l]=a;if(typeof c!="string"||!mo(l))continue;const d=Array.isArray(l.tabs)?l.tabs:[],u=[],f=new Map;for(const y of d){if(!mo(y))continue;const b=typeof y.id=="string"?y.id:null;if(!b)continue;const S=tp(b);S!==null&&(o=Math.max(o,S));const E=S===null?b:bn();f.set(b,E);const M=Yf.safeParse(y.purpose).data,W=M?{type:"project-action",actionId:M.actionId,executionId:null}:{type:"terminal"};u.push({id:E,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",purpose:W,createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const p=typeof l.activeTabId=="string"?l.activeTabId:null,h=p?f.get(p)??p:null,g=h?u.some(y=>y.id===h):!1;r.set(c,{tabs:u,activeTabId:g?h:u[0].id})}const s=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,i=Math.max(t.nextTabId,s,o+1);return{...t,sessions:r,buffers:new Map,actionMutationRevisions:new Map,nextActionMutationRevision:1,nextChunkId:1,nextTabId:i,hasHydrated:!0}}})));if(typeof window<"u"&&!Ci){Ci=!0;const e=hr.persist,t=()=>{hr.getState().hasHydrated||hr.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Le=20,ip=8,Fi=4096,ap=2160*60*6e4,z=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",s=/^[A-Za-z]:\/$/.test(r);return!o&&!s&&(r=r.replace(/\/+$/,"")),r},ct=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,ut=(e,t)=>{const n=z(t),r=z(e);if(!n||!r)return!1;const o=ct(n),s=ct(r);return s===o||s.startsWith(`${o}/`)},yn=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=z(r);if(!s||!o||typeof o!="object")continue;const i=o,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(p=>typeof p=="string").map(p=>z(p)).filter(p=>p.length<=Fi&&ut(p,s)))).slice(-50):[],c=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(p=>typeof p=="string").map(p=>z(p)).filter(p=>p.length<=Fi&&ut(p,s)))).slice(-500):[],l=typeof i.selectedPath=="string"?z(i.selectedPath):null,d=l&&ut(l,s)?l:a[0]??null,u=typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now();if(Date.now()-u>ap)continue;const f=n[s];if(f){const p=Array.from(new Set([...f.openPaths,...a])),h=Array.from(new Set([...f.expandedPaths,...c])),g=f.selectedPath??d??p[0]??null;n[s]={openPaths:p,selectedPath:g,expandedPaths:h,touchedAt:Math.max(f.touchedAt,u)};continue}n[s]={openPaths:a,selectedPath:d,expandedPaths:c,touchedAt:u}}return _e(n,Le)},_e=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},Gt=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},cp=Ze()(an(Un((e,t)=>({byRoot:{},activeRuntimeKey:B(),runtimeSnapshots:{},resetForRuntimeSwitch:n=>{e(r=>{const o={...r.runtimeSnapshots,[r.activeRuntimeKey]:{byRoot:yn(r.byRoot),updatedAt:Date.now()}};return{activeRuntimeKey:n,runtimeSnapshots:o,byRoot:yn(o[n]?.byRoot)}})},addOpenPath:(n,r,o)=>{const s=z((n||"").trim()),i=z((r||"").trim());!s||!i||!o?.allowOutsideRoot&&!ut(i,s)||e(a=>{const c=a.byRoot[s],l=Gt(c),d=l.openPaths.includes(i),u=d?l.openPaths:[...l.openPaths,i],f=l.selectedPath??i;if(c&&d&&c.selectedPath===f)return a;const p={...a.byRoot,[s]:{...l,openPaths:u,selectedPath:f}};return{byRoot:_e(p,Le)}})},removeOpenPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=h=>ct(h)===c,d=a.selectedPath?l(a.selectedPath):!1;if(!a.openPaths.some(l)&&!d)return i;const u=a.openPaths.filter(h=>!l(h)),f=d?u[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:_e(p,Le)}})},removeOpenPathsByPrefix:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=c.endsWith("/")?c:`${c}/`,d=h=>{const g=ct(h);return g===c||g.startsWith(l)},u=a.openPaths.filter(h=>!d(h));if(u.length===a.openPaths.length)return i;const f=a.selectedPath&&d(a.selectedPath)?u[0]??null:a.selectedPath,p={...i.byRoot,[o]:{...a,openPaths:u,selectedPath:f,touchedAt:Date.now()}};return{byRoot:_e(p,Le)}})},removeExpandedPathsByPrefix:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||e(i=>{const a=i.byRoot[o];if(!a)return i;const c=ct(s),l=c.endsWith("/")?c:`${c}/`,d=a.expandedPaths.filter(f=>{const p=ct(f);return p!==c&&!p.startsWith(l)});if(d.length===a.expandedPaths.length)return i;const u={...i.byRoot,[o]:{...a,expandedPaths:d,touchedAt:Date.now()}};return{byRoot:_e(u,Le)}})},setSelectedPath:(n,r,o)=>{const s=z((n||"").trim()),i=r?z(r.trim()):null;!s||i&&!o?.allowOutsideRoot&&!ut(i,s)||e(a=>{const c=a.byRoot[s],l=Gt(c),d=i&&!l.openPaths.includes(i)?[...l.openPaths,i]:l.openPaths;if(c&&c.selectedPath===i&&d===c.openPaths)return a;const u={...a.byRoot,[s]:{...l,openPaths:d,selectedPath:i}};return{byRoot:_e(u,Le)}})},ensureSelectedPath:n=>{const r=z((n||"").trim());if(!r)return;const o=t().byRoot[r];if(!o||o.selectedPath)return;const s=o.openPaths[0]??null;s&&t().setSelectedPath(r,s)},toggleExpandedPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||!ut(s,o)||e(i=>{const a=i.byRoot[o],c=Gt(a),d=c.expandedPaths.includes(s)?c.expandedPaths.filter(f=>f!==s):[...c.expandedPaths,s];if(a&&a.expandedPaths===d&&a.selectedPath===c.selectedPath&&a.openPaths===c.openPaths)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:d}};return{byRoot:_e(u,Le)}})},collapseAllExpandedPaths:n=>{const r=z((n||"").trim());r&&e(o=>{const s=o.byRoot[r];if(!s||s.expandedPaths.length===0)return o;const i={...o.byRoot,[r]:{...Gt(s),expandedPaths:[]}};return{byRoot:_e(i,Le)}})},expandPath:(n,r)=>{const o=z((n||"").trim()),s=z((r||"").trim());!o||!s||!ut(s,o)||e(i=>{const a=i.byRoot[o],c=Gt(a);if(c.expandedPaths.includes(s)&&a)return i;const d={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,s]}};return{byRoot:_e(d,Le)}})},expandPaths:(n,r)=>{const o=z((n||"").trim());if(!o||!r||r.length===0)return;const s=r.map(i=>z((i||"").trim())).filter(i=>i&&ut(i,o));s.length!==0&&e(i=>{const a=i.byRoot[o],c=Gt(a),l=new Set(c.expandedPaths),d=s.filter(f=>!l.has(f));if(d.length===0)return i;const u={...i.byRoot,[o]:{...c,expandedPaths:[...c.expandedPaths,...d]}};return{byRoot:_e(u,Le)}})}}),{name:"files-view-tabs-store",version:3,storage:As(),migrate:(e,t)=>t<3||!e||typeof e!="object"?{byRoot:{},activeRuntimeKey:B(),runtimeSnapshots:{}}:e,partialize:e=>{const t={...e.runtimeSnapshots,[e.activeRuntimeKey]:{byRoot:yn(e.byRoot),updatedAt:Date.now()}},n=Object.fromEntries(Object.entries(t).sort(([,r],[,o])=>o.updatedAt-r.updatedAt).slice(0,ip).map(([r,o])=>[r,{byRoot:yn(o.byRoot),updatedAt:o.updatedAt}]));return{activeRuntimeKey:e.activeRuntimeKey,runtimeSnapshots:n}},merge:(e,t)=>{const n=e&&typeof e=="object"?e:{},r=n.runtimeSnapshots&&typeof n.runtimeSnapshots=="object"?n.runtimeSnapshots:{},o=B();return{...t,activeRuntimeKey:o,runtimeSnapshots:r,byRoot:yn(r[o]?.byRoot)}}}),{name:"files-view-tabs-store"})),Fc=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",lp=()=>{if(typeof window>"u")return!1;const e=window.__AIWORKER_ELECTRON__?.arch?.toLowerCase?.();if(e==="arm64"||e==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const t=window.__VSCODE_CONFIG__?.arch?.toLowerCase?.();if(t==="arm64"||t==="aarch64")return(navigator.platform||"").toLowerCase().includes("win");const n=navigator.userAgentData;if(n?.architecture?.toLowerCase?.()==="arm64"||n?.architecture?.toLowerCase?.()==="aarch64")return(n.platform||navigator.platform||"").toLowerCase().includes("win");const r=navigator.userAgent.toLowerCase();return!!((r.includes("aarch64")||r.includes("arm64")||r.includes("armv"))&&r.includes("windows"))},zw=()=>{if(typeof window>"u"||!Fc()||dp()!=="ios")return!1;const e=navigator.userAgent||"",t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},dp=()=>{if(typeof window<"u"){const t=window.Capacitor?.getPlatform?.();if(t==="ios"||t==="android")return t}return Be()?"vscode":gt()?"desktop":"web"},jc="ask",ji=e=>e==="attach"||e==="inline"||e==="ask"?e:jc;function Ui(e){return e==="vim"?"vim":"default"}const Je="all";function Ni(e){return e==="all"||e==="backlog"||e==="todo"||e==="started"||e==="inReview"||e==="completed"||e==="canceled"||e==="duplicate"?e:"all"}function Bi(e){return e==="me"||e==="any"?e:"any"}function Uc(e){return typeof e!="string"?Je:e.trim()||Je}function Hi(e,t){const n=B();if(lc(n))return e;const r={...e};return t===Je?delete r[n]:r[n]=t,r}function up(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=Uc(r);o!==Je&&(t[n]=o)}return t}function zi(e){return e==="none"||e==="urgent"||e==="high"||e==="medium"||e==="low"||e==="all"?e:"all"}const rr={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},nt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},or=(e,t)=>e?e.title===t.title&&e.message===t.message:!1,fp=e=>{if(!e||typeof e!="object")return!1;const t=e;return or(t.completion,rr.completion)&&or(t.error,rr.error)&&or(t.question,rr.question)&&or(t.subtask,rr.subtask)},pp=380,hp=380,mp=1400,Nc=12,Wi=120,gn=280;let $i=0;const yp=e=>ne(e),ne=e=>{if(!e)return"";const t=e.replace(/\\/g,"/"),n=t.startsWith("//");let r=t.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?t.startsWith("/")?"/":"":r},Bc=e=>Number.isFinite(e)?Math.min(mp,Math.max(hp,Math.round(e))):pp,Fn=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.replace(/\\/g,"/"):null},Cr=e=>{const t=Fn(e);return t&&yp(t)||null},Dr=e=>{if(typeof e!="string")return null;const t=e.trim();return t?t.length>Wi?t.slice(0,Wi):t:null},Is=e=>e==="working"||e==="staged"||e==="turn"||e==="branch"?e:null,Hc=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},gp=(e,t)=>(e==="file"||e==="browser")&&t||e,zc=(e,t,n)=>{if(e==="diff")return e;if(typeof n=="string"){const r=n.trim();if(r)return r}return gp(e,t)},Wc=(e,t)=>t===e?e:`${e}:${t}`,$c=e=>{const t=Fn(e.targetPath),n=e.mode==="terminal"?Cr(e.targetDirectory):null,r=zc(e.mode,t,e.dedupeKey);return{id:Wc(e.mode,r),mode:e.mode,targetPath:t,targetDirectory:n,projectPlanId:typeof e.projectPlanId=="string"&&e.projectPlanId.trim()?e.projectPlanId.trim():null,projectPlanRef:Hc(e.projectPlanRef),dedupeKey:r,label:Dr(e.label),sessionTitleFallback:Dr(e.sessionTitleFallback),readOnly:e.readOnly===!0,stagedDiff:e.stagedDiff===!0,diffScope:Is(e.diffScope)??(e.stagedDiff===!0?"staged":"working"),touchedAt:Date.now()}},Gc=(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))},Kc=e=>{if(!Array.isArray(e))return[];const t=Be(),n=[],r=new Set;for(const o of e){if(!o||typeof o!="object")continue;const s=o;if(s.mode!=="diff"&&s.mode!=="walkthrough"&&s.mode!=="file"&&s.mode!=="context"&&s.mode!=="plan"&&s.mode!=="chat"&&s.mode!=="browser"&&s.mode!=="git"&&s.mode!=="pr"&&s.mode!=="linear"&&s.mode!=="notes"&&s.mode!=="terminal"||t&&s.mode==="browser")continue;const i=Fn(typeof s.targetPath=="string"?s.targetPath:null),a=s.mode==="terminal"?Cr(s.targetDirectory):null,c=typeof s.projectPlanId=="string"&&s.projectPlanId.trim()?s.projectPlanId.trim():null,l=Hc(s.projectPlanRef);if(s.mode==="plan"&&c!==null!=(l!==null))continue;const d=zc(s.mode,i,typeof s.dedupeKey=="string"?s.dedupeKey:null),u=Wc(s.mode,d);!u||r.has(u)||(r.add(u),n.push({id:u,mode:s.mode,targetPath:i,targetDirectory:a,projectPlanId:c,projectPlanRef:l,dedupeKey:d,label:Dr(typeof s.label=="string"?s.label:null),sessionTitleFallback:Dr(typeof s.sessionTitleFallback=="string"?s.sessionTitleFallback:null),readOnly:s.readOnly===!0,stagedDiff:s.stagedDiff===!0,diffScope:Is(s.diffScope)??(s.stagedDiff===!0?"staged":"working"),touchedAt:typeof s.touchedAt=="number"&&Number.isFinite(s.touchedAt)?s.touchedAt:Date.now()}))}return n},on=(e,t)=>t&&e.some(n=>n.id===t)?t:e.length===0?null:e[e.length-1].id,Tt=e=>{if(e){const t=Kc(e.tabs),n=on(t,e.activeTabId);return{...e,tabs:t,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,widthByMode:{},touchedAt:Date.now()}},wp=(e,t,n)=>{const r=n?.reveal!==!1,o=$c(t),s=o.mode==="file"&&o.targetPath?e.tabs.filter(d=>!(d.mode==="file"&&!d.targetPath)):e.tabs,i=s.findIndex(d=>d.id===o.id),a=i===-1?[...s,o]:s.map((d,u)=>u===i?{...d,mode:o.mode,targetPath:o.targetPath||d.targetPath,targetDirectory:o.targetDirectory,projectPlanId:o.projectPlanId??d.projectPlanId,projectPlanRef:o.projectPlanRef??d.projectPlanRef,dedupeKey:o.dedupeKey,label:o.label,sessionTitleFallback:o.sessionTitleFallback||d.sessionTitleFallback,stagedDiff:o.stagedDiff,diffScope:o.diffScope,readOnly:o.readOnly,touchedAt:Date.now()}:d),c=r?o.id:e.activeTabId??o.id,l=Gc(a,Nc,c);return{...e,isOpen:r?!0:e.isOpen,tabs:l,activeTabId:on(l,c),touchedAt:Date.now()}},bp=(e,t)=>{const n=new Set(t),r=e.tabs.filter(l=>n.has(l.id)),o=e.tabs.filter(l=>!n.has(l.id));if(o.length===e.tabs.length)return e;if(!(e.activeTabId?n.has(e.activeTabId):!1))return{...e,tabs:o,activeTabId:on(o,e.activeTabId),isOpen:o.length>0?e.isOpen:!1,touchedAt:Date.now()};const i=r.find(l=>l.id===e.activeTabId)?.mode??null,a=i?o.filter(l=>l.mode===i):[],c=a.length>0?a.reduce((l,d)=>d.touchedAt>=l.touchedAt?d:l):null;return{...e,tabs:o,activeTabId:c?.id??on(o,null),isOpen:c?e.isOpen:!1,touchedAt:Date.now()}},Sp=(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},Tp=(e,t,n)=>({...e,tabs:e.tabs.map(r=>r.id===t?{...r,targetPath:n}:r)}),So=e=>{if(!e||typeof e!="object")return{};const t=e,n={};for(const[r,o]of Object.entries(t)){const s=ne(r);if(!s||!o||typeof o!="object")continue;const i=o;let a=Kc(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat"||i.mode==="terminal")&&(a=[$c({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,targetDirectory:i.targetDirectory,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=a[0]?.id??null);const l=on(a,c),d=Gc(a,Nc,l),u={};if(i.widthByMode&&typeof i.widthByMode=="object")for(const[f,p]of Object.entries(i.widthByMode))(f==="diff"||f==="file"||f==="context"||f==="plan"||f==="chat"||f==="browser"||f==="git"||f==="pr"||f==="linear"||f==="notes"||f==="terminal")&&typeof p=="number"&&Number.isFinite(p)&&(u[f]=Bc(p));n[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:on(d,l),widthByMode:u,touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},kt=(e,t)=>{const n=Object.entries(e);if(n.length<=t)return e;n.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,s]of n.slice(0,t))r[o]=s;return r},Se=Ze()(an(Un((e,t)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:gn,hasManuallyResizedLeftSidebar:!1,contextPanelByDirectory:{},contextRailOrder:[],contextRailHiddenSurfaces:[],contextEditorTreeVisible:!0,contextEditorTreeWidth:240,notesPanelHeight:112,workStatusExpandedSections:{},workStatusScrollTop:0,workStatusPanelEnabled:!0,workStatusPanelVisible:!1,workStatusPanelFits:!1,workStatusOverlayOpen:!1,workStatusHiddenSections:[],isSessionSwitcherOpen:!1,isSessionDropdownOpen:!1,pendingDiffFile:null,pendingDiffStaged:!1,pendingDiffScope:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null,isSettingsDialogOpen:!1,isNewWorktreeDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsProjectPath:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,streamingAutoFollowEnabled:!0,sessionRecapEnabled:!0,sessionSuggestionEnabled:!0,sessionGoalEnabled:!0,sessionGoalDefaultBudgetEnabled:!1,sessionGoalDefaultBudget:2e5,collapsibleThinkingBlocks:!0,chatRenderMode:"live",activityRenderMode:"summary",showDeletionDialog:!0,showOpenCodeRestartConfirm:!0,autoDeleteEnabled:!1,autoSaveEnabled:!0,autoDeleteAfterDays:30,sessionRetentionAction:"archive",autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,globalDraftStarters:null,terminalFontSize:14,terminalShell:"auto",terminalLoginShells:[],editorFontSize:13,uiFont:Nf,monoFont:Bf,padding:100,cornerRadius:18,inputBarOffset:0,mobileKeyboardMode:Wf(),favoriteModels:[],hiddenModels:[],providerOrder:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,walkthroughTocWidth:224,gitChangesViewMode:"flat",toolJsonViewMode:"summary",linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Je,linearIssueListTeamIdByRuntime:{},linearIssueListPriority:"all",linearIssueFocus:null,isTimelineDialogOpen:!1,isPromptNavigatorPanelOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,dockBadgeEnabled:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...nt.completion},error:{...nt.error},question:{...nt.question},subtask:{...nt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,sessionTabsEnabled:!1,persistChatDraft:!0,showOpenCodeUpdateNotifications:!lp(),agentControlToolEnabled:!0,agentWebToolEnabled:!0,agentMemoryToolEnabled:!1,agentMemoryFeatureAvailable:!1,agentMemoryViewedAt:{},projectContextSidebarWidth:168,projectContextTab:"notes",inputSpellcheckEnabled:!1,largeTextPasteBehavior:jc,enterToSend:!1,enterToSendConfigured:!1,wideChatLayoutEnabled:!1,codeBlockLineWrap:!0,showToolFileIcons:!0,showTurnChangedFiles:!1,showExpandedBashTools:!1,showExpandedEditTools:!1,timeFormatPreference:"auto",weekStartPreference:"auto",desktopWindowControlsPosition:"right",desktopWindowControlsStyle:"classic",mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",collapsibleUserMessages:!0,stickyUserHeader:!1,promptNavigatorEnabled:!0,showSplitAssistantMessageActions:!1,allowPromptingSubagentSessions:!1,draftStartersVisible:!0,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},fileEditorKeymap:"default",setTheme:n=>{e({theme:n}),t().applyTheme()},toggleSidebar:()=>{e(n=>{const r=!n.isSidebarOpen;return r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:gn}:{isSidebarOpen:r}})},setSidebarOpen:n=>{e(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==gn?{isSidebarOpen:n,sidebarWidth:gn}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:gn}:{isSidebarOpen:n})},setSidebarWidth:n=>{e({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},setContextRailOrder:n=>{const r=Array.isArray(n)?n.filter((o,s)=>typeof o=="string"&&o.trim()!==""&&n.indexOf(o)===s):[];e({contextRailOrder:r})},toggleContextEditorTree:()=>{e(n=>({contextEditorTreeVisible:!n.contextEditorTreeVisible}))},setContextEditorTreeWidth:n=>{Number.isFinite(n)&&e({contextEditorTreeWidth:Math.min(480,Math.max(200,Math.round(n)))})},openContextSurface:(n,r)=>{const o=ne((n||"").trim());if(!o)return;const s=t(),i=s.contextPanelByDirectory[o],a=i?.tabs??[],c=a.find(u=>u.id===i?.activeTabId)??null,l=()=>{if(r==="terminal"){const f=(a.find(p=>p.mode==="terminal")??null)?.targetDirectory??null;if(f){const p=hr.getState().getDirectoryState(f);if(Kf(p))return}s.openContextPanelTab(o,{mode:"terminal",targetDirectory:null},{reveal:!1})}};if(i?.isOpen&&c?.mode===r){l(),s.closeContextPanel(o);return}const d=a.filter(u=>u.mode===r);if(d.length>0){l();const u=d.reduce((f,p)=>p.touchedAt>=f.touchedAt?p:f);s.setActiveContextPanelTab(o,u.id);return}r!=="chat"&&s.openContextPanelTab(o,{mode:r})},openContextPanelTab:(n,r,o)=>{const s=ne((n||"").trim());if(!s)return;const i=r.mode==="terminal"?{...r,targetDirectory:Cr(r.targetDirectory)===s?null:Cr(r.targetDirectory)}:r;e(a=>{const c=a.contextPanelByDirectory[s],l=Tt(c),d={...a.contextPanelByDirectory,[s]:wp(l,i,o)};return{contextPanelByDirectory:kt(d,20)}})},openContextDiff:(n,r,o=!1,s=null)=>{const i=ne((n||"").trim()),a=(r||"").trim();if(!i||!a)return;const c=Is(s)??(o?"staged":"working");t().openContextPanelTab(i,{mode:"diff",targetPath:a,stagedDiff:c==="staged",diffScope:c})},openContextFile:(n,r)=>{const o=ne((n||"").trim()),s=Fn(r);!o||!s||(t().openContextPanelTab(o,{mode:"file",targetPath:s}),t().setPendingFileFocusPath(s),t().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,s)=>{const i=ne((n||"").trim()),a=Fn(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,l=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1;!i||!a||(t().openContextPanelTab(i,{mode:"file",targetPath:a}),t().setPendingFileFocusPath(null),t().setPendingFileNavigation({path:a,line:c,column:l}))},openContextOverview:n=>{const r=ne((n||"").trim());r&&t().openContextPanelTab(r,{mode:"context"})},openContextPreview:(n,r)=>{const o=ne((n||"").trim()),s=(r||"").trim();!o||!s||Be()||t().openContextPanelTab(o,{mode:"browser",targetPath:s,dedupeKey:s,label:null})},openNewContextBrowserTab:n=>{const r=ne((n||"").trim());!r||Be()||($i+=1,t().openContextPanelTab(r,{mode:"browser",targetPath:"",dedupeKey:`browser:new:${Date.now()}-${$i}`,label:null}))},openContextBrowser:(n,r="",o)=>{const s=ne((n||"").trim());if(!s||Be())return;const i=typeof r=="string"&&r.trim().length>0?r.trim():"";t().openContextPanelTab(s,{mode:"browser",targetPath:i,dedupeKey:i||"browser",label:null},o)},setContextPanelTabTargetPath:(n,r,o)=>{const s=ne((n||"").trim()),i=(r||"").trim();!s||!i||e(a=>{const c=a.contextPanelByDirectory[s];return c?{contextPanelByDirectory:{...a.contextPanelByDirectory,[s]:Tp(c,i,o)}}:a})},setActiveContextPanelTab:(n,r)=>{const o=ne((n||"").trim()),s=(r||"").trim();!o||!s||e(i=>{const a=i.contextPanelByDirectory[o],c=Tt(a);if(!c.tabs.some(d=>d.id===s)||c.activeTabId===s&&c.isOpen)return i;const l={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:c.tabs.map(d=>d.id===s?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:kt(l,20)}})},reorderContextPanelTabs:(n,r,o)=>{const s=ne((n||"").trim()),i=(r||"").trim(),a=(o||"").trim();!s||!i||!a||e(c=>{const l=c.contextPanelByDirectory[s],d=Tt(l);if(!d.tabs.some(p=>p.id===i)||!d.tabs.some(p=>p.id===a))return c;const u=Sp(d,i,a);if(u.tabs===d.tabs)return c;const f={...c.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:kt(f,20)}})},closeContextPanelTab:(n,r)=>{t().closeContextPanelTabs(n,[r])},closeContextPanelTabs:(n,r)=>{const o=ne((n||"").trim()),s=(r??[]).map(a=>(a||"").trim()).filter(a=>a.length>0);if(!o||s.length===0)return;const i=s.map(a=>t().contextPanelByDirectory[o]?.tabs.find(c=>c.id===a)).filter(a=>!!a);e(a=>{const c=a.contextPanelByDirectory[o],l=Tt(c);if(!l.tabs.some(u=>s.includes(u.id)))return a;const d={...a.contextPanelByDirectory,[o]:bp(l,s)};return{contextPanelByDirectory:kt(d,20)}});for(const a of i)a.mode==="file"&&a.targetPath&&cp.getState().removeOpenPath(o,a.targetPath)},closeContextPanel:n=>{const r=ne((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Tt(s),isOpen:!1}};return{contextPanelByDirectory:kt(i,20)}})},toggleContextPanelExpanded:n=>{const r=ne((n||"").trim());r&&e(o=>{const s=o.contextPanelByDirectory[r],i=Tt(s),a={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:kt(a,20)}})},setContextPanelWidth:(n,r,o)=>{const s=ne((n||"").trim());s&&e(i=>{const a=i.contextPanelByDirectory[s],c=Tt(a),l={...i.contextPanelByDirectory,[s]:{...c,widthByMode:{...c.widthByMode,[r]:Bc(o)}}};return{contextPanelByDirectory:kt(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(Lf);if(o===1){for(const[i]of s)r.style.removeProperty(Ri(i));return}for(const[i,a]of s){const c=parseFloat(a);Number.isFinite(c)&&r.style.setProperty(Ri(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:n}=t(),r=document.documentElement,o=n/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);r.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{e({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{e(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{e({diffWrapLines:n})},setWalkthroughTocWidth:n=>{e({walkthroughTocWidth:Math.round(n)})},setGitChangesViewMode:n=>{e({gitChangesViewMode:n})},setToolJsonViewMode:n=>{e({toolJsonViewMode:n})},setLinearIssueListStatus:n=>{e({linearIssueListStatus:Ni(n)})},setLinearIssueListAssignee:n=>{e({linearIssueListAssignee:Bi(n)})},setLinearIssueListTeamId:n=>{const r=Uc(n);e(o=>({linearIssueListTeamId:r,linearIssueListTeamIdByRuntime:Hi(o.linearIssueListTeamIdByRuntime,r)}))},applyLinearIssueListFiltersForRuntime:()=>{const n=B();e(r=>({linearIssueListTeamId:lc(n)?Je:r.linearIssueListTeamIdByRuntime[n]??Je}))},setLinearIssueListPriority:n=>{e({linearIssueListPriority:zi(n)})},resetLinearIssueListFilters:()=>{e(n=>({linearIssueListStatus:"all",linearIssueListAssignee:"any",linearIssueListTeamId:Je,linearIssueListTeamIdByRuntime:Hi(n.linearIssueListTeamIdByRuntime,Je),linearIssueListPriority:"all"}))},setLinearIssueFocus:n=>{const r=n?.trim()??"";e({linearIssueFocus:r||null})},setInputBarOffset:n=>{e({inputBarOffset:n})},setMobileKeyboardMode:n=>{e(r=>r.mobileKeyboardMode===n?r:{mobileKeyboardMode:n})},toggleFavoriteModel:(n,r)=>{e(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},reorderFavoriteModel:(n,r,o,s)=>{e(i=>{const a=i.favoriteModels.findIndex(u=>u.providerID===n&&u.modelID===r),c=i.favoriteModels.findIndex(u=>u.providerID===o&&u.modelID===s);if(a===-1||c===-1||a===c)return i;const l=i.favoriteModels.slice(),[d]=l.splice(a,1);return d?(l.splice(c,0,d),{favoriteModels:l}):i})},setProviderOrder:n=>{e(r=>{const o=n.filter(i=>typeof i=="string"&&i.length>0),s=r.providerOrder;return s.length===o.length&&s.every((i,a)=>i===o[a])?r:{providerOrder:o}})},toggleHiddenModel:(n,r)=>{e(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},hideAllModels:(n,r)=>{e(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==n);return{hiddenModels:[...r.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:n,modelID:a})),...s]}})},showAllModels:n=>{e(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},setModelProvidersCollapsed:(n,r)=>{const o=Array.from(new Set(n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)));o.length!==0&&e(s=>{const i=new Set(o),a=s.collapsedModelProviders.filter(c=>!i.has(c));return{collapsedModelProviders:r?[...a,...o]:a}})},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=t();return o.some(s=>s.providerID===n&&s.modelID===r)},addRecentModel:(n,r)=>{e(o=>{const s=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...s].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&e(o=>{if(o.recentAgents.includes(r))return o;const s=o.recentAgents;return{recentAgents:[r,...s].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const s=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!s||!i)return;const a=`${s}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";e(l=>{const d=l.recentEfforts[a]??[];if(d.includes(c))return l;const u=d;return{recentEfforts:{...l.recentEfforts,[a]:[c,...u].slice(0,5)}}})},applyTheme:()=>{const{theme:n}=t(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{e(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:"",...n?{isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null}:{}}))},openMultiRunLauncher:()=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},openMultiRunLauncherWithPrompt:n=>{e({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1,isScheduledTasksDialogOpen:!1,isArchivePageOpen:!1,worktreesPageProjectId:null})},setTimelineDialogOpen:n=>{e({isTimelineDialogOpen:n})},setPromptNavigatorPanelOpen:n=>{e({isPromptNavigatorPanelOpen:n})},togglePromptNavigatorPanel:()=>{e(n=>({isPromptNavigatorPanelOpen:!n.isPromptNavigatorPanelOpen}))},setImagePreviewOpen:n=>{e({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{e({nativeNotificationsEnabled:n})},setNotificationMode:n=>{e({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{e({showTerminalQuickKeysOnDesktop:n})},setSessionTabsEnabled:n=>{e({sessionTabsEnabled:n})},setNotifyOnSubtasks:n=>{e({notifyOnSubtasks:n})},setDockBadgeEnabled:n=>{e({dockBadgeEnabled:n})},setNotifyOnCompletion:n=>{e({notifyOnCompletion:n})},setNotifyOnError:n=>{e({notifyOnError:n})},setNotifyOnQuestion:n=>{e({notifyOnQuestion:n})},setNotificationTemplates:n=>{e(r=>({notificationTemplates:typeof n=="function"?n(r.notificationTemplates):n}))},setSummarizeLastMessage:n=>{e({summarizeLastMessage:n})},setSummaryThreshold:n=>{e({summaryThreshold:n})},setSummaryLength:n=>{e({summaryLength:n})},setMaxLastMessageLength:n=>{e({maxLastMessageLength:n})},setPersistChatDraft:n=>{e({persistChatDraft:n})},setShowOpenCodeUpdateNotifications:n=>{e({showOpenCodeUpdateNotifications:n})},setAgentControlToolEnabled:n=>{e({agentControlToolEnabled:n})},setAgentWebToolEnabled:n=>{e({agentWebToolEnabled:n})},setAgentMemoryToolEnabled:n=>{e({agentMemoryToolEnabled:n})},setAgentMemoryFeatureAvailable:n=>{e({agentMemoryFeatureAvailable:n})},setProjectContextSidebarWidth:n=>{e({projectContextSidebarWidth:n})},markAgentMemoryViewed:(n,r)=>{e(o=>({agentMemoryViewedAt:r>(o.agentMemoryViewedAt[n]??0)?{...o.agentMemoryViewedAt,[n]:r}:o.agentMemoryViewedAt}))},setProjectContextTab:n=>{e({projectContextTab:n})},setInputSpellcheckEnabled:n=>{e({inputSpellcheckEnabled:n})},setLargeTextPasteBehavior:n=>{e({largeTextPasteBehavior:ji(n)})},setEnterToSend:n=>{e({enterToSend:n})},setEnterToSendConfigured:n=>{e({enterToSendConfigured:n})},setWideChatLayoutEnabled:n=>{e({wideChatLayoutEnabled:n})},setCodeBlockLineWrap:n=>{e({codeBlockLineWrap:n})},setShowToolFileIcons:n=>{e({showToolFileIcons:n})},setShowTurnChangedFiles:n=>{e({showTurnChangedFiles:n})},setShowExpandedBashTools:n=>{e({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{e({showExpandedEditTools:n})},setTimeFormatPreference:n=>{e({timeFormatPreference:n})},setWeekStartPreference:n=>{e({weekStartPreference:n})},setDesktopWindowControlsPosition:n=>{e({desktopWindowControlsPosition:n==="left"?"left":"right"})},setDesktopWindowControlsStyle:n=>{e({desktopWindowControlsStyle:n==="traffic-lights"?"traffic-lights":"classic"})},setMermaidRenderingMode:n=>{e({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{e({userMessageRenderingMode:n})},setCollapsibleUserMessages:n=>{e({collapsibleUserMessages:n})},setStickyUserHeader:n=>{e({stickyUserHeader:n})},setPromptNavigatorEnabled:n=>{e({promptNavigatorEnabled:n})},setShowSplitAssistantMessageActions:n=>{e({showSplitAssistantMessageActions:n})},setAllowPromptingSubagentSessions:n=>{e({allowPromptingSubagentSessions:n})},setReportUsage:n=>{e({reportUsage:n})},viewPagerPage:"center",setViewPagerPage:n=>{e({viewPagerPage:n}),e({isSessionSwitcherOpen:n==="left"})},setShortcutOverride:(n,r)=>{e(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{e(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{e({shortcutOverrides:{}})},setFileEditorKeymap:n=>{e({fileEditorKeymap:Ui(n)})},toggleExpandedInput:()=>{e(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{e({isExpandedInput:n})}}),{name:"ui-store",storage:As(),version:19,migrate:(e,t)=>{if(!e||typeof e!="object")return e;const n=e;if(t<16&&(delete n.activeMainTab,delete n.activeSurface),t<17&&delete n.expandedEditorToolbar,t<18&&delete n.shortcutOverrides,t<14){const r=n.contextPanelByDirectory;if(r&&typeof r=="object")for(const o of Object.values(r)){if(!o||typeof o!="object")continue;const s=o,i=s.widthByMode;if(i&&typeof i=="object"){const l=i;l.preview!==void 0&&(l.browser===void 0&&(l.browser=l.preview),delete l.preview)}if(!Array.isArray(s.tabs))continue;const a=new Set,c=[];for(const l of s.tabs){if(!l||typeof l!="object")continue;const d=l;if(d.mode!=="preview"){typeof d.id=="string"&&a.add(d.id),c.push(d);continue}const u=typeof d.targetPath=="string"?d.targetPath:"",f=typeof d.dedupeKey=="string"&&d.dedupeKey.trim()?d.dedupeKey.trim():u||"browser",p=f==="browser"?"browser":`browser:${f}`;a.has(p)||(a.add(p),c.push({...d,mode:"browser",id:p,dedupeKey:f}))}if(s.tabs=c,typeof s.activeTabId=="string"&&s.activeTabId.startsWith("preview")){const l=c.find(d=>typeof d.id=="string");s.activeTabId=l&&typeof l.id=="string"?l.id:null}}}if(t<13&&typeof n.autoSaveEnabled!="boolean"){let r=!0;try{if(typeof localStorage<"u"){const o=localStorage.getItem("aiworker:files:auto-save-enabled");o!==null&&(r=o!=="false",localStorage.removeItem("aiworker:files:auto-save-enabled"))}}catch{r=!0}n.autoSaveEnabled=r}if(t<12&&(n.desktopWindowControlsPosition==="auto"||n.desktopWindowControlsPosition==null)&&(n.desktopWindowControlsPosition="right"),t<11&&n.terminalFontSize===13&&(n.terminalFontSize=14),t<10&&delete n.diffViewMode,t<9&&((!n.workStatusExpandedSections||typeof n.workStatusExpandedSections!="object")&&(n.workStatusExpandedSections={}),(typeof n.workStatusScrollTop!="number"||!Number.isFinite(n.workStatusScrollTop))&&(n.workStatusScrollTop=0),typeof n.workStatusPanelEnabled!="boolean"&&(n.workStatusPanelEnabled=!0),Array.isArray(n.workStatusHiddenSections)||(n.workStatusHiddenSections=[]),(typeof n.notesPanelHeight!="number"||!Number.isFinite(n.notesPanelHeight))&&(n.notesPanelHeight=112)),t<1&&fp(n.notificationTemplates)&&(n.notificationTemplates={completion:{...nt.completion},error:{...nt.error},question:{...nt.question},subtask:{...nt.subtask}}),t<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,s=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof s=="number"&&!r.has(s)&&(n.messageLimit=s),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if(delete n.isRightSidebarOpen,delete n.rightSidebarWidth,delete n.rightSidebarTab,n.contextPanelByDirectory=So(n.contextPanelByDirectory),t<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[s,i]of Object.entries(r))typeof s=="string"&&typeof i=="string"&&(o[s]=i);n.shortcutOverrides=o}return t<6&&(n.contextPanelByDirectory=So(n.contextPanelByDirectory)),t<7&&(n.contextPanelByDirectory=So(n.contextPanelByDirectory)),t<8&&n.gitChangesViewMode!=="flat"&&n.gitChangesViewMode!=="tree"&&(n.gitChangesViewMode="flat"),n.linearIssueListStatus=Ni(n.linearIssueListStatus),n.linearIssueListAssignee=Bi(n.linearIssueListAssignee),delete n.linearIssueListTeamId,n.linearIssueListTeamIdByRuntime=up(n.linearIssueListTeamIdByRuntime),n.linearIssueListPriority=zi(n.linearIssueListPriority),n.fileEditorKeymap=Ui(n.fileEditorKeymap),n.largeTextPasteBehavior=ji(n.largeTextPasteBehavior),n.toolJsonViewMode!=="summary"&&n.toolJsonViewMode!=="formatted"&&n.toolJsonViewMode!=="raw"&&(n.toolJsonViewMode="summary"),typeof n.autoSaveEnabled!="boolean"&&(n.autoSaveEnabled=!0),n.contextRailHiddenSurfaces=Array.isArray(n.contextRailHiddenSurfaces)?n.contextRailHiddenSurfaces.filter(r=>typeof r=="string"&&r.trim()!==""):[],n.contextRailOrder=Array.isArray(n.contextRailOrder)?n.contextRailOrder.filter(r=>typeof r=="string"&&r.trim()!==""):[],n},partialize:e=>({theme:e.theme,isSidebarOpen:e.isSidebarOpen,sidebarWidth:e.sidebarWidth,contextPanelByDirectory:e.contextPanelByDirectory,contextRailOrder:e.contextRailOrder,contextRailHiddenSurfaces:e.contextRailHiddenSurfaces,contextEditorTreeVisible:e.contextEditorTreeVisible,contextEditorTreeWidth:e.contextEditorTreeWidth,notesPanelHeight:e.notesPanelHeight,workStatusExpandedSections:e.workStatusExpandedSections,workStatusScrollTop:e.workStatusScrollTop,workStatusPanelEnabled:e.workStatusPanelEnabled,workStatusHiddenSections:e.workStatusHiddenSections,isSessionSwitcherOpen:e.isSessionSwitcherOpen,sidebarSection:e.sidebarSection,settingsPage:e.settingsPage,settingsHasOpenedOnce:e.settingsHasOpenedOnce,settingsProjectsSelectedId:e.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:e.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:e.isSessionCreateDialogOpen,showReasoningTraces:e.showReasoningTraces,streamingAutoFollowEnabled:e.streamingAutoFollowEnabled,sessionRecapEnabled:e.sessionRecapEnabled,sessionSuggestionEnabled:e.sessionSuggestionEnabled,sessionGoalEnabled:e.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:e.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:e.sessionGoalDefaultBudget,collapsibleThinkingBlocks:e.collapsibleThinkingBlocks,chatRenderMode:e.chatRenderMode,activityRenderMode:e.activityRenderMode,showDeletionDialog:e.showDeletionDialog,showOpenCodeRestartConfirm:e.showOpenCodeRestartConfirm,autoDeleteEnabled:e.autoDeleteEnabled,autoSaveEnabled:e.autoSaveEnabled,autoDeleteAfterDays:e.autoDeleteAfterDays,sessionRetentionAction:e.sessionRetentionAction,autoDeleteLastRunAt:e.autoDeleteLastRunAt,messageLimit:e.messageLimit,fontSize:e.fontSize,globalDraftStarters:e.globalDraftStarters,terminalFontSize:e.terminalFontSize,terminalShell:e.terminalShell,terminalLoginShells:e.terminalLoginShells,editorFontSize:e.editorFontSize,uiFont:e.uiFont,monoFont:e.monoFont,padding:e.padding,cornerRadius:e.cornerRadius,favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,providerOrder:e.providerOrder,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts,diffLayoutPreference:e.diffLayoutPreference,diffWrapLines:e.diffWrapLines,walkthroughTocWidth:e.walkthroughTocWidth,gitChangesViewMode:e.gitChangesViewMode,toolJsonViewMode:e.toolJsonViewMode,linearIssueListStatus:e.linearIssueListStatus,linearIssueListAssignee:e.linearIssueListAssignee,linearIssueListTeamIdByRuntime:e.linearIssueListTeamIdByRuntime,linearIssueListPriority:e.linearIssueListPriority,nativeNotificationsEnabled:e.nativeNotificationsEnabled,notificationMode:e.notificationMode,showTerminalQuickKeysOnDesktop:e.showTerminalQuickKeysOnDesktop,sessionTabsEnabled:e.sessionTabsEnabled,notifyOnSubtasks:e.notifyOnSubtasks,dockBadgeEnabled:e.dockBadgeEnabled,notifyOnCompletion:e.notifyOnCompletion,notifyOnError:e.notifyOnError,notifyOnQuestion:e.notifyOnQuestion,notificationTemplates:e.notificationTemplates,summarizeLastMessage:e.summarizeLastMessage,summaryThreshold:e.summaryThreshold,summaryLength:e.summaryLength,maxLastMessageLength:e.maxLastMessageLength,persistChatDraft:e.persistChatDraft,showOpenCodeUpdateNotifications:e.showOpenCodeUpdateNotifications,agentControlToolEnabled:e.agentControlToolEnabled,agentWebToolEnabled:e.agentWebToolEnabled,agentMemoryToolEnabled:e.agentMemoryToolEnabled,agentMemoryViewedAt:e.agentMemoryViewedAt,projectContextSidebarWidth:e.projectContextSidebarWidth,inputSpellcheckEnabled:e.inputSpellcheckEnabled,largeTextPasteBehavior:e.largeTextPasteBehavior,enterToSend:e.enterToSend,enterToSendConfigured:e.enterToSendConfigured,wideChatLayoutEnabled:e.wideChatLayoutEnabled,codeBlockLineWrap:e.codeBlockLineWrap,showToolFileIcons:e.showToolFileIcons,showTurnChangedFiles:e.showTurnChangedFiles,showExpandedBashTools:e.showExpandedBashTools,showExpandedEditTools:e.showExpandedEditTools,timeFormatPreference:e.timeFormatPreference,weekStartPreference:e.weekStartPreference,desktopWindowControlsPosition:e.desktopWindowControlsPosition,desktopWindowControlsStyle:e.desktopWindowControlsStyle,mermaidRenderingMode:e.mermaidRenderingMode,userMessageRenderingMode:e.userMessageRenderingMode,collapsibleUserMessages:e.collapsibleUserMessages,stickyUserHeader:e.stickyUserHeader,promptNavigatorEnabled:e.promptNavigatorEnabled,showSplitAssistantMessageActions:e.showSplitAssistantMessageActions,allowPromptingSubagentSessions:e.allowPromptingSubagentSessions,draftStartersVisible:e.draftStartersVisible,shortcutOverrides:e.shortcutOverrides,fileEditorKeymap:e.fileEditorKeymap})}),{name:"ui-store"})),Ms="session",Rs=40,kp=1,vp=100,xs=e=>e==="global"||e==="session",qr=e=>e!=null&&Number.isInteger(e)&&e>=kp&&e<=vp,Xt="openchamber-input-history.v1",Ep=8,Ap=50,Pp=[40,25,10,5,1],To=Object.freeze([]);let Ge=null,Gi=0;const In=(e=Ms,t=Rs)=>({entryLimit:t,scope:e,globalBuckets:{},sessionBuckets:{}}),qc=()=>(Gi+=1,Date.now()*1e3+Gi),Vc=e=>JSON.stringify([e]),No=(e,t,n)=>JSON.stringify([e,t,n]),Cs=()=>{try{return globalThis.window?.localStorage??null}catch{return null}},Ip=()=>{const e=Cs(),t=Me?JSON.stringify(yr(Me.base)):Ge;if(!e)return t;try{return e.getItem(Xt)??(Me?null:Ge)}catch{return t}},Ki=Rl(w(),ds()),Mp=P({key:w().min(1),source:Ea([F("file-url"),F("vscode-file")]),filename:w().min(1),mimeType:w().min(1),size:C().finite().nonnegative(),reference:w().min(1)}),Rp=P({text:w(),attachmentKeys:Xe(w()),restorableAttachments:Xe(Mp),submittedAt:C().finite().nonnegative()}),xp=P({touchedAt:C().finite().nonnegative(),entries:Xe(ds())}),Cp=(e,t)=>{try{const n=JSON.parse(e),o=(t===1?Js([w().trim().min(1)]):Js([w().trim().min(1),w().trim().min(1),w().trim().min(1)])).safeParse(n);if(!o.success)return null;if(t===3){const s=dn(o.data[1]);if(!s||s!==o.data[1])return null}return o.data}catch{return null}},qi=(e,t)=>{const n=[];for(const[r,o]of Object.entries(e)){if(!Cp(r,t))continue;const s=xp.safeParse(o);if(!s.success)continue;const i=s.data.entries.map(a=>Rp.safeParse(a)).filter(a=>a.success).map(a=>a.data);n.push([r,{touchedAt:s.data.touchedAt,entries:i}])}return Object.fromEntries(n)},Dp=()=>{const e=Ip();if(e===null)return In();try{const t=JSON.parse(e),n=P({version:F(1),entryLimit:C().int().optional(),scope:Ea([F("global"),F("session")]).optional(),global:Ki.default({}),session:Ki.default({})}).safeParse(t);return n.success?{entryLimit:qr(n.data.entryLimit)?n.data.entryLimit:Rs,scope:n.data.scope??Ms,globalBuckets:qi(n.data.global,1),sessionBuckets:qi(n.data.session,3)}:In()}catch{const t=Cs();if(t)try{t.removeItem(Xt)}catch{}return Ge=null,In()}};let Me=null,mr=In();const Vi=(e,t,n)=>{const r={...e};for(const o of new Set([...Object.keys(t),...Object.keys(n)])){if(JSON.stringify(t[o])===JSON.stringify(n[o]))continue;const s=n[o];if(!s){delete r[o];continue}const i=new Set((t[o]?.entries??[]).map(d=>JSON.stringify(d))),a=new Set(s.entries.map(d=>JSON.stringify(d))),c=(e[o]?.entries??[]).filter(d=>{const u=JSON.stringify(d);return!i.has(u)||a.has(u)}),l=new Set(c.map(d=>JSON.stringify(d)));for(const d of s.entries){const u=JSON.stringify(d);!i.has(u)&&!l.has(u)&&c.push(d)}c.sort((d,u)=>d.submittedAt-u.submittedAt),r[o]={touchedAt:Math.max(s.touchedAt,e[o]?.touchedAt??0),entries:c}}return r},Sn=()=>{const e=Dp();if(mr=e,!Me)return e;const{base:t,value:n}=Me;return Bo({entryLimit:n.entryLimit===t.entryLimit?e.entryLimit:n.entryLimit,scope:n.scope===t.scope?e.scope:n.scope,globalBuckets:Vi(e.globalBuckets,t.globalBuckets,n.globalBuckets),sessionBuckets:Vi(e.sessionBuckets,t.sessionBuckets,n.sessionBuckets)})},Jc=(e,t)=>e.slice(Math.max(0,e.length-t)),Ji=(e,t,n)=>{const r=Object.entries(e).map(([o,s])=>[o,{touchedAt:s.touchedAt,entries:Jc(s.entries,n)}]).sort((o,s)=>s[1].touchedAt-o[1].touchedAt).slice(0,t);return Object.fromEntries(r)},Bo=(e,t=e.entryLimit)=>({entryLimit:e.entryLimit,scope:e.scope,globalBuckets:Ji(e.globalBuckets,Ep,t),sessionBuckets:Ji(e.sessionBuckets,Ap,t)}),yr=e=>({version:1,entryLimit:e.entryLimit,scope:e.scope,global:e.globalBuckets,session:e.sessionBuckets}),Yi=e=>e instanceof DOMException?e.name==="QuotaExceededError":e instanceof Error&&/quota/i.test(e.message),Tn=e=>{const t=Bo(e),n=JSON.stringify(yr(t));Me={base:mr,value:t};const r=Cs();if(!r)return Ge=n,t;try{return r.setItem(Xt,n),Me=null,Ge=n,t}catch(i){if(!(i instanceof Error)||!Yi(i))return Ge=n,t}try{r.removeItem(Xt)}catch{}for(const i of Pp){const a=Bo(t,i),c=JSON.stringify(yr(a));try{return r.setItem(Xt,c),Me=null,Ge=c,a}catch(l){if(!(l instanceof Error)||!Yi(l))return Me={base:mr,value:a},Ge=c,a}}const o=In(t.scope,t.entryLimit),s=JSON.stringify(yr(o));try{r.setItem(Xt,s),Me=null}catch{Me={base:mr,value:o}}return Ge=s,o},Op=(e,t,n)=>{const r=e.trim(),o=dn(t),s=n.trim();return!r||!o||!s?null:{runtimeKey:r,directory:o,sessionId:s}},Yc=e=>e.source==="vscode"&&e.vscodeSource==="file"?dn(e.vscodePath??null):e.dataUrl.trim()||null,Lp=e=>!(!e||e.startsWith("data:")||(e.startsWith("http://")||e.startsWith("https://"))&&e.includes("?")),Ho=e=>{const t=Yc(e),n=t===null?"none":t.startsWith("data:")?"data":t.slice(0,512);return[e.source,e.filename,e.mimeType,String(e.size),n].join("|")},_p=e=>{const t=Yc(e);return!t||!Lp(t)?null:e.source==="vscode"&&e.vscodeSource==="file"?{key:Ho(e),source:"vscode-file",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}:{key:Ho(e),source:"file-url",filename:e.filename,mimeType:e.mimeType,size:e.size,reference:t}},Fp=(e,t)=>({text:e,attachmentKeys:t.map(Ho),restorableAttachments:t.map(_p).filter(n=>n!==null)}),jp=(e,t)=>e.length===t.length&&e.every((n,r)=>{const o=t[r];return o!==void 0&&n.key===o.key&&n.source===o.source&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.size===o.size&&n.reference===o.reference}),Up=(e,t)=>e!==void 0&&e.text===t.text&&e.attachmentKeys.length===t.attachmentKeys.length&&e.attachmentKeys.every((n,r)=>n===t.attachmentKeys[r])&&jp(e.restorableAttachments,t.restorableAttachments),Qi=(e,t,n,r)=>{const o=e?[...e.entries]:[];for(const s of t){const i=o.at(-1);Up(i,s)||o.push({text:s.text,attachmentKeys:[...s.attachmentKeys],restorableAttachments:s.restorableAttachments.map(a=>({...a})),submittedAt:qc()})}return{touchedAt:n,entries:Jc(o,r)}},Np=Tn(Sn()),Qc=Ze(e=>({...Np,applyEntryLimit:t=>{qr(t)&&e(n=>{const r=Sn();if(r.entryLimit===t)return{...n,...r};const o=Tn({entryLimit:t,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},applyScope:t=>{xs(t)&&e(n=>{const r=Sn();if(r.scope===t)return{...n,...r};const o=Tn({entryLimit:r.entryLimit,scope:t,globalBuckets:r.globalBuckets,sessionBuckets:r.sessionBuckets});return{...n,...o}})},appendSubmissions:(t,n)=>{n.length!==0&&e(r=>{const o=Sn(),s=qc(),i=Vc(t.runtimeKey),a=No(t.runtimeKey,t.directory,t.sessionId),c=Tn({entryLimit:o.entryLimit,scope:o.scope,globalBuckets:{...o.globalBuckets,[i]:Qi(o.globalBuckets[i],n,s,o.entryLimit)},sessionBuckets:{...o.sessionBuckets,[a]:Qi(o.sessionBuckets[a],n,s,o.entryLimit)}});return{...r,...c}})},clearSession:t=>{e(n=>{const r=Sn(),o=No(t.runtimeKey,t.directory,t.sessionId);if(!(o in r.sessionBuckets))return{...n,...r};const s={...r.sessionBuckets};delete s[o];const i=Tn({entryLimit:r.entryLimit,scope:r.scope,globalBuckets:r.globalBuckets,sessionBuckets:s});return{...n,...i}})}})),Ww=(e,t)=>t?e.scope==="session"?e.sessionBuckets[No(t.runtimeKey,t.directory,t.sessionId)]?.entries??To:e.globalBuckets[Vc(t.runtimeKey)]?.entries??To:To,Bp=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Hp=e=>{const t=e.terminalId.trim(),n=e.terminalLabel.trim(),r=e.text.replace(/\r\n?/g,`
|
|
3
|
-
`).replace(/^\n+|\n+$/g,"");if(!t||!n||!r)return null;const o=Math.max(1,Math.floor(e.startLine));return{terminalId:t,terminalLabel:n,startLine:o,endLine:Math.max(o,Math.floor(e.endLine)),text:r}},zp=(e,t)=>{const n=t.map(Hp).filter(s=>s!==null);if(n.length===0)return e;const o=["<terminal_context>",...n.flatMap((s,i)=>[`- ${s.terminalLabel} lines ${s.startLine}-${s.endLine}:`,...s.text.split(`
|
|
4
|
-
`).map((a,c)=>` ${s.startLine+c} | ${a}`),...i===n.length-1?[]:[""]]),"</terminal_context>"].join(`
|
|
5
|
-
`);return e.trim()?`${e.trim()}
|
|
6
|
-
|
|
7
|
-
${o}`:o},$w=e=>{const t=Bp.exec(e);if(!t)return{visibleText:e,contexts:[]};const n=[];let r=null;for(const o of(t[1]??"").split(`
|
|
8
|
-
`)){const s=/^- (.+) lines (\d+)-(\d+):$/.exec(o);if(s){r&&n.push(r),r={terminalLabel:s[1],startLine:Number(s[2]),endLine:Number(s[3]),text:""};continue}const i=/^\s{2}\d+ \| ?(.*)$/.exec(o);r&&i&&(r.text+=`${r.text?`
|
|
9
|
-
`:""}${i[1]}`)}return r&&n.push(r),{visibleText:e.slice(0,t.index).trimEnd(),contexts:n}},Ds="aiworkerContext",Os="opencodeComment";function Wp(e){switch(e.kind){case"code-comment":{const t=`lines ${e.startLine}-${e.endLine}`,n=e.source==="diff"&&e.side?` (${e.side})`:"";return`Comment on \`${e.fileLabel}\` ${t}${n}:
|
|
10
|
-
\`\`\`${e.language}
|
|
11
|
-
${e.code}
|
|
12
|
-
\`\`\`
|
|
13
|
-
|
|
14
|
-
${e.text}`}case"terminal":return zp("",[{terminalId:e.terminalId,terminalLabel:e.terminalLabel,startLine:e.startLine,endLine:e.endLine,text:e.output}]);case"browser-annotation":return e.text?`${e.prompt}
|
|
15
|
-
|
|
16
|
-
${e.text}`:e.prompt;case"pr-comment":return`Attached GitHub PR comment (${e.label}):
|
|
17
|
-
|
|
18
|
-
${e.body}${e.text?`
|
|
19
|
-
|
|
20
|
-
${e.text}`:""}`;case"file-quote":{const t=e.startLine!=null&&e.endLine!=null?` lines ${e.startLine}-${e.endLine}`:"",n=e.quote.split(`
|
|
21
|
-
`).map(r=>`> ${r}`).join(`
|
|
22
|
-
`);return`Comment on this fragment of \`${e.fileLabel}\`${t}:
|
|
23
|
-
${n}${e.text?`
|
|
24
|
-
|
|
25
|
-
${e.text}`:""}`}case"chat-quote":return`Comment on this fragment of an earlier message in this conversation:
|
|
26
|
-
${e.quote.split(`
|
|
27
|
-
`).map(n=>`> ${n}`).join(`
|
|
28
|
-
`)}${e.text?`
|
|
29
|
-
|
|
30
|
-
${e.text}`:""}`;case"pr-check":return`Attached failed GitHub PR check (${e.label}):
|
|
31
|
-
\`\`\`
|
|
32
|
-
${e.output}
|
|
33
|
-
\`\`\`${e.text?`
|
|
34
|
-
|
|
35
|
-
${e.text}`:""}`;case"github-issue":case"github-pr":case"linear-issue":return""}}function Gw(e,t){const n=t??Wp(e),r={[Ds]:e};return e.kind==="code-comment"&&(r[Os]={path:e.fileLabel,selection:{startLine:e.startLine,endLine:e.endLine,startChar:0,endChar:0},comment:e.text,preview:e.code,origin:e.source==="diff"?"review":"file"}),{text:n,synthetic:!0,metadata:r}}function Kw(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 Xc=Ur("kind",[P({kind:F("code-comment"),source:mt(["diff","file","plan"]),fileLabel:w(),startLine:C(),endLine:C(),side:mt(["original","modified"]).optional(),language:w(),code:w(),text:w()}),P({kind:F("terminal"),terminalId:w(),terminalLabel:w(),startLine:C(),endLine:C(),output:w()}),P({kind:F("browser-annotation"),pageUrl:w(),prompt:w(),text:w()}),P({kind:F("pr-comment"),label:w(),body:w(),text:w()}),P({kind:F("pr-check"),label:w(),output:w(),text:w()}),P({kind:F("file-quote"),fileLabel:w(),startLine:C().optional(),endLine:C().optional(),quote:w(),text:w()}),P({kind:F("chat-quote"),messageId:w().optional(),quote:w(),text:w()}),P({kind:F("github-issue"),number:C().int().positive(),title:w(),url:w()}),P({kind:F("github-pr"),number:C().int().positive(),title:w(),url:w()}),P({kind:F("linear-issue"),identifier:w().min(1),title:w(),url:w()})]),Zc=P({path:w(),selection:P({startLine:C().finite(),endLine:C().finite(),startChar:C().finite().optional(),endChar:C().finite().optional()}).optional(),comment:w(),preview:w().optional(),origin:mt(["file","review"]).optional()}),$p=P({[Ds]:Xc,[Os]:Zc.optional()});function Gp(e){if(e.type!=="text")return null;const t=Xc.safeParse(e.metadata?.[Ds]);if(t.success)return t.data;const n=Zc.safeParse(e.metadata?.[Os]);if(n.success){const r=n.data;return r.selection?{kind:"code-comment",source:r.origin==="review"?"diff":"file",fileLabel:r.path,startLine:r.selection.startLine,endLine:r.selection.endLine,language:"",code:r.preview??"",text:r.comment}:{kind:"file-quote",fileLabel:r.path,quote:r.preview??"",text:r.comment}}return null}function qw(e){return e.some(t=>Gp(t)!==null)}function Vw(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 Ls="queue",_s=e=>e==="steer"||e==="queue",Fs=(e,t)=>e==="immediate"?"steer":_s(e)?e:t===!1?"steer":t===!0?"queue":Ls,it=()=>!Be(),Xi=50,zo=(e,t,n=B())=>{const r=dn(t);return!n||!r||!e?null:{runtimeKey:n,directory:r,sessionId:e}},ve=e=>`${e.runtimeKey}
|
|
36
|
-
${e.directory}
|
|
37
|
-
${e.sessionId}`,Pt=e=>{const[t,n,...r]=e.split(`
|
|
38
|
-
`);return zo(r.join(`
|
|
39
|
-
`),n,t)},Kp=P({providerID:w().min(1),modelID:w().min(1),agent:w().optional(),variant:w().optional()}),qp=P({id:w(),filename:w(),mimeType:w(),size:C(),source:mt(["local","server","vscode"]),serverPath:w().optional(),dataUrl:w().optional()}),Vp=Ur("kind",[P({kind:F("context"),text:w(),metadata:$p,instructions:w().optional()}),P({kind:F("instruction"),text:w()}),P({kind:F("synthetic"),text:w()})]),js=P({id:w().min(1),createdAt:C(),content:w(),text:w(),agentMention:w().optional(),attachments:Xe(qp),context:Xe(Vp).optional(),sendConfig:Kp}),Us=P({sessionId:w().min(1),directory:w(),items:Xe(js),sendingId:w().nullable()}),Zi=P({revision:C(),sessions:Xe(Us)}),Mn=P({revision:C(),session:Us}),Jp=Mn.extend({item:js}),Yp=Mn.extend({items:Xe(js)}),Qp=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}},Xp=e=>{const t=e.dataUrl??"",n=t?Qp(t):null,r={id:e.id,file:new File(n?[n]:[],e.filename,{type:e.mimeType}),dataUrl:t,mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source};return e.serverPath&&(r.serverPath=e.serverPath),r},sr=e=>{const t={id:e.id,content:e.content,text:e.text,createdAt:e.createdAt,sendConfig:{...e.sendConfig}};return e.agentMention&&(t.agentMention=e.agentMention),e.attachments.length>0&&(t.attachments=e.attachments.map(Xp)),e.context&&(t.context=e.context),t},Zp=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},ea=(e,t)=>{const n={content:e.content,text:e.text??e.content,attachments:(e.attachments??[]).filter(r=>!!r.dataUrl).map(Zp),context:e.context??[],sendConfig:t};return e.agentMention&&(n.agentMention=e.agentMention),n},vt=async(e,t,n)=>{const r=await m(t,n);if(!r.ok){const s=new Error(`Message queue request failed (${r.status})`);throw s.status=r.status,s}const o=e.safeParse(await r.json());if(!o.success)throw new Error("Invalid message queue response");return o.data},rt=(e,t)=>t===void 0?{method:e}:{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},ot=e=>`/api/message-queue/sessions/${encodeURIComponent(e)}`,ir=new Set,lt=new Map;let ko=0;const ta=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(r=>({...r,text:r.text??r.content}))])),eh=(e,t)=>{const n=e??{},r=t<2?n.queuedMessages??{}:{};return{queuedMessages:t<2?{}:ta(n.queuedMessages??{}),quarantinedLegacyMessages:ta({...n.quarantinedLegacyMessages??{},...r}),followUpBehavior:Fs(n.followUpBehavior,n.queueModeEnabled??null)}},Fe=(e,t)=>{const{[t]:n,...r}=e;return r},ar=(e,t,n)=>{const r=(e.queuedMessages[t]??[]).filter(o=>o.id!==n);return r.length===0?{queuedMessages:Fe(e.queuedMessages,t)}:{queuedMessages:{...e.queuedMessages,[t]:r}}},th=(e,t,n,r)=>{let o=e.queuedMessages,s=e.sendingIds;for(const i of new Set([...Object.keys(o),...Object.keys(s)])){const a=Pt(i);a?.runtimeKey!==t||a.sessionId!==n||(lt.get(i)??-1)>r||(lt.set(i,r),o=Fe(o,i),s=Fe(s,i))}return{queuedMessages:o,sendingIds:s}},el=Ze()(an(Un((e,t)=>{const n=(s,i,a)=>{if(a!==B())return;const c=zo(s.sessionId,s.directory,a);if(!c){if(s.items.length>0)return;e(d=>th(d,a,s.sessionId,i));return}const l=ve(c);(lt.get(l)??-1)>i||(lt.set(l,i),e(d=>{const u=s.items.map(sr),f=u.length>0?{...d.queuedMessages,[l]:u}:Fe(d.queuedMessages,l),p=s.sendingId?{...d.sendingIds,[l]:[s.sendingId]}:Fe(d.sendingIds,l);return{queuedMessages:f,sendingIds:p}}))},r=async s=>{try{const i=await vt(Zi,"/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 vt(Mn,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:Ls,sendingIds:{},addToQueue:async(s,i)=>{const a=ve(s),c=`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,l={id:c,content:i.content,text:i.text??i.content,createdAt:Date.now(),sendConfig:i.sendConfig};if(i.agentMention&&(l.agentMention=i.agentMention),i.attachments&&i.attachments.length>0&&(l.attachments=i.attachments),i.context&&i.context.length>0&&(l.context=i.context),e(f=>{const p=f.queuedMessages[a]??[],h={...f.queuedMessages,[a]:[...p,l].slice(-20)},g=Object.keys(h);if(g.length>Xi){g.sort((y,b)=>(h[y]?.[0]?.createdAt??0)-(h[b]?.[0]?.createdAt??0));for(const y of g.slice(0,g.length-Xi))delete h[y]}return{queuedMessages:h}}),!it())return;if(!i.sendConfig)throw e(f=>ar(f,a,c)),new Error("A queued message needs a provider and model to be delivered later.");const d=Op(s.runtimeKey,s.directory,s.sessionId),u=Fp(i.content,i.attachments??[]);try{const f=await vt(Mn,`${ot(s.sessionId)}/items`,rt("POST",{directory:s.directory,item:ea(i,i.sendConfig)}));e(p=>ar(p,a,c)),n(f.session,f.revision,s.runtimeKey),d&&Qc.getState().appendSubmissions(d,[u])}catch(f){throw e(p=>ar(p,a,c)),f}},removeFromQueue:(s,i)=>{const a=ve(s);e(c=>ar(c,a,i)),it()&&o(s,`${ot(s.sessionId)}/items/${encodeURIComponent(i)}`,rt("DELETE"))},reorderQueue:(s,i,a)=>{if(i===a)return;const c=ve(s),l=t().queuedMessages[c];if(!l)return;const d=l.findIndex(h=>h.id===i),u=l.findIndex(h=>h.id===a);if(d===-1||u===-1)return;const f=l.slice(),[p]=f.splice(d,1);if(f.splice(u,0,p),e(h=>({queuedMessages:{...h.queuedMessages,[c]:f}})),it()){const h=f.map(g=>g.id);o(s,`${ot(s.sessionId)}/order`,rt("PUT",{itemIds:h}))}},popToInput:async(s,i)=>{const[a]=await t().takeForSend(s,i);return a??null},takeForSend:async(s,i)=>{const a=ve(s);if(it()){if(i){const p=await vt(Jp,`${ot(s.sessionId)}/items/${encodeURIComponent(i)}/take`,rt("POST"));return n(p.session,p.revision,s.runtimeKey),[sr(p.item)]}const f=await vt(Yp,`${ot(s.sessionId)}/take`,rt("POST"));return n(f.session,f.revision,s.runtimeKey),f.items.map(sr)}const c=t(),l=c.sendingIds[a]??[],d=(c.queuedMessages[a]??[]).filter(f=>(i?f.id===i:!0)&&!l.includes(f.id));if(d.length===0)return[];const u=new Set(d.map(f=>f.id));return e(f=>{const p=(f.queuedMessages[a]??[]).filter(h=>!u.has(h.id));return p.length===0?{queuedMessages:Fe(f.queuedMessages,a)}:{queuedMessages:{...f.queuedMessages,[a]:p}}}),d},clearQueue:s=>{const i=ve(s);e(a=>{const c=a.sendingIds[i]??[],l=(a.queuedMessages[i]??[]).filter(d=>c.includes(d.id));return l.length>0?{queuedMessages:{...a.queuedMessages,[i]:l}}:{queuedMessages:Fe(a.queuedMessages,i)}}),it()&&o(s,ot(s.sessionId),rt("DELETE"))},forgetQueue:s=>{const i=ve(s);lt.delete(i),e(a=>({queuedMessages:Fe(a.queuedMessages,i),sendingIds:Fe(a.sendingIds,i)}))},clearAllQueues:()=>{e({queuedMessages:{},sendingIds:{}})},markSending:(s,i)=>{const a=ve(s);e(c=>{const l=c.sendingIds[a]??[];return l.includes(i)?c:{sendingIds:{...c.sendingIds,[a]:[...l,i]}}})},clearSending:(s,i)=>{const a=ve(s);e(c=>{const l=c.sendingIds[a];if(!l||!l.includes(i))return c;const d=l.filter(u=>u!==i);return d.length===0?{sendingIds:Fe(c.sendingIds,a)}:{sendingIds:{...c.sendingIds,[a]:d}}})},getSendableQueue:s=>{const i=ve(s),a=t(),c=a.queuedMessages[i]??[],l=a.sendingIds[i];return!l||l.length===0?c:c.filter(d=>!l.includes(d.id))},setFollowUpBehavior:s=>{e({followUpBehavior:s}),je({followUpBehavior:s})},getQueueForTarget:s=>t().queuedMessages[ve(s)]??[],hydrate:async()=>{if(!it())return;const s=B(),i=++ko,a=()=>i===ko&&s===B(),c=Object.entries(t().queuedMessages).map(([d,u])=>({target:Pt(d),queue:u})).filter(d=>d.target!==null&&d.target.runtimeKey===s&&!ir.has(s));for(const{target:d,queue:u}of c)for(const f of u)if(f.sendConfig){try{await vt(Mn,`${ot(d.sessionId)}/items`,rt("POST",{directory:d.directory,item:ea(f,f.sendConfig)}))}catch(p){console.warn("[queue] failed to migrate a locally queued message to the server:",p)}if(!a())return}const l=await vt(Zi,"/api/message-queue");a()&&(ir.add(s),e(d=>{const u={},f={};for(const[p,h]of Object.entries(d.queuedMessages))Pt(p)?.runtimeKey!==s&&(u[p]=h);for(const[p,h]of Object.entries(d.sendingIds))Pt(p)?.runtimeKey!==s&&(f[p]=h);for(const p of l.sessions){const h=zo(p.sessionId,p.directory,s);if(!h)continue;const g=ve(h);if((lt.get(g)??-1)>l.revision){d.queuedMessages[g]&&(u[g]=d.queuedMessages[g]),d.sendingIds[g]&&(f[g]=d.sendingIds[g]);continue}lt.set(g,l.revision),p.items.length>0&&(u[g]=p.items.map(sr)),p.sendingId&&(f[g]=[p.sendingId])}return{queuedMessages:u,sendingIds:f}}))},applyServerSession:n,setServerHold:async(s,i)=>{if(!it())return;const a=await m(`${ot(s)}/hold`,rt("PUT",{held:i}));if(!a.ok)throw new Error(`Message queue hold request failed (${a.status})`)},resetForRuntimeSwitch:s=>{ko+=1,!(!s||!ir.has(s))&&e(i=>{const a={},c={};for(const[l,d]of Object.entries(i.queuedMessages))Pt(l)?.runtimeKey===s?lt.delete(l):a[l]=d;for(const[l,d]of Object.entries(i.sendingIds))Pt(l)?.runtimeKey!==s&&(c[l]=d);return{queuedMessages:a,sendingIds:c}})}}},{name:"message-queue-store",version:3,storage:As(),partialize:e=>({queuedMessages:Object.fromEntries(Object.entries(e.queuedMessages).filter(([t])=>{const n=Pt(t)?.runtimeKey;return!n||!ir.has(n)})),quarantinedLegacyMessages:e.quarantinedLegacyMessages,followUpBehavior:e.followUpBehavior}),migrate:eh}),{name:"message-queue-store"})),nh=P({properties:P({revision:C(),session:Us})}),Jw=(e,t)=>{if(!it())return;const n=nh.safeParse(e);if(!n.success)return;const{session:r,revision:o}=n.data.properties;el.getState().applyServerSession(r,o,t)},tl="directoryTreeShowHidden",Wo="directory-show-hidden-change",na=()=>{if(typeof window>"u")return!0;try{const e=Bn().getItem(tl);return e===null?!0:e==="true"}catch{return!0}},rh=()=>{typeof window>"u"||window.dispatchEvent(new Event(Wo))},oh=(e,t={})=>{if(!(typeof window>"u")){try{Bn().setItem(tl,e?"true":"false"),rh()}catch{}t.persist!==!1&&je({directoryShowHidden:e})}},Yw=()=>{const e=Aa.c(2),[t,n]=wr.useState(na);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(na())};return window.addEventListener("storage",s),window.addEventListener(Wo,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(Wo,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),wr.useEffect(r,o),t},nl="filesViewShowGitignored",$o="files-view-show-gitignored-change",ra=()=>{if(typeof window>"u")return!1;try{return Bn().getItem(nl)==="true"}catch{return!1}},sh=()=>{typeof window>"u"||window.dispatchEvent(new Event($o))},ih=(e,t={})=>{if(!(typeof window>"u")){try{Bn().setItem(nl,e?"true":"false"),sh()}catch{}t.persist!==!1&&je({filesViewShowGitignored:e})}},Qw=()=>{const e=Aa.c(2),[t,n]=wr.useState(ra);let r,o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const s=()=>{n(ra())};return window.addEventListener("storage",s),window.addEventListener($o,s),()=>{window.removeEventListener("storage",s),window.removeEventListener($o,s)}},o=[],e[0]=r,e[1]=o):(r=e[0],o=e[1]),wr.useEffect(r,o),t},ah=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},ch=e=>{if(!e||typeof e!="object")return null;const t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},lh=e=>{const t=Se.getState();typeof e.showReasoningTraces=="boolean"&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks=="boolean"&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},dh=async()=>{if(typeof window>"u")return null;const e=localStorage.getItem("appearance-preferences");if(!e)return null;try{const t=JSON.parse(e),n=ch(t);return ah(n)}catch(t){return console.warn("Failed to parse stored appearance preferences:",t),null}},rl=[{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"}],uh=new Map(rl.map(e=>[e.name,e])),Xw=e=>uh.get(e),Zw=rl.map(e=>({type:"command",name:e.name})),eb="terminal-box",tb="book-open",nb=e=>`${e.type}:${e.name}`,rb=(e,t)=>e.type===t.type&&e.name===t.name,ob=e=>{const t=e.replace(/^\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},ol=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},fh=["bash","zsh","sh","fish","pwsh","powershell","cmd","dash","ksh","nu"],Or=e=>e==="auto"||typeof e=="string"&&fh.includes(e),ph=[{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"}],hh="finder",sb=new Set(["finder","terminal"]),mh=e=>{if(typeof window>"u")return e;const t=window.__AIWORKER_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},ib=e=>{if(!e)return null;const t=ph.find(n=>n.id===e)??null;return t?mh(t):null},yh=(e,t)=>{const n=e??{};return t<2&&(n.projectSortOrder="manual"),t<3&&n.projectSortOrder==="recent"&&(n.projectSortOrder="manual"),t<4&&delete n.displayMode,n},Go=Ze()(Un(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:yh})),gh=e=>{if(!(typeof window>"u")&&!(typeof window.__AIWORKER_HOME__=="string"&&window.__AIWORKER_HOME__.length>0))try{window.__AIWORKER_HOME__=e}catch{}},oa="aiworker.settingsMirror.v2.index",wh="aiworker.settingsMirror.v2:",bh=5,sa=e=>`${wh}${encodeURIComponent(e)}`,Kt=(e,t)=>{t===null?localStorage.removeItem(e):localStorage.setItem(e,t)},Sh=(e,t)=>{const n={themeId:e.themeId,themeVariant:e.themeVariant,lightThemeId:e.lightThemeId,darkThemeId:e.darkThemeId,useSystemTheme:e.useSystemTheme,lastDirectory:e.lastDirectory,homeDirectory:e.homeDirectory,projects:e.projects,activeProjectId:e.activeProjectId,sidebarProjectDisplayMode:e.sidebarProjectDisplayMode,sidebarSessionGroupingMode:e.sidebarSessionGroupingMode,sidebarProjectSortOrder:e.sidebarProjectSortOrder,sidebarShowRecentSection:e.sidebarShowRecentSection,pinnedDirectories:e.pinnedDirectories,gitmojiEnabled:e.gitmojiEnabled,directoryShowHidden:e.directoryShowHidden,filesViewShowGitignored:e.filesViewShowGitignored,openInAppId:e.openInAppId,pwaAppName:e.pwaAppName,mobileKeyboardMode:e.mobileKeyboardMode,openCodeUpdateToastDismissedVersion:e.openCodeUpdateToastDismissedVersion,inputHistoryScope:e.inputHistoryScope,inputHistoryLimit:e.inputHistoryLimit,dictationEnabled:e.dictationEnabled,sttProvider:e.sttProvider,sttServerUrl:e.sttServerUrl,sttModel:e.sttModel,sttLocalModel:e.sttLocalModel,sttLanguage:e.sttLanguage};localStorage.setItem(sa(t),JSON.stringify(n));let r=[];try{const s=JSON.parse(localStorage.getItem(oa)??"[]");Array.isArray(s)&&(r=s.filter(i=>typeof i=="string"))}catch{r=[]}const o=[t,...r.filter(s=>s!==t)].slice(0,bh);for(const s of r)o.includes(s)||localStorage.removeItem(sa(s));localStorage.setItem(oa,JSON.stringify(o))},Th=e=>{if(!(typeof window>"u")){if(Sh(e,B()),Kt("lastDirectory",e.lastDirectory||null),e.homeDirectory?(localStorage.setItem("homeDirectory",e.homeDirectory),gh(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"),Kt("openInAppId",typeof e.openInAppId=="string"&&e.openInAppId.length>0?e.openInAppId:null),typeof e.pwaAppName=="string"){const t=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);t.length>0?localStorage.setItem("aiworker.pwaName",t):localStorage.removeItem("aiworker.pwaName")}else localStorage.removeItem("aiworker.pwaName");if(_c(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"),Kt("sttServerUrl",typeof e.sttServerUrl=="string"?e.sttServerUrl:null),Kt("sttModel",typeof e.sttModel=="string"?e.sttModel:null),Kt("sttLocalModel",typeof e.sttLocalModel=="string"?e.sttLocalModel:null),Kt("sttLanguage",typeof e.sttLanguage=="string"?e.sttLanguage:null)}},Ko=(e,t,n=t)=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("aiworker:settings-synced",{detail:{settings:e,bootstrap:t,adoptTheme:n}}))};let qo="idle",cr=null;const Vo=new Set,ab=()=>qo,cb=e=>(Vo.add(e),()=>Vo.delete(e)),lb=e=>{Ke(e)},Ke=e=>{cr&&(clearTimeout(cr),cr=null);const t=e==="saved"?"idle":e;t!==qo&&(qo=t,Vo.forEach(n=>n())),t==="error"&&(cr=setTimeout(()=>Ke("saved"),6e3)),!(typeof window>"u")&&window.dispatchEvent(new CustomEvent("aiworker:settings-save-state",{detail:e}))},kh=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},vh=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},Eh=(e,t)=>{const n=Object.entries(e),r=Object.entries(t);return n.length!==r.length?!1:n.every(([o,s])=>t[o]===s)},vo=(e,t)=>e.length===t.length&&e.every((n,r)=>n.providerID===t[r]?.providerID&&n.modelID===t[r]?.modelID),Jo=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Yo=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.length>0)))},Ah=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=Yo(r);o&&o.length>0&&(t[n]=o.slice(0,5))}return Object.keys(t).length>0?t:void 0},Ph=(e,t)=>{const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>Array.isArray(t[r])&&Jo(e[r],t[r]))},Ih=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Mh=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&Ih.test(t)?t.toLowerCase():null},Rh=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=Mf(a);if(!c||n.has(c)||r.has(a))continue;n.add(c),r.add(a);const l={id:c,path:a};if(typeof s.label=="string"&&s.label.trim().length>0&&(l.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(l.icon=s.icon.trim()),s.iconImage===null)l.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,u=typeof d.mime=="string"?d.mime.trim():"",f=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,p=d.source==="custom"||d.source==="auto"?d.source:null;u&&f>0&&p&&(l.iconImage={mime:u,updatedAt:f,source:p})}if(typeof s.color=="string"&&s.color.trim().length>0&&(l.color=s.color.trim()),s.iconBackground===null)l.iconBackground=null;else{const d=Mh(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},xh=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},Ch=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},Eo=(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},sl=()=>{const e=Se.persist;if(e&&typeof e=="object")return e},il=()=>Gr()?.settings??null,Dh=e=>{const t=Se.getInitialState();return{openInAppId:hh,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:Ls,showDeletionDialog:t.showDeletionDialog,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,inputSpellcheckEnabled:t.inputSpellcheckEnabled,enterToSend:t.enterToSend,enterToSendConfigured:t.enterToSendConfigured,showOpenCodeUpdateNotifications:t.showOpenCodeUpdateNotifications,agentControlToolEnabled:t.agentControlToolEnabled,agentWebToolEnabled:t.agentWebToolEnabled,agentMemoryToolEnabled:t.agentMemoryToolEnabled,showToolFileIcons:t.showToolFileIcons,codeBlockLineWrap:t.codeBlockLineWrap,showTurnChangedFiles:t.showTurnChangedFiles,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,timeFormatPreference:t.timeFormatPreference,weekStartPreference:t.weekStartPreference,desktopWindowControlsPosition:t.desktopWindowControlsPosition,desktopWindowControlsStyle:t.desktopWindowControlsStyle,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,collapsibleUserMessages:t.collapsibleUserMessages,messageStreamTransport:"auto",inputHistoryScope:Ms,inputHistoryLimit:Rs,stickyUserHeader:t.stickyUserHeader,promptNavigatorEnabled:t.promptNavigatorEnabled,wideChatLayoutEnabled:t.wideChatLayoutEnabled,showSplitAssistantMessageActions:t.showSplitAssistantMessageActions,draftStartersVisible:t.draftStartersVisible,reportUsage:t.reportUsage,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,terminalShell:t.terminalShell,terminalLoginShells:t.terminalLoginShells,editorFontSize:t.editorFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,inputBarOffset:t.inputBarOffset,shortcutOverrides:t.shortcutOverrides,mobileKeyboardMode:"resize-content",favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,gitChangesViewMode:t.gitChangesViewMode,toolJsonViewMode:t.toolJsonViewMode,directoryShowHidden:!0,filesViewShowGitignored:!1,dictationEnabled:!0,sttProvider:"local",sttServerUrl:"http://localhost:8001/v1",sttModel:"deepdml/faster-whisper-large-v3-turbo-ct2",sttLocalModel:"parakeet-tdt-0.6b-v2-int8",sttLanguage:"",...e}},Qo=e=>{const t=Se.getState(),n=typeof window<"u"?window.__zustand_config_store__?.getState?.()??null:null,r=typeof window<"u"?window.__zustand_config_store__??null:null,o=el.getState(),s=Qc.getState();if(typeof e.workStatusPanelEnabled=="boolean"&&e.workStatusPanelEnabled!==t.workStatusPanelEnabled&&t.setWorkStatusPanelEnabled(e.workStatusPanelEnabled),Array.isArray(e.workStatusHiddenSections)){const c=Ic(e.workStatusHiddenSections);c.join("\0")!==t.workStatusHiddenSections.join("\0")&&t.setWorkStatusHiddenSections(c)}if(typeof e.showReasoningTraces=="boolean"&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.streamingAutoFollowEnabled=="boolean"&&e.streamingAutoFollowEnabled!==t.streamingAutoFollowEnabled&&t.setStreamingAutoFollowEnabled(e.streamingAutoFollowEnabled),typeof e.sessionRecapEnabled=="boolean"&&e.sessionRecapEnabled!==t.sessionRecapEnabled&&t.setSessionRecapEnabled(e.sessionRecapEnabled),typeof e.sessionSuggestionEnabled=="boolean"&&e.sessionSuggestionEnabled!==t.sessionSuggestionEnabled&&t.setSessionSuggestionEnabled(e.sessionSuggestionEnabled),typeof e.sessionGoalEnabled=="boolean"&&e.sessionGoalEnabled!==t.sessionGoalEnabled&&t.setSessionGoalEnabled(e.sessionGoalEnabled),typeof e.sessionGoalDefaultBudgetEnabled=="boolean"&&e.sessionGoalDefaultBudgetEnabled!==t.sessionGoalDefaultBudgetEnabled&&t.setSessionGoalDefaultBudgetEnabled(e.sessionGoalDefaultBudgetEnabled),typeof e.sessionGoalDefaultBudget=="number"&&Number.isFinite(e.sessionGoalDefaultBudget)&&e.sessionGoalDefaultBudget!==t.sessionGoalDefaultBudget&&t.setSessionGoalDefaultBudget(e.sessionGoalDefaultBudget),typeof e.collapsibleThinkingBlocks=="boolean"&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled=="boolean"&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoSaveEnabled=="boolean"&&e.autoSaveEnabled!==t.autoSaveEnabled&&t.setAutoSaveEnabled(e.autoSaveEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)){const c=Math.max(1,Math.min(365,e.autoDeleteAfterDays));c!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(c)}(e.sessionRetentionAction==="archive"||e.sessionRetentionAction==="delete")&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let i=null;if(_s(e.followUpBehavior)?i=e.followUpBehavior:typeof e.queueModeEnabled=="boolean"&&(i=Fs(void 0,e.queueModeEnabled)),i&&i!==o.followUpBehavior&&o.setFollowUpBehavior(i),typeof e.showDeletionDialog=="boolean"&&e.showDeletionDialog!==t.showDeletionDialog&&t.setShowDeletionDialog(e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&e.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&t.setNativeNotificationsEnabled(e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&e.notificationMode!==t.notificationMode&&t.setNotificationMode(e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&e.notifyOnSubtasks!==t.notifyOnSubtasks&&t.setNotifyOnSubtasks(e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&e.notifyOnCompletion!==t.notifyOnCompletion&&t.setNotifyOnCompletion(e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&e.notifyOnError!==t.notifyOnError&&t.setNotifyOnError(e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&e.notifyOnQuestion!==t.notifyOnQuestion&&t.setNotifyOnQuestion(e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"&&t.setNotificationTemplates(e.notificationTemplates),typeof e.summarizeLastMessage=="boolean"&&e.summarizeLastMessage!==t.summarizeLastMessage&&t.setSummarizeLastMessage(e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&t.setSummaryThreshold(e.summaryThreshold),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&t.setSummaryLength(e.summaryLength),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&t.setMaxLastMessageLength(e.maxLastMessageLength),typeof e.inputSpellcheckEnabled=="boolean"&&e.inputSpellcheckEnabled!==t.inputSpellcheckEnabled&&t.setInputSpellcheckEnabled(e.inputSpellcheckEnabled),(e.enterToSend===!0||e.enterToSend===!1)&&e.enterToSend!==t.enterToSend&&t.setEnterToSend(e.enterToSend),(e.enterToSendConfigured===!0||e.enterToSendConfigured===!1)&&e.enterToSendConfigured!==t.enterToSendConfigured&&t.setEnterToSendConfigured(e.enterToSendConfigured),typeof e.showOpenCodeUpdateNotifications=="boolean"&&e.showOpenCodeUpdateNotifications!==t.showOpenCodeUpdateNotifications&&t.setShowOpenCodeUpdateNotifications(e.showOpenCodeUpdateNotifications),typeof e.agentControlToolEnabled=="boolean"&&e.agentControlToolEnabled!==t.agentControlToolEnabled&&t.setAgentControlToolEnabled(e.agentControlToolEnabled),typeof e.agentWebToolEnabled=="boolean"&&e.agentWebToolEnabled!==t.agentWebToolEnabled&&t.setAgentWebToolEnabled(e.agentWebToolEnabled),typeof e.agentMemoryToolEnabled=="boolean"&&e.agentMemoryToolEnabled!==t.agentMemoryToolEnabled&&t.setAgentMemoryToolEnabled(e.agentMemoryToolEnabled),typeof e.agentMemoryFeatureAvailable=="boolean"&&e.agentMemoryFeatureAvailable!==t.agentMemoryFeatureAvailable&&t.setAgentMemoryFeatureAvailable(e.agentMemoryFeatureAvailable),typeof e.showToolFileIcons=="boolean"&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap=="boolean"&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles=="boolean"&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools=="boolean"&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&e.showExpandedEditTools!==t.showExpandedEditTools&&t.setShowExpandedEditTools(e.showExpandedEditTools),typeof e.timeFormatPreference=="string"&&(e.timeFormatPreference==="auto"||e.timeFormatPreference==="12h"||e.timeFormatPreference==="24h")&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference=="string"&&(e.weekStartPreference==="auto"||e.weekStartPreference==="sunday"||e.weekStartPreference==="monday")&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.desktopWindowControlsPosition=="string"){const c=e.desktopWindowControlsPosition==="left"?"left":e.desktopWindowControlsPosition==="right"||e.desktopWindowControlsPosition==="auto"?"right":null;c&&c!==t.desktopWindowControlsPosition&&t.setDesktopWindowControlsPosition(c)}if(typeof e.desktopWindowControlsStyle=="string"){const c=e.desktopWindowControlsStyle==="traffic-lights"?"traffic-lights":e.desktopWindowControlsStyle==="classic"?"classic":null;c&&c!==t.desktopWindowControlsStyle&&t.setDesktopWindowControlsStyle(c)}if(typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages=="boolean"&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport=="string"&&(e.messageStreamTransport==="auto"||e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse")&&n&&e.messageStreamTransport!==n.settingsMessageStreamTransport&&n.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.inputHistoryScope=="string"&&xs(e.inputHistoryScope)&&e.inputHistoryScope!==s.scope&&s.applyScope(e.inputHistoryScope),qr(e.inputHistoryLimit)&&e.inputHistoryLimit!==s.entryLimit&&s.applyEntryLimit(e.inputHistoryLimit),typeof e.stickyUserHeader=="boolean"&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.promptNavigatorEnabled=="boolean"&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.wideChatLayoutEnabled=="boolean"&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions=="boolean"&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.reportUsage=="boolean"&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){let c=ol(e.draftStarters);if(e.draftStartersCraftGoalAdded!==!0&&!c.some(l=>l.type==="command"&&l.name==="craft-goal")){const l=c.findIndex(u=>u.type==="command"&&u.name==="plan-feature"),d=l>=0?l+1:c.length;c=[...c.slice(0,d),{type:"command",name:"craft-goal"},...c.slice(d)]}if(e.draftStartersScheduleTaskAdded!==!0&&!c.some(l=>l.type==="command"&&l.name==="schedule-task")){const l=c.findIndex(u=>u.type==="command"&&u.name==="craft-goal"),d=l>=0?l+1:c.length;c=[...c.slice(0,d),{type:"command",name:"schedule-task"},...c.slice(d)]}JSON.stringify(t.globalDraftStarters)!==JSON.stringify(c)&&t.setGlobalDraftStarters(c),(e.draftStartersCraftGoalAdded!==!0||e.draftStartersScheduleTaskAdded!==!0)&&(e.draftStarters=c,e.draftStartersCraftGoalAdded=!0,e.draftStartersScheduleTaskAdded=!0)}else e.draftStartersCraftGoalAdded!==!0&&(e.draftStartersCraftGoalAdded=!0),e.draftStartersScheduleTaskAdded!==!0&&(e.draftStartersScheduleTaskAdded=!0);if(typeof e.draftStartersVisible=="boolean"&&e.draftStartersVisible!==t.draftStartersVisible&&t.setDraftStartersVisible(e.draftStartersVisible),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),Or(e.terminalShell)&&e.terminalShell!==t.terminalShell&&t.setTerminalShell(e.terminalShell),Array.isArray(e.terminalLoginShells)&&(e.terminalLoginShells.length!==t.terminalLoginShells.length||e.terminalLoginShells.some((c,l)=>c!==t.terminalLoginShells[l]))&&t.setTerminalLoginShells(e.terminalLoginShells),typeof e.editorFontSize=="number"&&Number.isFinite(e.editorFontSize)&&e.editorFontSize!==t.editorFontSize&&t.setEditorFontSize(e.editorFontSize),Oc(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),Lc(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&&!Eh(e.shortcutOverrides,t.shortcutOverrides)&&Se.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode=="string"){const c=Kr(e.mobileKeyboardMode,t.mobileKeyboardMode);c!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(c)}if(r&&n){const c={};typeof e.dictationEnabled=="boolean"&&e.dictationEnabled!==n.dictationEnabled&&(c.dictationEnabled=e.dictationEnabled),(e.sttProvider==="local"||e.sttProvider==="openai-compatible")&&e.sttProvider!==n.sttProvider&&(c.sttProvider=e.sttProvider),typeof e.sttServerUrl=="string"&&e.sttServerUrl!==n.sttServerUrl&&(c.sttServerUrl=e.sttServerUrl),typeof e.sttModel=="string"&&e.sttModel!==n.sttModel&&(c.sttModel=e.sttModel),typeof e.sttLocalModel=="string"&&e.sttLocalModel!==n.sttLocalModel&&(c.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage=="string"&&e.sttLanguage!==n.sttLanguage&&(c.sttLanguage=e.sttLanguage),Object.keys(c).length>0&&r.setState(c)}if(Array.isArray(e.favoriteModels)){const c=t.favoriteModels,l=e.favoriteModels;vo(c,l)||Se.setState({favoriteModels:l})}if(Array.isArray(e.hiddenModels)){const c=t.hiddenModels,l=e.hiddenModels;vo(c,l)||Se.setState({hiddenModels:l})}if(Array.isArray(e.collapsedModelProviders)){const c=t.collapsedModelProviders,l=e.collapsedModelProviders;Jo(c,l)||Se.setState({collapsedModelProviders:l})}if(Array.isArray(e.recentModels)){const c=t.recentModels,l=e.recentModels;vo(c,l)||Se.setState({recentModels:l})}if(Array.isArray(e.recentAgents)){const c=t.recentAgents,l=e.recentAgents;Jo(c,l)||Se.setState({recentAgents:l})}if(e.recentEfforts&&typeof e.recentEfforts=="object"){const c=t.recentEfforts,l=e.recentEfforts;Ph(c,l)||Se.setState({recentEfforts:l})}typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&e.diffLayoutPreference!==t.diffLayoutPreference&&t.setDiffLayoutPreference(e.diffLayoutPreference),typeof e.gitChangesViewMode=="string"&&(e.gitChangesViewMode==="flat"||e.gitChangesViewMode==="tree")&&e.gitChangesViewMode!==t.gitChangesViewMode&&t.setGitChangesViewMode(e.gitChangesViewMode),typeof e.toolJsonViewMode=="string"&&(e.toolJsonViewMode==="summary"||e.toolJsonViewMode==="formatted"||e.toolJsonViewMode==="raw")&&e.toolJsonViewMode!==t.toolJsonViewMode&&t.setToolJsonViewMode(e.toolJsonViewMode),typeof e.directoryShowHidden=="boolean"&&oh(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored=="boolean"&&ih(e.filesViewShowGitignored,{persist:!1});const a={};(e.sidebarProjectDisplayMode==="all"||e.sidebarProjectDisplayMode==="single")&&(a.projectDisplayMode=e.sidebarProjectDisplayMode),(e.sidebarSessionGroupingMode==="by-worktree"||e.sidebarSessionGroupingMode==="flat")&&(a.sessionGroupingMode=e.sidebarSessionGroupingMode),(e.sidebarProjectSortOrder==="manual"||e.sidebarProjectSortOrder==="a-z"||e.sidebarProjectSortOrder==="z-a"||e.sidebarProjectSortOrder==="date-added"||e.sidebarProjectSortOrder==="recent")&&(a.projectSortOrder=e.sidebarProjectSortOrder),typeof e.sidebarShowRecentSection=="boolean"&&(a.showRecentSection=e.sidebarShowRecentSection),Object.keys(a).length>0&&Go.setState(a)},Xo=e=>{if(!e||typeof e!="object")return null;const t=e,n={};if(typeof t.themeId=="string"&&t.themeId.length>0&&(n.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(n.useSystemTheme=t.useSystemTheme),typeof t.themeVariant=="string"&&(t.themeVariant==="light"||t.themeVariant==="dark")&&(n.themeVariant=t.themeVariant),typeof t.lightThemeId=="string"&&t.lightThemeId.length>0&&(n.lightThemeId=t.lightThemeId),typeof t.darkThemeId=="string"&&t.darkThemeId.length>0&&(n.darkThemeId=t.darkThemeId),typeof t.lastDirectory=="string"&&t.lastDirectory.length>0&&(n.lastDirectory=t.lastDirectory),typeof t.homeDirectory=="string"&&t.homeDirectory.length>0&&(n.homeDirectory=t.homeDirectory),typeof t.opencodeBinary=="string"){const h=t.opencodeBinary.trim();n.opencodeBinary=h.length>0?h:void 0}typeof t.desktopLanAccessEnabled=="boolean"&&(n.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled=="boolean"&&(n.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled=="boolean"&&(n.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled),typeof t.desktopMacMenuBarEnabled=="boolean"&&(n.desktopMacMenuBarEnabled=t.desktopMacMenuBarEnabled);const r=Rh(t.projects);if(r&&(n.projects=r),typeof t.activeProjectId=="string"&&t.activeProjectId.length>0&&(n.activeProjectId=t.activeProjectId),(t.sidebarProjectDisplayMode==="all"||t.sidebarProjectDisplayMode==="single")&&(n.sidebarProjectDisplayMode=t.sidebarProjectDisplayMode),(t.sidebarSessionGroupingMode==="by-worktree"||t.sidebarSessionGroupingMode==="flat")&&(n.sidebarSessionGroupingMode=t.sidebarSessionGroupingMode),(t.sidebarProjectSortOrder==="manual"||t.sidebarProjectSortOrder==="a-z"||t.sidebarProjectSortOrder==="z-a"||t.sidebarProjectSortOrder==="date-added"||t.sidebarProjectSortOrder==="recent")&&(n.sidebarProjectSortOrder=t.sidebarProjectSortOrder),typeof t.sidebarShowRecentSection=="boolean"&&(n.sidebarShowRecentSection=t.sidebarShowRecentSection),Array.isArray(t.securityScopedBookmarks)&&(n.securityScopedBookmarks=t.securityScopedBookmarks.filter(h=>typeof h=="string"&&h.length>0)),Array.isArray(t.pinnedDirectories)&&(n.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(h=>typeof h=="string"&&h.length>0)))),Array.isArray(t.draftStarters)&&(n.draftStarters=ol(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=Ic(t.workStatusHiddenSections)),typeof t.showReasoningTraces=="boolean"&&(n.showReasoningTraces=t.showReasoningTraces),typeof t.streamingAutoFollowEnabled=="boolean"&&(n.streamingAutoFollowEnabled=t.streamingAutoFollowEnabled),typeof t.inputHistoryScope=="string"&&xs(t.inputHistoryScope)&&(n.inputHistoryScope=t.inputHistoryScope),typeof t.inputHistoryLimit=="number"&&qr(t.inputHistoryLimit)&&(n.inputHistoryLimit=t.inputHistoryLimit),typeof t.sessionRecapEnabled=="boolean"&&(n.sessionRecapEnabled=t.sessionRecapEnabled),typeof t.sessionSuggestionEnabled=="boolean"&&(n.sessionSuggestionEnabled=t.sessionSuggestionEnabled),typeof t.sessionGoalEnabled=="boolean"&&(n.sessionGoalEnabled=t.sessionGoalEnabled),typeof t.sessionGoalDefaultBudgetEnabled=="boolean"&&(n.sessionGoalDefaultBudgetEnabled=t.sessionGoalDefaultBudgetEnabled),typeof t.sessionGoalDefaultBudget=="number"&&Number.isFinite(t.sessionGoalDefaultBudget)&&t.sessionGoalDefaultBudget>0&&(n.sessionGoalDefaultBudget=Math.floor(t.sessionGoalDefaultBudget)),typeof t.collapsibleThinkingBlocks=="boolean"&&(n.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled=="boolean"&&(n.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoSaveEnabled=="boolean"&&(n.autoSaveEnabled=t.autoSaveEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)&&(n.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction==="archive"||t.sessionRetentionAction==="delete")&&(n.sessionRetentionAction=t.sessionRetentionAction),typeof t.tunnelProvider=="string"){const h=t.tunnelProvider.trim().toLowerCase();h.length>0&&(n.tunnelProvider=h)}if(typeof t.tunnelMode=="string"){const h=t.tunnelMode.trim().toLowerCase();(h==="quick"||h==="managed-remote"||h==="managed-local")&&(n.tunnelMode=h)}if(t.tunnelBootstrapTtlMs===null?n.tunnelBootstrapTtlMs=null:typeof t.tunnelBootstrapTtlMs=="number"&&Number.isFinite(t.tunnelBootstrapTtlMs)&&(n.tunnelBootstrapTtlMs=t.tunnelBootstrapTtlMs),typeof t.tunnelSessionTtlMs=="number"&&Number.isFinite(t.tunnelSessionTtlMs)&&(n.tunnelSessionTtlMs=t.tunnelSessionTtlMs),t.managedLocalTunnelConfigPath===null)n.managedLocalTunnelConfigPath=null;else if(typeof t.managedLocalTunnelConfigPath=="string"){const h=t.managedLocalTunnelConfigPath.trim();n.managedLocalTunnelConfigPath=h.length>0?h:null}typeof t.managedRemoteTunnelHostname=="string"&&(n.managedRemoteTunnelHostname=t.managedRemoteTunnelHostname.trim()),t.managedRemoteTunnelToken===null?n.managedRemoteTunnelToken=null:typeof t.managedRemoteTunnelToken=="string"&&(n.managedRemoteTunnelToken=t.managedRemoteTunnelToken.trim());const o=xh(t.managedRemoteTunnelPresets);if(o&&(n.managedRemoteTunnelPresets=o),typeof t.managedRemoteTunnelSelectedPresetId=="string"){const h=t.managedRemoteTunnelSelectedPresetId.trim();n.managedRemoteTunnelSelectedPresetId=h.length>0?h:void 0}const s=Ch(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),_s(t.followUpBehavior)?n.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled=="boolean"&&(n.followUpBehavior=Fs(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog=="boolean"&&(n.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&(n.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&(n.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&(n.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&(n.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&(n.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&(n.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"){const h=t.notificationTemplates,g=M=>{const W=h[M];if(!W||typeof W!="object")return;const A=W,fe=typeof A.title=="string"?A.title:"",Q=typeof A.message=="string"?A.message:"";return{title:fe,message:Q}},y=g("completion"),b=g("error"),S=g("question"),E=g("subtask");(y||b||S||E)&&(n.notificationTemplates={completion:y??{title:"Task Complete",message:"Your task has finished."},error:b??{title:"Error Occurred",message:"An error occurred while processing your task."},question:S??{title:"Input Needed",message:"Please provide input to continue."},subtask:E??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof t.summarizeLastMessage=="boolean"&&(n.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&(n.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&(n.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&(n.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),(t.usageDisplayMode==="usage"||t.usageDisplayMode==="remaining")&&(n.usageDisplayMode=t.usageDisplayMode),Array.isArray(t.usageDropdownProviders)&&(n.usageDropdownProviders=t.usageDropdownProviders.filter(h=>typeof h=="string"&&h.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels=="object"){const h={};for(const[g,y]of Object.entries(t.usageSelectedModels))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageSelectedModels=h)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies=="object"){const h={};for(const[g,y]of Object.entries(t.usageCollapsedFamilies))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageCollapsedFamilies=h)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies=="object"){const h={};for(const[g,y]of Object.entries(t.usageExpandedFamilies))Array.isArray(y)&&(h[g]=y.filter(b=>typeof b=="string"));Object.keys(h).length>0&&(n.usageExpandedFamilies=h)}if(t.usageModelGroups&&typeof t.usageModelGroups=="object"){const h={};for(const[g,y]of Object.entries(t.usageModelGroups))if(y&&typeof y=="object"){const b=y,S={};Array.isArray(b.customGroups)&&(S.customGroups=b.customGroups.filter(E=>E&&typeof E=="object").map(E=>({id:String(E.id??""),label:String(E.label??""),models:Array.isArray(E.models)?E.models.filter(M=>typeof M=="string"):[],order:typeof E.order=="number"?E.order:0}))),b.modelAssignments&&typeof b.modelAssignments=="object"&&(S.modelAssignments=Object.fromEntries(Object.entries(b.modelAssignments).filter(([,E])=>typeof E=="string").map(([E,M])=>[E,String(M)]))),b.renamedGroups&&typeof b.renamedGroups=="object"&&(S.renamedGroups=Object.fromEntries(Object.entries(b.renamedGroups).filter(([,E])=>typeof E=="string").map(([E,M])=>[E,String(M)]))),Object.keys(S).length>0&&(h[g]=S)}Object.keys(h).length>0&&(n.usageModelGroups=h)}typeof t.inputSpellcheckEnabled=="boolean"&&(n.inputSpellcheckEnabled=t.inputSpellcheckEnabled),(t.enterToSend===!0||t.enterToSend===!1)&&(n.enterToSend=t.enterToSend),(t.enterToSendConfigured===!0||t.enterToSendConfigured===!1)&&(n.enterToSendConfigured=t.enterToSendConfigured),typeof t.showOpenCodeUpdateNotifications=="boolean"&&(n.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.agentControlToolEnabled=="boolean"&&(n.agentControlToolEnabled=t.agentControlToolEnabled),typeof t.agentWebToolEnabled=="boolean"&&(n.agentWebToolEnabled=t.agentWebToolEnabled),typeof t.agentMemoryToolEnabled=="boolean"&&(n.agentMemoryToolEnabled=t.agentMemoryToolEnabled),typeof t.openCodeUpdateToastDismissedVersion=="string"&&(n.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons=="boolean"&&(n.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap=="boolean"&&(n.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles=="boolean"&&(n.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools=="boolean"&&(n.showExpandedBashTools=t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&(n.showExpandedEditTools=t.showExpandedEditTools),typeof t.timeFormatPreference=="string"&&(t.timeFormatPreference==="auto"||t.timeFormatPreference==="12h"||t.timeFormatPreference==="24h")&&(n.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference=="string"&&(t.weekStartPreference==="auto"||t.weekStartPreference==="sunday"||t.weekStartPreference==="monday")&&(n.weekStartPreference=t.weekStartPreference),typeof t.desktopWindowControlsPosition=="string"&&(t.desktopWindowControlsPosition==="left"?n.desktopWindowControlsPosition="left":(t.desktopWindowControlsPosition==="right"||t.desktopWindowControlsPosition==="auto")&&(n.desktopWindowControlsPosition="right")),typeof t.desktopWindowControlsStyle=="string"&&(t.desktopWindowControlsStyle==="classic"||t.desktopWindowControlsStyle==="traffic-lights")&&(n.desktopWindowControlsStyle=t.desktopWindowControlsStyle),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&(n.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport=="string"&&(t.messageStreamTransport==="auto"||t.messageStreamTransport==="ws"||t.messageStreamTransport==="sse")&&(n.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&(n.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&(n.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&(n.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages=="boolean"&&(n.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader=="boolean"&&(n.stickyUserHeader=t.stickyUserHeader),typeof t.promptNavigatorEnabled=="boolean"&&(n.promptNavigatorEnabled=t.promptNavigatorEnabled),typeof t.wideChatLayoutEnabled=="boolean"&&(n.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions=="boolean"&&(n.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&(n.fontSize=t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&(n.terminalFontSize=t.terminalFontSize),Or(t.terminalShell)&&(n.terminalShell=t.terminalShell),Array.isArray(t.terminalLoginShells)&&(n.terminalLoginShells=[...new Set(t.terminalLoginShells.filter(Or))]),typeof t.editorFontSize=="number"&&Number.isFinite(t.editorFontSize)&&(n.editorFontSize=t.editorFontSize),Oc(t.uiFont)&&(n.uiFont=t.uiFont),Lc(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=vh(t.shortcutOverrides);i&&(n.shortcutOverrides=i),typeof t.mobileKeyboardMode=="string"&&(t.mobileKeyboardMode==="native"||t.mobileKeyboardMode==="resize-content")&&(n.mobileKeyboardMode=t.mobileKeyboardMode);const a=Eo(t.favoriteModels,64);a&&(n.favoriteModels=a);const c=Eo(t.hiddenModels,1024);c&&(n.hiddenModels=c);const l=Yo(t.collapsedModelProviders);l&&(n.collapsedModelProviders=l);const d=Eo(t.recentModels,16);d&&(n.recentModels=d);const u=Yo(t.recentAgents);u&&(n.recentAgents=u);const f=Ah(t.recentEfforts);if(f&&(n.recentEfforts=f),typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&(n.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode=="string"&&(t.gitChangesViewMode==="flat"||t.gitChangesViewMode==="tree")&&(n.gitChangesViewMode=t.gitChangesViewMode),typeof t.toolJsonViewMode=="string"&&(t.toolJsonViewMode==="summary"||t.toolJsonViewMode==="formatted"||t.toolJsonViewMode==="raw")&&(n.toolJsonViewMode=t.toolJsonViewMode),typeof t.directoryShowHidden=="boolean"&&(n.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored=="boolean"&&(n.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&(n.openInAppId=t.openInAppId),typeof t.pwaAppName=="string"){const h=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);n.pwaAppName=h.length>0?h:""}const p=kh(t.skillCatalogs);return p&&(n.skillCatalogs=p),typeof t.reportUsage=="boolean"&&(n.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt=="string"&&(n.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled=="boolean"&&(n.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset=="string"&&(t.responseStylePreset==="concise"||t.responseStylePreset==="detailed"||t.responseStylePreset==="mentor"||t.responseStylePreset==="pushback"||t.responseStylePreset==="noFiller"||t.responseStylePreset==="matchEnergy"||t.responseStylePreset==="warmPeer"||t.responseStylePreset==="custom")&&(n.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions=="string"&&(n.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled=="boolean"&&(n.dictationEnabled=t.dictationEnabled),t.sttProvider==="local"||t.sttProvider==="openai-compatible"?n.sttProvider=t.sttProvider:t.sttProvider==="server"?n.sttProvider="openai-compatible":(t.sttProvider==="browser"||t.sttProvider==="wasm")&&(n.sttProvider="local"),typeof t.sttServerUrl=="string"&&(n.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel=="string"&&(n.sttModel=t.sttModel.trim()),typeof t.sttLocalModel=="string"&&(n.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage=="string"&&(n.sttLanguage=t.sttLanguage.trim()),n};class Oh{revision=0;mutations=[];operations=new Set;record(t){if(this.revision+=1,this.operations.size>0){const n=this.mutations.at(-1),r=n?[...this.operations].some(o=>o.revision>=n.revision):!0;n&&!r?(n.revision=this.revision,n.changes={...n.changes,...t}):this.mutations.push({revision:this.revision,changes:t})}return this.revision}begin(t=this.revision){const n={revision:t};return this.operations.add(n),n}reconcile(t,n){let r=t;for(const o of this.mutations)o.revision<=n.revision||(r={...r,...o.changes});return r}finish(t){if(!this.operations.delete(t))return;if(this.operations.size===0){this.mutations=[];return}const n=Math.min(...[...this.operations].map(({revision:r})=>r));this.mutations=this.mutations.filter(r=>r.revision>n)}reset(){this.mutations=[],this.operations.clear()}}let Ns=0,qe=null,It=null,yt=null,xt=null,xe=null,Zo=[],ia=!1,Lr=0;const Ne=new Oh,Lh=2e3,_h=200,Bs=()=>({runtimeKey:B(),generation:Ns}),es=(e,t)=>e.runtimeKey===t.runtimeKey&&e.generation===t.generation,re=e=>e.generation===Ns&&e.runtimeKey===B(),wn=()=>{yt&&(xe&&(clearTimeout(xe),xe=null),_r({keepalive:!0}))},Hs=()=>{if(!(ia||typeof window>"u")){ia=!0,au(e=>{e.runtimeKey!==e.previousRuntimeKey&&(xe&&clearTimeout(xe),yt&&_r())}),pc(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Ns+=1,Ne.reset(),Lr=0,qe=null,It=null)});try{window.addEventListener("pagehide",wn,{capture:!0}),window.addEventListener("beforeunload",wn,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&wn()}),document.addEventListener("freeze",wn)),Fc()&&ls(async()=>{const{App:e}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:e}},__vite__mapDeps([3,4,5])).then(({App:e})=>e.addListener("appStateChange",({isActive:t})=>{t||wn()})).catch(()=>{})}catch{}}},Fh=async(e=Bs())=>{if(Hs(),qe&&es(qe.context,e)&&Date.now()-qe.at<Lh)return qe.value;if(It&&es(It.context,e))return It.promise;const t={context:e,promise:(async()=>{const n=il();if(n)try{const r=await n.load();if(!re(e))return null;const o=Xo(r.settings);return qe={value:o,at:Date.now(),context:e},o}catch(r){if(!re(e))return null;console.warn("Failed to load shared settings from runtime settings API:",r)}if(!re(e))return null;try{const r=await m("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!re(e)||!r.ok)return null;const o=await r.json().catch(()=>null);if(!re(e))return null;const s=Xo(o);return qe={value:s,at:Date.now(),context:e},s}catch(r){return re(e)&&console.warn("Failed to load shared settings from server:",r),null}})()};return It=t,t.promise.finally(()=>{It===t&&(It=null)}),t.promise},db=async e=>{const t=e?.bootstrap!==!1,n=e?.adoptTheme??t;if(typeof window>"u")return;Hs();const r=Bs(),o=Ne.begin(),s=[sl(),Go.persist],i=d=>!d?.hasHydrated||d.hasHydrated()||!d.onFinishHydration?Promise.resolve():new Promise(u=>{let f=!1;const p=()=>{f||(f=!0,u())},h=d.onFinishHydration(()=>{h?.(),p()});d.hasHydrated?.()&&p()}),a=()=>Promise.all(s.map(i)).then(()=>{}),c=d=>!yt||!xt||!re(xt)?d:{...d,...yt},l=async d=>{if(!re(r))return;let u=c(Ne.reconcile(d,o));if(await a(),!re(r))return;u=c(Ne.reconcile(d,o));const f=u.draftStartersCraftGoalAdded!==!0||u.draftStartersScheduleTaskAdded!==!0,p=typeof u.autoSaveEnabled!="boolean",h=u.sidebarProjectDisplayMode===void 0,g=u.sidebarSessionGroupingMode===void 0,y=u.sidebarProjectSortOrder===void 0,b=u.sidebarShowRecentSection===void 0,S=Dh(u);try{Th(u)}catch(W){console.warn("persistToLocalStorage failed:",W)}p&&(S.autoSaveEnabled=Se.getState().autoSaveEnabled);const E=Go.getState();h&&(S.sidebarProjectDisplayMode=E.projectDisplayMode),g&&(S.sidebarSessionGroupingMode=E.sessionGroupingMode),y&&(S.sidebarProjectSortOrder=E.projectSortOrder),b&&(S.sidebarShowRecentSection=E.showRecentSection),u.draftStarters===void 0&&Se.setState({globalDraftStarters:null});try{Qo(S)}catch(W){console.warn("applyDesktopUiPreferences failed:",W)}const M={};f&&(S.draftStarters&&(M.draftStarters=S.draftStarters),M.draftStartersCraftGoalAdded=!0,M.draftStartersScheduleTaskAdded=!0),p&&(M.autoSaveEnabled=S.autoSaveEnabled),h&&(M.sidebarProjectDisplayMode=S.sidebarProjectDisplayMode),g&&(M.sidebarSessionGroupingMode=S.sidebarSessionGroupingMode),y&&(M.sidebarProjectSortOrder=S.sidebarProjectSortOrder),b&&(M.sidebarShowRecentSection=S.sidebarShowRecentSection),!(Object.keys(M).length>0&&(await je(M),!re(r)))&&Ko(S,t,n)};try{const d=await Fh(r);d&&re(r)&&await l(d)}catch(d){console.warn("Failed to synchronise settings:",d)}finally{Ne.finish(o)}};async function _r({keepalive:e=!1}={}){const t=yt,n=xt,r=Lr,o=Zo;yt=null,xt=null,Lr=0,xe=null,Zo=[];try{if(!t||!n||Object.keys(t).length===0||!re(n)){Ke("saved");return}const s=Ne.begin(r);try{const i=il();if(i)try{const a=await i.save(t);if(!re(n))return;if(a){const c=Ne.reconcile(a,s);Qo(c),Ko(c,!1),qe=null}Ke(a?"saved":"error");return}catch(a){if(!re(n))return;console.warn("Failed to update settings via runtime settings API:",a)}if(!re(n))return;try{const a=await m("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t),keepalive:e});if(!re(n))return;if(!a.ok){console.warn("Failed to update shared settings via API:",a.status,a.statusText),Ke("error");return}const c=Xo(await a.json().catch(()=>null));if(!re(n))return;if(c){const l=Ne.reconcile(c,s);Qo(l),Ko(l,!1),Ke("saved"),qe=null}else Ke("error")}catch(a){re(n)&&(console.warn("Failed to update shared settings via API:",a),Ke("error"))}}finally{Ne.finish(s)}}finally{o.forEach(s=>s())}}const je=async e=>{if(typeof window>"u")return;Hs();const t=Bs();xt&&!es(xt,t)&&(xe&&clearTimeout(xe),_r()),yt={...yt??{},...e},xt=t,Lr=Ne.record(e),Ke("saving"),xe&&clearTimeout(xe);const n=new Promise(r=>{Zo.push(r)});return xe=setTimeout(()=>{_r()},_h),n},ub=async()=>{if(typeof window>"u")return;const e=sl();try{const t=await dh();if(!t)return;const n=()=>lh(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)}},jh=3e4,Uh=40,Nh=60,Bh=(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])},aa=(e,t)=>{try{const n=JSON.parse(e);return Array.isArray(n)&&n[1]===t}catch{return!1}},Hh=Ze()(an((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,o=Nh,s){if(!n||n.trim().length===0)return[];const i=n.trim(),a=B(),c=typeof r=="string"?r.trim():"",l=!!s?.includeHidden,d=s?.respectGitignore??!0,u=s?.type==="directory"?"directory":"file",f=Bh(a,i,c,o,l,d,u),p=Date.now(),h=t().cache[f];if(h&&p-h.timestamp<jh)return h.files;const g=t().inFlight[f];if(g)return g;const y=Ue.searchFiles(c,{directory:i,limit:o,includeHidden:l,respectGitignore:d,dirs:u!=="file",type:u}).then(b=>(e(S=>{if(S.inFlight[f]!==y)return S;const E={...S.cache,[f]:{files:b,timestamp:Date.now()}},M=S.cacheKeys.filter(W=>W!==f);for(M.push(f);M.length>Uh;){const W=M.shift();W&&delete E[W]}return{cache:E,cacheKeys:M}}),b)).finally(()=>{e(b=>{if(b.inFlight[f]!==y)return b;const S={...b.inFlight};return delete S[f],{inFlight:S}})});return e(b=>({inFlight:{...b.inFlight,[f]:y}})),y},invalidateDirectory(n){if(!n||n.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}const r=n.trim();e(o=>{const s={...o.cache},i=o.cacheKeys.filter(l=>aa(l,r)?(delete s[l],!1):!0),a=Object.entries(o.inFlight).filter(([l])=>!aa(l,r)),c=Object.fromEntries(a);return{cache:s,cacheKeys:i,inFlight:c}})},resetForRuntimeSwitch(){e({cache:{},cacheKeys:[],inFlight:{}})}}),{name:"file-search-store"})),zh=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("aiworker_stream_debug")==="1"}catch{return!1}},ts="aiworker_stream_perf",Wh=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ts)==="1"}catch{return!1}};let jt=Wh();const ca=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),$h=()=>{if(!jt||typeof window>"u")return null;if(!window.__aiworkerStreamPerfState){const e=Date.now();window.__aiworkerStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__aiworkerStreamPerfState},al=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),zs=(e,t)=>{const n=$h();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()},Gh=e=>{if(jt=e,!(typeof window>"u"))try{if(e){window.localStorage.setItem(ts,"1"),window.__aiworkerStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(ts),delete window.__aiworkerStreamPerfState,delete window.__aiworkerVsCodeStreamPerfState}catch{}},Kh=()=>{typeof window>"u"||(jt&&(window.__aiworkerStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__aiworkerVsCodeStreamPerfState&&(window.__aiworkerVsCodeStreamPerfState={...window.__aiworkerVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},qh=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__aiworkerStreamPerfState;return!jt||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:al(e.counters)}},fb=()=>{if(typeof window>"u")return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const e=window.__aiworkerVsCodeStreamPerfState;if(!jt||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};const t=typeof e.startedAt=="number"?e.startedAt:null,n=typeof e.lastUpdatedAt=="number"?e.lastUpdatedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:n,durationMs:t?Math.max(0,Date.now()-t):0,entries:al(e.counters)}},pb=(e,t=1)=>{zs(e,t)},hb=(e,t)=>{zs(e,t)},mb=e=>{!jt||typeof performance>"u"||typeof performance.mark!="function"||performance.mark(`aiworker.${e}`)},yb=(e,t)=>{if(!jt)return t();const n=ca();try{return t()}finally{zs(e,ca()-n)}};typeof window<"u"&&(window.__aiworkerStreamPerformance={setEnabled:Gh,reset:Kh,getSnapshot:qh});var Vh={};let Ce=null,la=0;const Re=Bn(),da=Re.getItem("lastDirectory"),Jh=typeof da=="string"&&da.length>0,lr=e=>{try{Hh.getState().invalidateDirectory(e)}catch(t){console.warn("Failed to invalidate file search cache:",t)}},sn=e=>{const t=e.trim();if(!t)return t;const n=t.replace(/\\/g,"/").replace(/^([a-z]):/,(r,o)=>o.toUpperCase()+":");return n.length>1?n.replace(/\/+$/,""):n},Yh=(e,t)=>{const n=e.trim();return n.startsWith("~")?n==="~"?t||n:(n.startsWith("~/")||n.startsWith("~\\"))&&t?`${t}${n.slice(1)}`:n:n},gr=(e,t)=>{const n=Yh(e,t);return sn(n)},Qh=()=>{const e=Re.getItem("homeDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},Xh=()=>{const e=Re.getItem("lastDirectory");if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},Zh=()=>{if(typeof process>"u")return null;const e=Vh,t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t=="string"&&t.trim().length>0){const r=sn(t);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=sn(n);return r.length>0?r:null}return null},Fr=()=>{if(typeof window<"u"){if(Ce)return Ce;const t=typeof window.__AIWORKER_HOME__=="string"&&window.__AIWORKER_HOME__.length>0?window.__AIWORKER_HOME__:null;if(t&&t.length>0)return Ce=t,Re.setItem("homeDirectory",t),t;const n=Qh();if(n&&!Be())return Ce=n,n}const e=Zh();return e||"/"},em=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},tm=e=>(Ce=e,typeof window<"u"&&Re.setItem("homeDirectory",e),je({homeDirectory:e}),e),ns=async()=>{const e=r=>{const o=em(r);return o?tm(o):null};try{const r=await Ue.getFilesystemHome(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await Ue.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 gc(),o=e(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const t=Fr(),n=e(t);return n||t},nm=()=>{if(!Be())return null;const e=yc()?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const t=sn(e);return t.length>0?t:null},jn=nm()||Fr(),jr=(()=>{const e=Xh();return e&&!Be()?gr(e,jn):jn})();jr&&Ue.setDirectory(jr);const rm=!!(jn&&jn!=="/"),rs=Ze()(an((e,t)=>({currentDirectory:jr,directoryHistory:[jr],historyIndex:0,homeDirectory:jn,hasPersistedDirectory:Jh,isHomeReady:rm,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const o=Ce||t().homeDirectory||Re.getItem("homeDirectory"),s=gr(n,o);zh()&&console.log("[DirectoryStore] setDirectory called with path:",s),Ue.setDirectory(s),lr(),e(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return Re.setItem("lastDirectory",s),je({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=t();if(n.historyIndex>0){const r=n.historyIndex-1,o=n.directoryHistory[r];Ue.setDirectory(o),lr(),Re.setItem("lastDirectory",o),je({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=t();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,o=n.directoryHistory[r];Ue.setDirectory(o),lr(),Re.setItem("lastDirectory",o),je({lastDirectory:o}),e({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=t(),o=Ce||t().homeDirectory||Fr();if(n===o||n==="/")return;const s=n.endsWith("/")?n.slice(0,-1):n,i=s.lastIndexOf("/");if(i===-1){const a=Ce||Fr();r(a)}else r(i===0?"/":s.substring(0,i))},goHome:async()=>{const n=Ce||t().homeDirectory||await ns();t().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=t(),o=n;Ce=o;const s=r.homeDirectory!==o,i=Re.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,c=!a&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!s&&!c){r.isHomeReady||e({isHomeReady:!0});return}const l=typeof o=="string"&&o!==""&&o!=="/",d=r.currentDirectory?gr(r.currentDirectory,o):r.currentDirectory,u=r.directoryHistory.map(g=>gr(g,o)),f=u.some((g,y)=>g!==r.directoryHistory[y]),p=!!(d&&d!==r.currentDirectory),h={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:l};if(c?(h.currentDirectory=o,h.directoryHistory=[o],h.historyIndex=0,h.isSwitchingDirectory=!1):(p||f)&&(h.currentDirectory=d,h.directoryHistory=u,h.historyIndex=Math.min(r.historyIndex,u.length-1),h.isSwitchingDirectory=!1),e(()=>h),(c||p)&&l){const g=c?o:d;Ue.setDirectory(g),lr(),Re.setItem("lastDirectory",g),je({lastDirectory:g})}je({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&(ns().then(e=>{rs.getState().synchronizeHomeDirectory(e)}),pc(()=>{Ce=null;const e=++la;ns().then(t=>{e===la&&rs.getState().synchronizeHomeDirectory(t)})}));const om=(e,t)=>{const n=Br();return n?n.openWebSocket(ld(e),t):wd(new WebSocket(e))},cl=1,ua=512*1024,sm=0,qt=1,im=15e3,Ws=new TextEncoder,ll=new TextDecoder,$s=mt(["interactive","command"]),dl=mt(["running","exited","error"]),am=mt(["node","bun"]),Gs=Ur("type",[P({type:F("terminal")}),P({type:F("project-action"),actionId:w(),executionId:w()})]),cm=P({sessionId:w(),cols:C(),rows:C(),status:dl,mode:$s.optional(),purpose:Gs.optional()}),lm=P({sessionId:w(),cwd:w(),status:mt(["running","exited"]),createdAt:C().nullable().optional().transform(e=>e??null),mode:$s.optional(),purpose:Gs.optional()}),fa={mode:$s.optional(),purpose:Gs.optional()},dm=Ur("t",[P({t:F("hello")}),P({t:F("pong")}),P({t:F("error"),s:w().optional(),message:w().optional(),code:w().optional(),fatal:xl().optional()}),P({t:F("snapshot"),s:w(),q:C().int().nonnegative().default(0),history:w().default(""),status:dl,exitCode:C().nullish().transform(e=>e??void 0),signal:C().nullable().optional(),runtime:am.optional(),ptyBackend:w().optional(),...fa}),P({t:F("output"),s:w(),q:C().int().nonnegative(),d:w(),r:w().optional()}),P({t:F("exit"),s:w(),q:C().int().nonnegative(),exitCode:C().nullish().transform(e=>e??void 0),signal:C().nullable().optional()}),P({t:F("restarted"),s:w(),q:C().int().nonnegative(),history:w().default(""),...fa})]),um=e=>{const t=Ws.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=cl,n.set(t,1),n},fm=e=>{let t=e instanceof ArrayBuffer?new Uint8Array(e):Ws.encode(e);t[0]===cl&&(t=t.subarray(1));try{return dm.safeParse(JSON.parse(ll.decode(t))).data??null}catch{return null}},pm="TERMINAL_CWD_MISSING";class ul extends Error{code;constructor(t,n){super(t),this.name="TerminalRequestError",this.code=n}}const gb=e=>e instanceof ul&&e.code===pm,hm=P({error:w().optional(),code:w().optional()}),Vr=async(e,t)=>{const n=hm.safeParse(await e.json().catch(()=>null)).data;return new ul(n?.error??t,n?.code??null)},mm=e=>{const t=Ws.encode(e);if(t.byteLength<=ua)return e;let n=t.byteLength-ua;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;return ll.decode(t.subarray(n))},ym=P({sessions:Xe(ds())});class fl{constructor(t={refreshAuth:Wr,openSocket:()=>om(ye().websocket("/api/terminal/ws")),clearUrlAuthToken:Nn}){this.dependencies=t}socket=null;opening=null;subscribers=new Map;projections=new Map;reconnectTimer=null;keepaliveTimer=null;idleCloseTimer=null;failures=0;wakeCleanup=null;generation=0;disposed=!1;subscribe(t,n){this.cancelIdleClose();const r={handlers:n,lastSequence:-1},o=this.subscribers.get(t)??new Set,s=o.size===0;o.add(r),this.subscribers.set(t,o);const i=this.projections.get(t);i&&(r.lastSequence=i.sequence,n.onEvent({type:"snapshot",sequence:i.sequence,data:i.history,status:i.status,mode:i.mode,purpose:i.purpose,exitCode:i.exitCode,signal:i.signal,runtime:i.runtime,ptyBackend:i.ptyBackend}));const a=this.socket?.readyState===qt;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===qt){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===qt)return;if(this.opening)return await this.opening,this.socket?.readyState===qt?void 0:this.ensureConnected();const t=this.generation,n=(async()=>{if(await this.dependencies.refreshAuth(),t!==this.generation||this.disposed)throw new Error("Terminal runtime changed");await new Promise((r,o)=>{let s=!1,i=!1,a=!1,c=null;const l=()=>t===this.generation&&!this.disposed&&c!==null&&this.socket===c,d=()=>{a||i||!l()||(a=!0,this.dependencies.clearUrlAuthToken?.())},u=p=>{s||(s=!0,clearTimeout(f),p?o(p):r())},f=setTimeout(()=>{d(),c?.close(),u(new Error("Terminal connection timed out"))},1e4);try{const p=this.dependencies.openSocket();c=p,p.binaryType="arraybuffer",this.socket=p,p.onopen=()=>{if(!l()){p.close(),u(new Error("Terminal runtime changed"));return}i=!0,this.failures=0,this.send({t:"hello",v:3});for(const h of this.subscribers.keys())this.send({t:"attach",v:3,s:h});this.startKeepalive(),u()},p.onmessage=h=>{this.handleMessage(h.data)},p.onerror=()=>{const h=l();h&&d(),u(new Error("Terminal WebSocket failed")),h&&this.subscribers.size>0&&this.scheduleReconnect()},p.onclose=()=>{const h=l();h&&(this.stopKeepalive(),d()),this.socket===p&&(this.socket=null),u(new Error("Terminal WebSocket closed")),h&&this.subscribers.size>0&&this.scheduleReconnect()}}catch(p){u(p instanceof Error?p:new Error("Terminal WebSocket failed")),!this.disposed&&this.subscribers.size>0&&this.scheduleReconnect()}})})();this.opening=n;try{await n}finally{this.opening===n&&(this.opening=null)}}handleMessage(t){const n=fm(t);if(!n||n.t==="hello"||n.t==="pong")return;if(n.t==="error"){const s=new Error(n.message??"Terminal error");s.code=n.code;const i=n.s?[n.s]:[...this.subscribers.keys()];for(const a of i)for(const c of this.subscribers.get(a)??[])c.handlers.onError?.(s,n.fatal===!0);return}if(!n.s)return;const r=this.subscribers.get(n.s);if(!r)return;if(n.t==="snapshot"){const s={sequence:n.q??0,history:n.history??"",status:n.status,mode:n.mode,purpose:n.purpose,exitCode:n.exitCode,signal:n.signal??null,runtime:n.runtime,ptyBackend:n.ptyBackend};this.projections.set(n.s,s);for(const i of r)i.lastSequence=s.sequence,i.handlers.onEvent({type:"snapshot",sequence:s.sequence,data:s.history,status:s.status,mode:s.mode,purpose:s.purpose,exitCode:s.exitCode,signal:s.signal,runtime:s.runtime,ptyBackend:s.ptyBackend});return}const o=this.projections.get(n.s);o&&n.q>o.sequence&&(n.t==="output"?this.projections.set(n.s,{...o,sequence:n.q,history:mm(o.history+(n.r??n.d))}):n.t==="exit"?this.projections.set(n.s,{...o,sequence:n.q,status:"exited",exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&this.projections.set(n.s,{...o,sequence:n.q,history:n.history??"",status:"running",mode:n.mode??o.mode,purpose:n.purpose??o.purpose,exitCode:void 0,signal:null}));for(const s of r)n.q<=s.lastSequence||(s.lastSequence=n.q,n.t==="output"?s.handlers.onEvent({type:"data",sequence:n.q,data:n.d,replayData:n.r}):n.t==="exit"?s.handlers.onEvent({type:"exit",sequence:n.q,exitCode:n.exitCode,signal:n.signal??null}):n.t==="restarted"&&s.handlers.onEvent({type:"snapshot",sequence:n.q,data:n.history??"",status:"running",mode:n.mode??o?.mode,purpose:n.purpose??o?.purpose}))}send(t){if(!this.socket||this.socket.readyState!==qt)return!1;try{return this.socket.send(um(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())},im))}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===sm||t.readyState===qt)&&t.close()}}let Lt=new fl;async function gm(e){const t=await m("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Vr(t,"Failed to create terminal session");const n=await t.json().catch(()=>null),r=cm.safeParse(n).data;if(!r)throw new Error("Failed to create terminal session");return r}async function wm(e){const t=await m(`/api/terminal/sessions?cwd=${encodeURIComponent(e)}`);if(!t.ok)throw await Vr(t,"Failed to list terminal sessions");const n=await t.json().catch(()=>null),r=ym.safeParse(n).data?.sessions;if(!Array.isArray(r))throw new Error("Failed to list terminal sessions");const o=[];for(const s of r){const i=lm.safeParse(s).data;i&&o.push(i)}return o}async function bm(e){e.length!==0&&await un("/api/terminal/touch","POST",{sessionIds:e})}async function Sm(){const e=await m("/api/terminal/shells");if(!e.ok)throw await Vr(e,"Failed to list terminal shells");const t=await e.json().catch(()=>[]);return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&Or(n.id)&&typeof n.name=="string"&&typeof n.supportsLogin=="boolean"):[]}function Tm(e,t,n){return Lt.subscribe(e,{onEvent:t,onError:n})}async function km(e,t){await Lt.write(e,t)}async function un(e,t,n){const r={method:t};n!==void 0&&(r.headers={"Content-Type":"application/json"},r.body=JSON.stringify(n));const o=await m(e,r);if(!o.ok)throw await Vr(o,"Terminal command failed");return o}async function vm(e,t,n){await un(`/api/terminal/${e}/resize`,"POST",{cols:t,rows:n})}async function Em(e,t){await un(`/api/terminal/${e}/appearance`,"POST",t)}async function Am(e){await un(`/api/terminal/${e}`,"DELETE"),Lt.forget(e)}async function Pm(e,t){return(await un(`/api/terminal/${e}/restart`,"POST",t)).json()}async function Im(e){const n=await(await un("/api/terminal/force-kill","POST",e)).json().catch(()=>null);if(Array.isArray(n?.killedSessionIds))for(const r of n.killedSessionIds)typeof r=="string"&&Lt.forget(r);else e.sessionId&&Lt.forget(e.sessionId)}function wb(){Lt.dispose(),Lt=new fl}const Mm=()=>({async listShells(){return Sm()},async listSessions(e){return wm(e)},async touchSessions(e){await bm(e)},async createSession(e){return gm(e)},connect(e,t){const n=Tm(e,t.onEvent,t.onError);return{close:()=>n()}},async sendInput(e,t){await km(e,t)},async resize(e){await vm(e.sessionId,e.cols,e.rows)},async updateAppearance(e,t){await Em(e,t)},async close(e){await Am(e)},async restartSession(e,t){return Pm(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 Im(e)}}),os=new Set,Rm=e=>(os.add(e),()=>{os.delete(e)}),xm=e=>{for(const t of os)t(e)},T="/api/git",Cm=1200,Dm=5e3,ss=new Map,kn=new Map,pl=new Map,pa=new Map,dr=new Map,hl=e=>e.trim(),Ks=(e,t)=>JSON.stringify([e,hl(t)]),ml=(e,t,n)=>JSON.stringify([e,hl(t),n??"full"]),is=(e,t)=>pl.get(Ks(e,t))??0,yl=(e,t)=>{const n=Ks(e,t);pl.set(n,is(e,t)+1);for(const r of[void 0,"light"]){const o=ml(e,t,r);ss.delete(o),kn.delete(o)}};Rm(e=>{yl(B(),e)});const Hn=e=>{xm(e)},K=async(e,t)=>{const n=await t.json();return Hn(e),n};function k(e,t,n){const r={...n};return t&&(r.directory=t),ye().api(e,r)}async function Om(e){const t=Ks(B(),e),n=Date.now(),r=pa.get(t);if(r&&r.expiresAt>n)return r.value;const o=dr.get(t);if(o)return o;const s=(async()=>{const i=await m(k(`${T}/check`,e));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const c=!!(await i.json()).isGitRepository;return pa.set(t,{value:c,expiresAt:Date.now()+Dm}),c})();dr.set(t,s);try{return await s}finally{dr.get(t)===s&&dr.delete(t)}}class Lm extends Error{constructor(){super("Nested git repository discovery is not supported by this runtime"),this.name="GitDirectoriesUnsupportedError"}}async function bb(e){const t=await m("/api/fs/git-dirs",{query:{path:e}});if(t.status===501)throw new Lm;if(!t.ok)throw new Error(`Failed to list git directories: ${t.statusText}`);const n=await t.json();if(!Array.isArray(n?.repositories))throw new Error("Unexpected git directories response");return n.repositories.map(r=>dn(r?.path??null)).filter(r=>r!==null)}async function _m(e,t){const n=t?.mode,r=B();t?.fresh&&yl(r,e);const o=ml(r,e,n),s=Date.now(),i=ss.get(o);if(i&&i.expiresAt>s)return i.value;const a=kn.get(o);if(a)return a;const c=(async()=>{const l=is(r,e),d=await m(k(`${T}/status`,e,n?{mode:n}:void 0));if(!d.ok)throw new Error(`Failed to get git status: ${d.statusText}`);const u=await d.json();return is(r,e)===l&&ss.set(o,{value:u,expiresAt:Date.now()+Cm}),u})();kn.set(o,c);try{return await c}finally{kn.get(o)===c&&kn.delete(o)}}async function Sb(e){const t=await m(k(`${T}/primary-root`,e));if(!t.ok)throw new Error(`Failed to resolve git primary root: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function Tb(e){const t=await m(k(`${T}/toplevel`,e));if(!t.ok)throw new Error(`Failed to resolve git toplevel: ${t.statusText}`);const n=await t.json().catch(()=>({}));return{root:typeof n.root=="string"&&n.root?n.root:e}}async function kb(e,t){const n=await m(k(`${T}/commit-summaries`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shas:t})});if(!n.ok)throw new Error(`Failed to get git commit summaries: ${n.statusText}`);const r=await n.json().catch(()=>({}));return{commits:Array.isArray(r.commits)?r.commits.map(o=>({sha:typeof o.sha=="string"?o.sha:"",short:typeof o.short=="string"?o.short:"",subject:typeof o.subject=="string"?o.subject:""})).filter(o=>o.sha&&o.short):[]}}async function Fm(e,t){const{path:n,staged:r,contextLines:o}=t;if(!n)throw new Error("path is required to fetch git diff");const s=await m(k(`${T}/diff`,e,{path:n,staged:r?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function jm(e,t){const{base:n,head:r,path:o,contextLines:s}=t;if(!n||!r)throw new Error("base and head are required to fetch git range diff");const i=await m(k(`${T}/range-diff`,e,{base:n,head:r,path:o||void 0,context:s}));if(!i.ok)throw new Error(`Failed to get git range diff: ${i.statusText}`);return i.json()}async function Um(e,t){const{base:n,head:r}=t;if(!n||!r)throw new Error("base and head are required to fetch git range files");const o=await m(k(`${T}/range-files`,e,{base:n,head:r}));if(!o.ok)throw new Error(`Failed to get git range files: ${o.statusText}`);const s=await o.json();return Array.isArray(s.files)?s.files.filter(i=>{if(!i||typeof i!="object")return!1;const a=i;return typeof a.path=="string"&&typeof a.status=="string"}):[]}async function Nm(e,t){if(!t)throw new Error("branch is required to get branch base");const n=await m(k(`${T}/branch-base`,e,{branch:t}));if(!n.ok)throw new Error(`Failed to get branch base: ${n.statusText}`);return n.json()}async function Bm(e,t){const{path:n,staged:r}=t;if(!n)throw new Error("path is required to fetch git file diff");const o=await m(k(`${T}/file-diff`,e,{path:n,staged:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function Hm(e,t,n){if(!t)throw new Error("path is required to revert git changes");const r=await m(k(`${T}/revert`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to revert git changes")}Hn(e)}async function zm(e,t){await gl(e,[t])}async function gl(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to stage git changes");const r=await m(k(`${T}/stage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to stage git changes")}Hn(e)}async function Wm(e,t){await wl(e,[t])}async function wl(e,t){const n=t.map(o=>o.trim()).filter(Boolean);if(n.length===0)throw new Error("path is required to unstage git changes");const r=await m(k(`${T}/unstage`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to unstage git changes")}Hn(e)}async function $m(e,t,n){await qs(e,t,n,"stage")}async function Gm(e,t,n){await qs(e,t,n,"unstage")}async function Km(e,t,n){await qs(e,t,n,"discard")}async function qs(e,t,n,r){if(!t)throw new Error("path is required to apply a git hunk");if(typeof n!="string"||!n.trim())throw new Error("patch is required to apply a git hunk");const o=await m(k(`${T}/apply-hunk`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,patch:n,action:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to apply git hunk")}Hn(e)}async function qm(e){if(!e)return!1;const t=await m(k(`${T}/worktree-type`,e));if(!t.ok)throw new Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function Vm(e){const t=await m(k(`${T}/branches`,e));if(!t.ok)throw new Error(`Failed to get branches: ${t.statusText}`);return t.json()}async function Jm(e,t){const n=await m(k(`${T}/branch-push-status`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branches:t})});if(!n.ok)throw new Error(`Failed to get branch push status: ${n.statusText}`);return n.json()}async function Ym(e,t){if(!t?.branch)throw new Error("branch is required to delete a branch");const n=await m(k(`${T}/branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete branch")}return K(e,n)}async function Qm(e,t){if(!t?.branch)throw new Error("branch is required to delete remote branch");const n=await m(k(`${T}/remote-branches`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete remote branch")}return K(e,n)}async function Xm(e,t){const n=t?.remote?.trim();if(!n)throw new Error("remote is required to remove a remote");const r=await m(k(`${T}/remotes`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to remove remote")}return K(e,r)}async function Zm(e,t,n){if(!Array.isArray(t)||t.length===0)throw new Error("No files provided to generate commit message");const r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);const o=await m(k(`${T}/commit-message`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){const c=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:c});const l=typeof c?.traceId=="string"&&c.traceId?` (traceId: ${c.traceId})`:"";throw new Error(`${c.error||"Failed to generate commit message"}${l}`)}const s=await o.json();if(!s?.message||typeof s.message!="object")throw new Error("Malformed commit generation response");const i=typeof s.message.subject=="string"&&s.message.subject.trim().length>0?s.message.subject.trim():"",a=Array.isArray(s.message.highlights)?s.message.highlights.filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim()):[];return{message:{subject:i,highlights:a}}}async function ey(e,t){const{base:n,head:r,context:o,zenModel:s,providerId:i,modelId:a}=t;if(!n||!r)throw new Error("base and head are required");const c={base:n,head:r};o?.trim()&&(c.context=o.trim()),s&&(c.zenModel=s),i&&(c.providerId=i),a&&(c.modelId=a);const l=await m(k(`${T}/pr-description`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){const p=await l.json().catch(()=>({error:l.statusText}));throw new Error(p.error||"Failed to generate PR description")}const d=await l.json().catch(()=>null),u=typeof d?.title=="string"?d.title:"",f=typeof d?.body=="string"?d.body:"";if(!u&&!f)throw new Error("Malformed PR description response");return{title:u,body:f}}async function ha(e){const t=await m(k(`${T}/worktrees`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list worktrees")}return t.json()}async function ma(e,t){const n=await m(k(`${T}/worktrees/validate`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to validate worktree")}return n.json()}async function ty(e){const t=await m(k(`${T}/worktrees/bootstrap-status`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to get worktree bootstrap status")}return t.json()}async function ny(e,t){const n=await m(k(`${T}/worktrees/preview`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to preview worktree")}return n.json()}async function ya(e,t){const n=await m(k(`${T}/worktrees`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to create worktree")}return n.json()}async function ga(e,t){const n=await m(k(`${T}/worktrees`,e),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to delete worktree")}return n.json()}async function ry(e,t,n={}){const r=await m(k(`${T}/commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create commit")}return K(e,r)}async function oy(e,t={}){const n=await m(k(`${T}/push`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to push")}return K(e,n)}async function sy(e,t={}){const n=await m(k(`${T}/pull`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to pull")}return K(e,n)}async function iy(e,t={}){const n=await m(k(`${T}/fetch`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to fetch")}return K(e,n)}async function ay(e){const t=await m(k(`${T}/stashes`,e));if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to list stashes")}return t.json()}async function cy(e,t){const n=await m(k(`${T}/stashes/file-counts`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refs:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to count stash files")}return n.json()}async function bl(e,t={}){const n=await m(k(`${T}/stash`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to stash changes")}return K(e,n)}const Vs=async(e,t,n)=>{const r=await m(k(`${T}/${t}`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||`Failed to ${t}`)}return K(e,r)},ly=(e,t)=>Vs(e,"stash/apply",t),Sl=(e,t)=>Vs(e,"stash/pop",t),dy=(e,t)=>Vs(e,"stash/drop",t);async function uy(e,t){const n=await m(k(`${T}/checkout`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout branch")}return K(e,n)}async function fy(e,t,n){const r=await m(k(`${T}/branches`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to create branch")}return K(e,r)}async function py(e,t,n){const r=await m(k(`${T}/branches/rename`,e),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to rename branch")}return K(e,r)}async function hy(e,t={}){const n=await m(k(`${T}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?"true":void 0}));if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(`Failed to get git log: ${r.error||n.statusText}`)}return n.json()}async function my(e,t){const n=await m(k(`${T}/commit-files`,e,{hash:t}));if(!n.ok)throw new Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function vb(e,t,n,r){const o=await m(k(`${T}/commit-file-diff`,e,{hash:t,path:n,binary:r?"true":void 0}));if(!o.ok)throw new Error(`Failed to get commit file diff: ${o.statusText}`);return o.json()}async function yy(){const e=await m(k(`${T}/identities`,void 0));if(!e.ok)throw new Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function gy(e){const t=await m(k(`${T}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to create git identity")}return t.json()}async function wy(e,t){const n=await m(k(`${T}/identities/${e}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to update git identity")}return n.json()}async function by(e){const t=await m(k(`${T}/identities/${e}`,void 0),{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to delete git identity")}}async function Sy(e){if(!e)return null;const t=await m(k(`${T}/current-identity`,e));if(!t.ok)throw new Error(`Failed to get current git identity: ${t.statusText}`);const n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Ty(e){if(!e)return!1;const t=await m(k(`${T}/has-local-identity`,e));if(!t.ok)throw new Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function Eb(){const e=await m(k(`${T}/global-identity`,void 0));if(!e.ok)throw new Error(`Failed to get global git identity: ${e.statusText}`);const t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function ky(e,t){const n=await m(k(`${T}/set-identity`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to set git identity")}return n.json()}async function Ab(){const e=await m(k(`${T}/discover-credentials`,void 0));if(!e.ok)throw new Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Pb(e,t){if(!e)return null;const n=await m(k(`${T}/remote-url`,e,{remote:t}));return n.ok?(await n.json()).url??null:null}async function vy(e){const t=await m(k(`${T}/remotes`,e));if(!t.ok)throw new Error(`Failed to get remotes: ${t.statusText}`);return t.json()}async function Ey(e,t){const n=await m(k(`${T}/rebase`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to rebase")}return K(e,n)}async function Ay(e){const t=await m(k(`${T}/rebase/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort rebase")}return K(e,t)}async function Py(e,t){const n=await m(k(`${T}/merge`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to merge")}return K(e,n)}async function Iy(e,t){const n=await m(k(`${T}/checkout-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to checkout commit")}return K(e,n)}async function My(e,t){const n=await m(k(`${T}/cherry-pick`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to cherry-pick")}return K(e,n)}async function Ry(e,t){const n=await m(k(`${T}/revert-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t})});if(!n.ok){const r=await n.json().catch(()=>({error:n.statusText}));throw new Error(r.error||"Failed to revert commit")}return K(e,n)}async function xy(e,t,n,r){const o=await m(k(`${T}/reset-to-commit`,e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hash:t,mode:n,force:r})});if(!o.ok){const s=await o.json().catch(()=>({error:o.statusText}));throw new Error(s.error||"Failed to reset")}return K(e,o)}async function Cy(e){const t=await m(k(`${T}/merge/abort`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to abort merge")}return K(e,t)}async function Dy(e){const t=await m(k(`${T}/rebase/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue rebase")}return K(e,t)}async function Oy(e){const t=await m(k(`${T}/merge/continue`,e),{method:"POST"});if(!t.ok){const n=await t.json().catch(()=>({error:t.statusText}));throw new Error(n.error||"Failed to continue merge")}return K(e,t)}async function Ly(e,t){return await bl(e,{message:t?.message}),{success:!0}}async function _y(e){return await Sl(e,{ref:"stash@{0}"}),{success:!0}}async function Fy(e){const t=await m(k(`${T}/conflict-details`,e));if(!t.ok)throw new Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function jy(e,t){const n=await m(`${T}/validate-directory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw new Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function Uy(e){const t=await m(`${T}/canonicalize-worktree-state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!t.ok)throw new Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}const Ny=()=>({checkIsGitRepository:Om,getGitStatus:_m,getGitDiff:Fm,getGitFileDiff:Bm,getGitRangeDiff:jm,getGitRangeFiles:Um,getBranchBase:Nm,revertGitFile:Hm,stageGitFile:zm,stageGitFiles:gl,unstageGitFile:Wm,unstageGitFiles:wl,stageGitHunk:$m,unstageGitHunk:Gm,revertGitHunk:Km,isLinkedWorktree:qm,getGitBranches:Vm,getGitUnpushedBranchCounts:Jm,deleteGitBranch:Ym,deleteRemoteBranch:Qm,removeRemote:Xm,generateCommitMessage:Zm,generatePullRequestDescription:ey,listGitWorktrees:ha,validateGitWorktree:ma,createGitWorktree:ya,deleteGitWorktree:ga,validateWorktreeDirectory:jy,canonicalizeWorktreeState:Uy,createGitCommit(e,t,n){return ry(e,t,n)},gitPush:oy,gitPull:sy,gitFetch:iy,listGitStashes:ay,countGitStashFiles:cy,stashGitChanges:bl,applyGitStash:ly,popGitStash:Sl,dropGitStash:dy,checkoutBranch:uy,createBranch:fy,renameBranch:py,getGitLog(e,t){return hy(e,t)},getCommitFiles:my,getCurrentGitIdentity:Sy,hasLocalIdentity:Ty,setGitIdentity:ky,getGitIdentities:yy,createGitIdentity:gy,updateGitIdentity:wy,deleteGitIdentity:by,getRemotes:vy,rebase:Ey,abortRebase:Ay,continueRebase:Dy,merge:Py,abortMerge:Cy,continueMerge:Oy,checkoutCommit:Iy,cherryPick:My,revertCommit:Ry,resetToCommit:xy,stash:Ly,stashPop:_y,getConflictDetails:Fy,worktree:{list:ha,validate:ma,bootstrapStatus:ty,preview:ny,create:ya,remove:ga}}),te=e=>e.replace(/\\/g,"/"),By=(e,t)=>{if(!t||!Array.isArray(t.entries))throw new Rt("Directory listing returned an invalid response",{reason:"invalid-response"});return{directory:te(t?.directory||t?.path||e),entries:t.entries.filter(r=>!!(r&&typeof r.name=="string"&&typeof r.path=="string")).map(r=>({name:r.name,path:te(r.path),isDirectory:!!r.isDirectory}))}},Pe=(e,t)=>{const n=t||e?.();return n?{"x-opencode-directory":n}:void 0},Hy=({getDirectory:e})=>({async listDirectory(t,n){const r=te(t),o=new URLSearchParams;r&&o.set("path",r),n?.respectGitignore&&o.set("respectGitignore","true");const s=await m("/api/fs/list",{query:o,headers:Pe(e)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Rt(a.error||"Failed to list directory",{reason:Rr(a.reason),status:s.status})}const i=await s.json();return By(r,i)},async search(t){const n=new URLSearchParams,r=te(t.directory);r&&n.set("directory",r),n.set("query",t.query),n.set("dirs","false"),n.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&n.set("limit",String(t.maxResults));const o=await m("/api/find/file",{query:n,headers:Pe(e)});if(!o.ok){const a=await o.json().catch(()=>({error:o.statusText}));throw new Error(a.error||"Failed to search files")}const s=await o.json();return(Array.isArray(s)?s:[]).map(a=>({path:te(`${r}/${a}`),preview:[te(a)]}))},async createDirectory(t){const n=te(t),r=await m("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to create directory")}const o=await r.json();return{success:!!o?.success,path:typeof o?.path=="string"?te(o.path):n}},async statFile(t,n){const r=te(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant);const s=await m("/api/fs/stat",{query:o,headers:Pe(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to stat file")}const i=await s.json().catch(()=>({}));return{path:typeof i.path=="string"?te(i.path):r,isFile:!!i.isFile,size:typeof i.size=="number"?i.size:0,mtimeMs:typeof i.mtimeMs=="number"?i.mtimeMs:void 0}},async readFile(t,n){const r=te(t),o=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&o.set("allowOutsideWorkspace","true"),n?.outsideFileGrant&&o.set("outsideFileGrant",n.outsideFileGrant),n?.optional&&o.set("optional","true");const s=await m("/api/fs/read",{query:o,cache:n?.optional||n?.fresh?"no-store":"default",headers:Pe(e,n?.directory)});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Error(a.error||"Failed to read file")}return{content:await s.text(),path:r}},async writeFile(t,n){const r=te(t),o=await m("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:r,content:n})});if(!o.ok){const i=await o.json().catch(()=>({error:o.statusText}));throw new Error(i.error||"Failed to write file")}const s=await o.json().catch(()=>({}));return{success:!!s.success,path:typeof s.path=="string"?te(s.path):r}},async uploadFile(t,n,r){const o=te(t),s=await m("/api/fs/upload",{method:"POST",query:{path:o,overwrite:r?.overwrite?"true":void 0},headers:{"Content-Type":"application/octet-stream",...Pe(e,r?.directory)},body:n});if(!s.ok){const a=await s.json().catch(()=>({error:s.statusText}));throw new Rt(a.error||"Failed to upload file",{reason:Rr(a.reason),status:s.status})}const i=await s.json().catch(()=>({}));return{success:!!i.success,path:i.path?te(i.path):o}},async delete(t){const n=te(t),r=await m("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to delete file")}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){const r=await m("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){const s=await r.json().catch(()=>({error:r.statusText}));throw new Error(s.error||"Failed to rename file")}const o=await r.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?te(o.path):n}},async revealPath(t){const n=await m("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json",...Pe(e)},body:JSON.stringify({path:te(t)})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to reveal path")}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){const n=te(t),r=await m("/api/fs/raw",{query:{path:n,download:!0},headers:Pe(e)});if(!r.ok)throw new Error(`Download failed (${r.status})`);const o=await r.blob(),s=n.split("/").pop()||"file",i=window.Capacitor,a=new File([o],s,{type:o.type||"application/octet-stream"});if(i?.isNativePlatform?.()===!0&&navigator.canShare?.({files:[a]})){await navigator.share({files:[a]});return}const c=URL.createObjectURL(o),l=document.createElement("a");l.href=c,l.download=s,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),100)}}),wa="/api/config/settings",zy="/api/config/reload",ba=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid settings response");return e},Wy=()=>({async load(){const e=await m(wa,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load settings: ${e.statusText}`);return{settings:ba(await e.json()),source:"web"}},async save(e){const t=await m(wa,{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 ba(await t.json())},async restartOpenCode(){const e=await m(zy,{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}}}),$y=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),Gy=1500,as=5e3,Ky="openchamber-notification-claim:",Rn=new Map,qy=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Vy=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("|")},Jy=e=>{for(const[t,n]of Rn)e-n>as&&Rn.delete(t)},Yy=e=>{const t=Vy(e);if(!t)return!0;const n=Date.now();Jy(n);const r=Rn.get(t)??0;if(n-r<as)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${Ky}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<as)return Rn.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return Rn.set(t,n),!0},Tl=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),Gy)})])??e}catch{return e}},Qy=async e=>{const t=await Tl();if(!t||typeof t.showNotification!="function")return!1;try{return await t.showNotification(e?.title??"AiWorker",{body:e?.body,tag:e?.tag}),!0}catch(n){return console.warn("Failed to send notification via service worker",n),!1}},Xy=async()=>{const e=await Tl();if(!e||!("pushManager"in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},Zy=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(!qy()&&await Xy()||!Yy(e))return!0;try{return await Qy(e)||new Notification(e?.title??"AiWorker",{body:e?.body,tag:e?.tag}),!0}catch(t){return console.warn("Failed to send notification",t),!1}},eg=async e=>{if(typeof window>"u")return!1;const t=window.__AIWORKER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke("desktop_notify",{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(n){return console.warn("Failed to send native notification (desktop)",n),!1}},tg=()=>({async notifyAgentCompletion(e){return await eg(e)||await Zy(e)},canNotify:()=>typeof window<"u"&&window.__AIWORKER_DESKTOP__?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),ng=()=>({async getAvailableTools(){const e=await m("/api/experimental/tool/ids");if(!e.ok)throw new Error(`Tools API returned ${e.status} ${e.statusText}`);const t=await e.json();if(!Array.isArray(t))throw new Error("Tools API returned invalid data format");return t.filter(n=>typeof n=="string"&&n!=="invalid").sort()}}),Vt=async(e,t)=>{try{const n=await m(e,{...t,credentials:"include",headers:{Accept:"application/json",...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},rg=()=>({async getVapidPublicKey(){return Vt("/api/push/vapid-public-key")},async subscribe(e){return Vt("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unsubscribe(e){return Vt("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async setVisibility(e){return Vt("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return Vt("/api/push/apns-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},async unregisterApnsToken(e){return Vt("/api/push/apns-token",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}),ee=async e=>await e.json().catch(()=>null),og=({urls:e})=>({async authStatus(){const t=await m("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to load GitHub status");return n},async authStart(){const t=await m("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),n=await ee(t);if(!t.ok||!n||!("deviceCode"in n))throw new Error(n?.error||t.statusText||"Failed to start GitHub auth");return n},async authComplete(t){const n=await m("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to complete GitHub auth");return r},async authDisconnect(){const t=await m("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok)throw new Error(n?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!n?.removed}},async authActivate(t){const n=await m("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to activate GitHub account");return r},async authSetGhCliDisabled(t){const n=await m("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:t})}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update gh CLI setting");return{disabled:!!r.disabled}},async me(){const t=await m("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),n=await ee(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to fetch GitHub user");return n},async prStatus(t,n,r,o){const s=new URLSearchParams({directory:t,branch:n,...r?{remote:r}:{},...o?.force?{force:"true"}:{}}),i=await m(`/api/github/pr/status?${s.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),a=await ee(i);if(!i.ok||!a)throw new Error(a?.error||i.statusText||"Failed to load PR status");return a},async prCreate(t){const n=await m("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to create PR");return r},async prUpdate(t){const n=await m("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to update PR");return r},async prMerge(t){const n=await m("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to merge PR");return r},async prReady(t){const n=await m("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to mark PR ready");return r},async repoUpstream(t){const n=await m(`/api/github/repo/upstream?directory=${encodeURIComponent(t)}`,{method:"GET",headers:{Accept:"application/json"}}),r=await ee(n);if(!n.ok||!r)throw new Error(r?.error||n.statusText||"Failed to detect upstream repo");return r},async repoBranches(t,n){const r=await m(`/api/github/repo/branches?owner=${encodeURIComponent(t)}&repo=${encodeURIComponent(n)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await ee(r);if(!r.ok||!o)throw new Error(o?.error||r.statusText||"Failed to fetch repo branches");return o.branches??[]},async prsList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await m(`/api/github/pulls/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull requests");return i},async prContext(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&o.set("diff","1"),r?.includeCheckDetails&&o.set("checkDetails","1"),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/pulls/context",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load pull request context");return i},async issuesList(t,n){const r=n?.page??1,o=new URLSearchParams({directory:t,page:String(r)});n?.query&&o.set("query",n.query);const s=await m(`/api/github/issues/list?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issues");return i},async issueGet(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/issues/get",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue");return i},async issueComments(t,n,r){const o=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(o.set("owner",r.sourceRepo.owner),o.set("repo",r.sourceRepo.repo));const s=await m(e.api("/api/github/issues/comments",o),{method:"GET",headers:{Accept:"application/json"}}),i=await ee(s);if(!s.ok||!i)throw new Error(i?.error||s.statusText||"Failed to load issue comments");return i}});async function we(e){try{return await e.json()}catch{return null}}function be(e,t){return e?.error?.trim()||t}function kl(e){return Number.isFinite(e)?e??null:null}function vl(e){return Object.prototype.toString.call(e)==="[object String]"?`${e}`:null}function El(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 sg(e){const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,urlKey:e?.urlKey?.trim()||null}}function ig(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:El(e?.user),authorizedAt:kl(n)}}function Sa(e){if(e?.connected!==!0&&e?.connected!==!1)return null;const t=Array.isArray(e.workspaces)?e.workspaces.map(ig).filter(n=>n!=null):[];return{connected:e.connected,user:El(e.user),organization:sg(e.organization),scope:e.scope?.trim()||void 0,workspaces:e.connected?t:void 0}}function ag(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 cg(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 lg(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:kl(r)??0}}function dg(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 ug(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 fg(e){return e!==0&&e!==1&&e!==2&&e!==3&&e!==4?null:e}function pg(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 hg(e){if(!e)return null;const t=e?.id?.trim(),n=e?.name?.trim();return!t||!n?null:{id:t,name:n,color:pg(e.color)}}function mg(e){return Array.isArray(e)?e.map(hg).filter(t=>t!=null):[]}function Al(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:cg(e.state),assignee:dg(e.assignee),team:ug(e.team),priority:fg(e.priority),labels:mg(e.labels)}}function yg(e){const t=e?.id?.trim();if(!t)return null;const n=e?.body;return{id:t,body:vl(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 Pl(e){const t=Al(e);if(!t)return null;const n=Array.isArray(e?.comments)?e.comments.map(yg).filter(o=>o!=null):[],r=e?.description;return{...t,description:vl(r),comments:n}}function gg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issues:Array.isArray(e.issues)?e.issues.map(Al).filter(n=>n!=null):[],cursor:e.cursor?.trim()||null,hasMore:e.hasMore===!0}}function wg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:Pl(e.issue)}}function bg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,states:Array.isArray(e.states)?e.states.map(lg).filter(n=>n!=null):[]}}function Sg(e){return e?.connected!==!0&&e?.connected!==!1?null:e.connected===!1?{connected:!1}:{connected:!0,issue:Pl(e.issue)}}function Tg(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 Ta(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(Tg).filter(n=>n!=null):[];return{connected:!0,defaultProjectPath:e.defaultProjectPath?.trim()||null,teams:t}}const kg=["already-posted","issue-not-found","not-started","disabled","origin-not-public"];function vg(e){return kg.find(t=>t===e)??null}function ka(e){return e?.sessionComments!==!0&&e?.sessionComments!==!1?null:{sessionComments:e.sessionComments}}function Eg(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=vg(e.skipped);return e.posted===!1&&t?{connected:!0,posted:!1,skipped:t}:null}const Ag=()=>({async authStatus(){const e=await m("/api/linear/auth/status",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=Sa(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear status"));return n},async authStart(e){const t=await m("/api/linear/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{origin:e}:{})}),n=await we(t),r=ag(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to start Linear auth"));return r},async authDisconnect(){const e=await m("/api/linear/auth",{method:"DELETE",headers:{Accept:"application/json"}}),t=await we(e);if(!e.ok)throw new Error(be(t,e.statusText||"Failed to disconnect Linear"));return{removed:t?.removed===!0}},async authActivate(e){const t=await m("/api/linear/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({organizationId:e})}),n=await we(t),r=Sa(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to switch Linear workspace"));return r},async issuesList(e){const t=new URLSearchParams,n=e?.query?.trim(),r=e?.cursor?.trim(),o=e?.status?.trim(),s=e?.assignee?.trim(),i=e?.teamId?.trim(),a=e?.priority?.trim();n&&t.set("query",n),r&&t.set("cursor",r),o&&t.set("status",o),s&&t.set("assignee",s),i&&t.set("teamId",i),a&&t.set("priority",a);const c=t.toString(),l=c?`?${c}`:"",d=await m(`/api/linear/issues/list${l}`,{method:"GET",headers:{Accept:"application/json"}}),u=await we(d),f=gg(u);if(!d.ok||!f)throw new Error(be(u,d.statusText||"Failed to load Linear issues"));return f},async issueGet(e){const t=new URLSearchParams({id:e}),n=await m(`/api/linear/issues/get?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await we(n),o=wg(r);if(!n.ok||!o)throw new Error(be(r,n.statusText||"Failed to load Linear issue"));return o},async issueStates(e){const t=new URLSearchParams({teamId:e}),n=await m(`/api/linear/issues/states?${t.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),r=await we(n),o=bg(r);if(!n.ok||!o)throw new Error(be(r,n.statusText||"Failed to load Linear workflow states"));return o},async issueUpdate(e){const t=await m("/api/linear/issues/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:e.id,stateId:e.stateId})}),n=await we(t),r=Sg(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to update Linear issue"));return r},async mappingGet(){const e=await m("/api/linear/mapping",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=Ta(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear mapping"));return n},async mappingSet(e){const t=await m("/api/linear/mapping",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({defaultProjectPath:e.defaultProjectPath,teamProjectPaths:e.teamProjectPaths})}),n=await we(t),r=Ta(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to save Linear mapping"));return r},async sessionStatusPost(e){const t=await m("/api/linear/session-status",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({kind:e.kind,sessionId:e.sessionId,issueIdentifier:e.issueIdentifier,sessionOrigin:e.sessionOrigin})}),n=await we(t),r=Eg(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to post Linear session status"));return r},async preferencesGet(){const e=await m("/api/linear/preferences",{method:"GET",headers:{Accept:"application/json"}}),t=await we(e),n=ka(t);if(!e.ok||!n)throw new Error(be(t,e.statusText||"Failed to load Linear preferences"));return n},async preferencesSet(e){const t=await m("/api/linear/preferences",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({sessionComments:e.sessionComments})}),n=await we(t),r=ka(n);if(!t.ok||!r)throw new Error(be(n,t.statusText||"Failed to save Linear preferences"));return r}}),st=async e=>await e.json().catch(()=>null),Pg=()=>({async listClients(){const e=await m("/api/client-auth/clients",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load remote clients");return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){const t=await m("/api/client-auth/clients",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??""})}),n=await st(t);if(!t.ok||!n?.client||typeof n.token!="string")throw new Error(n?.error||t.statusText||"Failed to create remote client token");return n},async createPairingSession(e={}){const t=await m("/api/client-auth/pairing/sessions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:e.label??"",...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay=="boolean"?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect=="boolean"?{includeDirect:e.includeDirect}:{}})}),n=await st(t);if(!t.ok||typeof n?.pairing?.secret!="string"||!n?.server)throw new Error(n?.error||t.statusText||"Failed to create pairing session");return n},async listPendingPairings(){const e=await m("/api/client-auth/pairing/sessions",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pending pairings");return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){const e=await m("/api/client-auth/pairing/transports",{method:"GET",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to load pairing transports");return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable!==!1}},async cancelPairing(e){const t=await m(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await st(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to cancel pairing");return{cancelled:n.cancelled===!0}},async revokeClient(e){const t=await m(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Accept:"application/json"}}),n=await st(t);if(!t.ok||!n)throw new Error(n?.error||t.statusText||"Failed to revoke remote client");return n},async purgeRevokedClients(){const e=await m("/api/client-auth/clients",{method:"DELETE",headers:{Accept:"application/json"}}),t=await st(e);if(!e.ok||!t)throw new Error(t?.error||e.statusText||"Failed to clear revoked clients");return t}}),Ig=()=>({api:(...e)=>ye().api(...e),authenticatedAsset:(...e)=>ye().authenticatedAsset(...e),auth:(...e)=>ye().auth(...e),health:(...e)=>ye().health(...e),rawFile:(...e)=>ye().rawFile(...e),sse:(...e)=>ye().sse(...e),websocket:(...e)=>ye().websocket(...e)}),Mg=(e={})=>{const t=e.urls??ys();Kd(t);const n=Ig();return{runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Mm(),git:Ny(),files:Hy({getDirectory:()=>rs.getState().currentDirectory}),settings:Wy(),permissions:$y(),notifications:tg(),github:og({urls:n}),linear:Ag(),push:rg(),clientAuth:Pg(),tools:ng()}},Rg=3e3,va=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},xg=()=>{const e=t=>typeof t=="string"?t.trim():"";return{apiBaseUrl:e(window.__AIWORKER_API_BASE_URL__),clientToken:e(window.__AIWORKER_CLIENT_TOKEN__),localOrigin:e(window.__AIWORKER_LOCAL_ORIGIN__),runtimeHeaders:window.__AIWORKER_RUNTIME_HEADERS__,relayHostId:e(window.__AIWORKER_RELAY_HOST_ID__)}};let cs=Promise.resolve();const Ib=()=>cs,Mb=e=>{const{apiBaseUrl:t,clientToken:n,localOrigin:r,runtimeHeaders:o,relayHostId:s,relay:i}=e??xg(),a=e?null:mc(),c=s||(a?.target==="remote"?a.hostId:""),l=rc({apiBaseUrl:t||void 0,realtimeBaseUrl:t||void 0});return iu({apiBaseUrl:t,runtimeKey:va(t,r)?"local":c?`host:${c}`:null}),Ga(n||null),Ka(o||null),i&&Er({apiBaseUrl:t,clientToken:n||null,requestHeaders:o||null,runtimeKey:s?`host:${s}`:null,relay:i}),Ue.reconnectToRuntimeBaseUrl(),Wr(t||void 0).catch(()=>{}),r&&!va(t,r)&&Object.keys(zr()).length>0&&Xa(r).catch(()=>{}),cc(),cs=i?Promise.resolve():Promise.race([ef(s||void 0).catch(()=>{}),new Promise(d=>{window.setTimeout(d,1e4)})]).then(()=>{Ue.reconnectToRuntimeBaseUrl()}),cs.then(()=>{window.setTimeout(()=>{Ju().catch(()=>{})},Rg)}),Mg({urls:l})};export{ye as $,ue as A,gw as B,bu as C,hh as D,hr as E,yw as F,Be as G,mw as H,dn as I,pb as J,ln as K,ks as L,ou as M,Sc as N,ph as O,Iw as P,zu as Q,pt as R,bc as S,Y as T,qa as U,nw as V,ow as W,Yw as X,Qw as Y,Hh as Z,Cw as _,B as a,Vw as a$,As as a0,Br as a1,Wr as a2,om as a3,zr as a4,Fg as a5,yp as a6,rw as a7,je as a8,Go as a9,cw as aA,lw as aB,iw as aC,Gf as aD,po as aE,gb as aF,Uf as aG,Bf as aH,wb as aI,el as aJ,Kg as aK,qg as aL,Vg as aM,uu as aN,yc as aO,Mf as aP,zh as aQ,Ow as aR,Cc as aS,Gp as aT,xm as aU,zo as aV,it as aW,Op as aX,Qc as aY,au as aZ,hd as a_,Hw as aa,$f as ab,mb as ac,yu as ad,sw as ae,qh as af,fb as ag,Kh as ah,Zn as ai,Pn as aj,Of as ak,Ie as al,Dw as am,du as an,mc as ao,zg as ap,Gh as aq,Bw as ar,Wg as as,$g as at,pw as au,fw as av,dw as aw,uw as ax,_t as ay,lb as az,dp as b,Hm as b$,Ua as b0,ty as b1,ol as b2,gc as b3,Nn as b4,Jw as b5,Cy as b6,Ay as b7,ly as b8,Uy as b9,yy as bA,hy as bB,jm as bC,Um as bD,_m as bE,Jm as bF,Eb as bG,Pb as bH,vy as bI,ma as bJ,ha as bK,iy as bL,sy as bM,oy as bN,Ty as bO,qm as bP,ay as bQ,Py as bR,Sl as bS,ny as bT,Ey as bU,Xm as bV,py as bW,xy as bX,Sb as bY,Tb as bZ,Ry as b_,Om as ba,uy as bb,Iy as bc,My as bd,Oy as be,Dy as bf,cy as bg,fy as bh,ry as bi,gy as bj,ya as bk,Ym as bl,by as bm,ga as bn,Qm as bo,Ab as bp,dy as bq,Nm as br,vb as bs,my as bt,Fy as bu,Sy as bv,Vm as bw,kb as bx,Fm as by,Bm as bz,Mb as c,qw as c$,Km as c0,ky as c1,zm as c2,gl as c3,$m as c4,Ly as c5,bl as c6,_y as c7,Wm as c8,wl as c9,fo as cA,hb as cB,bb as cC,Lm as cD,Rm as cE,aw as cF,ve as cG,Xw as cH,eb as cI,ob as cJ,tb as cK,Zw as cL,nb as cM,rl as cN,rb as cO,Gw as cP,Kw as cQ,Fp as cR,Ww as cS,Ds as cT,yb as cU,tw as cV,Fw as cW,Pc as cX,Lw as cY,_w as cZ,jw as c_,Gm as ca,wy as cb,jy as cc,de as cd,Uw as ce,Lf as cf,lc as cg,zw as ch,Mw as ci,Rw as cj,le as ck,Lu as cl,$u as cm,Vu as cn,Wu as co,vs as cp,Hu as cq,xw as cr,Ew as cs,Pw as ct,Aw as cu,_u as cv,Zu as cw,Hg as cx,$w as cy,er as cz,Bn as d,Pt as d0,jf as d1,Nf as d2,cb as d3,ab as d4,Fu as d5,Ru as d6,Sw as d7,Tw as d8,hw as d9,Je as dA,ih as da,qr as db,Nw as dc,_f as dd,Ff as de,Or as df,vp as dg,kp as dh,oh as di,Kr as dj,lp as dk,Jg as dl,Qg as dm,Zg as dn,Yg as dp,Xg as dq,ew as dr,ib as ds,bw as dt,sb as du,mh as dv,Ng as dw,Bg as dx,ww as dy,vw as dz,$r as e,jg as f,Ib as g,Ug as h,Fc as i,fs as j,at as k,kw as l,rs as m,cp as n,Gr as o,Pu as p,Sr as q,m as r,Er as s,Gg as t,Se as u,pc as v,Ue as w,ub as x,db as y,gt as z};
|