@algochad/archcoder 2.0.2 → 2.0.4

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-HTKwyaEM.js","assets/vendor--DbVqbJpV.css","assets/main-B6oiMU86.js","assets/main-5QGBtzdq.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-HTKwyaEM.js","assets/vendor--DbVqbJpV.css","assets/main-DAvs5z8b.js","assets/main-5QGBtzdq.css"])))=>i.map(i=>d[i]);
2
2
  import{_ as qe,c as oi,a as Me,d as ve,p as tt,b as rt,e as Ra,R,X as nl,K as ol,M as sl,N as il,f as al,A as cl,g as ll,i as dl,s as ul,E as fl,j as pl,k as ml,l as gl,m as yl,n as hl,H as Sl,T as wl,o as bl,q as Ml,t as vl,r as Dl,F as Il,u as ht}from"./vendor-.bun-HTKwyaEM.js";(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function e(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(o){if(o.ep)return;o.ep=!0;const s=e(o);fetch(o.href,s)}})();const Oa=1,pr=1,Al="/api/terminal/input-ws",Pl=1200,Tl=1e3,kl=3e4,Cl=250,El=2e4,xl=5e3,xo="__openchamberTerminalInputWsState",_l=new TextEncoder,Rl=new TextDecoder,ja=t=>{if(/^wss?:\/\//i.test(t))return t;if(/^https?:\/\//i.test(t)){const n=new URL(t);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}if(typeof window>"u")return"";const r=t.startsWith("/")?t:`/${t}`;return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${r}`},si=t=>{const r=_l.encode(JSON.stringify(t)),e=new Uint8Array(r.length+1);return e[0]=Oa,e.set(r,1),e},Fa=t=>t?((t.transports??[]).includes("ws")||t.preferred==="ws")&&typeof t.ws?.path=="string"&&t.ws.path.length>0:!1;class La{socket=null;socketUrl="";boundSessionId=null;openPromise=null;reconnectTimeout=null;reconnectAttempt=0;keepaliveInterval=null;closed=!1;configure(r){if(r){if(this.socketUrl===r){if(this.closed=!1,this.isConnectedOrConnecting())return;this.ensureConnected();return}this.socketUrl=r,this.closed=!1,this.resetConnection(),this.ensureConnected()}}async sendInput(r,e){if(!r||!e||this.closed||!this.socketUrl)return!1;const n=await this.getOpenSocket(Pl);if(!n||n.readyState!==pr)return!1;try{return this.boundSessionId!==r&&(n.send(si({t:"b",s:r,v:1})),this.boundSessionId=r),n.send(e),!0}catch{return this.handleSocketFailure(),!1}}unbindSession(r){r&&this.boundSessionId===r&&(this.boundSessionId=null)}close(){this.closed=!0,this.clearReconnectTimeout(),this.resetConnection(),this.socketUrl=""}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(r){return this.closed||r&&this.socketUrl!==r?!1:this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)?!0:this.openPromise!==null}sendControl(r){if(!this.socket||this.socket.readyState!==pr)return!1;try{return this.socket.send(si(r)),!0}catch{return this.handleSocketFailure(),!1}}startKeepalive(){this.stopKeepalive(),this.keepaliveInterval=setInterval(()=>{this.closed||this.sendControl({t:"p",v:1})},El)}stopKeepalive(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=null)}scheduleReconnect(){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;const r=Math.min(Tl*Math.pow(2,this.reconnectAttempt),kl),e=Math.floor(Math.random()*Cl),n=r+e;this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempt+=1,this.ensureConnected()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null)}async getOpenSocket(r){if(this.socket&&this.socket.readyState===pr)return this.socket;if(this.ensureConnected(),this.socket&&this.socket.readyState===pr)return this.socket;const e=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(n=>{setTimeout(()=>n(null),r)})]);return e&&e.readyState===pr?e:this.socket&&this.socket.readyState===pr?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)||this.openPromise||(this.clearReconnectTimeout(),this.openPromise=new Promise(r=>{let e=!1,n=null;const o=s=>{e||(e=!0,n&&(clearTimeout(n),n=null),this.openPromise=null,r(s))};try{const s=new WebSocket(this.socketUrl);s.binaryType="arraybuffer",s.onopen=()=>{this.socket=s,this.reconnectAttempt=0,this.startKeepalive(),o(s)},s.onmessage=i=>{this.handleSocketMessage(i.data)},s.onclose=()=>{this.socket===s&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect()),o(null)},this.socket=s,n=setTimeout(()=>{s.readyState===WebSocket.CONNECTING&&(s.close(),o(null))},xl)}catch{o(null),this.closed||this.scheduleReconnect()}}))}async handleSocketMessage(r){const e=await this.asUint8Array(r);if(!(!e||e.length<2)&&e[0]===Oa)try{const n=JSON.parse(Rl.decode(e.subarray(1)));if(n.t==="po")return;n.t==="e"&&((n.c==="NOT_BOUND"||n.c==="SESSION_NOT_FOUND")&&(this.boundSessionId=null),n.f===!0&&this.handleSocketFailure())}catch{this.handleSocketFailure()}}async asUint8Array(r){if(r instanceof ArrayBuffer)return new Uint8Array(r);if(r instanceof Uint8Array)return r;if(typeof Blob<"u"&&r instanceof Blob){const e=await r.arrayBuffer();return new Uint8Array(e)}return null}handleSocketFailure(){this.boundSessionId=null,this.resetConnection(),this.scheduleReconnect()}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){const r=this.socket;this.socket=null,r.onopen=null,r.onmessage=null,r.onerror=null,r.onclose=null,(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close()}this.boundSessionId=null}}const tr=()=>{const t=globalThis;return t[xo]||(t[xo]={capability:null,manager:null}),t[xo]},Na=t=>{const r=tr();if(r.capability=t??null,!Fa(r.capability)){r.manager?.close(),r.manager=null;return}const e=r.capability?.ws?.path;if(!e)return;const n=ja(e);n&&(r.manager||(r.manager=new La),r.manager.configure(n))},Ol=async(t,r)=>{const e=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain"},body:r});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to send input"}));throw new Error(n.error||"Failed to send terminal input")}};async function jl(t){const r=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t.cwd,cols:t.cols||80,rows:t.rows||24})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}const e=await r.json();return Na(e.capabilities?.input),e}function Fl(t,r,e,n={}){const{maxRetries:o=3,initialRetryDelay:s=1e3,maxRetryDelay:i=8e3,connectionTimeout:a=1e4}=n;let l=null,c=0,d=null,u=null,f=!1,m=!1,p=!1;const g=()=>{d&&(clearTimeout(d),d=null),u&&(clearTimeout(u),u=null)},S=()=>{f=!0,g(),l&&(l.close(),l=null)},h=()=>{if(!(f||p)){if(l&&l.readyState!==EventSource.CLOSED){console.warn("Attempted to create duplicate EventSource, skipping");return}m=!1,l=new EventSource(`/api/terminal/${t}/stream`),u=setTimeout(()=>{!m&&l?.readyState!==EventSource.OPEN&&(console.error("Terminal connection timeout"),l?.close(),v(new Error("Connection timeout"),!1))},a),l.onopen=()=>{m||(m=!0,c=0,g(),r({type:"connected"}))},l.onmessage=b=>{try{const D=JSON.parse(b.data);D.type==="exit"&&(tr().manager?.unbindSession(t),p=!0,S()),r(D)}catch(D){console.error("Failed to parse terminal event:",D),e?.(D,!1)}},l.onerror=b=>{console.error("Terminal stream error:",b,"readyState:",l?.readyState),g();const D=p||l?.readyState===EventSource.CLOSED;l?.close(),l=null,p||v(new Error("Terminal stream connection error"),D)}}},v=(b,D)=>{if(!(f||p))if(c<o&&!D){c++;const I=Math.min(s*Math.pow(2,c-1),i);console.log(`Reconnecting to terminal stream (attempt ${c}/${o}) in ${I}ms`),r({type:"reconnecting",attempt:c,maxAttempts:o}),d=setTimeout(()=>{!f&&!p&&h()},I)}else console.error(`Terminal connection failed after ${c} attempts`),e?.(b,!0),S()};return h(),S}async function Ll(t,r){const e=tr();e.manager&&await e.manager.sendInput(t,r)||await Ol(t,r)}async function Nl(t,r,e){const n=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:r,rows:e})});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(o.error||"Failed to resize terminal")}}async function $l(t){tr().manager?.unbindSession(t);const r=await fetch(`/api/terminal/${t}`,{method:"DELETE"});if(!r.ok){const e=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(e.error||"Failed to close terminal")}}async function Ul(t,r){tr().manager?.unbindSession(t);const e=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r.cwd,cols:r.cols??80,rows:r.rows??24})});if(!e.ok){const o=await e.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(o.error||"Failed to restart terminal")}const n=await e.json();return Na(n.capabilities?.input),n}async function Bl(t){const r=await fetch("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const e=await r.json().catch(()=>({error:"Failed to force kill terminal"}));throw new Error(e.error||"Failed to force kill terminal")}t.sessionId&&tr().manager?.unbindSession(t.sessionId)}function Ug(){const t=tr();if(t.capability&&!Fa(t.capability))return;const r=t.capability?.ws?.path??Al,e=ja(r);e&&(t.manager||(t.manager=new La),!t.manager.isConnectedOrConnecting(e)&&(t.manager.configure(e),t.manager.prime()))}const zl=t=>{const r=t?.retry;return{maxRetries:r?.maxRetries??3,initialRetryDelay:r?.initialDelayMs??1e3,maxRetryDelay:r?.maxDelayMs??8e3,connectionTimeout:t?.connectionTimeoutMs??1e4}},Hl=()=>({async createSession(t){return jl(t)},connect(t,r,e){const n=Fl(t,r.onEvent,r.onError,zl(e));return{close:()=>n()}},async sendInput(t,r){await Ll(t,r)},async resize(t){await Nl(t.sessionId,t.cols,t.rows)},async close(t){await $l(t)},async restartSession(t,r){return Ul(t,{cwd:r.cwd??"",cols:r.cols,rows:r.rows})},async forceKill(t){await Bl(t)}}),Wl=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_DESKTOP_SERVER__?.origin;return t||window.location.origin},Y="/api/git",Gl=1200,ql=5e3,ii=new Map,Dn=new Map,ai=new Map,In=new Map,$a=t=>t.trim();function X(t,r,e){const n=new URL(t,Wl());if(r&&n.searchParams.set("directory",r),e)for(const[o,s]of Object.entries(e))s!==void 0&&n.searchParams.set(o,String(s));return n.toString()}async function Ua(t){const r=$a(t),e=Date.now(),n=ai.get(r);if(n&&n.expiresAt>e)return n.value;const o=In.get(r);if(o)return o;const s=(async()=>{const i=await fetch(X(`${Y}/check`,t));if(!i.ok)throw new Error(`Failed to check git repository: ${i.statusText}`);const l=!!(await i.json()).isGitRepository;return ai.set(r,{value:l,expiresAt:Date.now()+ql}),l})();In.set(r,s);try{return await s}finally{In.get(r)===s&&In.delete(r)}}async function Ba(t){const r=$a(t),e=Date.now(),n=ii.get(r);if(n&&n.expiresAt>e)return n.value;const o=Dn.get(r);if(o)return o;const s=(async()=>{const i=await fetch(X(`${Y}/status`,t));if(!i.ok)throw new Error(`Failed to get git status: ${i.statusText}`);const a=await i.json();return ii.set(r,{value:a,expiresAt:Date.now()+Gl}),a})();Dn.set(r,s);try{return await s}finally{Dn.get(r)===s&&Dn.delete(r)}}async function Vl(t,r){const{path:e,staged:n,contextLines:o}=r;if(!e)throw new Error("path is required to fetch git diff");const s=await fetch(X(`${Y}/diff`,t,{path:e,staged:n?"true":void 0,context:o}));if(!s.ok)throw new Error(`Failed to get git diff: ${s.statusText}`);return s.json()}async function Kl(t,r){const{path:e,staged:n}=r;if(!e)throw new Error("path is required to fetch git file diff");const o=await fetch(X(`${Y}/file-diff`,t,{path:e,staged:n?"true":void 0}));if(!o.ok)throw new Error(`Failed to get git file diff: ${o.statusText}`);return o.json()}async function Jl(t,r){if(!r)throw new Error("path is required to revert git changes");const e=await fetch(X(`${Y}/revert`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to revert git changes")}}async function Ql(t){if(!t)return!1;const r=await fetch(X(`${Y}/worktree-type`,t));if(!r.ok)throw new Error(`Failed to detect worktree type: ${r.statusText}`);return!!(await r.json()).linked}async function za(t){const r=await fetch(X(`${Y}/branches`,t));if(!r.ok)throw new Error(`Failed to get branches: ${r.statusText}`);return r.json()}async function Yl(t,r){if(!r?.branch)throw new Error("branch is required to delete a branch");const e=await fetch(X(`${Y}/branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to delete branch")}return e.json()}async function Ha(t,r){if(!r?.branch)throw new Error("branch is required to delete remote branch");const e=await fetch(X(`${Y}/remote-branches`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to delete remote branch")}return e.json()}async function Xl(t,r){const e=r?.remote?.trim();if(!e)throw new Error("remote is required to remove a remote");const n=await fetch(X(`${Y}/remotes`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:e})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to remove remote")}return n.json()}async function Zl(t,r,e){if(!Array.isArray(r)||r.length===0)throw new Error("No files provided to generate commit message");const n={files:r};e?.zenModel&&(n.zenModel=e.zenModel),e?.providerId&&(n.providerId=e.providerId),e?.modelId&&(n.modelId=e.modelId);const o=await fetch(X(`${Y}/commit-message`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const l=await o.json().catch(()=>({error:o.statusText}));console.error("[git-generation][browser] http error",{status:o.status,statusText:o.statusText,error:l});const c=typeof l?.traceId=="string"&&l.traceId?` (traceId: ${l.traceId})`:"";throw new Error(`${l.error||"Failed to generate commit message"}${c}`)}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(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):[];return{message:{subject:i,highlights:a}}}async function ed(t,r){const{base:e,head:n,context:o,zenModel:s,providerId:i,modelId:a}=r;if(!e||!n)throw new Error("base and head are required");const l={base:e,head:n};o?.trim()&&(l.context=o.trim()),s&&(l.zenModel=s),i&&(l.providerId=i),a&&(l.modelId=a);const c=await fetch(X(`${Y}/pr-description`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!c.ok){const m=await c.json().catch(()=>({error:c.statusText}));throw new Error(m.error||"Failed to generate PR description")}const d=await c.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 os(t){const r=await fetch(X(`${Y}/worktrees`,t));if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to list worktrees")}return r.json()}async function ss(t,r){const e=await fetch(X(`${Y}/worktrees/validate`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r??{})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to validate worktree")}return e.json()}async function Wa(t){const r=await fetch(X(`${Y}/worktrees/bootstrap-status`,t));if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to get worktree bootstrap status")}return r.json()}async function td(t,r){const e=await fetch(X(`${Y}/worktrees/preview`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r??{})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to preview worktree")}return e.json()}async function is(t,r){const e=await fetch(X(`${Y}/worktrees`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r??{})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to create worktree")}return e.json()}async function as(t,r){const e=await fetch(X(`${Y}/worktrees`,t),{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(r??{})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to delete worktree")}return e.json()}async function rd(t,r,e={}){const n=await fetch(X(`${Y}/commit`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:r,addAll:e.addAll??!1,files:e.files})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create commit")}return n.json()}async function nd(t,r={}){const e=await fetch(X(`${Y}/push`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to push")}return e.json()}async function od(t,r={}){const e=await fetch(X(`${Y}/pull`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to pull")}return e.json()}async function sd(t,r={}){const e=await fetch(X(`${Y}/fetch`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to fetch")}return e.json()}async function id(t,r){const e=await fetch(X(`${Y}/checkout`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to checkout branch")}return e.json()}async function ad(t,r,e){const n=await fetch(X(`${Y}/branches`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r,startPoint:e})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to create branch")}return n.json()}async function cd(t,r,e){const n=await fetch(X(`${Y}/branches/rename`,t),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:r,newName:e})});if(!n.ok){const o=await n.json().catch(()=>({error:n.statusText}));throw new Error(o.error||"Failed to rename branch")}return n.json()}async function Ga(t,r={}){const e=await fetch(X(`${Y}/log`,t,{maxCount:r.maxCount,from:r.from,to:r.to,file:r.file}));if(!e.ok)throw new Error(`Failed to get git log: ${e.statusText}`);return e.json()}async function qa(t,r){const e=await fetch(X(`${Y}/commit-files`,t,{hash:r}));if(!e.ok)throw new Error(`Failed to get commit files: ${e.statusText}`);return e.json()}async function Va(){const t=await fetch(X(`${Y}/identities`,void 0));if(!t.ok)throw new Error(`Failed to get git identities: ${t.statusText}`);return t.json()}async function Ka(t){const r=await fetch(X(`${Y}/identities`,void 0),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to create git identity")}return r.json()}async function Ja(t,r){const e=await fetch(X(`${Y}/identities/${t}`,void 0),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to update git identity")}return e.json()}async function Qa(t){const r=await fetch(X(`${Y}/identities/${t}`,void 0),{method:"DELETE"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to delete git identity")}}async function ld(t){if(!t)return null;const r=await fetch(X(`${Y}/current-identity`,t));if(!r.ok)throw new Error(`Failed to get current git identity: ${r.statusText}`);const e=await r.json();return e?{userName:e.userName??null,userEmail:e.userEmail??null,sshCommand:e.sshCommand??null}:null}async function dd(t){if(!t)return!1;const r=await fetch(X(`${Y}/has-local-identity`,t));if(!r.ok)throw new Error(`Failed to check local identity: ${r.statusText}`);return(await r.json().catch(()=>null))?.hasLocalIdentity===!0}async function ud(){const t=await fetch(X(`${Y}/global-identity`,void 0));if(!t.ok)throw new Error(`Failed to get global git identity: ${t.statusText}`);const r=await t.json();return!r||!r.userName&&!r.userEmail?null:{userName:r.userName??null,userEmail:r.userEmail??null,sshCommand:r.sshCommand??null}}async function fd(t,r){const e=await fetch(X(`${Y}/set-identity`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:r})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to set git identity")}return e.json()}async function pd(){const t=await fetch(X(`${Y}/discover-credentials`,void 0));if(!t.ok)throw new Error(`Failed to discover git credentials: ${t.statusText}`);return t.json()}async function md(t){const r=await fetch(X(`${Y}/remotes`,t));if(!r.ok)throw new Error(`Failed to get remotes: ${r.statusText}`);return r.json()}async function gd(t,r){const e=await fetch(X(`${Y}/rebase`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to rebase")}return e.json()}async function yd(t){const r=await fetch(X(`${Y}/rebase/abort`,t),{method:"POST"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to abort rebase")}return r.json()}async function hd(t,r){const e=await fetch(X(`${Y}/merge`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to merge")}return e.json()}async function Sd(t){const r=await fetch(X(`${Y}/merge/abort`,t),{method:"POST"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to abort merge")}return r.json()}async function wd(t){const r=await fetch(X(`${Y}/rebase/continue`,t),{method:"POST"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to continue rebase")}return r.json()}async function bd(t){const r=await fetch(X(`${Y}/merge/continue`,t),{method:"POST"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to continue merge")}return r.json()}async function Md(t,r){const e=await fetch(X(`${Y}/stash`,t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r||{})});if(!e.ok){const n=await e.json().catch(()=>({error:e.statusText}));throw new Error(n.error||"Failed to stash")}return e.json()}async function vd(t){const r=await fetch(X(`${Y}/stash/pop`,t),{method:"POST"});if(!r.ok){const e=await r.json().catch(()=>({error:r.statusText}));throw new Error(e.error||"Failed to pop stash")}return r.json()}async function Ya(t){const r=await fetch(X(`${Y}/conflict-details`,t));if(!r.ok)throw new Error(`Failed to get conflict details: ${r.statusText}`);return r.json()}const Dd=()=>({checkIsGitRepository:Ua,getGitStatus:Ba,getGitDiff:Vl,getGitFileDiff:Kl,revertGitFile:Jl,isLinkedWorktree:Ql,getGitBranches:za,deleteGitBranch:Yl,deleteRemoteBranch:Ha,removeRemote:Xl,generateCommitMessage:Zl,generatePullRequestDescription:ed,listGitWorktrees:os,validateGitWorktree:ss,createGitWorktree:is,deleteGitWorktree:as,createGitCommit(t,r,e){return rd(t,r,e)},gitPush:nd,gitPull:od,gitFetch:sd,checkoutBranch:id,createBranch:ad,renameBranch:cd,getGitLog(t,r){return Ga(t,r)},getCommitFiles:qa,getCurrentGitIdentity:ld,hasLocalIdentity:dd,setGitIdentity:fd,getGitIdentities:Va,createGitIdentity:Ka,updateGitIdentity:Ja,deleteGitIdentity:Qa,getRemotes:md,rebase:gd,abortRebase:yd,continueRebase:wd,merge:hd,abortMerge:Sd,continueMerge:bd,stash:Md,stashPop:vd,getConflictDetails:Ya,worktree:{list:os,validate:ss,create:is,remove:as}}),Ne=t=>t.replace(/\\/g,"/"),Id=(t,r)=>{const e=Ne(r?.directory||r?.path||t),n=Array.isArray(r?.entries)?r.entries:[];return{directory:e,entries:n.filter(o=>!!(o&&typeof o.name=="string"&&typeof o.path=="string")).map(o=>({name:o.name,path:Ne(o.path),isDirectory:!!o.isDirectory}))}},Ad=()=>({async listDirectory(t){const r=Ne(t),e=new URLSearchParams;r&&e.set("path",r);const n=await fetch(`/api/fs/list${e.toString()?`?${e.toString()}`:""}`);if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to list directory")}const o=await n.json();return Id(r,o)},async search(t){const r=new URLSearchParams,e=Ne(t.directory);e&&r.set("directory",e),r.set("query",t.query),r.set("dirs","false"),r.set("type","file"),typeof t.maxResults=="number"&&Number.isFinite(t.maxResults)&&r.set("limit",String(t.maxResults));const n=await fetch(`/api/find/file?${r.toString()}`);if(!n.ok){const i=await n.json().catch(()=>({error:n.statusText}));throw new Error(i.error||"Failed to search files")}const o=await n.json();return(Array.isArray(o)?o:[]).map(i=>({path:Ne(`${e}/${i}`),preview:[Ne(i)]}))},async createDirectory(t){const r=Ne(t),e=await fetch("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to create directory")}const n=await e.json();return{success:!!n?.success,path:typeof n?.path=="string"?Ne(n.path):r}},async readFile(t){const r=Ne(t),e=await fetch(`/api/fs/read?path=${encodeURIComponent(r)}`);if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to read file")}return{content:await e.text(),path:r}},async writeFile(t,r){const e=Ne(t),n=await fetch("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,content:r})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Failed to write file")}const o=await n.json().catch(()=>({}));return{success:!!o.success,path:typeof o.path=="string"?Ne(o.path):e}},async delete(t){const r=Ne(t),e=await fetch("/api/fs/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to delete file")}return{success:!!(await e.json().catch(()=>({}))).success}},async rename(t,r){const e=await fetch("/api/fs/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPath:t,newPath:r})});if(!e.ok){const o=await e.json().catch(()=>({error:e.statusText}));throw new Error(o.error||"Failed to rename file")}const n=await e.json().catch(()=>({}));return{success:!!n.success,path:typeof n.path=="string"?Ne(n.path):r}},async revealPath(t){const r=await fetch("/api/fs/reveal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ne(t)})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to reveal path")}return{success:!!(await r.json().catch(()=>({}))).success}}}),ci="/api/config/settings",Pd="/api/config/reload",li=t=>!t||typeof t!="object"?{}:t,Td=()=>({async load(){const t=await fetch(ci,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load settings: ${t.statusText}`);return{settings:li(await t.json().catch(()=>({}))),source:"web"}},async save(t){const r=await fetch(ci,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||"Failed to save settings")}return li(await r.json().catch(()=>({})))},async restartOpenCode(){const t=await fetch(Pd,{method:"POST"});if(!t.ok){const r=await t.json().catch(()=>({error:t.statusText}));throw new Error(r.error||"Failed to restart OpenCode")}return{restarted:!0}}}),kd=()=>({async requestDirectoryAccess(t){return{success:!0,path:t.path}},async startAccessingDirectory(t){return{success:!0}},async stopAccessingDirectory(t){return{success:!0}}}),Cd=async t=>{if(typeof Notification>"u")return console.info("Notifications not supported in this environment",t),!1;if(Notification.permission==="default"&&await Notification.requestPermission()!=="granted"||Notification.permission!=="granted")return console.warn("Notification permission not granted"),!1;try{return new Notification(t?.title??"ArchCoder",{body:t?.body,tag:t?.tag}),!0}catch(r){return console.warn("Failed to send notification",r),!1}},Ed=async t=>{if(typeof window>"u")return!1;const r=window.__TAURI__;if(!r?.core?.invoke)return!1;try{return await r.core.invoke("desktop_notify",{payload:{title:t?.title,body:t?.body,tag:t?.tag}}),!0}catch(e){return console.warn("Failed to send native notification (tauri)",e),!1}},xd=()=>({async notifyAgentCompletion(t){return await Ed(t)||Cd(t)},canNotify:()=>typeof window<"u"&&window.__TAURI__?.core?.invoke?!0:typeof Notification<"u"?Notification.permission==="granted":!1}),_d=()=>({async getAvailableTools(){const t=await fetch("/api/experimental/tool/ids");if(!t.ok)throw new Error(`Tools API returned ${t.status} ${t.statusText}`);const r=await t.json();if(!Array.isArray(r))throw new Error("Tools API returned invalid data format");return r.filter(e=>typeof e=="string"&&e!=="invalid").sort()}}),An=async(t,r)=>{try{const e=await fetch(t,{...r,credentials:"include",headers:{Accept:"application/json",...r?.headers??{}}});return e.ok?await e.json():null}catch{return null}},Rd=()=>({async getVapidPublicKey(){return An("/api/push/vapid-public-key")},async subscribe(t){return An("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async unsubscribe(t){return An("/api/push/subscribe",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async setVisibility(t){return An("/api/push/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0})}}),Re=async t=>await t.json().catch(()=>null),Od=()=>({async authStatus(){const t=await fetch("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),r=await Re(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to load GitHub status");return r},async authStart(){const t=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),r=await Re(t);if(!t.ok||!r||!("deviceCode"in r))throw new Error(r?.error||t.statusText||"Failed to start GitHub auth");return r},async authComplete(t){const r=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:t})}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to complete GitHub auth");return e},async authDisconnect(){const t=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}}),r=await Re(t);if(!t.ok)throw new Error(r?.error||t.statusText||"Failed to disconnect GitHub");return{removed:!!r?.removed}},async authActivate(t){const r=await fetch("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:t})}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to activate GitHub account");return e},async me(){const t=await fetch("/api/github/me",{method:"GET",headers:{Accept:"application/json"}}),r=await Re(t);if(!t.ok||!r)throw new Error(r?.error||t.statusText||"Failed to fetch GitHub user");return r},async prStatus(t,r,e){const n=new URLSearchParams({directory:t,branch:r,...e?{remote:e}:{}}),o=await fetch(`/api/github/pr/status?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}}),s=await Re(o);if(!o.ok||!s)throw new Error(s?.error||o.statusText||"Failed to load PR status");return s},async prCreate(t){const r=await fetch("/api/github/pr/create",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to create PR");return e},async prUpdate(t){const r=await fetch("/api/github/pr/update",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to update PR");return e},async prMerge(t){const r=await fetch("/api/github/pr/merge",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to merge PR");return e},async prReady(t){const r=await fetch("/api/github/pr/ready",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),e=await Re(r);if(!r.ok||!e)throw new Error(e?.error||r.statusText||"Failed to mark PR ready");return e},async prsList(t,r){const e=r?.page??1,n=await fetch(`/api/github/pulls/list?directory=${encodeURIComponent(t)}&page=${encodeURIComponent(String(e))}`,{method:"GET",headers:{Accept:"application/json"}}),o=await Re(n);if(!n.ok||!o)throw new Error(o?.error||n.statusText||"Failed to load pull requests");return o},async prContext(t,r,e){const n=new URL("/api/github/pulls/context",window.location.origin);n.searchParams.set("directory",t),n.searchParams.set("number",String(r)),e?.includeDiff&&n.searchParams.set("diff","1"),e?.includeCheckDetails&&n.searchParams.set("checkDetails","1");const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}}),s=await Re(o);if(!o.ok||!s)throw new Error(s?.error||o.statusText||"Failed to load pull request context");return s},async issuesList(t,r){const e=r?.page??1,n=await fetch(`/api/github/issues/list?directory=${encodeURIComponent(t)}&page=${encodeURIComponent(String(e))}`,{method:"GET",headers:{Accept:"application/json"}}),o=await Re(n);if(!n.ok||!o)throw new Error(o?.error||n.statusText||"Failed to load issues");return o},async issueGet(t,r){const e=await fetch(`/api/github/issues/get?directory=${encodeURIComponent(t)}&number=${encodeURIComponent(String(r))}`,{method:"GET",headers:{Accept:"application/json"}}),n=await Re(e);if(!e.ok||!n)throw new Error(n?.error||e.statusText||"Failed to load issue");return n},async issueComments(t,r){const e=await fetch(`/api/github/issues/comments?directory=${encodeURIComponent(t)}&number=${encodeURIComponent(String(r))}`,{method:"GET",headers:{Accept:"application/json"}}),n=await Re(e);if(!e.ok||!n)throw new Error(n?.error||e.statusText||"Failed to load issue comments");return n}}),jd=()=>({runtime:{platform:"web",isDesktop:!1,isVSCode:!1,label:"web"},terminal:Hl(),git:Dd(),files:Ad(),settings:Td(),permissions:kd(),notifications:xd(),github:Od(),push:Rd(),tools:_d()});function Fd(t={}){const{immediate:r=!1,onNeedRefresh:e,onOfflineReady:n,onRegistered:o,onRegisteredSW:s,onRegisterError:i}=t;let a,l;const c=async(u=!0)=>{await l};async function d(){if("serviceWorker"in navigator){if(a=await qe(async()=>{const{Workbox:u}=await import("./vendor-.bun-HTKwyaEM.js").then(f=>f.fD);return{Workbox:u}},__vite__mapDeps([0,1])).then(({Workbox:u})=>new u("/sw.js",{scope:"/",type:"classic"})).catch(u=>{i?.(u)}),!a)return;a.addEventListener("activated",u=>{(u.isUpdate||u.isExternal)&&window.location.reload()}),a.addEventListener("installed",u=>{u.isUpdate||n?.()}),a.register({immediate:r}).then(u=>{s?s("/sw.js",u):o?.(u)}).catch(u=>{i?.(u)})}}return l=d(),c}const Ke=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",di=t=>{const r=t.trim();if(!r)return null;try{return new URL(r).origin}catch{try{return new URL(r.endsWith("/")?r:`${r}/`).origin}catch{return null}}},ui=t=>{const r=t.trim();if(!r)return null;try{return new URL(r)}catch{try{return new URL(r.endsWith("/")?r:`${r}/`)}catch{return null}}},Ld=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),fi=t=>{const r=Ld(t);return r==="localhost"||r==="127.0.0.1"||r==="::1"},dt=()=>{if(typeof window>"u")return!1;if(rr())return!0;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",r=ui(t),e=ui(window.location.origin);if(r&&e){if(r.origin===e.origin)return!0;const s=r.port||(r.protocol==="https:"?"443":"80"),i=e.port||(e.protocol==="https:"?"443":"80");return r.protocol===e.protocol&&s===i&&fi(r.hostname)&&fi(e.hostname)}const n=di(t),o=di(window.location.origin)||window.location.origin;return!!(n&&o&&n===o)},Nd=()=>typeof window>"u"?!1:!!(typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"&&window.__OPENCHAMBER_LOCAL_ORIGIN__.length>0||Ke()||rr()),rr=()=>typeof window>"u"?!1:typeof window.electronAPI<"u",nr=()=>typeof window>"u"?!1:(window.__ARCHCODER_RUNTIME_APIS__||window.__OPENCHAMBER_RUNTIME_APIS__)?.runtime?.isVSCode===!0,$d=()=>{if(typeof window>"u")return!1;const r=(window.__ARCHCODER_RUNTIME_APIS__||window.__OPENCHAMBER_RUNTIME_APIS__)?.runtime?.platform;return r==="web"?!0:r==="desktop"||r==="vscode"?!1:!nr()},mo=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Ud=async t=>{if(rr())try{const r=await window.electronAPI?.dialog?.showOpenDialog({title:"Select Working Directory",properties:["openDirectory"]});if(r&&!r.canceled&&r.filePaths.length>0)return{success:!0,path:r.filePaths[0]}}catch(r){console.warn("Failed to request directory access (electron)",r)}if(Ke()&&dt())try{const e=await window.__TAURI__?.dialog?.open?.({directory:!0,multiple:!1,title:"Select Working Directory"});if(e&&typeof e=="string")return{success:!0,path:e}}catch(r){console.warn("Failed to request directory access (tauri)",r)}return{success:!0,path:t}},Bd=async t=>{if(rr())try{const r=await window.electronAPI?.dialog?.showOpenDialog({title:"Select File",filters:t?.filters,properties:["openFile"]});if(r&&!r.canceled&&r.filePaths.length>0)return{success:!0,path:r.filePaths[0]}}catch(r){console.warn("Failed to request file access (electron)",r)}if(Ke()&&dt())try{const e=await window.__TAURI__?.dialog?.open?.({directory:!1,multiple:!1,title:"Select File",...t?.filters?{filters:t.filters}:{}});if(e&&typeof e=="string")return{success:!0,path:e}}catch(r){console.warn("Failed to request file access (tauri)",r)}return{success:!1,error:"Native file picker not available"}},zd=async t=>({success:!0}),Hd=async t=>({success:!0}),Wd=async()=>{if(!Ke()||!dt())return null;try{return await window.__TAURI__?.core?.invoke?.("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates (tauri)",t),null}},Gd=async t=>{if(!Ke()||!dt())return!1;const r=window.__TAURI__;let e=null,n=0,o;try{return typeof t=="function"&&r?.event?.listen&&(e=await r.event.listen("archcoder:update-progress",s=>{const i=s?.payload;if(!i||typeof i!="object")return;const a=i,l=typeof a.event=="string"?a.event:null,c=a.data&&typeof a.data=="object"?a.data:null;if(l==="Started"){n=0,o=typeof c?.contentLength=="number"?c.contentLength:void 0,t({downloaded:n,total:o});return}if(l==="Progress"){const d=c?.downloaded,u=c?.total;typeof d=="number"&&(n=d),typeof u=="number"&&(o=u),t({downloaded:n,total:o});return}l==="Finished"&&t({downloaded:n,total:o})})),await r?.core?.invoke?.("desktop_download_and_install_update"),!0}catch(s){return console.warn("Failed to download update (tauri)",s),!1}finally{if(e)try{const s=e();s instanceof Promise&&await s}catch{}}},qd=async()=>{if(!Ke()||!dt())return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_restart"),!0}catch(t){return console.warn("Failed to restart for update (tauri)",t),!1}},Vd=async(t,r)=>{const e=t?.trim();if(!e)return!1;if(Ke()&&dt())try{return await window.__TAURI__?.core?.invoke?.("desktop_open_path",{path:e,app:typeof r=="string"&&r.trim().length>0?r.trim():void 0}),!0}catch(n){return console.warn("Failed to open path (tauri)",n),!1}if(rr())try{return await window.electronAPI?.desktop?.openPath(e),!0}catch(n){return console.warn("Failed to open path (electron)",n),!1}return!1},Kd=async(t,r,e,n)=>{const o=t?.trim(),s=r?.trim(),i=e?.trim(),a=typeof n=="string"?n.trim():"";if(!o||!s||!i)return!1;if(Ke()&&dt())try{return await window.__TAURI__?.core?.invoke?.("desktop_open_in_app",{projectPath:o,appId:s,appName:i,filePath:a.length>0?a:void 0}),!0}catch(l){return console.warn("Failed to open project in app (tauri)",l),!1}if(rr())try{const l=a.length>0?a:o;if(s==="vscode"||s==="vscodium"||s==="cursor"||s==="windsurf"||s==="zed"){const c=`vscode://file/${encodeURIComponent(l)}`;return await window.electronAPI?.shell?.openExternal(c),!0}return s==="terminal"||s==="iterm2"||s==="ghostty"?(await window.electronAPI?.desktop?.openInTerminal(o),!0):s==="finder"||s==="explorer"||s==="files"?(await window.electronAPI?.desktop?.openPath(o),!0):(await window.electronAPI?.desktop?.openInApp(l,i),!0)}catch(l){return console.warn("Failed to open project in app (electron)",l),!1}return!1},Jd=async(t,r)=>{if(!Ke()||!dt())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const e=Array.isArray(t)?t.filter(n=>typeof n=="string"):[];if(e.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await window.__TAURI__?.core?.invoke?.("desktop_get_installed_apps",{apps:e,force:r===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const s=o;return Array.isArray(s.apps)?{apps:s.apps.filter(a=>a&&typeof a=="object").map(a=>{const l=a;return{name:typeof l.name=="string"?l.name:"",iconDataUrl:typeof l.iconDataUrl=="string"?l.iconDataUrl:null}}).filter(a=>a.name.length>0),success:!0,hasCache:s.hasCache===!0,isCacheStale:s.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(n){return console.warn("Failed to fetch installed apps (tauri)",n),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},Qd=async()=>{if(!Ke()||!dt())return null;try{return await window.__TAURI__?.core?.invoke?.("desktop_read_clipboard_image")}catch(t){return console.warn("Failed to read clipboard image (native)",t),null}},Bg=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Wd,downloadDesktopUpdate:Gd,fetchDesktopInstalledApps:Jd,getDesktopHomeDirectory:mo,isDesktopLocalOriginActive:dt,isDesktopShell:Nd,isElectronShell:rr,isTauriShell:Ke,isVSCodeRuntime:nr,isWebRuntime:$d,openDesktopPath:Vd,openDesktopProjectInApp:Kd,readClipboardImage:Qd,requestDirectoryAccess:Ud,requestFileAccess:Bd,restartToApplyUpdate:qd,startAccessingDirectory:zd,stopAccessingDirectory:Hd},Symbol.toStringTag,{value:"Module"})),Yd=300*1e3,Xd=250,Zd=t=>t.replace(/\\/g,"/").replace(/\/+$/,"")||t,go=new Map,Jr=new Map,yo=t=>Zd(t),eu=async t=>{const r=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__?.git:void 0;return r?.worktree?.bootstrapStatus?r.worktree.bootstrapStatus(t):r?.getGitWorktreeBootstrapStatus?r.getGitWorktreeBootstrapStatus(t):Wa(t)},tu=t=>{const r=yo(t);r&&go.set(r,{status:"pending",error:null,updatedAt:Date.now()})},ru=t=>{const r=yo(t);r&&(go.delete(r),Jr.delete(r))},nu=(t,r)=>{const e=yo(t);e&&(go.set(e,r),r.status!=="pending"&&Jr.delete(e))},ou=async(t,r)=>{const e=Date.now();for(;Date.now()-e<r;){const n=await eu(t);if(nu(t,n),n.status==="ready")return;if(n.status==="failed")throw new Error(n.error||"Worktree bootstrap failed");await new Promise(o=>setTimeout(o,Xd))}throw new Error("Timed out waiting for worktree bootstrap")},cs=async(t,r=Yd)=>{const e=yo(t);if(!e)return;const n=go.get(e);if(n?.status==="ready")return;if(n?.status==="failed")throw new Error(n.error||"Worktree bootstrap failed");const o=Jr.get(e);if(o)return o;const s=ou(t,r).finally(()=>{Jr.delete(e)});return Jr.set(e,s),s},su="/api",iu=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,au=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(iu.test(r)||typeof window>"u")return r;const e=window.location?.href||window.location?.origin;if(!e)return r;try{return new URL(r,e).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},cu=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!r)return null;const e=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return e?`${e}/api`:null},mr=t=>t.replace(/\\/g,"/"),pi=400,mi=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class lu{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();globalSseAbortController=null;globalSseTask=null;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseStaleDeltas=new Set;globalSseFlushTimer=null;globalSseLastFlushAt=0;listDirectoryInFlight=new Map;listDirectoryCache=new Map;constructor(r=su){const n=cu()||r;this.baseUrl=au(n),this.client=oi({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(r){const e=this.normalizeCandidatePath(r)??r,n=e||"",o=this.scopedClients.get(n);if(o)return o;const s=oi({baseUrl:this.baseUrl,directory:e});return this.scopedClients.set(n,s),s}normalizeCandidatePath(r){if(typeof r!="string")return null;const e=r.trim();if(!e)return null;const n=e.replace(/\\/g,"/").replace(/^([a-z]):/,(s,i)=>i.toUpperCase()+":");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const e=r.match(/^([A-Za-z]:)(?:\/|$)/);if(e){const s=e[1],a=r.slice(s.length+(r.charAt(s.length)==="/"?1:0)).split("/").filter(Boolean);return a.length>=2?{homeDirectory:`${s}/${a[0]}/${a[1]}`,username:a[1]}:a.length===1?{homeDirectory:`${s}/${a[0]}`,username:a[0]}:{homeDirectory:s,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=this.normalizeCandidatePath(r)??r}getDirectory(){return this.currentDirectory}async withDirectory(r,e){const n=async()=>{if(r==null)return e();const s=this.currentDirectory;this.currentDirectory=this.normalizeCandidatePath(r)??r;try{return await e()}finally{this.currentDirectory=s}},o=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,e=o=>{const s=this.normalizeCandidatePath(o);s&&r.add(s)};try{const s=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;s&&(e(s.directory),e(s.worktree),e(s.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);e(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(s=>e(s.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(e(this.currentDirectory),typeof window<"u")try{e(window.localStorage.getItem("lastDirectory")),e(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&e(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async probeDirectory(r){const e=this.normalizeCandidatePath(r);if(!e)return!1;try{const o=(await this.client.path.get({directory:e})).data,s=typeof o?.directory=="string"?o.directory:null;return!!(s&&s.trim().length>0)}catch{return!1}}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const e=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!e.data)throw new Error("Failed to create session");return e.data}async getSession(r){const e=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!e.data)throw new Error("Session not found");return e.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,e){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:e});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r,e){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof e=="number"?{limit:e}:{}})).data||[]}async getSessionTodos(r){try{const e=this.baseUrl.replace(/\/$/,""),n=new URL(`${e}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const s=await o.json().catch(()=>null);return!s||!Array.isArray(s)?[]:s}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const e=r.toLowerCase();return e.startsWith("text/")&&e!=="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(e)}isHeicMime(r){if(!r)return!1;const e=r.toLowerCase();return e==="image/heic"||e==="image/heif"}async convertHeicToJpeg(r){try{const e=(await qe(async()=>{const{default:u}=await import("./vendor-.bun-HTKwyaEM.js").then(f=>f.h);return{default:u}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),s=atob(o),i=new Uint8Array(s.length);for(let u=0;u<s.length;u++)i[u]=s.charCodeAt(u);const a=new Blob([i],{type:r.mime}),l=await e({blob:a,toType:"image/jpeg",quality:.9}),c=await new Promise((u,f)=>{const m=new FileReader;m.onload=()=>u(m.result),m.onerror=f,m.readAsDataURL(l)});let d=r.filename;return d&&(d=d.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:d,url:c}}catch(e){return console.warn("Failed to convert HEIC to JPEG:",e),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(!this.shouldNormalizeToTextPlain(r.mime))return r;let e=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),s=r.url.substring(n);e=`data:${o.replace(/^[^;,]+/,"text/plain")}${s}`}}return{mime:"text/plain",filename:r.filename,url:e}}async toNormalizedFilePartInput(r){const e=await this.normalizeFilePart(r);return{...r.id?{id:r.id}:{},type:"file",mime:e.mime,filename:e.filename,url:e.url}}async sendMessage(r){const e=Date.now(),n=r.messageId??`temp_${e}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText,synthetic:r.prefaceTextSynthetic!==!1}),r.text&&r.text.trim()){const l={type:"text",text:r.text};o.push(l)}if(r.files&&r.files.length>0)for(const l of r.files){const c=await this.toNormalizedFilePartInput(l);o.push(c)}if(r.additionalParts&&r.additionalParts.length>0){for(const l of r.additionalParts)if(l.text&&l.text.trim()&&o.push({type:"text",text:l.text,...l.synthetic?{synthetic:!0}:{}}),l.files&&l.files.length>0)for(const c of l.files){const d=await this.toNormalizedFilePartInput(c);o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0)for(const l of r.agentMentions)l?.name&&o.push({type:"agent",name:l.name,...l.source?{source:l.source}:{}});if(o.length===0)throw new Error("Message must have at least one part (text or file)");this.currentDirectory&&await cs(this.currentDirectory);const s=this.baseUrl.replace(/\/+$/,"");let i;try{i=new URL(`${s}/session/${encodeURIComponent(r.id)}/prompt_async`),this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory)}catch(l){throw console.error("[git-generation][browser] failed to build prompt_async URL",{baseUrl:this.baseUrl,normalizedBase:s,sessionId:r.id,directory:this.currentDirectory,message:l instanceof Error?l.message:String(l),error:l}),l}r.format&&console.info("[git-generation][browser] send structured message",{sessionId:r.id,providerID:r.providerID,modelID:r.modelID,agent:r.agent,variant:r.variant,directory:this.currentDirectory,baseUrl:this.baseUrl,formatType:r.format.type});let a;try{a=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,...r.format?{format:r.format}:{},parts:o})})}catch(l){throw console.error("[git-generation][browser] prompt_async request failed before response",{sessionId:r.id,url:i.toString(),directory:this.currentDirectory,hasFormat:!!r.format,message:l instanceof Error?l.message:String(l),error:l}),l}if(!a.ok){let l="";try{l=await a.text()}catch{}const c=l&&l.trim().length>0?`: ${l.trim()}`:"";throw new Error(`Failed to send message (${a.status})${c}`)}return n}async sendCommand(r){const e=Date.now(),n=r.messageId??`temp_${e}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.files&&r.files.length>0)for(const c of r.files)o.push(await this.toNormalizedFilePartInput(c));const s=this.baseUrl.replace(/\/+$/,""),i=new URL(`${s}/session/${encodeURIComponent(r.id)}/command`);this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory);const a={command:r.command,arguments:r.arguments??"",model:`${r.providerID}/${r.modelID}`,...r.agent?{agent:r.agent}:{},...r.variant?{variant:r.variant}:{},...o.length>0?{parts:o}:{},...r.messageId?{messageID:r.messageId}:{}},l=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(a)});if(!l.ok){let c="";try{c=await l.text()}catch{}const d=c&&c.trim().length>0?`: ${c.trim()}`:"";throw new Error(`Failed to run command (${l.status})${d}`)}return n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,e,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:e,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const e=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!e.data)throw new Error("Failed to unrevert session");return e.data}async forkSession(r,e){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:e});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const e=this.baseUrl.replace(/\/$/,""),n=new URL(`${e}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const s=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return{};const i=await s.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async getWebServerSessionActivity(){try{const r=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const e=await r.json().catch(()=>null);return!e||typeof e!="object"?null:e}catch{return null}}async listToolIds(r){try{const e=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(e?{directory:e}:void 0)).data||[]).filter(s=>typeof s=="string"&&s!=="invalid")}catch{return[]}}async replyToPermission(r,e,n){const o=new Promise((i,a)=>{setTimeout(()=>{a(new Error("Permission response timeout"))},5e3)}),s=this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:e,...n?.message?{message:n.message}:{}});try{return(await Promise.race([s,o])).data||!1}catch(i){throw i instanceof Error&&i.message==="Permission response timeout"&&console.error("Permission response timeout:",{requestId:r,reply:e}),i}}async listPendingPermissions(r){const e=[],n=async l=>{try{const c=typeof l=="string"?l.trim():"";return(await this.client.permission.list(c?{directory:c}:void 0)).data||[]}catch{return[]}};e.push(n(null));const o=new Set;for(const l of r?.directories??[]){const c=this.normalizeCandidatePath(l??null);c&&o.add(c)}for(const l of o)e.push(n(l));const s=await Promise.all(e),i=[],a=new Set;for(const l of s)for(const c of l){if(!c||typeof c!="object")continue;const d=c.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(c))}return i}async replyToQuestion(r,e){const n=!Array.isArray(e)||e.length===0?[]:Array.isArray(e[0])?e:[e];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const e=[],n=async l=>{try{const c=typeof l=="string"?l.trim():"";return(await this.client.question.list(c?{directory:c}:void 0)).data||[]}catch{return[]}};e.push(n(null));const o=new Set;for(const l of r?.directories??[]){const c=this.normalizeCandidatePath(l??null);c&&o.add(c)}for(const l of o)e.push(n(l));const s=await Promise.all(e),i=[],a=new Set;for(const l of s)for(const c of l){if(!c||typeof c!="object")continue;const d=c.id;typeof d!="string"||d.length===0||a.has(d)||(a.add(d),i.push(c))}return i}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const e=`${this.baseUrl}/config`,n=await fetch(e,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const s=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,s),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const e=await this.getConfig(),n=r(e);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const e=r,n=typeof e.directory=="string"?e.directory:typeof e.properties=="object"&&e.properties!==null?e.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof e.type=="string")return{directory:o&&o.length>0?o:"global",payload:e};const s=e.payload;if(s&&typeof s=="object"){const i=s;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}return null}emitGlobalSseEvent(r){this.enqueueGlobalSseEvent(r)}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(e){console.warn("[OpencodeClient] Global SSE open handler error:",e)}}notifyGlobalSseError(r){for(const e of this.globalSseErrorListeners)try{e(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(e=>{e?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",e)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null,this.clearGlobalSseQueue())}clearGlobalSseQueue(){this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length=0,this.globalSseBuffer.length=0,this.globalSseCoalesced.clear(),this.globalSseStaleDeltas.clear()}getGlobalSseDeltaKey(r){const e=r.payload;if((typeof e.type=="string"?e.type:null)!=="message.part.delta")return null;const o=typeof e.properties=="object"&&e.properties!==null?e.properties:null,s=typeof o?.messageID=="string"?o.messageID:typeof o?.messageId=="string"?o.messageId:null,i=typeof o?.partID=="string"?o.partID:typeof o?.partId=="string"?o.partId:null;return!s||!i?null:`${r.directory}:${s}:${i}`}getGlobalSseUpdatedPartKey(r){const e=r.payload;if((typeof e.type=="string"?e.type:null)!=="message.part.updated")return null;const o=typeof e.properties=="object"&&e.properties!==null?e.properties:null,s=o?.part&&typeof o.part=="object"?o.part:null,i=typeof s?.messageID=="string"?s.messageID:typeof s?.messageId=="string"?s.messageId:null,a=typeof s?.id=="string"?s.id:typeof s?.partID=="string"?s.partID:typeof s?.partId=="string"?s.partId:null;return!i||!a?null:`${r.directory}:${i}:${a}`}getGlobalSseCoalesceKey(r){const e=r.payload,n=typeof e.type=="string"?e.type:null;if(!n)return null;const o=typeof e.properties=="object"&&e.properties!==null?e.properties:null;if(n==="session.status"){const s=typeof o?.sessionID=="string"?o.sessionID:typeof o?.sessionId=="string"?o.sessionId:null;return s?`session.status:${r.directory}:${s}`:null}if(n==="openchamber:session-status"){const s=typeof o?.sessionId=="string"?o.sessionId:typeof o?.sessionID=="string"?o.sessionID:null;return s?`openchamber:session-status:${s}`:null}if(n==="message.part.updated"){const s=this.getGlobalSseUpdatedPartKey(r);return s?`message.part.updated:${s}`:null}return null}flushGlobalSseQueue=()=>{if(this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length===0)return;const r=this.globalSseQueue,e=this.globalSseStaleDeltas.size>0?new Set(this.globalSseStaleDeltas):void 0;this.globalSseQueue=this.globalSseBuffer,this.globalSseBuffer=r,this.globalSseQueue.length=0,this.globalSseCoalesced.clear(),this.globalSseStaleDeltas.clear(),this.globalSseLastFlushAt=Date.now();for(const n of r)if(n){if(e){const o=this.getGlobalSseDeltaKey(n);if(o&&e.has(o))continue}for(const o of this.globalSseListeners)try{o(n)}catch(s){console.warn("[OpencodeClient] Global SSE listener error:",s)}}this.globalSseBuffer.length=0};scheduleGlobalSseFlush(){if(this.globalSseFlushTimer)return;const r=Date.now()-this.globalSseLastFlushAt,e=Math.max(0,16-r);this.globalSseFlushTimer=setTimeout(this.flushGlobalSseQueue,e)}enqueueGlobalSseEvent(r){const e=this.getGlobalSseCoalesceKey(r);if(e){const n=this.globalSseCoalesced.get(e);if(n!==void 0){this.globalSseQueue[n]=void 0;const o=this.getGlobalSseUpdatedPartKey(r);o&&this.globalSseStaleDeltas.add(o)}this.globalSseCoalesced.set(e,this.globalSseQueue.length)}this.globalSseQueue.push(r),this.scheduleGlobalSseFlush()}async runGlobalSseLoop(r){let e=0;const n=250,o=8,s=i=>new Promise(a=>setTimeout(a,i));for(;!r.signal.aborted;){try{const i=await this.client.global.event({signal:r.signal,onSseError:l=>{l?.name==="AbortError"||r.signal.aborted||this.notifyGlobalSseError(l)}});e=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();let a=Date.now();for await(const l of i.stream){if(r.signal.aborted)break;const c=typeof l.directory=="string"&&l.directory.length>0?l.directory:"global",d=this.normalizeRoutedSsePayload({directory:c,payload:l.payload});d&&(this.emitGlobalSseEvent(d),Date.now()-a>=o&&(a=Date.now(),await s(0)))}this.globalSseIsConnected=!1}catch(i){if(this.globalSseIsConnected=!1,i?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",i),this.notifyGlobalSseError(i)}if(r.signal.aborted)break;e+=1,await s(Math.min(n*Math.max(e,1),2e3))}this.flushGlobalSseQueue()}subscribeToGlobalEvents(r,e,n,o){const s=this.normalizeCandidatePath(o?.directory??null),i=a=>{s&&a.directory!==s||r(a)};return this.globalSseListeners.add(i),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(a){console.warn("[OpencodeClient] Global SSE open handler error:",a)}},0)),e&&this.globalSseErrorListeners.add(e),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),n&&this.globalSseOpenListeners.delete(n),e&&this.globalSseErrorListeners.delete(e),this.maybeStopGlobalSse()}}subscribeToEvents(r,e,n,o,s){const i=s?.key??"default",a=s?.scope??"directory",l=this.sseAbortControllers.get(i);l&&l.abort();const c=new AbortController;this.sseAbortControllers.set(i,c);let d;if(a==="global"){let f=null;const m=g=>{if(g.directory==="global")return g.payload;const S=g.payload,h=typeof S.properties=="object"&&S.properties!==null?S.properties:{};return h.directory===g.directory?g.payload:{...S,properties:{...h,directory:g.directory}}},p=()=>{if(f){try{f()}catch{}f=null}this.sseAbortControllers.get(i)===c&&this.sseAbortControllers.delete(i)};return c.signal.addEventListener("abort",p,{once:!0}),f=this.subscribeToGlobalEvents(g=>{c.signal.aborted||r(m(g))},e?g=>{c.signal.aborted||e(g)}:void 0,n?()=>{c.signal.aborted||n()}:void 0),()=>{p(),c.abort()}}const u=f=>{if(!f||typeof f!="object")return null;const m=f;if(typeof m.type=="string")return m;const p=m.payload;if(p&&typeof p=="object"){const g=p;if(typeof g.type=="string"){if(typeof m.directory=="string"&&m.directory.length>0){const h={...(typeof g.properties=="object"&&g.properties!==null?g.properties:null)??{},directory:m.directory};return{...g,properties:h}}return g}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const f=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",f??"default");const m=async p=>{try{const g=f?{directory:f}:void 0,S={signal:c.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),e&&!c.signal.aborted&&e(v))},onSseEvent:v=>{if(c.signal.aborted)return;v.id&&typeof v.id=="string"&&(d=v.id);const b=v.data,D=u(b);D&&r(D)}};d&&(S.headers={...S.headers||{},"Last-Event-ID":d});const h=await this.client.event.subscribe(g,S);n&&!c.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const v of h.stream)if(c.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(g){if(g?.name==="AbortError"||c.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",g),e&&e(g);const S=Math.min(3e3*Math.pow(2,p),3e4);await new Promise(h=>setTimeout(h,S)),c.signal.aborted||await m(p+1);return}if(!c.signal.aborted){const g=Math.min(3e3*Math.pow(2,p),3e4);await new Promise(S=>setTimeout(S,g)),await m(p+1)}};try{await m(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===c&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===c&&this.sseAbortControllers.delete(i),c.abort()}}async readFile(r){try{const e=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!e.ok)throw new Error(`Failed to read file: ${e.statusText}`);return await e.text()}catch{return`// Content of ${r}
3
3
  // This would be loaded from the server`}}async listFiles(r){try{const e=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:e})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model,template:e.template}))}catch{return[]}}async getCommandDetails(r){try{const e=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(e.data){const n=e.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const e=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;e==="/api"?r="/health":e.endsWith("/api")?r=`${e.slice(0,-4)}/health`:r=`${e}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r,e){const n=mi();if(n?.createDirectory)try{return await n.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"Failed to create directory")}const o={path:r,...e?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},s=await fetch(`${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 listLocalDirectory(r,e){const o=`${typeof r=="string"?mr(r.trim()):""}|${e?.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 c=(async()=>{const d=mi();if(d)try{const u=await d.listDirectory(r||"",e);if(!u||!Array.isArray(u.entries))return[];const f=u.entries.map(m=>({name:m.name,path:mr(m.path),isDirectory:!!m.isDirectory,isFile:!m.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(o,{entries:f,expiresAt:Date.now()+pi}),f}catch(u){throw console.error("Failed to list directory contents:",u),u}try{const u=new URLSearchParams;r&&r.trim().length>0&&u.set("path",r),e?.respectGitignore&&u.set("respectGitignore","true");const f=u.toString(),m=await fetch(`${this.baseUrl}/fs/list${f?`?${f}`:""}`);if(!m.ok){const S=await m.json().catch(()=>({})),h=typeof S.error=="string"?S.error:"Failed to list directory";throw new Error(h)}const p=await m.json();if(!p||!Array.isArray(p.entries))return[];const g=p.entries;return this.listDirectoryCache.set(o,{entries:g,expiresAt:Date.now()+pi}),g}catch(u){throw console.error("Failed to list directory contents:",u),u}})().finally(()=>{this.listDirectoryInFlight.get(o)===c&&this.listDirectoryInFlight.delete(o)});return this.listDirectoryInFlight.set(o,c),c}async searchFiles(r,e){const n=typeof e?.directory=="string"&&e.directory.trim().length>0?e.directory.trim():this.currentDirectory,o=n?mr(n):null,s=n?this.getScopedApiClient(n):this.client;try{const i=await s.find.files({query:r,limit:typeof e?.limit=="number"&&Number.isFinite(e.limit)?e.limit:void 0,dirs:e?.dirs===!1||e?.type==="file"?"false":"true",type:e?.type});return(Array.isArray(i?.data)?i.data:[]).map(l=>{const c=mr(l),d=c.split("/").filter(Boolean).pop()||c,u=mr(o?`${o}/${c}`:c);return{name:d,path:u,relativePath:c,extension:d.includes(".")?d.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const r=await mo();if(r)return r;try{const e=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok){const o=await e.json().catch(()=>({})),s=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(s)}const n=await e.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(e){return console.warn("Failed to resolve filesystem home directory:",e),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const e=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",e,"with path:",r);try{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const s=o??{},i=typeof s.error=="string"&&s.error.length>0?s.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const O=new lu,du="openchamber-message-cursors",eo="cursors",uu=1,Xa="openchamber.messageCursors",Ps=()=>typeof window<"u",Za=()=>Ps()&&typeof indexedDB<"u",fu=()=>Za()?new Promise((t,r)=>{const e=indexedDB.open(du,uu);e.onupgradeneeded=()=>{const n=e.result;n.objectStoreNames.contains(eo)||n.createObjectStore(eo)},e.onerror=()=>{r(e.error??new Error("Failed to open IndexedDB"))},e.onsuccess=()=>{t(e.result)}}):Promise.reject(new Error("IndexedDB not supported"));let Lr=null;const pu=()=>(Lr||(Lr=fu().then(t=>(t.onclose=()=>{Lr=null},t.onversionchange=()=>{t.close()},t)).catch(t=>{throw Lr=null,t})),Lr),mu=()=>{if(!Ps())return{};try{const t=window.localStorage.getItem(Xa);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},gu=t=>{if(Ps())try{window.localStorage.setItem(Xa,JSON.stringify(t))}catch{}},yu=async(t,r,e)=>{if(!t||!r)return;if(Za())try{const o=await pu();await new Promise((s,i)=>{const a=o.transaction(eo,"readwrite");a.objectStore(eo).put({messageId:r,completedAt:e},t),a.oncomplete=()=>s(),a.onerror=()=>i(a.error??new Error("Cursor write failed")),a.onabort=()=>i(a.error??new Error("Cursor write aborted"))});return}catch{}const n=mu();n[t]={messageId:r,completedAt:e},gu(n)};let _o=null,Ro=null;const to=()=>{const t=new Map;return{getItem:r=>t.get(r)??null,setItem:(r,e)=>{t.set(r,e)},removeItem:r=>{t.delete(r)},clear:()=>{t.clear()},key:r=>Array.from(t.keys())[r]??null,get length(){return t.size}}},hu=()=>{if(typeof window>"u"||!window.localStorage)return to();const t=window.localStorage,r=to();let e=!0;const n=()=>{e=!1};return{getItem:c=>{if(e)try{const d=t.getItem(c);if(d!==null)return d}catch{n()}return r.getItem(c)},setItem:(c,d)=>{if(e)try{t.setItem(c,d),r.removeItem(c);return}catch{n();try{t.removeItem(c)}catch{}}r.setItem(c,d)},removeItem:c=>{try{t.removeItem(c)}catch{n()}r.removeItem(c)},clear:()=>{try{t.clear()}catch{n()}r.clear()},key:c=>{if(e)try{return t.key(c)}catch{n()}return r.key(c)},get length(){if(e)try{return t.length+r.length}catch{n()}return r.length}}},ye=()=>(_o||(_o=hu()),_o),Su=()=>{if(typeof window>"u"||!window.sessionStorage)return to();const t=window.sessionStorage,r=to();let e=!0;const n=()=>{e=!1};return{getItem:c=>{if(e)try{const d=t.getItem(c);if(d!==null)return d}catch{n()}return r.getItem(c)},setItem:(c,d)=>{if(e)try{t.setItem(c,d),r.removeItem(c);return}catch{n();try{t.removeItem(c)}catch{}}r.setItem(c,d)},removeItem:c=>{try{t.removeItem(c)}catch{n()}r.removeItem(c)},clear:()=>{try{t.clear()}catch{n()}r.clear()},key:c=>{if(e)try{return t.key(c)}catch{n()}return r.key(c)},get length(){if(e)try{return t.length+r.length}catch{n()}return r.length}}},zg=()=>(Ro||(Ro=Su()),Ro),wu=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},bu=t=>{if(t)try{const r=wu();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},Mu=(t,r)=>{if(!t||t.length===0)return"ask";for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n.permission===r&&n.pattern==="*")return n.action}for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Oo=t=>{const r=bu(t);return r?Mu(r.permission,"edit"):"ask"},gi=t=>{if(!t||typeof t!="object")return 0;const r=t.input??0,e=t.output??0,n=t.reasoning??0,o=t.cache&&typeof t.cache=="object"?t.cache.read??0:0,s=t.cache&&typeof t.cache=="object"?t.cache.write??0:0;return r+e+n+o+s},jo=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return gi(r);const e=t.parts.find(n=>typeof n.tokens<"u");return!e||typeof e.tokens>"u"?0:typeof e.tokens=="number"?e.tokens:gi(e.tokens)},Fo=(t,r,e)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(e)&&e>0,s=o?Math.max(e,0):0,i=Math.min(o?s:32e3,32e3),a=Math.min(i,n),l=n>0?Math.max(n-a,1):0,c=l>0?t/l*100:0;return{percentage:Math.min(c,100),contextLimit:n,outputLimit:s,thresholdLimit:l||1,normalizedOutput:a}},Nr=["ask","allow","full"],yi="__global__",ne=Me()(ve(tt((t,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(e,n,o)=>{t(s=>{const i=new Map(s.sessionModelSelections);return i.set(e,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:e=>{const{sessionModelSelections:n}=r();return n.get(e)||null},saveSessionAgentSelection:(e,n)=>{t(o=>{const s=new Map(o.sessionAgentSelections);s.set(e,n);const i=new Map(o.currentAgentContext);return i.set(e,n),{sessionAgentSelections:s,currentAgentContext:i}})},getSessionAgentSelection:e=>{const{sessionAgentSelections:n}=r();return n.get(e)||null},saveAgentModelForSession:(e,n,o,s)=>{t(i=>{const a=new Map(i.sessionAgentModelSelections);let l=a.get(e);return l?l=new Map(l):l=new Map,l.set(n,{providerId:o,modelId:s}),a.set(e,l),{sessionAgentModelSelections:a}})},getAgentModelForSession:(e,n)=>{const{sessionAgentModelSelections:o}=r(),s=o.get(e);return s&&s.get(n)||null},saveAgentModelVariantForSession:(e,n,o,s,i)=>{t(a=>{const l=new Map(a.sessionAgentModelVariantSelections);let c=l.get(e);c?c=new Map(c):c=new Map;let d=c.get(n);d?d=new Map(d):d=new Map;const u=`${o}/${s}`;return i===void 0?(d.delete(u),d.size===0?(c.delete(n),c.size===0?l.delete(e):l.set(e,c)):(c.set(n,d),l.set(e,c))):(d.set(u,i),c.set(n,d),l.set(e,c)),{sessionAgentModelVariantSelections:l}})},getAgentModelVariantForSession:(e,n,o,s)=>{const{sessionAgentModelVariantSelections:i}=r(),a=i.get(e);if(!a)return;const l=a.get(n);if(l)return l.get(`${o}/${s}`)},analyzeAndSaveExternalSessionChoices:async(e,n,o)=>{const{saveAgentModelForSession:s,saveAgentModelVariantForSession:i}=r(),a=new Map,l=(p,g)=>{if("mode"in p&&p.mode&&typeof p.mode=="string"&&n.find(b=>b.name===p.mode))return p.mode;if("agent"in p&&p.agent&&typeof p.agent=="string"&&n.find(b=>b.name===p.agent))return p.agent;if(p.providerID&&p.modelID){const v=n.find(b=>b.model?.providerID===p.providerID&&b.model?.modelID===p.modelID);if(v)return v.name}const{currentAgentContext:S}=r(),h=S.get(e);if(h&&n.find(v=>v.name===h))return h;if(g>0&&p.providerID&&p.modelID){const b=(o.get(e)||[]).filter(D=>D.info.role==="assistant").sort((D,I)=>D.info.time.created-I.info.time.created);for(let D=g-1;D>=0;D--){const M=b[D].info;if(M.providerID===p.providerID&&M.modelID===p.modelID){if(M.mode&&typeof M.mode=="string"&&n.find(T=>T.name===M.mode))return M.mode;const C=n.find(k=>k.model?.providerID===M.providerID&&k.model?.modelID===M.modelID);if(C)return C.name}}}return p.providerID&&p.modelID&&n.find(b=>b.name==="build")?"build":null},c=o.get(e)||[],d=c.filter(p=>p.info.role==="assistant"||p.info.role==="user").sort((p,g)=>p.info.time.created-g.info.time.created),u=c.filter(p=>p.info.role==="assistant").sort((p,g)=>p.info.time.created-g.info.time.created);let f,m;for(let p=0;p<d.length;p++){const g=d[p],{info:S}=g,h=S;if(h.role==="user"){const v=typeof h.mode=="string"&&h.mode.trim().length>0?h.mode:typeof h.agent=="string"&&h.agent.trim().length>0?h.agent:void 0,b=typeof h.model?.providerID=="string"&&h.model.providerID.trim().length>0?h.model.providerID:typeof h.providerID=="string"&&h.providerID.trim().length>0?h.providerID:void 0,D=typeof h.model?.modelID=="string"&&h.model.modelID.trim().length>0?h.model.modelID:typeof h.modelID=="string"&&h.modelID.trim().length>0?h.modelID:void 0,I=typeof h.variant=="string"&&h.variant.trim().length>0?h.variant:void 0;if(v&&b&&D&&n.find(M=>M.name===v)){const M={providerId:b,modelId:D,timestamp:S.time.created},C=a.get(v);(!C||M.timestamp>C.timestamp)&&a.set(v,M),i(e,v,b,D,I)}f=I,m=h.model?.providerID&&h.model?.modelID?{providerID:h.model.providerID,modelID:h.model.modelID}:void 0;continue}if(h.providerID&&h.modelID){const v=l(h,u.indexOf(g));if(v&&n.find(b=>b.name===v)){m&&m.providerID===h.providerID&&m.modelID===h.modelID&&i(e,v,h.providerID,h.modelID,f);const b={providerId:h.providerID,modelId:h.modelID,timestamp:S.time.created},D=a.get(v);(!D||b.timestamp>D.timestamp)&&a.set(v,b)}}f=void 0,m=void 0}for(const[p,g]of a)s(e,p,g.providerId,g.modelId);return a},getContextUsage:(e,n,o,s)=>{if(!e)return null;const i=Fo(0,n,o),a=i.contextLimit,l=i.normalizedOutput??0,c=i.thresholdLimit;if(a===0||c===0)return null;const u=(s.get(e)||[]).filter(b=>b.info.role==="assistant");if(u.length===0)return null;const f=u[u.length-1],m=f.info.id,p=b=>{const D=()=>{t(I=>{const M=I.sessionContextUsage.get(e);if(M&&M.totalTokens===b.totalTokens&&M.percentage===b.percentage&&M.contextLimit===b.contextLimit&&(M.outputLimit??0)===(b.outputLimit??0)&&(M.normalizedOutput??0)===(b.normalizedOutput??0)&&M.thresholdLimit===b.thresholdLimit&&M.lastMessageId===b.lastMessageId)return I;const C=new Map(I.sessionContextUsage);return C.set(e,b),{sessionContextUsage:C}})};typeof queueMicrotask=="function"?queueMicrotask(D):typeof window<"u"?window.setTimeout(D,0):setTimeout(D,0)},g=r().sessionContextUsage.get(e);if(g&&g.lastMessageId===m){const b=g.normalizedOutput??g.outputLimit??0,D=g.contextLimit!==a||b!==l||g.thresholdLimit!==c;if(D&&g.totalTokens>0){const I=g.totalTokens/c*100,M={totalTokens:g.totalTokens,percentage:Math.min(I,100),contextLimit:a,outputLimit:i.outputLimit,normalizedOutput:l,thresholdLimit:c,lastMessageId:m};return p(M),M}if(!D&&g.totalTokens>0)return g}const S=jo(f);if(S===0)return g||null;const h=Fo(S,n,o),v={totalTokens:S,percentage:h.percentage,contextLimit:h.contextLimit,outputLimit:h.outputLimit,normalizedOutput:h.normalizedOutput,thresholdLimit:h.thresholdLimit,lastMessageId:m};return p(v),v},updateSessionContextUsage:(e,n,o,s)=>{const a=(s.get(e)||[]).filter(u=>u.info.role==="assistant");if(a.length===0)return;const l=a[a.length-1],c=jo(l);if(c===0)return;const d=Fo(c,n,o);t(u=>{const f=new Map(u.sessionContextUsage);return f.set(e,{totalTokens:c,percentage:d.percentage,contextLimit:d.contextLimit,outputLimit:d.outputLimit,normalizedOutput:d.normalizedOutput,thresholdLimit:d.thresholdLimit,lastMessageId:l.info.id}),{sessionContextUsage:f}})},initializeSessionContextUsage:(e,n,o,s)=>{const a=r().sessionContextUsage.get(e);(!a||a.totalTokens===0)&&r().updateSessionContextUsage(e,n,o,s)},pollForTokenUpdates:(e,n,o,s=10)=>{let i=0;const a=()=>{i++;const c=(o.get(e)||[]).find(d=>d.info.id===n);if(c&&c.info.role==="assistant"&&jo(c)>0){r().updateSessionContextUsage(e,0,0,o);return}i<s&&setTimeout(a,1e3)};setTimeout(a,2e3)},getCurrentAgent:e=>{const{currentAgentContext:n}=r();return n.get(e)},getSessionAgentEditMode:(e,n,o=Oo(n))=>{if(!e||!n)return o;const i=r().sessionAgentEditModes.get(e)?.get(n);if(i!==void 0)return i;if(e!==yi){const l=r().sessionAgentEditModes.get(yi)?.get(n);if(l!==void 0)return l}return o},setSessionAgentEditMode:(e,n,o,s=Oo(n))=>{if(!e||!n)return;const i=s??"ask";i==="deny"||o==="deny"||Nr.includes(o)&&t(a=>{const l=new Map(a.sessionAgentEditModes),c=new Map(l.get(e)??new Map);return o===i?(c.delete(n),c.size===0?l.delete(e):l.set(e,c)):(c.set(n,o),l.set(e,c)),{sessionAgentEditModes:l}})},toggleSessionAgentEditMode:(e,n,o=Oo(n))=>{if(!e||!n)return;const s=o??"ask";if(s==="deny")return;const i=r().getSessionAgentEditMode(e,n,s),a=Nr.indexOf(i),l=Nr.indexOf(s),d=((a>=0?a:l>=0?l:0)+1)%Nr.length,u=Nr[d];r().setSessionAgentEditMode(e,n,u,s)}}),{name:"context-store",storage:rt(()=>ye()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([r,e])=>[r,Array.from(e.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([r,e])=>[r,Array.from(e.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(t.currentAgentContext.entries()),sessionContextUsage:Array.from(t.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(t.sessionAgentEditModes.entries()).map(([r,e])=>[r,Array.from(e.entries())])}),merge:(t,r)=>{const e=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([s,i])=>{e.set(s,new Map(i))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([s,i])=>{const a=new Map;i.forEach(([l,c])=>{a.set(l,new Map(c))}),n.set(s,a)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([s,i])=>{o.set(s,new Map(i))}),{...r,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:e,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),ls=new Set;function ho(t){return ls.add(t),()=>{ls.delete(t)}}function ct(t,r){const e=Array.isArray(t)?t:[t],n=Array.from(new Set(e));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const s of ls)try{const i=s(o);i instanceof Promise&&i.catch(a=>{console.error("[ConfigSync] Async listener failed:",a)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function cn(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const Ts="Updating OpenCode configuration...";let wt=0,$t=Ts;const ds=new Set;function ro(){const t={isUpdating:wt>0,message:$t};ds.forEach(r=>r(t))}function lt(t){wt+=1,wt===1?($t=t||Ts,ro()):t&&($t=t,ro())}function ze(){wt!==0&&(wt-=1,wt===0&&($t=Ts,ro()))}function Ce(t){$t===t&&wt>0||($t=t,wt>0&&ro())}function Hg(t){return ds.add(t),t({isUpdating:wt>0,message:$t}),()=>{ds.delete(t)}}function Wg(){return{isUpdating:wt>0,message:$t}}const vu={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Gg={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function hi(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Pn={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Lo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Pn.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Lo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Pn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Lo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Pn.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Lo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Pn.tool.inline})},Tn={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}"}},jt={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},kn=(t,r)=>t?t.title===r.title&&t.message===r.message:!1,Du=t=>{if(!t||typeof t!="object")return!1;const r=t;return kn(r.completion,Tn.completion)&&kn(r.error,Tn.error)&&kn(r.question,Tn.question)&&kn(r.subtask,Tn.subtask)},ks=600,Iu=360,Au=1400,ec=12,Si=120,$r=300,Ur=400,Ge=t=>{if(!t)return"";const r=t.replace(/\\/g,"/"),e=r.startsWith("//");let n=r.replace(/\/+$/g,"");return n=n.replace(/\/+/g,"/"),e&&!n.startsWith("//")&&(n=`/${n}`),n===""?r.startsWith("/")?"/":"":n},tc=t=>Number.isFinite(t)?Math.min(Au,Math.max(Iu,Math.round(t))):ks,no=t=>{if(typeof t!="string")return null;const r=t.trim();return r?r.replace(/\\/g,"/"):null},rc=t=>{if(typeof t!="string")return null;const r=t.trim();return r?r.length>Si?r.slice(0,Si):r:null},Pu=(t,r)=>t==="file"&&r||t,nc=(t,r,e)=>{if(typeof e=="string"){const n=e.trim();if(n)return n}return Pu(t,r)},oc=(t,r)=>r===t?t:`${t}:${r}`,sc=t=>{const r=no(t.targetPath),e=nc(t.mode,r,t.dedupeKey);return{id:oc(t.mode,e),mode:t.mode,targetPath:r,dedupeKey:e,label:rc(t.label),touchedAt:Date.now()}},ic=(t,r,e)=>{if(t.length<=r)return t;const o=[...t].sort((a,l)=>a.touchedAt-l.touchedAt).filter(a=>a.id!==e),s=t.length-r;if(s<=0||o.length===0)return t.slice(-r);const i=new Set(o.slice(0,s).map(a=>a.id));return t.filter(a=>!i.has(a.id))},ac=t=>{if(!Array.isArray(t))return[];const r=[],e=new Set;for(const n of t){if(!n||typeof n!="object")continue;const o=n;if(o.mode!=="diff"&&o.mode!=="file"&&o.mode!=="context"&&o.mode!=="plan"&&o.mode!=="chat")continue;const s=no(typeof o.targetPath=="string"?o.targetPath:null),i=nc(o.mode,s,typeof o.dedupeKey=="string"?o.dedupeKey:null),a=oc(o.mode,i);!a||e.has(a)||(e.add(a),r.push({id:a,mode:o.mode,targetPath:s,dedupeKey:i,label:rc(typeof o.label=="string"?o.label:null),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return r},ln=(t,r)=>r&&t.some(e=>e.id===r)?r:t.length===0?null:t[t.length-1].id,Gt=t=>{if(t){const r=ac(t.tabs),e=ln(r,t.activeTabId);return{...t,tabs:r,activeTabId:e,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:ks,touchedAt:Date.now()}},Tu=(t,r)=>{const e=sc(r),n=t.tabs.findIndex(a=>a.id===e.id),o=n===-1?[...t.tabs,e]:t.tabs.map((a,l)=>l===n?{...a,mode:e.mode,targetPath:e.targetPath,dedupeKey:e.dedupeKey,label:e.label,touchedAt:Date.now()}:a),s=e.id,i=ic(o,ec,s);return{...t,isOpen:!0,tabs:i,activeTabId:ln(i,s),touchedAt:Date.now()}},ku=(t,r)=>{const e=t.tabs.filter(o=>o.id!==r),n=t.activeTabId===r?e[e.length-1]?.id??null:ln(e,t.activeTabId);return{...t,tabs:e,activeTabId:n,isOpen:e.length>0?t.isOpen:!1,touchedAt:Date.now()}},Cu=(t,r,e)=>{if(r===e)return t;const n=t.tabs.findIndex(a=>a.id===r),o=t.tabs.findIndex(a=>a.id===e);if(n===-1||o===-1)return t;const s=[...t.tabs],[i]=s.splice(n,1);return i?(s.splice(o,0,i),{...t,tabs:s,touchedAt:Date.now()}):t},No=t=>{if(!t||typeof t!="object")return{};const r=t,e={};for(const[n,o]of Object.entries(r)){const s=Ge(n);if(!s||!o||typeof o!="object")continue;const i=o;let a=ac(i.tabs),l=typeof i.activeTabId=="string"?i.activeTabId:null;a.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat")&&(a=[sc({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],l=a[0]?.id??null);const c=ln(a,l),d=ic(a,ec,c);e[s]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:d,activeTabId:ln(d,c),width:tc(typeof i.width=="number"?i.width:ks),touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return e},qt=(t,r)=>{const e=Object.entries(t);if(e.length<=r)return t;e.sort((o,s)=>(s[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const n={};for(const[o,s]of e.slice(0,r))n[o]=s;return n},Oe=Me()(ve(tt((t,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:$r,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:Ur,hasManuallyResizedRightSidebar:!1,rightSidebarTab:"git",contextPanelByDirectory:{},isBottomTerminalOpen:!1,isBottomTerminalExpanded:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,pendingFileNavigation:null,pendingFileFocusPath:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,chatRenderMode:"sorted",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,terminalFontSize:13,padding:100,cornerRadius:18,inputBarOffset:0,favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,isAgentFlowOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...jt.completion},error:{...jt.error},question:{...jt.question},subtask:{...jt.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,inputSpellcheckEnabled:!1,showToolFileIcons:!0,showExpandedBashTools:!1,showExpandedEditTools:!1,mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",stickyUserHeader:!0,showMobileSessionStatusBar:!0,isMobileSessionStatusBarCollapsed:!1,isExpandedInput:!1,reportUsage:!0,shortcutOverrides:{},setTheme:e=>{t({theme:e}),r().applyTheme()},toggleSidebar:()=>{t(e=>{const n=!e.isSidebarOpen;return n&&!e.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:$r}:{isSidebarOpen:n}})},setSidebarOpen:e=>{t(n=>n.isSidebarOpen===e?e&&!n.hasManuallyResizedLeftSidebar&&n.sidebarWidth!==$r?{isSidebarOpen:e,sidebarWidth:$r}:n:e&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:e,sidebarWidth:$r}:{isSidebarOpen:e})},setSidebarWidth:e=>{t({sidebarWidth:e,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(e=>{const n=!e.isRightSidebarOpen;return n&&!e.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:Ur}:{isRightSidebarOpen:n}})},setRightSidebarOpen:e=>{t(n=>n.isRightSidebarOpen===e?e&&!n.hasManuallyResizedRightSidebar&&n.rightSidebarWidth!==Ur?{isRightSidebarOpen:e,rightSidebarWidth:Ur}:n:e&&!n.hasManuallyResizedRightSidebar?{isRightSidebarOpen:e,rightSidebarWidth:Ur}:{isRightSidebarOpen:e})},setRightSidebarWidth:e=>{t({rightSidebarWidth:e,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:e=>{t({rightSidebarTab:e})},openContextPanelTab:(e,n)=>{const o=Ge((e||"").trim());o&&t(s=>{const i=s.contextPanelByDirectory[o],a=Gt(i),l={...s.contextPanelByDirectory,[o]:Tu(a,n)};return{contextPanelByDirectory:qt(l,20)}})},openContextDiff:(e,n)=>{const o=Ge((e||"").trim()),s=(n||"").trim();!o||!s||(r().openContextPanelTab(o,{mode:"diff",targetPath:s}),r().setPendingDiffFile(s))},openContextFile:(e,n)=>{const o=Ge((e||"").trim()),s=no(n);!o||!s||(r().openContextPanelTab(o,{mode:"file",targetPath:s}),r().setPendingFileFocusPath(s),r().setPendingFileNavigation(null))},openContextFileAtLine:(e,n,o,s)=>{const i=Ge((e||"").trim()),a=no(n),l=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,c=Number.isFinite(s)?Math.max(1,Math.trunc(s)):1;!i||!a||(r().openContextPanelTab(i,{mode:"file",targetPath:a}),r().setPendingFileFocusPath(null),r().setPendingFileNavigation({path:a,line:l,column:c}))},openContextOverview:e=>{const n=Ge((e||"").trim());n&&r().openContextPanelTab(n,{mode:"context"})},openContextPlan:e=>{const n=Ge((e||"").trim());n&&r().openContextPanelTab(n,{mode:"plan"})},setActiveContextPanelTab:(e,n)=>{const o=Ge((e||"").trim()),s=(n||"").trim();!o||!s||t(i=>{const a=i.contextPanelByDirectory[o],l=Gt(a);if(!l.tabs.some(d=>d.id===s)||l.activeTabId===s&&l.isOpen)return i;const c={...i.contextPanelByDirectory,[o]:{...l,isOpen:!0,activeTabId:s,touchedAt:Date.now(),tabs:l.tabs.map(d=>d.id===s?{...d,touchedAt:Date.now()}:d)}};return{contextPanelByDirectory:qt(c,20)}})},reorderContextPanelTabs:(e,n,o)=>{const s=Ge((e||"").trim()),i=(n||"").trim(),a=(o||"").trim();!s||!i||!a||t(l=>{const c=l.contextPanelByDirectory[s],d=Gt(c);if(!d.tabs.some(m=>m.id===i)||!d.tabs.some(m=>m.id===a))return l;const u=Cu(d,i,a);if(u.tabs===d.tabs)return l;const f={...l.contextPanelByDirectory,[s]:u};return{contextPanelByDirectory:qt(f,20)}})},closeContextPanelTab:(e,n)=>{const o=Ge((e||"").trim()),s=(n||"").trim();!o||!s||t(i=>{const a=i.contextPanelByDirectory[o],l=Gt(a);if(!l.tabs.some(d=>d.id===s))return i;const c={...i.contextPanelByDirectory,[o]:ku(l,s)};return{contextPanelByDirectory:qt(c,20)}})},closeContextPanel:e=>{const n=Ge((e||"").trim());n&&t(o=>{const s=o.contextPanelByDirectory[n];if(!s||!s.isOpen)return o;const i={...o.contextPanelByDirectory,[n]:{...Gt(s),isOpen:!1}};return{contextPanelByDirectory:qt(i,20)}})},toggleContextPanelExpanded:e=>{const n=Ge((e||"").trim());n&&t(o=>{const s=o.contextPanelByDirectory[n],i=Gt(s),a={...o.contextPanelByDirectory,[n]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:qt(a,20)}})},setContextPanelWidth:(e,n)=>{const o=Ge((e||"").trim());o&&t(s=>{const i=s.contextPanelByDirectory[o],a=Gt(i),l={...s.contextPanelByDirectory,[o]:{...a,width:tc(n)}};return{contextPanelByDirectory:qt(l,20)}})},toggleBottomTerminal:()=>{t(e=>{const n=!e.isBottomTerminalOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalOpen:e=>{t(n=>{if(n.isBottomTerminalOpen===e){if(!e)return n;if(!n.hasManuallyResizedBottomTerminal&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return n.bottomTerminalHeight===o&&n.hasManuallyResizedBottomTerminal===!1?n:{isBottomTerminalOpen:e,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return n}if(e&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:e,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:e}})},setBottomTerminalExpanded:e=>{t({isBottomTerminalExpanded:e})},setBottomTerminalHeight:e=>{t({bottomTerminalHeight:e,hasManuallyResizedBottomTerminal:!0})},setSessionSwitcherOpen:e=>{t({isSessionSwitcherOpen:e})},setMainTabGuard:e=>{r().mainTabGuard!==e&&t({mainTabGuard:e})},setActiveMainTab:e=>{const n=r().mainTabGuard;n&&!n(e)||t({activeMainTab:e})},setPendingDiffFile:e=>{t({pendingDiffFile:e})},setPendingFileNavigation:e=>{t({pendingFileNavigation:e})},setPendingFileFocusPath:e=>{t({pendingFileFocusPath:e})},navigateToDiff:e=>{const n=r().mainTabGuard;n&&!n("diff")||t({pendingDiffFile:e,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:e}=r();return e&&t({pendingDiffFile:null}),e},setIsMobile:e=>{t({isMobile:e})},toggleCommandPalette:()=>{t(e=>({isCommandPaletteOpen:!e.isCommandPaletteOpen}))},setCommandPaletteOpen:e=>{t({isCommandPaletteOpen:e})},toggleHelpDialog:()=>{t(e=>({isHelpDialogOpen:!e.isHelpDialogOpen}))},setHelpDialogOpen:e=>{t({isHelpDialogOpen:e})},setAboutDialogOpen:e=>{t({isAboutDialogOpen:e})},setOpenCodeStatusDialogOpen:e=>{t({isOpenCodeStatusDialogOpen:e})},setOpenCodeStatusText:e=>{t({openCodeStatusText:e})},setSessionCreateDialogOpen:e=>{t({isSessionCreateDialogOpen:e})},setSettingsDialogOpen:e=>{t(n=>e?n.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:e=>{t({isModelSelectorOpen:e})},setSidebarSection:e=>{t({sidebarSection:e})},setSettingsPage:e=>{t({settingsPage:e})},setSettingsProjectsSelectedId:e=>{t({settingsProjectsSelectedId:e})},setSettingsRemoteInstancesSelectedId:e=>{t({settingsRemoteInstancesSelectedId:e})},setEventStreamStatus:(e,n)=>{t({eventStreamStatus:e,eventStreamHint:n??null})},setShowReasoningTraces:e=>{t({showReasoningTraces:e})},setChatRenderMode:e=>{t({chatRenderMode:e})},setActivityRenderMode:e=>{t({activityRenderMode:e})},setShowDeletionDialog:e=>{t({showDeletionDialog:e})},setAutoDeleteEnabled:e=>{t({autoDeleteEnabled:e})},setAutoDeleteAfterDays:e=>{const n=Math.max(1,Math.min(365,e));t({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:e=>{t({autoDeleteLastRunAt:e})},setMessageLimit:e=>{const n=Math.max(10,Math.min(500,Math.round(e)));t({messageLimit:n})},setFontSize:e=>{const n=Math.max(50,Math.min(200,e));t({fontSize:n}),r().applyTypography()},setTerminalFontSize:e=>{const n=Math.round(e),o=Math.max(9,Math.min(52,n));t({terminalFontSize:o})},setPadding:e=>{const n=Math.max(50,Math.min(200,e));t({padding:n}),r().applyPadding()},setCornerRadius:e=>{t({cornerRadius:e})},applyTypography:()=>{const{fontSize:e}=r(),n=document.documentElement,o=e/100,s=Object.entries(vu);if(o===1){for(const[i]of s)n.style.removeProperty(hi(i));return}for(const[i,a]of s){const l=parseFloat(a);Number.isFinite(l)&&n.style.setProperty(hi(i),`${l*o}rem`)}},applyPadding:()=>{const{padding:e}=r(),n=document.documentElement,o=e/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const s=Math.sqrt(o);n.style.setProperty("--padding-scale",s.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:e=>{t({diffLayoutPreference:e})},setDiffFileLayout:(e,n)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[e]:n}}))},setDiffWrapLines:e=>{t({diffWrapLines:e})},setDiffViewMode:e=>{t({diffViewMode:e})},setInputBarOffset:e=>{t({inputBarOffset:e})},setKeyboardOpen:e=>{t({isKeyboardOpen:e})},toggleFavoriteModel:(e,n)=>{t(o=>o.favoriteModels.some(i=>i.providerID===e&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===e&&i.modelID===n))}:{favoriteModels:[{providerID:e,modelID:n},...o.favoriteModels]})},toggleHiddenModel:(e,n)=>{t(o=>o.hiddenModels.some(i=>i.providerID===e&&i.modelID===n)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===e&&i.modelID===n))}:{hiddenModels:[{providerID:e,modelID:n},...o.hiddenModels]})},isHiddenModel:(e,n)=>{const{hiddenModels:o}=r();return o.some(s=>s.providerID===e&&s.modelID===n)},hideAllModels:(e,n)=>{t(o=>{const s=o.hiddenModels.filter(a=>a.providerID!==e);return{hiddenModels:[...n.filter(a=>typeof a=="string"&&a.length>0).map(a=>({providerID:e,modelID:a})),...s]}})},showAllModels:e=>{t(n=>({hiddenModels:n.hiddenModels.filter(o=>o.providerID!==e)}))},toggleModelProviderCollapsed:e=>{const n=typeof e=="string"?e.trim():"";n&&t(o=>o.collapsedModelProviders.includes(n)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==n)}:{collapsedModelProviders:[...o.collapsedModelProviders,n]})},isFavoriteModel:(e,n)=>{const{favoriteModels:o}=r();return o.some(s=>s.providerID===e&&s.modelID===n)},addRecentModel:(e,n)=>{t(o=>{const s=o.recentModels.filter(i=>!(i.providerID===e&&i.modelID===n));return{recentModels:[{providerID:e,modelID:n},...s].slice(0,5)}})},addRecentAgent:e=>{const n=typeof e=="string"?e.trim():"";n&&t(o=>{if(o.recentAgents.includes(n))return o;const s=o.recentAgents;return{recentAgents:[n,...s].slice(0,5)}})},addRecentEffort:(e,n,o)=>{const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";if(!s||!i)return;const a=`${s}/${i}`,l=typeof o=="string"&&o.trim().length>0?o.trim():"default";t(c=>{const d=c.recentEfforts[a]??[];if(d.includes(l))return c;const u=d;return{recentEfforts:{...c.recentEfforts,[a]:[l,...u].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(e=>{const n={};return e.isBottomTerminalOpen&&!e.hasManuallyResizedBottomTerminal&&(n.bottomTerminalHeight=Math.floor(window.innerHeight*.32)),n})},applyTheme:()=>{const{theme:e}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),e==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(e)},setMultiRunLauncherOpen:e=>{t(n=>({isMultiRunLauncherOpen:e,multiRunLauncherPrefillPrompt:e?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:e=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:e,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:e=>{t({isTimelineDialogOpen:e})},setImagePreviewOpen:e=>{t({isImagePreviewOpen:e})},setAgentFlowOpen:e=>{t({isAgentFlowOpen:e})},setNativeNotificationsEnabled:e=>{t({nativeNotificationsEnabled:e})},setNotificationMode:e=>{t({notificationMode:e})},setShowTerminalQuickKeysOnDesktop:e=>{t({showTerminalQuickKeysOnDesktop:e})},setNotifyOnSubtasks:e=>{t({notifyOnSubtasks:e})},setNotifyOnCompletion:e=>{t({notifyOnCompletion:e})},setNotifyOnError:e=>{t({notifyOnError:e})},setNotifyOnQuestion:e=>{t({notifyOnQuestion:e})},setNotificationTemplates:e=>{t({notificationTemplates:e})},setSummarizeLastMessage:e=>{t({summarizeLastMessage:e})},setSummaryThreshold:e=>{t({summaryThreshold:e})},setSummaryLength:e=>{t({summaryLength:e})},setMaxLastMessageLength:e=>{t({maxLastMessageLength:e})},setPersistChatDraft:e=>{t({persistChatDraft:e})},setInputSpellcheckEnabled:e=>{t({inputSpellcheckEnabled:e})},setShowToolFileIcons:e=>{t({showToolFileIcons:e})},setShowExpandedBashTools:e=>{t({showExpandedBashTools:e})},setShowExpandedEditTools:e=>{t({showExpandedEditTools:e})},setMermaidRenderingMode:e=>{t({mermaidRenderingMode:e})},setUserMessageRenderingMode:e=>{t({userMessageRenderingMode:e})},setStickyUserHeader:e=>{t({stickyUserHeader:e})},setShowMobileSessionStatusBar:e=>{t({showMobileSessionStatusBar:e})},setIsMobileSessionStatusBarCollapsed:e=>{t({isMobileSessionStatusBarCollapsed:e})},setReportUsage:e=>{t({reportUsage:e})},viewPagerPage:"center",setViewPagerPage:e=>{t({viewPagerPage:e}),t(e==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:e==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(e,n)=>{t(o=>({shortcutOverrides:{...o.shortcutOverrides,[e]:n}}))},clearShortcutOverride:e=>{t(n=>{const o={...n.shortcutOverrides};return delete o[e],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{t({shortcutOverrides:{}})},toggleExpandedInput:()=>{t(e=>({isExpandedInput:!e.isExpandedInput}))},setExpandedInput:e=>{t({isExpandedInput:e})}}),{name:"ui-store",storage:rt(()=>ye()),version:7,migrate:(t,r)=>{if(!t||typeof t!="object")return t;const e=t;if(r<1&&Du(e.notificationTemplates)&&(e.notificationTemplates={completion:{...jt.completion},error:{...jt.error},question:{...jt.question},subtask:{...jt.subtask}}),r<3){const n=new Set([90,120,180,220]),o=e.memoryLimitHistorical,s=e.memoryLimitActiveSession;typeof o=="number"&&!n.has(o)?e.messageLimit=o:typeof s=="number"&&!n.has(s)&&(e.messageLimit=s),delete e.memoryLimitHistorical,delete e.memoryLimitViewport,delete e.memoryLimitActiveSession}if((typeof e.rightSidebarTab!="string"||e.rightSidebarTab!=="git"&&e.rightSidebarTab!=="files")&&(e.rightSidebarTab="git"),e.contextPanelByDirectory=No(e.contextPanelByDirectory),r<5)if(!e.shortcutOverrides||typeof e.shortcutOverrides!="object")e.shortcutOverrides={};else{const n=e.shortcutOverrides,o={};for(const[s,i]of Object.entries(n))typeof s=="string"&&typeof i=="string"&&(o[s]=i);e.shortcutOverrides=o}return r<6&&(e.contextPanelByDirectory=No(e.contextPanelByDirectory)),r<7&&(e.contextPanelByDirectory=No(e.contextPanelByDirectory)),e},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,rightSidebarTab:t.rightSidebarTab,contextPanelByDirectory:t.contextPanelByDirectory,isBottomTerminalOpen:t.isBottomTerminalOpen,isBottomTerminalExpanded:t.isBottomTerminalExpanded,bottomTerminalHeight:t.bottomTerminalHeight,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,settingsPage:t.settingsPage,settingsHasOpenedOnce:t.settingsHasOpenedOnce,settingsProjectsSelectedId:t.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:t.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,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,persistChatDraft:t.persistChatDraft,inputSpellcheckEnabled:t.inputSpellcheckEnabled,showToolFileIcons:t.showToolFileIcons,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,stickyUserHeader:t.stickyUserHeader,showMobileSessionStatusBar:t.showMobileSessionStatusBar,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,shortcutOverrides:t.shortcutOverrides})}),{name:"ui-store"})),Eu=Me()(ve(tt((t,r)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(e,n)=>{const s={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};t(i=>{const a=i.queuedMessages[e]??[];return{queuedMessages:{...i.queuedMessages,[e]:[...a,s]}}})},removeFromQueue:(e,n)=>{t(o=>{const i=(o.queuedMessages[e]??[]).filter(a=>a.id!==n);if(i.length===0){const{[e]:a,...l}=o.queuedMessages;return{queuedMessages:l}}return{queuedMessages:{...o.queuedMessages,[e]:i}}})},popToInput:(e,n)=>{const i=(r().queuedMessages[e]??[]).find(a=>a.id===n);return i?(t(a=>{const c=(a.queuedMessages[e]??[]).filter(d=>d.id!==n);if(c.length===0){const{[e]:d,...u}=a.queuedMessages;return{queuedMessages:u}}return{queuedMessages:{...a.queuedMessages,[e]:c}}}),i):null},clearQueue:e=>{t(n=>{const{[e]:o,...s}=n.queuedMessages;return{queuedMessages:s}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:e=>{t({queueModeEnabled:e}),Ze({queueModeEnabled:e})},getQueueForSession:e=>r().queuedMessages[e]??[]}),{name:"message-queue-store",storage:rt(()=>ye()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),cc="directoryTreeShowHidden",us="directory-show-hidden-change",wi=()=>{if(typeof window>"u")return!0;try{const t=ye().getItem(cc);return t===null?!0:t==="true"}catch{return!0}},xu=()=>{typeof window>"u"||window.dispatchEvent(new Event(us))},_u=(t,r={})=>{if(!(typeof window>"u")){try{ye().setItem(cc,t?"true":"false"),xu()}catch{}r.persist!==!1&&Ze({directoryShowHidden:t})}},qg=()=>{const t=Ra.c(2),[r,e]=R.useState(wi);let n,o;return t[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{e(wi())};return window.addEventListener("storage",s),window.addEventListener(us,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(us,s)}},o=[],t[0]=n,t[1]=o):(n=t[0],o=t[1]),R.useEffect(n,o),r},lc="filesViewShowGitignored",fs="files-view-show-gitignored-change",bi=()=>{if(typeof window>"u")return!1;try{return ye().getItem(lc)==="true"}catch{return!1}},Ru=()=>{typeof window>"u"||window.dispatchEvent(new Event(fs))},Ou=(t,r={})=>{if(!(typeof window>"u")){try{ye().setItem(lc,t?"true":"false"),Ru()}catch{}r.persist!==!1&&Ze({filesViewShowGitignored:t})}},Vg=()=>{const t=Ra.c(2),[r,e]=R.useState(bi);let n,o;return t[0]===Symbol.for("react.memo_cache_sentinel")?(n=()=>{if(typeof window>"u")return;const s=()=>{e(bi())};return window.addEventListener("storage",s),window.addEventListener(fs,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(fs,s)}},o=[],t[0]=n,t[1]=o):(n=t[0],o=t[1]),R.useEffect(n,o),r},ju=t=>{if(!t||typeof t!="object")return null;const r={};return typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),Object.keys(r).length>0?r:null},Fu=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},Lu=t=>{const r=Oe.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},Nu=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const r=JSON.parse(t),e=Fu(r);return ju(e)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let dc=null;const Kg=t=>{dc=t},Nt=()=>dc,ps=t=>{if(!(typeof window>"u")){if(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),window.__OPENCHAMBER_HOME__=t.homeDirectory),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(t.projects)&&t.projects.length>0){const r=t.projects.filter(e=>e.sidebarCollapsed===!0).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0);r.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(r)):localStorage.removeItem("oc.sessions.projectCollapse")}if(typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof t.directoryShowHidden=="boolean"&&localStorage.setItem("directoryTreeShowHidden",t.directoryShowHidden?"true":"false"),typeof t.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",t.filesViewShowGitignored?"true":"false"),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&localStorage.setItem("openInAppId",t.openInAppId),typeof t.pwaAppName=="string"){const r=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);r.length>0?localStorage.setItem("archcoder.pwaName",r):localStorage.removeItem("archcoder.pwaName")}}},$u=t=>{if(!Array.isArray(t))return;const r=[],e=new Set;for(const n of t){if(!n||typeof n!="object")continue;const o=n,s=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",a=typeof o.source=="string"?o.source.trim():"",l=typeof o.subpath=="string"?o.subpath.trim():"",c=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!s||!i||!a||e.has(s)||(e.add(s),r.push({id:s,label:i,source:a,...l?{subpath:l}:{},...c?{gitIdentityId:c}:{}}))}return r},Uu=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Bu=t=>{if(typeof t!="string")return null;const r=t.trim();return r&&Uu.test(r)?r.toLowerCase():null},zu=t=>{if(!Array.isArray(t))return;const r=[],e=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.path=="string"?s.path.trim():"";if(!i||!a)continue;const l=a==="/"?a:a.replace(/\\/g,"/").replace(/\/+$/,"");if(!l||e.has(i)||n.has(l))continue;e.add(i),n.add(l);const c={id:i,path:l};if(typeof s.label=="string"&&s.label.trim().length>0&&(c.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(c.icon=s.icon.trim()),s.iconImage===null)c.iconImage=null;else if(s.iconImage&&typeof s.iconImage=="object"){const d=s.iconImage,u=typeof d.mime=="string"?d.mime.trim():"",f=typeof d.updatedAt=="number"&&Number.isFinite(d.updatedAt)?Math.max(0,Math.round(d.updatedAt)):0,m=d.source==="custom"||d.source==="auto"?d.source:null;u&&f>0&&m&&(c.iconImage={mime:u,updatedAt:f,source:m})}if(typeof s.color=="string"&&s.color.trim().length>0&&(c.color=s.color.trim()),s.iconBackground===null)c.iconBackground=null;else{const d=Bu(s.iconBackground);d&&(c.iconBackground=d)}typeof s.addedAt=="number"&&Number.isFinite(s.addedAt)&&s.addedAt>=0&&(c.addedAt=s.addedAt),typeof s.lastOpenedAt=="number"&&Number.isFinite(s.lastOpenedAt)&&s.lastOpenedAt>=0&&(c.lastOpenedAt=s.lastOpenedAt),typeof s.sidebarCollapsed=="boolean"&&(c.sidebarCollapsed=s.sidebarCollapsed),r.push(c)}return r.length>0?r:void 0},Hu=t=>{if(!Array.isArray(t))return;const r=[],e=new Set,n=new Set;for(const o of t){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():"",l=typeof s.hostname=="string"?s.hostname.trim().toLowerCase():"";!i||!a||!l||e.has(i)||n.has(l)||(e.add(i),n.add(l),r.push({id:i,name:a,hostname:l}))}return r},Wu=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const r=t,e={};for(const[n,o]of Object.entries(r)){const s=n.trim(),i=typeof o=="string"?o.trim():"";!s||!i||(e[s]=i)}return Object.keys(e).length>0?e:void 0},Mi=(t,r)=>{if(!Array.isArray(t))return;const e=[],n=new Set;for(const o of t){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 l=`${i}/${a}`;if(!n.has(l)&&(n.add(l),e.push({providerID:i,modelID:a}),e.length>=r))break}return e},uc=()=>{const t=Oe.persist;if(t&&typeof t=="object")return t},fc=()=>Nt()?.settings??null,ms=t=>{const r=Oe.getState(),e=Eu.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,t.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}if(typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==e.queueModeEnabled&&e.setQueueMode(t.queueModeEnabled),typeof t.showDeletionDialog=="boolean"&&t.showDeletionDialog!==r.showDeletionDialog&&r.setShowDeletionDialog(t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==r.nativeNotificationsEnabled&&r.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==r.notificationMode&&r.setNotificationMode(t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&t.notifyOnSubtasks!==r.notifyOnSubtasks&&r.setNotifyOnSubtasks(t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&t.notifyOnCompletion!==r.notifyOnCompletion&&r.setNotifyOnCompletion(t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&t.notifyOnError!==r.notifyOnError&&r.setNotifyOnError(t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&t.notifyOnQuestion!==r.notifyOnQuestion&&r.setNotifyOnQuestion(t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"&&r.setNotificationTemplates(t.notificationTemplates),typeof t.summarizeLastMessage=="boolean"&&t.summarizeLastMessage!==r.summarizeLastMessage&&r.setSummarizeLastMessage(t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&r.setSummaryThreshold(t.summaryThreshold),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&r.setSummaryLength(t.summaryLength),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&r.setMaxLastMessageLength(t.maxLastMessageLength),typeof t.inputSpellcheckEnabled=="boolean"&&t.inputSpellcheckEnabled!==r.inputSpellcheckEnabled&&r.setInputSpellcheckEnabled(t.inputSpellcheckEnabled),typeof t.showToolFileIcons=="boolean"&&t.showToolFileIcons!==r.showToolFileIcons&&r.setShowToolFileIcons(t.showToolFileIcons),typeof t.showExpandedBashTools=="boolean"&&t.showExpandedBashTools!==r.showExpandedBashTools&&r.setShowExpandedBashTools(t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&t.showExpandedEditTools!==r.showExpandedEditTools&&r.setShowExpandedEditTools(t.showExpandedEditTools),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&t.chatRenderMode!==r.chatRenderMode&&r.setChatRenderMode(t.chatRenderMode),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&t.activityRenderMode!==r.activityRenderMode&&r.setActivityRenderMode(t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&t.mermaidRenderingMode!==r.mermaidRenderingMode&&r.setMermaidRenderingMode(t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&t.userMessageRenderingMode!==r.userMessageRenderingMode&&r.setUserMessageRenderingMode(t.userMessageRenderingMode),typeof t.stickyUserHeader=="boolean"&&t.stickyUserHeader!==r.stickyUserHeader&&r.setStickyUserHeader(t.stickyUserHeader),typeof t.reportUsage=="boolean"&&t.reportUsage!==r.reportUsage&&r.setReportUsage(t.reportUsage),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==r.fontSize&&r.setFontSize(t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&t.terminalFontSize!==r.terminalFontSize&&r.setTerminalFontSize(t.terminalFontSize),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==r.padding&&r.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==r.cornerRadius&&r.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==r.inputBarOffset&&r.setInputBarOffset(t.inputBarOffset),Array.isArray(t.favoriteModels)){const n=r.favoriteModels,o=t.favoriteModels;n.length===o.length&&n.every((i,a)=>i.providerID===o[a]?.providerID&&i.modelID===o[a]?.modelID)||Oe.setState({favoriteModels:o})}if(Array.isArray(t.recentModels)){const n=r.recentModels,o=t.recentModels;n.length===o.length&&n.every((i,a)=>i.providerID===o[a]?.providerID&&i.modelID===o[a]?.modelID)||Oe.setState({recentModels:o})}typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==r.diffLayoutPreference&&r.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.diffViewMode=="string"&&(t.diffViewMode==="single"||t.diffViewMode==="stacked")&&t.diffViewMode!==r.diffViewMode&&r.setDiffViewMode(t.diffViewMode),typeof t.directoryShowHidden=="boolean"&&_u(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&Ou(t.filesViewShowGitignored,{persist:!1})},vi=t=>{if(!t||typeof t!="object")return null;const r=t,e={};if(typeof r.themeId=="string"&&r.themeId.length>0&&(e.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(e.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(e.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(e.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(e.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(e.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(e.homeDirectory=r.homeDirectory),typeof r.opencodeBinary=="string"){const c=r.opencodeBinary.trim();e.opencodeBinary=c.length>0?c:void 0}const n=zu(r.projects);if(n&&(e.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(e.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(e.approvedDirectories=r.approvedDirectories.filter(c=>typeof c=="string"&&c.length>0)),Array.isArray(r.securityScopedBookmarks)&&(e.securityScopedBookmarks=r.securityScopedBookmarks.filter(c=>typeof c=="string"&&c.length>0)),Array.isArray(r.pinnedDirectories)&&(e.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(c=>typeof c=="string"&&c.length>0)))),typeof r.showReasoningTraces=="boolean"&&(e.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(e.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(e.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.tunnelProvider=="string"){const c=r.tunnelProvider.trim().toLowerCase();c.length>0&&(e.tunnelProvider=c)}if(typeof r.tunnelMode=="string"){const c=r.tunnelMode.trim().toLowerCase();(c==="quick"||c==="managed-remote"||c==="managed-local")&&(e.tunnelMode=c)}if(r.tunnelBootstrapTtlMs===null?e.tunnelBootstrapTtlMs=null:typeof r.tunnelBootstrapTtlMs=="number"&&Number.isFinite(r.tunnelBootstrapTtlMs)&&(e.tunnelBootstrapTtlMs=r.tunnelBootstrapTtlMs),typeof r.tunnelSessionTtlMs=="number"&&Number.isFinite(r.tunnelSessionTtlMs)&&(e.tunnelSessionTtlMs=r.tunnelSessionTtlMs),r.managedLocalTunnelConfigPath===null)e.managedLocalTunnelConfigPath=null;else if(typeof r.managedLocalTunnelConfigPath=="string"){const c=r.managedLocalTunnelConfigPath.trim();e.managedLocalTunnelConfigPath=c.length>0?c:null}typeof r.managedRemoteTunnelHostname=="string"&&(e.managedRemoteTunnelHostname=r.managedRemoteTunnelHostname.trim()),r.managedRemoteTunnelToken===null?e.managedRemoteTunnelToken=null:typeof r.managedRemoteTunnelToken=="string"&&(e.managedRemoteTunnelToken=r.managedRemoteTunnelToken.trim());const o=Hu(r.managedRemoteTunnelPresets);if(o&&(e.managedRemoteTunnelPresets=o),typeof r.managedRemoteTunnelSelectedPresetId=="string"){const c=r.managedRemoteTunnelSelectedPresetId.trim();e.managedRemoteTunnelSelectedPresetId=c.length>0?c:void 0}const s=Wu(r.managedRemoteTunnelPresetTokens);if(s&&(e.managedRemoteTunnelPresetTokens=s),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(e.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(e.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(e.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(e.autoCreateWorktree=r.autoCreateWorktree),typeof r.gitmojiEnabled=="boolean"&&(e.gitmojiEnabled=r.gitmojiEnabled),typeof r.queueModeEnabled=="boolean"&&(e.queueModeEnabled=r.queueModeEnabled),typeof r.showDeletionDialog=="boolean"&&(e.showDeletionDialog=r.showDeletionDialog),typeof r.nativeNotificationsEnabled=="boolean"&&(e.nativeNotificationsEnabled=r.nativeNotificationsEnabled),typeof r.notificationMode=="string"&&(r.notificationMode==="always"||r.notificationMode==="hidden-only")&&(e.notificationMode=r.notificationMode),typeof r.notifyOnSubtasks=="boolean"&&(e.notifyOnSubtasks=r.notifyOnSubtasks),typeof r.notifyOnCompletion=="boolean"&&(e.notifyOnCompletion=r.notifyOnCompletion),typeof r.notifyOnError=="boolean"&&(e.notifyOnError=r.notifyOnError),typeof r.notifyOnQuestion=="boolean"&&(e.notifyOnQuestion=r.notifyOnQuestion),r.notificationTemplates&&typeof r.notificationTemplates=="object"){const c=r.notificationTemplates,d=g=>{const S=c[g];if(!S||typeof S!="object")return;const h=S,v=typeof h.title=="string"?h.title:"",b=typeof h.message=="string"?h.message:"";return{title:v,message:b}},u=d("completion"),f=d("error"),m=d("question"),p=d("subtask");(u||f||m||p)&&(e.notificationTemplates={completion:u??{title:"Task Complete",message:"Your task has finished."},error:f??{title:"Error Occurred",message:"An error occurred while processing your task."},question:m??{title:"Input Needed",message:"Please provide input to continue."},subtask:p??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof r.summarizeLastMessage=="boolean"&&(e.summarizeLastMessage=r.summarizeLastMessage),typeof r.summaryThreshold=="number"&&Number.isFinite(r.summaryThreshold)&&(e.summaryThreshold=Math.max(0,Math.round(r.summaryThreshold))),typeof r.summaryLength=="number"&&Number.isFinite(r.summaryLength)&&(e.summaryLength=Math.max(10,Math.round(r.summaryLength))),typeof r.maxLastMessageLength=="number"&&Number.isFinite(r.maxLastMessageLength)&&(e.maxLastMessageLength=Math.max(10,Math.round(r.maxLastMessageLength))),typeof r.usageAutoRefresh=="boolean"&&(e.usageAutoRefresh=r.usageAutoRefresh),typeof r.usageRefreshIntervalMs=="number"&&Number.isFinite(r.usageRefreshIntervalMs)&&(e.usageRefreshIntervalMs=r.usageRefreshIntervalMs),(r.usageDisplayMode==="usage"||r.usageDisplayMode==="remaining")&&(e.usageDisplayMode=r.usageDisplayMode),Array.isArray(r.usageDropdownProviders)&&(e.usageDropdownProviders=r.usageDropdownProviders.filter(c=>typeof c=="string"&&c.length>0)),r.usageSelectedModels&&typeof r.usageSelectedModels=="object"){const c={};for(const[d,u]of Object.entries(r.usageSelectedModels))Array.isArray(u)&&(c[d]=u.filter(f=>typeof f=="string"));Object.keys(c).length>0&&(e.usageSelectedModels=c)}if(r.usageCollapsedFamilies&&typeof r.usageCollapsedFamilies=="object"){const c={};for(const[d,u]of Object.entries(r.usageCollapsedFamilies))Array.isArray(u)&&(c[d]=u.filter(f=>typeof f=="string"));Object.keys(c).length>0&&(e.usageCollapsedFamilies=c)}if(r.usageExpandedFamilies&&typeof r.usageExpandedFamilies=="object"){const c={};for(const[d,u]of Object.entries(r.usageExpandedFamilies))Array.isArray(u)&&(c[d]=u.filter(f=>typeof f=="string"));Object.keys(c).length>0&&(e.usageExpandedFamilies=c)}if(r.usageModelGroups&&typeof r.usageModelGroups=="object"){const c={};for(const[d,u]of Object.entries(r.usageModelGroups))if(u&&typeof u=="object"){const f=u,m={};Array.isArray(f.customGroups)&&(m.customGroups=f.customGroups.filter(p=>p&&typeof p=="object").map(p=>({id:String(p.id??""),label:String(p.label??""),models:Array.isArray(p.models)?p.models.filter(g=>typeof g=="string"):[],order:typeof p.order=="number"?p.order:0}))),f.modelAssignments&&typeof f.modelAssignments=="object"&&(m.modelAssignments=Object.fromEntries(Object.entries(f.modelAssignments).filter(([,p])=>typeof p=="string").map(([p,g])=>[p,String(g)]))),f.renamedGroups&&typeof f.renamedGroups=="object"&&(m.renamedGroups=Object.fromEntries(Object.entries(f.renamedGroups).filter(([,p])=>typeof p=="string").map(([p,g])=>[p,String(g)]))),Object.keys(m).length>0&&(c[d]=m)}Object.keys(c).length>0&&(e.usageModelGroups=c)}typeof r.inputSpellcheckEnabled=="boolean"&&(e.inputSpellcheckEnabled=r.inputSpellcheckEnabled),typeof r.showToolFileIcons=="boolean"&&(e.showToolFileIcons=r.showToolFileIcons),typeof r.showExpandedBashTools=="boolean"&&(e.showExpandedBashTools=r.showExpandedBashTools),typeof r.showExpandedEditTools=="boolean"&&(e.showExpandedEditTools=r.showExpandedEditTools),typeof r.chatRenderMode=="string"&&(r.chatRenderMode==="sorted"||r.chatRenderMode==="live")&&(e.chatRenderMode=r.chatRenderMode),typeof r.activityRenderMode=="string"&&(r.activityRenderMode==="collapsed"||r.activityRenderMode==="summary")&&(e.activityRenderMode=r.activityRenderMode),typeof r.mermaidRenderingMode=="string"&&(r.mermaidRenderingMode==="svg"||r.mermaidRenderingMode==="ascii")&&(e.mermaidRenderingMode=r.mermaidRenderingMode),typeof r.userMessageRenderingMode=="string"&&(r.userMessageRenderingMode==="markdown"||r.userMessageRenderingMode==="plain")&&(e.userMessageRenderingMode=r.userMessageRenderingMode),typeof r.stickyUserHeader=="boolean"&&(e.stickyUserHeader=r.stickyUserHeader),typeof r.fontSize=="number"&&Number.isFinite(r.fontSize)&&(e.fontSize=r.fontSize),typeof r.terminalFontSize=="number"&&Number.isFinite(r.terminalFontSize)&&(e.terminalFontSize=r.terminalFontSize),typeof r.padding=="number"&&Number.isFinite(r.padding)&&(e.padding=r.padding),typeof r.cornerRadius=="number"&&Number.isFinite(r.cornerRadius)&&(e.cornerRadius=r.cornerRadius),typeof r.inputBarOffset=="number"&&Number.isFinite(r.inputBarOffset)&&(e.inputBarOffset=r.inputBarOffset);const i=Mi(r.favoriteModels,64);i&&(e.favoriteModels=i);const a=Mi(r.recentModels,16);if(a&&(e.recentModels=a),typeof r.diffLayoutPreference=="string"&&(r.diffLayoutPreference==="dynamic"||r.diffLayoutPreference==="inline"||r.diffLayoutPreference==="side-by-side")&&(e.diffLayoutPreference=r.diffLayoutPreference),typeof r.diffViewMode=="string"&&(r.diffViewMode==="single"||r.diffViewMode==="stacked")&&(e.diffViewMode=r.diffViewMode),typeof r.directoryShowHidden=="boolean"&&(e.directoryShowHidden=r.directoryShowHidden),typeof r.filesViewShowGitignored=="boolean"&&(e.filesViewShowGitignored=r.filesViewShowGitignored),typeof r.openInAppId=="string"&&r.openInAppId.length>0&&(e.openInAppId=r.openInAppId),typeof r.pwaAppName=="string"){const c=r.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);e.pwaAppName=c.length>0?c:""}const l=$u(r.skillCatalogs);return l&&(e.skillCatalogs=l),typeof r.reportUsage=="boolean"&&(e.reportUsage=r.reportUsage),e},Gu=async()=>{const t=fc();if(t)try{const r=await t.load();return vi(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const e=await r.json().catch(()=>null);return vi(e)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Jg=async()=>{if(typeof window>"u")return;const t=uc(),r=e=>{ps(e);const n=()=>ms(e);if(t?.hasHydrated?.())n();else if(n(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("archcoder:settings-synced",{detail:e}))};try{const e=await Gu();e&&r(e)}catch(e){console.warn("Failed to synchronise settings:",e)}},Ze=async t=>{if(typeof window>"u")return;const r=fc();if(r)try{const e=await r.save(t);e&&(ps(e),ms(e));return}catch(e){console.warn("Failed to update settings via runtime settings API:",e)}try{const e=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!e.ok){console.warn("Failed to update shared settings via API:",e.status,e.statusText);return}const n=await e.json().catch(()=>null);n&&(ps(n),ms(n))}catch(e){console.warn("Failed to update shared settings via API:",e)}},Qg=async()=>{if(typeof window>"u")return;const t=uc();try{const r=await Nu();if(!r)return;const e=()=>Lu(r);if(t?.hasHydrated?.()){e();return}if(e(),t?.onFinishHydration){const n=t.onFinishHydration(()=>{n?.(),e()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},qu=3e4,Vu=40,Ku=60,Ju=(t,r,e,n,o,s)=>{const i=t.trim(),a=r.trim().toLowerCase();return`${i}::${a}::${e}::${n?"1":"0"}::${o?"1":"0"}::${s}`},Qu=Me()(ve((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(e,n,o=Ku,s){if(!e||e.trim().length===0)return[];const i=e.trim(),a=typeof n=="string"?n.trim():"",l=!!s?.includeHidden,c=s?.respectGitignore??!0,d=s?.type==="directory"?"directory":"file",u=Ju(i,a,o,l,c,d),f=Date.now(),m=r().cache[u];if(m&&f-m.timestamp<qu)return m.files;const p=r().inFlight[u];if(p)return p;const g=O.searchFiles(a,{directory:i,limit:o,includeHidden:l,respectGitignore:c,dirs:d!=="file",type:d}).then(S=>(t(h=>{const v={...h.cache,[u]:{files:S,timestamp:Date.now()}},b=h.cacheKeys.filter(D=>D!==u);for(b.push(u);b.length>Vu;){const D=b.shift();D&&delete v[D]}return{cache:v,cacheKeys:b}}),S)).finally(()=>{t(S=>{const h={...S.inFlight};return delete h[u],{inFlight:h}})});return t(S=>({inFlight:{...S.inFlight,[u]:g}})),g},invalidateDirectory(e){if(!e||e.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${e.trim()}::`;t(s=>{const i={...s.cache},a=s.cacheKeys.filter(d=>d.startsWith(o)?(delete i[d],!1):!0),l=Object.entries(s.inFlight).filter(([d])=>!d.startsWith(o)),c=Object.fromEntries(l);return{cache:i,cacheKeys:a,inFlight:c}})}}),{name:"file-search-store"})),we=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("archcoder_stream_debug")==="1"}catch{return!1}};var Yu={};let St=null;const at=ye(),Di=at.getItem("lastDirectory"),Xu=typeof Di=="string"&&Di.length>0,Cn=t=>{try{Qu.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Dr=t=>{const r=t.trim();if(!r)return r;const e=r.replace(/\\/g,"/");return e.length>1?e.replace(/\/+$/,""):e},Zu=(t,r)=>{const e=t.trim();return e.startsWith("~")?e==="~"?r||e:(e.startsWith("~/")||e.startsWith("~\\"))&&r?`${r}${e.slice(1)}`:e:e},Wn=(t,r)=>{const e=Zu(t,r);return Dr(e)},ef=()=>{const t=at.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const r=Dr(t);return r.length>0?r:null},tf=()=>{const t=at.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const r=Dr(t);return r.length>0?r:null},rf=()=>{if(typeof process>"u")return null;const t=Yu,r=t?.HOME||t?.USERPROFILE||(t?.HOMEDRIVE&&t?.HOMEPATH?`${t.HOMEDRIVE}${t.HOMEPATH}`:void 0);if(typeof r=="string"&&r.trim().length>0){const n=Dr(r);return n.length>0?n:null}const e=process?.cwd?.();if(typeof e=="string"&&e.trim().length>0){const n=Dr(e);return n.length>0?n:null}return null},oo=()=>{if(typeof window<"u"){if(St)return St;const r=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(r&&r.length>0)return St=r,at.setItem("homeDirectory",r),r;const e=ef();if(e&&!nr())return St=e,e}const t=rf();return t||"/"},nf=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const e=r.replace(/\\/g,"/");if(e.length>1){const n=e.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return e==="/"||e.length===0?null:e},of=t=>(St=t,typeof window<"u"&&at.setItem("homeDirectory",t),Ze({homeDirectory:t}),t),pc=async()=>{const t=n=>{const o=nf(n);return o?of(o):null};try{const n=await O.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await O.getSystemInfo(),o=t(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await mo(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=oo(),e=t(r);return e||r},sf=()=>{if(!nr())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=Dr(t);return r.length>0?r:null},dn=sf()||oo(),so=(()=>{const t=tf();return t&&!nr()?Wn(t,dn):dn})();so&&O.setDirectory(so);const af=!!(dn&&dn!=="/"),be=Me()(ve((t,r)=>({currentDirectory:so,directoryHistory:[so],historyIndex:0,homeDirectory:dn,hasPersistedDirectory:Xu,isHomeReady:af,isSwitchingDirectory:!1,setDirectory:(e,n)=>{const o=St||r().homeDirectory||at.getItem("homeDirectory"),s=Wn(e,o);we()&&console.log("[DirectoryStore] setDirectory called with path:",s),O.setDirectory(s),Cn(),t(i=>{const a=[...i.directoryHistory.slice(0,i.historyIndex+1),s];return at.setItem("lastDirectory",s),Ze({lastDirectory:s}),{currentDirectory:s,directoryHistory:a,historyIndex:a.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const e=r();if(e.historyIndex>0){const n=e.historyIndex-1,o=e.directoryHistory[n];O.setDirectory(o),Cn(),at.setItem("lastDirectory",o),Ze({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const e=r();if(e.historyIndex<e.directoryHistory.length-1){const n=e.historyIndex+1,o=e.directoryHistory[n];O.setDirectory(o),Cn(),at.setItem("lastDirectory",o),Ze({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:e,setDirectory:n}=r(),o=St||r().homeDirectory||oo();if(e===o||e==="/")return;const s=e.endsWith("/")?e.slice(0,-1):e,i=s.lastIndexOf("/");if(i===-1){const a=St||oo();n(a)}else n(i===0?"/":s.substring(0,i))},goHome:async()=>{const e=St||r().homeDirectory||await pc();r().setDirectory(e)},synchronizeHomeDirectory:e=>{const n=r(),o=e;St=o;const s=n.homeDirectory!==o,i=at.getItem("lastDirectory"),a=typeof i=="string"&&i.length>0,l=!a&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!s&&!l){n.isHomeReady||t({isHomeReady:!0});return}const c=typeof o=="string"&&o!==""&&o!=="/",d=n.currentDirectory?Wn(n.currentDirectory,o):n.currentDirectory,u=n.directoryHistory.map(g=>Wn(g,o)),f=u.some((g,S)=>g!==n.directoryHistory[S]),m=!!(d&&d!==n.currentDirectory),p={homeDirectory:o,hasPersistedDirectory:a,isHomeReady:c};if(l?(p.currentDirectory=o,p.directoryHistory=[o],p.historyIndex=0,p.isSwitchingDirectory=!1):(m||f)&&(p.currentDirectory=d,p.directoryHistory=u,p.historyIndex=Math.min(n.historyIndex,u.length-1),p.isSwitchingDirectory=!1),t(()=>p),(l||m)&&c){const g=l?o:d;O.setDirectory(g),Cn(),at.setItem("lastDirectory",g),Ze({lastDirectory:g})}Ze({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&pc().then(t=>{be.getState().synchronizeHomeDirectory(t)});const cf=[{key:"code",Icon:nl,label:"Code"},{key:"terminal",Icon:ol,label:"Terminal"},{key:"rocket",Icon:sl,label:"Rocket"},{key:"flask",Icon:il,label:"Lab"},{key:"gamepad",Icon:al,label:"Game"},{key:"briefcase",Icon:cl,label:"Work"},{key:"home",Icon:ll,label:"Home"},{key:"globe",Icon:dl,label:"Web"},{key:"leaf",Icon:ul,label:"Nature"},{key:"shield",Icon:fl,label:"Security"},{key:"palette",Icon:pl,label:"Design"},{key:"server",Icon:ml,label:"Server"},{key:"phone",Icon:gl,label:"Mobile"},{key:"database",Icon:yl,label:"Data"},{key:"lightbulb",Icon:hl,label:"Idea"},{key:"music",Icon:Sl,label:"Music"},{key:"camera",Icon:wl,label:"Media"},{key:"book",Icon:bl,label:"Docs"},{key:"heart",Icon:Ml,label:"Favorite"}],Yg=Object.fromEntries(cf.map(t=>[t.key,t.Icon])),mc=[{key:"keyword",label:"Purple",cssVar:"var(--syntax-keyword)"},{key:"string",label:"Green",cssVar:"var(--syntax-string)"},{key:"number",label:"Pink",cssVar:"var(--syntax-number)"},{key:"type",label:"Gold",cssVar:"var(--syntax-type)"},{key:"constant",label:"Cyan",cssVar:"var(--syntax-constant)"},{key:"comment",label:"Muted",cssVar:"var(--syntax-comment)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"primary",label:"Blue",cssVar:"var(--primary)"},{key:"success",label:"Green",cssVar:"var(--status-success)"}],Xg=Object.fromEntries(mc.map(t=>[t.key,t.cssVar])),Zg=(t,r)=>{if(!t.iconImage||typeof t.iconImage.updatedAt!="number"||t.iconImage.updatedAt<=0)return null;const e=new URLSearchParams({v:String(t.iconImage.updatedAt)});return typeof r?.iconColor=="string"&&r.iconColor.trim()&&e.set("iconColor",r.iconColor.trim()),(r?.themeVariant==="light"||r?.themeVariant==="dark")&&e.set("theme",r.themeVariant),`/api/projects/${encodeURIComponent(t.id)}/icon?${e.toString()}`},lf=t=>{const r=mc.map(s=>s.key),e=new Map;for(const s of r)e.set(s,0);for(const s of t)s.color&&e.has(s.color)&&e.set(s.color,(e.get(s.color)??0)+1);const n=Math.min(...e.values()),o=r.filter(s=>e.get(s)===n);return o[Math.floor(Math.random()*o.length)]},br=ye(),gc="projects",gs="activeProjectId",df=(t,r)=>{const e=t.trim();return!e.startsWith("~")||!r?e:e==="~"?r:e.startsWith("~/")||e.startsWith("~\\")?`${r}${e.slice(1)}`:e},uf=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,yc=t=>{if(typeof t!="string")return null;const r=t.trim();return r&&uf.test(r)?r.toLowerCase():null},So=t=>{const r=t.trim();if(!r)return"";const e=br.getItem("homeDirectory")||be.getState().homeDirectory||"",o=df(r,e).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},hc=t=>{const r=So(t);if(!r||r==="/")return"Root";const e=r.split("/").filter(Boolean);return(e[e.length-1]||r).replace(/[-_]/g," ").replace(/\b\w/g,o=>o.toUpperCase())},ff=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,pf=t=>{if(!t||typeof t!="object")return;const r=t,e=typeof r.mime=="string"?r.mime.trim():"",n=typeof r.updatedAt=="number"&&Number.isFinite(r.updatedAt)?Math.max(0,Math.round(r.updatedAt)):0,o=r.source==="custom"||r.source==="auto"?r.source:null;if(!(!e||!n||!o))return{mime:e,updatedAt:n,source:o}},mf=t=>{const r=typeof t.type=="string"?t.type.trim().toLowerCase():"";if(r==="image/png"||r==="image/jpeg"||r==="image/svg+xml")return r;const e=t.name.toLowerCase();return e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".svg")?"image/svg+xml":null},gf=async t=>await new Promise((r,e)=>{const n=new FileReader;n.onerror=()=>{e(new Error("Failed to read icon file"))},n.onload=()=>{const o=typeof n.result=="string"?n.result:"";if(!o){e(new Error("Failed to read icon file"));return}r(o)},n.readAsDataURL(t)}),Sc=t=>{if(!Array.isArray(t))return[];const r=[],e=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const s=o,i=typeof s.id=="string"?s.id.trim():"",a=typeof s.path=="string"?s.path.trim():"";if(!i||!a)continue;const l=So(a);if(!l||e.has(i)||n.has(l))continue;e.add(i),n.add(l);const c={id:i,path:l};if(typeof s.label=="string"&&s.label.trim().length>0&&(c.label=s.label.trim()),typeof s.icon=="string"&&s.icon.trim().length>0&&(c.icon=s.icon.trim()),s.iconImage===null)c.iconImage=null;else{const d=pf(s.iconImage);d&&(c.iconImage=d)}if(typeof s.color=="string"&&s.color.trim().length>0&&(c.color=s.color.trim()),s.iconBackground===null)c.iconBackground=null;else{const d=yc(s.iconBackground);d&&(c.iconBackground=d)}typeof s.addedAt=="number"&&Number.isFinite(s.addedAt)&&s.addedAt>=0&&(c.addedAt=s.addedAt),typeof s.lastOpenedAt=="number"&&Number.isFinite(s.lastOpenedAt)&&s.lastOpenedAt>=0&&(c.lastOpenedAt=s.lastOpenedAt),typeof s.sidebarCollapsed=="boolean"&&(c.sidebarCollapsed=s.sidebarCollapsed),r.push(c)}return r},yf=()=>{try{const t=br.getItem(gc);return t?Sc(JSON.parse(t)):[]}catch{return[]}},hf=()=>{try{const t=br.getItem(gs);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},Cs=(t,r)=>{try{br.setItem(gc,JSON.stringify(t))}catch{}try{r?br.setItem(gs,r):br.removeItem(gs)}catch{}},gr=(t,r)=>{Cs(t,r),Ze({projects:t,activeProjectId:r??void 0})},Sf=yf(),wf=()=>{if(typeof window>"u"||!(window.__ARCHCODER_RUNTIME_APIS__||window.__OPENCHAMBER_RUNTIME_APIS__)?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const e=So(r);if(!e)return null;const n=`vscode:${e}`,o={id:n,path:e,label:hc(e),addedAt:Date.now(),lastOpenedAt:Date.now()};return we()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},$e=wf(),Es=$e?.projects??Sf,wc=$e?.activeProjectId??hf()??Es[0]?.id??null;$e&&Cs(Es,wc);const et=Me()(ve((t,r)=>({projects:Es,activeProjectId:wc,validateProjectPath:e=>{if(typeof e!="string"||e.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=So(e);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(e,n)=>{if($e)return null;const{validateProjectPath:o}=r(),s=o(e);if(!s.ok||!s.normalizedPath)return null;const i=s.normalizedPath,a=r().projects.find(p=>p.path===i);if(a)return r().setActiveProject(a.id),a;const l=Date.now(),c=n?.label?.trim()||hc(i),d=n?.id?.trim(),f={id:d&&!r().projects.some(p=>p.id===d)?d:ff(),path:i,label:c,color:lf(r().projects),addedAt:l,lastOpenedAt:l},m=[...r().projects,f];return t({projects:m}),we()&&console.info("[ProjectsStore] Added project",f),r().setActiveProject(f.id),r().discoverProjectIcon(f.id),f},removeProject:e=>{if($e)return;const n=r(),o=n.projects.filter(i=>i.id!==e);let s=n.activeProjectId;if(n.activeProjectId===e&&(s=o[0]?.id??null),t({projects:o,activeProjectId:s}),gr(o,s),s){const i=o.find(a=>a.id===s);i&&(O.setDirectory(i.path),be.getState().setDirectory(i.path,{showOverlay:!1}))}else be.getState().goHome()},setActiveProject:e=>{if($e)return;const{projects:n,activeProjectId:o}=r();if(o===e)return;const s=n.find(l=>l.id===e);if(!s)return;const i=Date.now(),a=n.map(l=>l.id===e?{...l,lastOpenedAt:i}:l);t({projects:a,activeProjectId:e}),gr(a,e),O.setDirectory(s.path),be.getState().setDirectory(s.path,{showOverlay:!1})},setActiveProjectIdOnly:e=>{if($e)return;const{projects:n,activeProjectId:o}=r();if(o===e||!n.find(l=>l.id===e))return;const i=Date.now(),a=n.map(l=>l.id===e?{...l,lastOpenedAt:i}:l);t({projects:a,activeProjectId:e}),gr(a,e)},renameProject:(e,n)=>{if($e)return;const o=n.trim();if(!o)return;const{projects:s,activeProjectId:i}=r(),a=s.map(l=>l.id===e?{...l,label:o}:l);t({projects:a}),gr(a,i)},updateProjectMeta:(e,n)=>{if($e)return;const{projects:o,activeProjectId:s}=r(),i=o.map(a=>{if(a.id!==e)return a;const l={...a};if(n.label!==void 0){const c=n.label.trim();c&&(l.label=c)}return n.icon!==void 0&&(l.icon=n.icon),n.color!==void 0&&(l.color=n.color),n.iconBackground!==void 0&&(l.iconBackground=yc(n.iconBackground)),l});t({projects:i}),gr(i,s)},uploadProjectIcon:async(e,n)=>{if($e)return{ok:!1,error:"Custom icons are not supported in this runtime"};const o=mf(n);if(!o)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(n.size)||n.size<=0)return{ok:!1,error:"Icon file is empty"};if(n.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await gf(n)).replace(/^data:[^;]+;/i,`data:${o};`),a=await fetch(`/api/projects/${encodeURIComponent(e)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!a.ok)return{ok:!1,error:(await a.json().catch(()=>null))?.error||"Failed to upload project icon"};const l=await a.json().catch(()=>null);return l?.settings&&r().synchronizeFromSettings(l.settings),{ok:!0}}catch(s){return{ok:!1,error:(s instanceof Error?s.message:String(s))||"Failed to upload project icon"}}},removeProjectIcon:async e=>{if($e)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const n=await fetch(`/api/projects/${encodeURIComponent(e)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!n.ok)return{ok:!1,error:(await n.json().catch(()=>null))?.error||"Failed to remove project icon"};const o=await n.json().catch(()=>null);return o?.settings&&r().synchronizeFromSettings(o.settings),{ok:!0}}catch(n){return{ok:!1,error:(n instanceof Error?n.message:String(n))||"Failed to remove project icon"}}},discoverProjectIcon:async(e,n)=>{if($e)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const o=await fetch(`/api/projects/${encodeURIComponent(e)}/icon/discover`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({force:n?.force===!0})}),s=await o.json().catch(()=>null);return o.ok?(s?.settings&&r().synchronizeFromSettings(s.settings),{ok:!0,skipped:s?.skipped===!0,reason:typeof s?.reason=="string"?s.reason:void 0}):{ok:!1,error:s?.error||"Failed to discover project icon"}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to discover project icon"}}},reorderProjects:(e,n)=>{if($e)return;const{projects:o,activeProjectId:s}=r();if(e<0||e>=o.length||n<0||n>=o.length||e===n)return;const i=[...o],[a]=i.splice(e,1);i.splice(n,0,a),t({projects:i}),gr(i,s)},synchronizeFromSettings:e=>{if($e)return;const n=Sc(e.projects??[]),o=typeof e.activeProjectId=="string"&&e.activeProjectId.trim()?e.activeProjectId.trim():null,s=r(),i=JSON.stringify(s.projects)!==JSON.stringify(n),a=s.activeProjectId!==o;if(!(!i&&!a)&&(t({projects:n,activeProjectId:o}),Cs(n,o),o)){const l=n.find(c=>c.id===o);l&&(O.setDirectory(l.path),be.getState().setDirectory(l.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:e,activeProjectId:n}=r();return n?e.find(o=>o.id===n)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("archcoder:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&et.getState().synchronizeFromSettings(r)});const bf=new Set(["init","review"]),ey=t=>bf.has(t.name),Qr="useCommandsStore",ys=t=>new Promise(r=>setTimeout(r,t)),Mf=5e3,vf="__default__",Ii=new Map,$o=new Map,Df=t=>t?.trim()||vf,Ai=t=>t.map(r=>[r.name,r.scope??"",r.description??"",r.agent??"",r.model??"",String(r.isBuiltIn===!0)].join("|")).join("||"),En=()=>{try{const r=et.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const e=O.getDirectory();if(e?.trim())return e.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},If=2e4,Pi=300,Ti=4,Af=800,Pf=200,Tf=2e3,wo=Me()(ve(tt((t,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:e=>{t({selectedCommandName:e})},setCommandDraft:e=>{t({commandDraft:e})},loadCommands:async()=>{const e=En(),n=Df(e),o=Date.now(),s=Ii.get(n)??0;if(r().commands.length>0&&o-s<Mf)return!0;const a=$o.get(n);if(a)return a;const l=(async()=>{t({isLoading:!0});const c=r().commands,d=Ai(c);let u=null;for(let f=0;f<3;f++)try{const m=e?`?directory=${encodeURIComponent(e)}`:"",p=await O.withDirectory(e,()=>O.listCommandsWithDetails()),g=await Promise.all(p.map(async h=>{try{const v=await fetch(`/api/config/commands/${encodeURIComponent(h.name)}${m}`,{headers:{"Cache-Control":"no-cache",...e?{"x-opencode-directory":e}:{}}});if(v.ok){const b=await v.json();let D=b.scope;if(!D&&b.sources){const I=b.sources;D=(I.md?.exists?I.md.scope:void 0)??(I.json?.exists?I.json.scope:void 0)??I.md?.scope??I.json?.scope}return D==="project"||D==="user"?{...h,scope:D}:{...h,scope:void 0}}}catch(v){console.warn(`[CommandsStore] Failed to fetch config for command ${h.name}:`,v)}return h})),S=Ai(g);return t(d!==S?{commands:g,isLoading:!1}:{isLoading:!1}),Ii.set(n,Date.now()),!0}catch(m){u=m;const p=200*(f+1);await new Promise(g=>setTimeout(g,p))}return console.error("Failed to load commands:",u),t({commands:c,isLoading:!1}),!1})();$o.set(n,l);try{return await l}finally{$o.delete(n)}},createCommand:async e=>{lt("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",e.name);const o={template:e.template||""};e.description&&(o.description=e.description),e.agent&&(o.agent=e.agent),e.model&&(o.model=e.model),e.scope&&(o.scope=e.scope),console.log("[CommandsStore] Command config to save:",o);const s=En(),i=s?`?directory=${encodeURIComponent(s)}`:"",a=await fetch(`/api/config/commands/${encodeURIComponent(e.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-opencode-directory":s}:{}},body:JSON.stringify(o)}),l=await a.json().catch(()=>null);if(!a.ok){const u=l?.error||"Failed to create command";throw new Error(u)}if(console.log("[CommandsStore] Command created successfully"),l?.requiresReload??!0)return n=!0,await Uo({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await r().loadCommands();return d&&ct("commands",{source:Qr}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||ze()}},updateCommand:async(e,n)=>{lt("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",e),console.log("[CommandsStore] Config received:",n);const s={};n.description!==void 0&&(s.description=n.description),n.agent!==void 0&&(s.agent=n.agent),n.model!==void 0&&(s.model=n.model),n.template!==void 0&&(s.template=n.template),console.log("[CommandsStore] Command config to update:",s);const i=En(),a=i?`?directory=${encodeURIComponent(i)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(e)}${a}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(s)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to update command";throw new Error(f)}if(console.log("[CommandsStore] Command updated successfully"),c?.requiresReload??!0)return o=!0,await Uo({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&ct("commands",{source:Qr}),u}catch(s){return console.error("[CommandsStore] Failed to update command:",s),!1}finally{o||ze()}},deleteCommand:async e=>{lt("Deleting command configuration…");let n=!1;try{const o=En(),s=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(e)}${s}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),a=await i.json().catch(()=>null);if(!i.ok){const d=a?.error||"Failed to delete command";throw new Error(d)}if(console.log("[CommandsStore] Command deleted successfully"),a?.requiresReload??!0)return n=!0,await Uo({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await r().loadCommands();return c&&ct("commands",{source:Qr}),r().selectedCommandName===e&&t({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||ze()}},getCommandByName:e=>{const{commands:n}=r();return n.find(o=>o.name===e)}}),{name:"commands-store",storage:rt(()=>ye()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=wo);async function kf(t){const r=typeof t=="number"&&t>0?Math.min(t,Pi):0;r>0&&await ys(r);const e=Date.now();let n=0,o=null;for(;Date.now()-e<If;){n+=1,Ce(`Waiting for OpenCode… (attempt ${n})`);try{if(await O.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(a){o=a}const s=Date.now()-e,i=n<=Ti&&s<1200?Pi:Math.min(Af+Math.max(0,n-Ti)*Pf,Tf);await ys(i)}throw o||new Error("OpenCode did not become ready in time")}async function Uo(t={}){const{message:r,delayMs:e}=t;try{Ce(r||"Refreshing commands…")}catch{}try{await kf(e),Ce("Refreshing commands…"),await wo.getState().loadCommands(),ct("commands",{source:Qr})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Ce("OpenCode refresh failed. Please retry refreshing configuration manually."),await ys(1500)}finally{ze()}}let ki=null;ki||(ki=ho(t=>{if(t.source!==Qr&&cn(t,"commands")){const{loadCommands:r}=wo.getState();r()}}));const Ft=()=>{const t=O.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null};function Cf(t){const r=t.replace(/\\/g,"/"),e=r.lastIndexOf("/skills/");if(e===-1)return;const o=r.substring(e+8).split("/");return o.length>=3?o[0]:void 0}const Yr="useSkillsStore",hs=t=>new Promise(r=>setTimeout(r,t)),Ef=5e3,xf="__default__",Ci=new Map,Bo=new Map,_f=t=>t?.trim()||xf,Rf=2e4,Ei=300,xi=4,Of=800,jf=200,Ff=2e3,mn=Me()(ve(tt((t,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:e=>{t({selectedSkillName:e})},setSkillDraft:e=>{t({skillDraft:e})},loadSkills:async()=>{const e=Ft(),n=_f(e),o=Date.now(),s=Ci.get(n)??0;if(r().skills.length>0&&o-s<Ef)return!0;const a=Bo.get(n);if(a)return a;const l=(async()=>{t({isLoading:!0});const c=r().skills;let d=null;for(let u=0;u<3;u++)try{const f=e?`?directory=${encodeURIComponent(e)}`:"",m=await fetch(`/api/config/skills${f}`);if(!m.ok)throw new Error(`Failed to list skills: ${m.status}`);const S=((await m.json()).skills||[]).map(h=>({name:h.name,path:h.path,scope:h.scope??"user",source:h.source??"opencode",description:h.sources?.md?.description||"",group:Cf(h.path)}));return t({skills:S,isLoading:!1}),Ci.set(n,Date.now()),!0}catch(f){d=f;const m=200*(u+1);await new Promise(p=>setTimeout(p,m))}return console.error("Failed to load skills:",d),t({skills:c,isLoading:!1}),!1})();Bo.set(n,l);try{return await l}finally{Bo.delete(n)}},getSkillDetail:async e=>{try{const n=Ft(),o=n?`?directory=${encodeURIComponent(n)}`:"",s=await fetch(`/api/config/skills/${encodeURIComponent(e)}${o}`);return s.ok?await s.json():null}catch{return null}},createSkill:async e=>{lt("Creating skill...");let n=!1;try{const o={name:e.name,description:e.description};e.instructions&&(o.instructions=e.instructions),e.scope&&(o.scope=e.scope),e.source&&(o.source=e.source),e.supportingFiles&&(o.supportingFiles=e.supportingFiles);const s=Ft(),i=s?`?directory=${encodeURIComponent(s)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(e.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),l=await a.json().catch(()=>null);if(!a.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}if(l?.requiresReload??!1)return n=!0,await Gn({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await r().loadSkills();return d&&ct("skills",{source:Yr}),d}catch{return!1}finally{n||ze()}},updateSkill:async(e,n)=>{lt("Updating skill...");let o=!1;try{const s={};n.description!==void 0&&(s.description=n.description),n.instructions!==void 0&&(s.instructions=n.instructions),n.supportingFiles!==void 0&&(s.supportingFiles=n.supportingFiles);const i=Ft(),a=i?`?directory=${encodeURIComponent(i)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(e)}${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to update skill";throw new Error(f)}if(c?.requiresReload??!1)return o=!0,await Gn({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadSkills();return u&&ct("skills",{source:Yr}),u}catch{return!1}finally{o||ze()}},deleteSkill:async e=>{lt("Deleting skill...");let n=!1;try{const o=Ft(),s=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(e)}${s}`,{method:"DELETE"}),a=await i.json().catch(()=>null);if(!i.ok){const d=a?.error||"Failed to delete skill";throw new Error(d)}if(a?.requiresReload??!1)return n=!0,await Gn({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await r().loadSkills();return c&&ct("skills",{source:Yr}),r().selectedSkillName===e&&t({selectedSkillName:null}),c}catch{return!1}finally{n||ze()}},getSkillByName:e=>{const{skills:n}=r();return n.find(o=>o.name===e)},readSupportingFile:async(e,n)=>{try{const o=Ft(),s=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(e)}/files/${encodeURIComponent(n)}?${s.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(e,n,o)=>{try{const s=Ft(),i=s?`?directory=${encodeURIComponent(s)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(e)}/files/${encodeURIComponent(n)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(e,n)=>{try{const o=Ft(),s=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(e)}/files/${encodeURIComponent(n)}${s}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:rt(()=>ye()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=mn);async function Lf(t){const r=typeof t=="number"&&t>0?Math.min(t,Ei):0;r>0&&await hs(r);const e=Date.now();let n=0,o=null;for(;Date.now()-e<Rf;){n+=1,Ce(`Waiting for OpenCode… (attempt ${n})`);try{if(await O.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(a){o=a}const s=Date.now()-e,i=n<=xi&&s<1200?Ei:Math.min(Of+Math.max(0,n-xi)*jf,Ff);await hs(i)}throw o||new Error("OpenCode did not become ready in time")}async function Gn(t){try{Ce(t?.message||"Refreshing skills…")}catch{}try{await Lf(t?.delayMs),Ce("Refreshing skills…"),await mn.getState().loadSkills()&&ct("skills",{source:Yr})}catch{Ce("OpenCode refresh failed. Please retry."),await hs(1500)}finally{ze()}}let _i=null;_i||(_i=ho(t=>{if(t.source!==Yr&&cn(t,"skills")){const{loadSkills:r}=mn.getState();r()}}));const Ri=[{id:"anthropic",label:"Anthropic",description:"Anthropic's public skills repository",source:"anthropics/skills",defaultSubpath:"skills",sourceType:"github"},{id:"clawdhub",label:"ClawdHub",description:"Community skill registry with vector search",source:"clawdhub:registry",sourceType:"clawdhub"}],Nf=5e3,$f="__default__",Oi=new Map,zo=new Map,Uf=t=>t?.trim()||$f,Br=()=>{const t=O.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Bf=Me()(ve((t,r)=>({sources:Ri,itemsBySource:{},selectedSourceId:Ri[0]?.id??null,pageInfoBySource:{},loadedSourceIds:{},clawdhubHasMoreBySource:{},isLoadingCatalog:!1,isLoadingSource:!1,isLoadingMore:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:e=>t({selectedSourceId:e}),loadCatalog:async e=>{const n=Br(),o=Uf(n),s=Date.now(),i=Oi.get(o)??0,a=r().sources.length>0;if(!e?.refresh&&a&&s-i<Nf)return!0;const l=zo.get(o);if(!e?.refresh&&l)return l;const c=(async()=>{t({isLoadingCatalog:!0,lastCatalogError:null});const d={sources:r().sources,itemsBySource:r().itemsBySource,pageInfoBySource:r().pageInfoBySource,loadedSourceIds:r().loadedSourceIds,clawdhubHasMoreBySource:r().clawdhubHasMoreBySource};let u=null;try{const f=e?.refresh?"?refresh=true":"",m=new AbortController,p=window.setTimeout(()=>m.abort(),3e3);try{const g=await fetch(`/api/config/skills/catalog${f}`,{method:"GET",headers:{Accept:"application/json"},signal:m.signal}),S=await g.json().catch(()=>null);if(!g.ok||!S?.ok)throw u=S?.error||{kind:"unknown",message:`Failed to load catalog (${g.status})`},new Error(u.message);const h=S.sources&&S.sources.length>0?S.sources:d.sources,v=e?.refresh?{}:r().itemsBySource||{},b=e?.refresh?{}:r().pageInfoBySource||{},D=e?.refresh?{}:r().loadedSourceIds||{},I=e?.refresh?{}:r().clawdhubHasMoreBySource||{},M=r().selectedSourceId,C=M&&h.some(k=>k.id===M)?M:h[0]?.id??null;return t({sources:h,itemsBySource:v,pageInfoBySource:b,loadedSourceIds:D,clawdhubHasMoreBySource:I,selectedSourceId:C}),Oi.set(o,Date.now()),!0}finally{window.clearTimeout(p)}}catch(f){return u=u||{kind:"unknown",message:f instanceof Error?f.message:String(f)},t({sources:d.sources,itemsBySource:d.itemsBySource,pageInfoBySource:d.pageInfoBySource,loadedSourceIds:d.loadedSourceIds,clawdhubHasMoreBySource:d.clawdhubHasMoreBySource,lastCatalogError:u||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}})();zo.set(o,c);try{return await c}finally{zo.delete(o)}},loadSource:async(e,n)=>{if(!e)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=Br(),s=n?.refresh?"&refresh=true":"",i=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(e)}${s}`:`?sourceId=${encodeURIComponent(e)}${s}`,a=await fetch(`/api/config/skills/catalog/source${i}`,{method:"GET",headers:{Accept:"application/json"}}),l=await a.json().catch(()=>null),c=Array.isArray(l?.items);if(!a.ok||!l?.ok&&!c){const f=await fetch(`/api/config/skills/catalog${i}`,{method:"GET",headers:{Accept:"application/json"}}),m=await f.json().catch(()=>null),p=m?.itemsBySource?.[e];return f.ok&&m?.ok&&Array.isArray(p)?(t(g=>({itemsBySource:{...g.itemsBySource,[e]:p},pageInfoBySource:{...g.pageInfoBySource,[e]:{nextCursor:null}},loadedSourceIds:{...g.loadedSourceIds,[e]:!0},clawdhubHasMoreBySource:{...g.clawdhubHasMoreBySource,[e]:!1}})),!0):(t({lastCatalogError:l?.error||{kind:"unknown",message:`Failed to load source (${a.status})`}}),!1)}const d=l?.items||[],u=l?.nextCursor??null;return t(f=>({itemsBySource:{...f.itemsBySource,[e]:d},pageInfoBySource:{...f.pageInfoBySource,[e]:{nextCursor:u}},loadedSourceIds:{...f.loadedSourceIds,[e]:!0},clawdhubHasMoreBySource:{...f.clawdhubHasMoreBySource,[e]:d.length>0}})),!0}catch(o){return t({lastCatalogError:{kind:"unknown",message:o instanceof Error?o.message:String(o)}}),!1}finally{t({isLoadingSource:!1})}},loadMoreClawdHub:async()=>{const e=r().selectedSourceId;if(!e)return!1;const o=r().pageInfoBySource[e]?.nextCursor||null;t({isLoadingMore:!0});try{const s=Br(),i=[`sourceId=${encodeURIComponent(e)}`];s&&i.push(`directory=${encodeURIComponent(s)}`),o&&i.push(`cursor=${encodeURIComponent(o)}`);const a=`?${i.join("&")}`,l=await fetch(`/api/config/skills/catalog/source${a}`,{method:"GET",headers:{Accept:"application/json"}}),c=await l.json().catch(()=>null);if(!l.ok||!c?.ok)return!1;const d=c.nextCursor??null,u=r().itemsBySource[e]||[],f=c.items||[],m=new Map(u.map(S=>[`${S.sourceId}:${S.skillDir}`,S]));let p=0;for(const S of f){const h=`${S.sourceId}:${S.skillDir}`;m.has(h)||(p+=1),m.set(h,S)}const g=f.length===0||p===0;return t(S=>({itemsBySource:{...S.itemsBySource,[e]:Array.from(m.values())},pageInfoBySource:{...S.pageInfoBySource,[e]:{nextCursor:d}},clawdhubHasMoreBySource:{...S.clawdhubHasMoreBySource,[e]:!g}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async e=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=Br(),o=n?`?directory=${encodeURIComponent(n)}`:"",s=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),i=await s.json().catch(()=>null);if(!s.ok||!i){const a=i?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:a}),{ok:!1,error:a}}return i.ok?(t({scanResults:i.items||[]}),i):(t({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{t({isScanning:!1})}},installSkills:async(e,n)=>{lt("Installing skills…"),t({isInstalling:!0,lastInstallError:null});let o=!1;try{const i=(typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():null)??Br(),a=i?`?directory=${encodeURIComponent(i)}`:"",l=await fetch(`/api/config/skills/install${a}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),c=await l.json().catch(()=>null);if(!c){const d={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:d}),Ce("Failed to install skills. Please retry."),{ok:!1,error:d}}if(!l.ok||!c.ok){const d=c.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:d}),Ce(d.message||"Failed to install skills. Please retry."),{ok:!1,error:d}}return c.requiresReload?(o=!0,await Gn({message:c.message,delayMs:c.reloadDelayMs})):(Ce(c.message||"Refreshing skills…"),mn.getState().loadSkills()),c}catch(s){const i={kind:"unknown",message:s instanceof Error?s.message:String(s)};return t({lastInstallError:i}),Ce("Failed to install skills. Please retry."),{ok:!1,error:i}}finally{t({isInstalling:!1}),o||ze()}}}),{name:"skills-catalog-store"})),zf=()=>{const t=O.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},xn=()=>{try{const r=et.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const e=O.getDirectory();if(e?.trim())return e.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},Hf=5e3,Wf="__default__",ji=new Map,Ho=new Map,Gf=t=>t?.trim()||Wf,Fi=t=>t.map(r=>{const e=r;return[r.name,e.scope??"",e.group??"",e.description??"",String(e.hidden===!0),String(e.native===!0)].join("|")}).join("||");function qf(t){if(!t)return;const r=t.replace(/\\/g,"/"),e=r.lastIndexOf("/agents/");if(e===-1)return;const o=r.substring(e+8).split("/");return o.length>1?o[0]:void 0}const ty=t=>{const r=t;return r.native===!0||r.builtIn===!0},Vf=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},bc=t=>t.filter(r=>!Vf(r)),qn="useAgentsStore",io=t=>new Promise(r=>setTimeout(r,t)),Kf=2e4,Li=300,Ni=4,Jf=800,Qf=200,Yf=2e3,xs=Me()(ve(tt((t,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:e=>{t({selectedAgentName:e})},setAgentDraft:e=>{t({agentDraft:e})},loadAgents:async()=>{const e=xn(),n=Gf(e),o=Date.now(),s=ji.get(n)??0;if(r().agents.length>0&&o-s<Hf)return!0;const a=Ho.get(n);if(a)return a;const l=(async()=>{t({isLoading:!0});const c=r().agents,d=Fi(c);for(let u=0;u<3;u++)try{const f=e?`?directory=${encodeURIComponent(e)}`:"",m=await O.withDirectory(e,()=>O.listAgents()),p=await Promise.all(m.map(async S=>{try{const h=await fetch(`/api/config/agents/${encodeURIComponent(S.name)}${f}`,{headers:{"Cache-Control":"no-cache",...e?{"x-opencode-directory":e}:{}}});if(h.ok){const v=await h.json();let b=v.scope;if(!b&&v.sources){const M=v.sources;b=(M.md?.exists?M.md.scope:void 0)??(M.json?.exists?M.json.scope:void 0)??M.md?.scope??M.json?.scope}const D=v.sources?.md?.path,I=qf(D);return b==="project"||b==="user"?{...S,scope:b,group:I}:{...S,scope:void 0,group:I}}}catch(h){console.warn(`[AgentsStore] Failed to fetch config for agent ${S.name}:`,h)}return S})),g=Fi(p);return t(d!==g?{agents:p,isLoading:!1}:{isLoading:!1}),ji.set(n,Date.now()),!0}catch{}return t({isLoading:!1}),!1})();Ho.set(n,l);try{return await l}finally{Ho.delete(n)}},createAgent:async e=>{lt("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",e.name);const o={mode:e.mode||"subagent"};e.description&&(o.description=e.description),e.model&&(o.model=e.model),e.temperature!==void 0&&(o.temperature=e.temperature),e.top_p!==void 0&&(o.top_p=e.top_p),e.prompt&&(o.prompt=e.prompt),e.permission&&(o.permission=e.permission),e.disable!==void 0&&(o.disable=e.disable),e.scope&&(o.scope=e.scope),console.log("[AgentsStore] Agent config to save:",o);const s=xn(),i=s?`?directory=${encodeURIComponent(s)}`:"",a=await fetch(`/api/config/agents/${encodeURIComponent(e.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-opencode-directory":s}:{}},body:JSON.stringify(o)}),l=await a.json().catch(()=>null);if(!a.ok){const u=l?.error||"Failed to create agent";throw new Error(u)}if(l?.requiresReload??!0)return n=!0,await Xr({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const d=await r().loadAgents();return d&&ct("agents",{source:qn}),d}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||ze()}},updateAgent:async(e,n)=>{lt("Updating agent configuration…");let o=!1;try{const s={};n.mode!==void 0&&(s.mode=n.mode),n.description!==void 0&&(s.description=n.description),n.model!==void 0&&(s.model=n.model),n.temperature!==void 0&&(s.temperature=n.temperature),n.top_p!==void 0&&(s.top_p=n.top_p),n.prompt!==void 0&&(s.prompt=n.prompt),n.permission!==void 0&&(s.permission=n.permission),n.disable!==void 0&&(s.disable=n.disable);const i=xn(),a=i?`?directory=${encodeURIComponent(i)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(e)}${a}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(s)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to update agent";throw new Error(f)}if(c?.requiresReload??!0)return o=!0,await Xr({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&ct("agents",{source:qn}),u}catch(s){throw console.error("Failed to update agent:",s),s}finally{o||ze()}},deleteAgent:async e=>{lt("Deleting agent configuration…");let n=!1;try{const o=xn(),s=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(e)}${s}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),a=await i.json().catch(()=>null);if(!i.ok){const d=a?.error||"Failed to delete agent";throw new Error(d)}if(a?.requiresReload??!0)return n=!0,await Xr({message:a?.message,delayMs:a?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const c=await r().loadAgents();return c&&ct("agents",{source:qn}),r().selectedAgentName===e&&t({selectedAgentName:null}),c}catch{return!1}finally{n||ze()}},getAgentByName:e=>{const{agents:n}=r();return n.find(o=>o.name===e)},getVisibleAgents:()=>{const{agents:e}=r();return bc(e)}}),{name:"agents-store",storage:rt(()=>ye()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=xs);async function Xf(t){const r=typeof t=="number"&&t>0?Math.min(t,Li):0;r>0&&await io(r);const e=Date.now();let n=0,o=null;for(;Date.now()-e<Kf;){n+=1,Ce(`Waiting for OpenCode… (attempt ${n})`);try{if(await O.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(a){o=a}const s=Date.now()-e,i=n<=Ni&&s<1200?Li:Math.min(Jf+Math.max(0,n-Ni)*Qf,Yf);await io(i)}throw o||new Error("OpenCode did not become ready in time")}const Zf=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function ep(t={}){const{message:r,delayMs:e}=t,n=Zf(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Ce(r||"Refreshing configuration…")}catch{}try{await Xf(e);const s=ke.getState(),i=xs.getState(),a=wo.getState(),l=mn.getState(),c=Bf.getState(),d=n.includes("all")||n.includes("providers"),u=n.includes("all")||n.includes("agents"),f=n.includes("all")||n.includes("agents"),m=n.includes("all")||n.includes("commands"),p=n.includes("all")||n.includes("skills"),g=zf(),S=o==="projects"?et.getState().projects:[],h=Array.from(new Set([...g?[g]:[],...S.map(D=>D.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&ke.setState({directoryScoped:{}});const v=[];for(const D of h)d&&v.push(s.loadProviders({directory:D}).then(()=>{})),u&&v.push(s.loadAgents({directory:D}).then(()=>{}));const b=[];f&&b.push(i.loadAgents().then(()=>{})),m&&b.push(a.loadCommands().then(()=>{})),p&&(b.push(l.loadSkills().then(()=>{})),b.push(c.loadCatalog().then(()=>{}))),Ce("Refreshing configuration…"),await Promise.all([...v,...b])}catch{Ce("OpenCode refresh failed. Please retry."),await io(1500)}finally{ze()}}async function Xr(t){await ep(t)}async function ry(t){lt(t?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),e=await r.json().catch(()=>null);if(!r.ok){const o=e?.error||"Failed to reload configuration";throw new Error(o)}const n={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};e?.requiresReload?await Xr({...n,message:e.message,delayMs:e.reloadDelayMs}):await Xr(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Ce("Failed to reload configuration. Please try again."),await io(2e3),ze(),r}}let $i=null;$i||($i=ho(t=>{if(t.source!==qn&&cn(t,"agents")){const{loadAgents:r}=xs.getState();r()}}));const tp="https://models.dev/api.json",rp="/api/openchamber/models-metadata",Ui="opencode",Bi="big-pickle",Vt="zen",zi="big-pickle",np=async()=>{try{const t=Nt()?.settings;if(t)try{const c=(await t.load())?.settings;if(c){const d=typeof c?.defaultModel=="string"?c.defaultModel.trim():"",u=typeof c?.defaultVariant=="string"?c.defaultVariant.trim():"",f=typeof c?.defaultAgent=="string"?c.defaultAgent.trim():"",m=typeof c?.gitmojiEnabled=="boolean"?c.gitmojiEnabled:void 0,p=typeof c?.zenModel=="string"?c.zenModel.trim():"";return{defaultModel:d.length>0?d:void 0,defaultVariant:u.length>0?u:void 0,defaultAgent:f.length>0?f:void 0,autoCreateWorktree:typeof c?.autoCreateWorktree=="boolean"?c.autoCreateWorktree:void 0,gitmojiEnabled:m,zenModel:p.length>0?p:void 0}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const e=await r.json(),n=typeof e?.defaultModel=="string"?e.defaultModel.trim():"",o=typeof e?.defaultVariant=="string"?e.defaultVariant.trim():"",s=typeof e?.defaultAgent=="string"?e.defaultAgent.trim():"",i=typeof e?.gitmojiEnabled=="boolean"?e.gitmojiEnabled:void 0,a=typeof e?.zenModel=="string"?e.zenModel.trim():"";return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:s.length>0?s:void 0,autoCreateWorktree:typeof e?.autoCreateWorktree=="boolean"?e.autoCreateWorktree:void 0,gitmojiEnabled:i,zenModel:a.length>0?a:void 0}}catch{return{}}},_n=t=>{if(!t||typeof t!="string")return null;const r=t.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},op=t=>t?.toLowerCase?.()??"",sp=t=>t==="primary"||t==="all"||t===void 0||t===null,ao=t=>{if(typeof t!="string")return;const r=t.trim();return r.length>0?r:void 0},Hi=(t,r,e)=>{const n=t.find(o=>o.id===r);return n?n.models.some(o=>o.id===e):!1},Wo=({providers:t,settingsZenModel:r})=>{const e=ao(r);if(!Array.isArray(t)||t.length===0)return e?{providerId:Vt,modelId:e}:null;if(e&&Hi(t,Vt,e))return{providerId:Vt,modelId:e};if(Hi(t,Vt,zi))return{providerId:Vt,modelId:zi};const n=t.find(o=>o.id===Vt);if(n?.models.length){const o=Math.floor(Math.random()*n.models.length),s=ao(n.models[o]?.id);if(s)return{providerId:Vt,modelId:s}}return null},un=t=>typeof t=="object"&&t!==null,co=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),ip=t=>{if(!un(t))return!1;const r=t;if(r.modalities){const{input:e,output:n}=r.modalities;if(e&&!co(e)||n&&!co(n))return!1}return!0},ap=t=>{if(!un(t))return!1;const r=t;return r.models===void 0||un(r.models)},Mc=(t,r)=>{const e=op(t);return!e||!r?"":`${e}/${r}`},cp=t=>{const r=new Map;if(!un(t))return r;for(const[e,n]of Object.entries(t)){if(!ap(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:e,s=n.models;if(!(!s||!un(s)))for(const[i,a]of Object.entries(s)){if(!ip(a))continue;const l=typeof i=="string"&&i.length>0?i:a.id;if(!l||typeof l!="string"||l.length===0)continue;const c={id:typeof a.id=="string"&&a.id.length>0?a.id:l,providerId:o,name:typeof a.name=="string"?a.name:void 0,tool_call:typeof a.tool_call=="boolean"?a.tool_call:void 0,reasoning:typeof a.reasoning=="boolean"?a.reasoning:void 0,temperature:typeof a.temperature=="boolean"?a.temperature:void 0,attachment:typeof a.attachment=="boolean"?a.attachment:void 0,modalities:a.modalities?{input:co(a.modalities.input)?a.modalities.input:void 0,output:co(a.modalities.output)?a.modalities.output:void 0}:void 0,cost:a.cost,limit:a.limit,knowledge:typeof a.knowledge=="string"?a.knowledge:void 0,release_date:typeof a.release_date=="string"?a.release_date:void 0,last_updated:typeof a.last_updated=="string"?a.last_updated:void 0},d=Mc(o,l);d&&r.set(d,c)}}return r},lp=async()=>{if(typeof fetch!="function")return new Map;const t=[rp,tp];for(const r of t){const e=typeof AbortController<"u"?new AbortController:void 0,n=e?setTimeout(()=>e.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),s={signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?s.mode="cors":s.credentials="same-origin";const i=await fetch(r,s);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const a=await i.json();return cp(a)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let Go=null;const dp=(t,r)=>{t().size>0||Go||(Go=lp().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{Go=null}))},up=t=>new Promise(r=>setTimeout(r,t)),_s="__global__",Mr=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:_s},yr=t=>t===_s?null:t,fp=()=>{if(typeof window>"u")return _s;const t=O.getDirectory()??be.getState().currentDirectory;return Mr(t)},ke=Me()(ve(tt((t,r)=>({activeDirectoryKey:fp(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,settingsGitmojiEnabled:!1,settingsZenModel:void 0,voiceProvider:(()=>{if(typeof window<"u"){const e=localStorage.getItem("voiceProvider");if(e==="openai"||e==="browser"||e==="say")return e}return"browser"})(),speechRate:(()=>{if(typeof window<"u"){const e=localStorage.getItem("speechRate");if(e){const n=parseFloat(e);if(!isNaN(n)&&n>=.5&&n<=2)return n}}return 1})(),speechPitch:(()=>{if(typeof window<"u"){const e=localStorage.getItem("speechPitch");if(e){const n=parseFloat(e);if(!isNaN(n)&&n>=.5&&n<=2)return n}}return 1})(),speechVolume:(()=>{if(typeof window<"u"){const e=localStorage.getItem("speechVolume");if(e){const n=parseFloat(e);if(!isNaN(n)&&n>=0&&n<=1)return n}}return 1})(),sayVoice:(()=>{if(typeof window<"u"){const e=localStorage.getItem("sayVoice");if(e)return e}return"Samantha"})(),browserVoice:(()=>{if(typeof window<"u"){const e=localStorage.getItem("browserVoice");if(e)return e}return""})(),openaiVoice:(()=>{if(typeof window<"u"){const e=localStorage.getItem("openaiVoice");if(e)return e}return"nova"})(),openaiApiKey:(()=>{if(typeof window<"u"){const e=localStorage.getItem("openaiApiKey");if(e)return e}return""})(),showMessageTTSButtons:typeof window<"u"&&localStorage.getItem("showMessageTTSButtons")==="true",voiceModeEnabled:typeof window<"u"&&localStorage.getItem("voiceModeEnabled")==="true",summarizeMessageTTS:typeof window<"u"&&localStorage.getItem("summarizeMessageTTS")==="true",summarizeVoiceConversation:typeof window<"u"&&localStorage.getItem("summarizeVoiceConversation")==="true",summarizeCharacterThreshold:(()=>{if(typeof window<"u"){const e=localStorage.getItem("summarizeCharacterThreshold");if(e){const n=parseInt(e,10);if(!isNaN(n)&&n>=50&&n<=2e3)return n}}return 200})(),summarizeMaxLength:(()=>{if(typeof window<"u"){const e=localStorage.getItem("summarizeMaxLength");if(e){const n=parseInt(e,10);if(!isNaN(n)&&n>=50&&n<=2e3)return n}}return 500})(),activateDirectory:async e=>{const n=Mr(e);t(o=>{const s=o.directoryScoped[n];return s?{activeDirectoryKey:n,providers:s.providers,agents:s.agents,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentVariant:s.currentVariant,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:yr(n)}),await r().loadAgents({directory:yr(n)}))},loadProviders:async e=>{const n=Mr(e?.directory??yr(r().activeDirectoryKey)),o=r().directoryScoped[n],s=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),i=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let a=null;for(let l=0;l<3;l++)try{dp(()=>r().modelsMetadata,m=>t({modelsMetadata:m}));const c=await O.withDirectory(yr(n),()=>O.getProviders()),d=Array.isArray(c?.providers)?c.providers:[],u=c?.default||{},f=d.map(m=>{const p=m.models??{},g=Object.keys(p).map(S=>p[S]);return{...m,models:g}});t(m=>{const g={...m.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,defaultProviders:u},S={directoryScoped:{...m.directoryScoped,[n]:g}};if(m.activeDirectoryKey===n&&(S.providers=f,S.defaultProviders=u,!m.currentProviderId&&!m.currentModelId&&m.settingsDefaultModel)){const h=_n(m.settingsDefaultModel);if(h){const v=f.find(b=>b.id===h.providerId);if(v?.models.some(b=>b.id===h.modelId)){const b=v.models.find(I=>I.id===h.modelId),D=m.settingsDefaultVariant&&b?.variants?.[m.settingsDefaultVariant]?m.settingsDefaultVariant:void 0;S.currentProviderId=h.providerId,S.currentModelId=h.modelId,S.currentVariant=D,S.selectedProviderId=h.providerId,g.currentProviderId=h.providerId,g.currentModelId=h.modelId,g.currentVariant=D,g.selectedProviderId=h.providerId}}}return S});return}catch(c){a=c;const d=200*(l+1);await new Promise(u=>setTimeout(u,d))}console.error("Failed to load providers:",a),t(l=>{const d={...l.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:s,defaultProviders:i},u={directoryScoped:{...l.directoryScoped,[n]:d}};if(l.activeDirectoryKey===n&&(u.providers=s,u.defaultProviders=i,!l.currentProviderId&&!l.currentModelId&&l.settingsDefaultModel)){const f=_n(l.settingsDefaultModel);if(f){const m=s.find(p=>p.id===f.providerId);if(m?.models.some(p=>p.id===f.modelId)){const p=m.models.find(S=>S.id===f.modelId),g=l.settingsDefaultVariant&&p?.variants?.[l.settingsDefaultVariant]?l.settingsDefaultVariant:void 0;u.currentProviderId=f.providerId,u.currentModelId=f.modelId,u.currentVariant=g,u.selectedProviderId=f.providerId,d.currentProviderId=f.providerId,d.currentModelId=f.modelId,d.currentVariant=g,d.selectedProviderId=f.providerId}}}return u})},setProvider:e=>{const{providers:n}=r(),o=n.find(a=>a.id===e);if(!o)return;const i=o.models[0]?.id||"";t(a=>{const l=a.activeDirectoryKey,d={...a.directoryScoped[l]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},currentProviderId:e,currentModelId:i,selectedProviderId:e};return{currentProviderId:e,currentModelId:i,selectedProviderId:e,directoryScoped:{...a.directoryScoped,[l]:d}}})},setModel:e=>{t(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:e};return{currentModelId:e,directoryScoped:{...n.directoryScoped,[o]:i}}})},setCurrentVariant:e=>{t(n=>{if(n.currentVariant===e)return n;const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:e};return{currentVariant:e,directoryScoped:{...n.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const e=r().getCurrentModelVariants();if(e.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(e[0]);return}const o=e.indexOf(n);if(o===-1||o===e.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(e[o+1])},setSelectedProvider:e=>{t(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:e};return{selectedProviderId:e,directoryScoped:{...n.directoryScoped,[o]:i}}})},saveAgentModelSelection:(e,n,o)=>{t(s=>{const i=s.activeDirectoryKey,a={...s.agentModelSelections,[e]:{providerId:n,modelId:o}},c={...s.directoryScoped[i]??{providers:s.providers,agents:s.agents,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders},agentModelSelections:a};return{agentModelSelections:a,directoryScoped:{...s.directoryScoped,[i]:c}}})},getAgentModelSelection:e=>{const{agentModelSelections:n}=r();return n[e]||null},loadAgents:async e=>{const n=Mr(e?.directory??yr(r().activeDirectoryKey)),s=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let i=null;for(let a=0;a<3;a++)try{const[l,c]=await Promise.all([O.withDirectory(yr(n),()=>O.listAgents()),np()]),d=Array.isArray(l)?l:[],u=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[],f=ao(r().settingsZenModel),m=ao(c.zenModel),p=Wo({providers:u,settingsZenModel:f}),g=Wo({providers:u,settingsZenModel:m}),v=(p||g)?.modelId||m||f;if(t(E=>{const L={...E.directoryScoped[n]??{providers:u,agents:s,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:u,agents:d},z={settingsDefaultModel:c.defaultModel,settingsDefaultVariant:c.defaultVariant,settingsDefaultAgent:c.defaultAgent,settingsAutoCreateWorktree:c.autoCreateWorktree??!1,settingsGitmojiEnabled:c.gitmojiEnabled??!1,settingsZenModel:v,directoryScoped:{...E.directoryScoped,[n]:L}};return E.activeDirectoryKey===n&&(z.agents=d),z}),v&&v!==m&&v&&Ze({zenModel:v,gitProviderId:"",gitModelId:""}).catch(()=>{}),d.length===0)return t(E=>{const L={...E.directoryScoped[n]??{providers:u,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:u,agents:[],currentAgentName:void 0},z={directoryScoped:{...E.directoryScoped,[n]:L}};return E.activeDirectoryKey===n&&(z.currentAgentName=void 0),z}),!0;const D=(E,j)=>{const L=u.find(z=>z.id===E);return L?L.models.some(z=>z.id===j):!1},I=d.filter(E=>sp(E.mode));let k=I.find(E=>E.name==="build")||I[0]||d[0];const T={};if(c.defaultAgent){const E=d.find(j=>j.name===c.defaultAgent);E?k=E:T.defaultAgent=""}let _,$,U;if(c.defaultModel){const E=_n(c.defaultModel);if(E&&D(E.providerId,E.modelId)){if(_=E.providerId,$=E.modelId,c.defaultVariant){const z=u.find(W=>W.id===E.providerId)?.models.find(W=>W.id===E.modelId)?.variants;z&&Object.prototype.hasOwnProperty.call(z,c.defaultVariant)?U=c.defaultVariant:T.defaultVariant=""}}else T.defaultModel=""}if(!_&&k?.model?.providerID&&k?.model?.modelID){const{providerID:E,modelID:j}=k.model;D(E,j)&&(_=E,$=j)}if(!_)if(D(Ui,Bi))_=Ui,$=Bi;else{const E=u[0],j=E?.models[0];E&&j&&(_=E.id,$=j.id)}return t(E=>{const j=E.directoryScoped[n]??{providers:u,agents:d,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},L={...j,providers:u,agents:d,currentAgentName:k.name,currentProviderId:_??j.currentProviderId,currentModelId:$??j.currentModelId,currentVariant:U},z={directoryScoped:{...E.directoryScoped,[n]:L}};return E.activeDirectoryKey===n&&(z.currentAgentName=k.name,_&&$&&(z.currentProviderId=_,z.currentModelId=$,z.currentVariant=U)),z}),Object.keys(T).length>0&&(t({settingsDefaultModel:T.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:T.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:T.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),Ze(T).catch(()=>{})),!0}catch(l){i=l;const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}return console.error("Failed to load agents:",i),t(a=>{const l=a.activeDirectoryKey===n?a.providers:a.directoryScoped[n]?.providers??[],d={...a.directoryScoped[n]??{providers:l,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:l,agents:s},u={directoryScoped:{...a.directoryScoped,[n]:d}};return a.activeDirectoryKey===n&&(u.agents=s),u}),!1},setAgent:e=>{const{agents:n,providers:o,settingsDefaultModel:s,settingsDefaultVariant:i}=r();if(t(a=>{const l=a.activeDirectoryKey,d={...a.directoryScoped[l]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},currentAgentName:e};return{currentAgentName:e,directoryScoped:{...a.directoryScoped,[l]:d}}}),e&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const l=a.getState(),{currentSessionId:c,isOpenChamberCreatedSession:d,initializeNewOpenChamberSession:u,getAgentModelForSession:f}=l;c&&a.setState(m=>{const p=new Map(m.currentAgentContext);return p.set(c,e),{currentAgentContext:p}}),c&&d(c)&&(f(c,e)||u(c,n))}}if(e&&typeof window<"u"){const a=window.__zustand_session_store__;if(a?.getState){const{currentSessionId:d,getAgentModelForSession:u}=a.getState();if(d&&u(d,e))return}if(s){const d=_n(s);if(d&&o.find(f=>f.id===d.providerId)?.models.some(f=>f.id===d.modelId)){t(f=>{const m=f.activeDirectoryKey,p=f.directoryScoped[m]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentVariant:f.currentVariant,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders};let g;if(i){const b=o.find(D=>D.id===d.providerId)?.models.find(D=>D.id===d.modelId)?.variants;b&&Object.prototype.hasOwnProperty.call(b,i)&&(g=i)}const S={...p,currentProviderId:d.providerId,currentModelId:d.modelId,currentVariant:g};return{currentProviderId:d.providerId,currentModelId:d.modelId,currentVariant:g,directoryScoped:{...f.directoryScoped,[m]:S}}});return}}const c=n.find(d=>d.name===e)?.model;if(c?.providerID&&c?.modelID){const{providerID:d,modelID:u}=c;o.find(p=>p.id===d)?.models.find(p=>p.id===u)&&t(p=>{const g=p.activeDirectoryKey,h={...p.directoryScoped[g]??{providers:p.providers,agents:p.agents,currentProviderId:p.currentProviderId,currentModelId:p.currentModelId,currentAgentName:p.currentAgentName,selectedProviderId:p.selectedProviderId,agentModelSelections:p.agentModelSelections,defaultProviders:p.defaultProviders},currentProviderId:d,currentModelId:u,selectedProviderId:d};return{currentProviderId:d,currentModelId:u,selectedProviderId:d,directoryScoped:{...p.directoryScoped,[g]:h}}})}}},setSettingsDefaultModel:e=>{t({settingsDefaultModel:e})},setSettingsDefaultVariant:e=>{t({settingsDefaultVariant:e})},setSettingsDefaultAgent:e=>{t({settingsDefaultAgent:e})},setSettingsAutoCreateWorktree:e=>{t({settingsAutoCreateWorktree:e})},setSettingsGitmojiEnabled:e=>{t({settingsGitmojiEnabled:e})},setSettingsZenModel:e=>{t({settingsZenModel:e})},getResolvedGitGenerationModel:()=>{const e=r();return Wo({providers:e.providers,settingsZenModel:e.settingsZenModel})},setVoiceProvider:e=>{t({voiceProvider:e}),typeof window<"u"&&localStorage.setItem("voiceProvider",e)},setSpeechRate:e=>{const n=Math.max(.5,Math.min(2,e));t({speechRate:n}),typeof window<"u"&&localStorage.setItem("speechRate",String(n))},setSpeechPitch:e=>{const n=Math.max(.5,Math.min(2,e));t({speechPitch:n}),typeof window<"u"&&localStorage.setItem("speechPitch",String(n))},setSpeechVolume:e=>{const n=Math.max(0,Math.min(1,e));t({speechVolume:n}),typeof window<"u"&&localStorage.setItem("speechVolume",String(n))},setSayVoice:e=>{t({sayVoice:e}),typeof window<"u"&&localStorage.setItem("sayVoice",e)},setBrowserVoice:e=>{t({browserVoice:e}),typeof window<"u"&&localStorage.setItem("browserVoice",e)},setOpenaiVoice:e=>{t({openaiVoice:e}),typeof window<"u"&&localStorage.setItem("openaiVoice",e)},setOpenaiApiKey:e=>{t({openaiApiKey:e}),typeof window<"u"&&localStorage.setItem("openaiApiKey",e)},setShowMessageTTSButtons:e=>{t({showMessageTTSButtons:e}),typeof window<"u"&&localStorage.setItem("showMessageTTSButtons",String(e))},setVoiceModeEnabled:e=>{t({voiceModeEnabled:e}),typeof window<"u"&&localStorage.setItem("voiceModeEnabled",String(e))},setSummarizeMessageTTS:e=>{t({summarizeMessageTTS:e}),typeof window<"u"&&localStorage.setItem("summarizeMessageTTS",String(e))},setSummarizeVoiceConversation:e=>{t({summarizeVoiceConversation:e}),typeof window<"u"&&localStorage.setItem("summarizeVoiceConversation",String(e))},setSummarizeCharacterThreshold:e=>{const n=Math.max(50,Math.min(2e3,e));t({summarizeCharacterThreshold:n}),typeof window<"u"&&localStorage.setItem("summarizeCharacterThreshold",String(n))},setSummarizeMaxLength:e=>{const n=Math.max(50,Math.min(2e3,e));t({summarizeMaxLength:n}),typeof window<"u"&&localStorage.setItem("summarizeMaxLength",String(n))},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const s=await O.checkHealth();return t({isConnected:s}),s}catch(s){o=s,n+=1;const i=400*n;await up(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const e=we();e&&console.log("Starting app initialization...");const n=await r().checkConnection();if(e&&console.log("Connection check result:",n),!n){e&&console.log("Server not connected"),t({isConnected:!1});return}e&&console.log("Initializing app..."),await O.initApp(),e&&console.log("Loading providers..."),await r().loadProviders(),e&&console.log("Loading agents..."),await r().loadAgents(),t({isInitialized:!0,isConnected:!0}),e&&console.log("App initialized successfully")}catch(e){console.error("Failed to initialize app:",e),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:e,currentProviderId:n}=r();return e.find(o=>o.id===n)},getCurrentModel:()=>{const e=r().getCurrentProvider(),{currentModelId:n}=r();if(e)return e.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:e,currentAgentName:n}=r();if(n)return e.find(o=>o.name===n)},getModelMetadata:(e,n)=>{const o=Mc(e,n);if(!o)return;const{modelsMetadata:s}=r();return s.get(o)},getVisibleAgents:()=>{const{agents:e}=r();return bc(e)}}),{name:"config-store",storage:rt(()=>ye()),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled,settingsZenModel:t.settingsZenModel,speechRate:t.speechRate,speechPitch:t.speechPitch,speechVolume:t.speechVolume})})));typeof window<"u"&&(window.__zustand_config_store__=ke);let Wi=null;Wi||(Wi=ho(async t=>{const r=[];if(cn(t,"agents")){const{loadAgents:e}=ke.getState();r.push(e().then(()=>{}))}if(cn(t,"providers")){const{loadProviders:e}=ke.getState();r.push(e())}r.length>0&&await Promise.all(r)}));let Gi=null;typeof window<"u"&&!Gi&&(Gi=be.subscribe((t,r)=>{const e=Mr(t.currentDirectory),n=Mr(r.currentDirectory);e!==n&&ke.getState().activateDirectory(t.currentDirectory)}));const Ie=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function pp(t){const r=Ie();return r?r.checkIsGitRepository(t):Ua(t)}async function vc(t){const r=Ie();return r?r.getGitStatus(t):Ba(t)}async function ny(t){const r=Ie();return r?r.getGitBranches(t):za(t)}async function mp(t,r){const e=Ie();return e?e.deleteRemoteBranch(t,r):Ha(t,r)}async function oy(t,r,e){const n=Date.now(),o=Dc();if(!o)throw new Error("Select existing session for generation");console.info("[git-generation][browser] request",{transport:"session",kind:"commit",directory:t,selectedFiles:r.length,sessionId:o.sessionId,providerId:o.providerID,modelId:o.modelID,agent:o.agent});const s=`You are generating a Conventional Commits subject line using session context and selected file paths.
4
4
 
@@ -45,4 +45,4 @@ ${k}`:k:T;return _.trim()?{command:_}:null})();t({lastUsedProvider:{providerID:n
45
45
  `).replace(/\n\s*\n+/g,`
46
46
  `),Tr=new Map,yg=()=>{let t,r;return{promise:new Promise((n,o)=>{t=n,r=o}),resolve:t,reject:r}},hg=()=>`worktree_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,ky=()=>{const t=hg();return Tr.set(t,yg()),t},Cy=(t,r)=>{const e=Tr.get(t);e&&(Tr.delete(t),e.resolve(r))},Ey=(t,r)=>{const e=Tr.get(t);e&&(Tr.delete(t),e.reject(r))},Sg=t=>{const r=Tr.get(t);return r?r.promise:Promise.reject(new Error("Pending worktree request not found"))},ie=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const e=r.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Ia=new Map,Yc="oc.chatInput.lastDraftTarget",Xc=ye(),wg=()=>{try{const t=Xc.getItem(Yc);if(!t)return null;const r=JSON.parse(t);return{projectId:typeof r?.projectId=="string"?r.projectId:null,directory:ie(typeof r?.directory=="string"?r.directory:null)}}catch{return null}},Vr=t=>{try{Xc.setItem(Yc,JSON.stringify(t))}catch{}},Zc=(t,r)=>{const e=ie(r);if(!e)return null;let n=null;for(const o of t){const s=ie(o.path);if(!s)continue;const i=e===s,a=e.startsWith(`${s}/`);!i&&!a||(!n||s.length>(ie(n.path)?.length??0))&&(n=o)}return n},bg=(t,r,e)=>{const n=ie(e);if(!n)return null;let o=null,s=null,i=-1;for(const[c,d]of r.entries())for(const u of d){const f=ie(u.path);if(!f)continue;const m=n===f,p=n.startsWith(`${f}/`);!m&&!p||f.length>i&&(i=f.length,o=u,s=ie(c))}if(!o)return null;const l=[ie(o.projectDirectory),s].filter(c=>!!c);for(const c of l){const d=t.find(f=>ie(f.path)===c)??null;if(d)return d;const u=Zc(t,c);if(u)return u}return null},Kr=(t,r,e)=>bg(t,r,e)??Zc(t,e),Mg=t=>{const r=t[t.length-1],e=typeof r?.info?.id=="string"?r.info.id:"",n=[...t].reverse().find(s=>s.info?.role==="assistant"),o=typeof n?.info?.id=="string"?n.info.id:"";return`${t.length}:${e}:${o}`},Aa=(t,r,e)=>{if(!r)return null;const n=e(r)?.path;if(typeof n=="string"&&n.trim().length>0)return ie(n);const o=t.find(s=>s.id===r);return o?ie(o.directory??null):null},V=Me()(ve((t,r)=>({sessions:[],archivedSessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,sessionHistoryMeta:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,questions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionStatus:new Map,sessionAttentionStates:new Map,userSummaryTitles:new Map,pendingInputText:null,pendingInputMode:"replace",pendingSyntheticParts:null,newSessionDraft:{open:!0,selectedProjectId:null,directoryOverride:null,pendingWorktreeRequestId:null,bootstrapPendingDirectory:null,preserveDirectoryOverride:!1,parentID:null},voiceStatus:"disconnected",voiceMode:"idle",setVoiceStatus:e=>{t({voiceStatus:e})},setVoiceMode:e=>{t({voiceMode:e})},getSessionAgentEditMode:(e,n,o)=>ne.getState().getSessionAgentEditMode(e,n,o),toggleSessionAgentEditMode:(e,n,o)=>ne.getState().toggleSessionAgentEditMode(e,n,o),setSessionAgentEditMode:(e,n,o,s)=>ne.getState().setSessionAgentEditMode(e,n,o,s),loadSessions:()=>q.getState().loadSessions(),openNewSessionDraft:e=>{const n=et.getState(),o=n.projects,s=r().availableWorktreesByProject,i=n.getActiveProject(),a=ie(be.getState().currentDirectory??null),l=wg(),c=e?.directoryOverride!==void 0?ie(e.directoryOverride):null,d=e?.projectId?o.find(v=>v.id===e.projectId)??null:null,u=Kr(o,s,c),f=i||(n.activeProjectId?o.find(v=>v.id===n.activeProjectId)??null:o[0]??null),m=l?.projectId?o.find(v=>v.id===l.projectId)??null:null,p=Kr(o,s,l?.directory??null),g=Kr(o,s,a),S=d||c!==null?d??u??f:a?g??f:p??m??f,h=c!==null?c:d?ie(d.path??null):a||(l?.directory?l.directory:ie(S?.path??null));Vr({projectId:S?.id??null,directory:h}),t({newSessionDraft:{open:!0,selectedProjectId:S?.id??null,directoryOverride:h,pendingWorktreeRequestId:e?.pendingWorktreeRequestId??null,bootstrapPendingDirectory:ie(e?.bootstrapPendingDirectory??null),preserveDirectoryOverride:e?.preserveDirectoryOverride===!0,parentID:e?.parentID??null,title:e?.title,initialPrompt:e?.initialPrompt,syntheticParts:e?.syntheticParts,targetFolderId:e?.targetFolderId},currentSessionId:null,error:null,...e?.initialPrompt?{pendingInputText:e.initialPrompt,pendingInputMode:"replace"}:{}});try{const v=ke.getState(),b=v.getVisibleAgents();let D;if(v.settingsDefaultAgent){const I=b.find(M=>M.name===v.settingsDefaultAgent);I&&(D=I.name)}D||(D=b.find(I=>I.name==="build")?.name||b[0]?.name),D&&v.setAgent(D)}catch{}},overrideNewSessionDraftTarget:e=>{const n=et.getState(),o=n.projects,s=r().availableWorktreesByProject,i=ie(e?.directoryOverride??null),a=e?.projectId?o.find(f=>f.id===e.projectId)??null:null,l=Kr(o,s,i),c=a??l??n.getActiveProject()??o[0]??null,d=a??l??c,u=i??ie(d?.path??null);Vr({projectId:d?.id??null,directory:u}),t(f=>{const m=f.newSessionDraft,p=Object.prototype.hasOwnProperty.call(e,"pendingWorktreeRequestId"),g=Object.prototype.hasOwnProperty.call(e,"bootstrapPendingDirectory");return{newSessionDraft:{...m,open:!0,selectedProjectId:d?.id??null,directoryOverride:u,pendingWorktreeRequestId:p?e.pendingWorktreeRequestId??null:m.pendingWorktreeRequestId??null,bootstrapPendingDirectory:g?ie(e.bootstrapPendingDirectory??null):m.bootstrapPendingDirectory??null,preserveDirectoryOverride:e?.preserveDirectoryOverride===!0,title:e?.title??m.title,initialPrompt:e?.initialPrompt??m.initialPrompt},currentSessionId:null,error:null,...e?.initialPrompt?{pendingInputText:e.initialPrompt,pendingInputMode:"replace"}:{}}})},setNewSessionDraftTarget:({projectId:e,directoryOverride:n},o)=>{const s=et.getState().projects,i=e?s.find(u=>u.id===e)??null:null,a=ie(n),l=ie(i?.path??null),c=a??l??null;let d=!1;t(u=>!u.newSessionDraft?.open||o?.force!==!0&&(u.newSessionDraft.pendingWorktreeRequestId||u.newSessionDraft.bootstrapPendingDirectory||u.newSessionDraft.preserveDirectoryOverride)?u:(d=!0,{newSessionDraft:{...u.newSessionDraft,selectedProjectId:i?.id??null,directoryOverride:c,pendingWorktreeRequestId:null,bootstrapPendingDirectory:null,preserveDirectoryOverride:!1,parentID:null}})),d&&Vr({projectId:i?.id??null,directory:c})},closeNewSessionDraft:()=>{const e=q.getState().currentSessionId;t({newSessionDraft:{open:!1,selectedProjectId:null,directoryOverride:null,pendingWorktreeRequestId:null,bootstrapPendingDirectory:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0},currentSessionId:e})},setPendingDraftWorktreeRequest:e=>{t(n=>n.newSessionDraft?.open?{newSessionDraft:{...n.newSessionDraft,pendingWorktreeRequestId:e}}:n)},resolvePendingDraftWorktreeTarget:(e,n,o)=>{t(s=>!s.newSessionDraft?.open||s.newSessionDraft.pendingWorktreeRequestId!==e?s:{newSessionDraft:{...s.newSessionDraft,selectedProjectId:o?.projectId??s.newSessionDraft.selectedProjectId??null,directoryOverride:ie(n),pendingWorktreeRequestId:null,bootstrapPendingDirectory:ie(o?.bootstrapPendingDirectory??s.newSessionDraft.bootstrapPendingDirectory??null),preserveDirectoryOverride:o?.preserveDirectoryOverride??!0}})},setDraftBootstrapPendingDirectory:e=>{t(n=>n.newSessionDraft?.open?{newSessionDraft:{...n.newSessionDraft,bootstrapPendingDirectory:ie(e)}}:n)},setDraftPreserveDirectoryOverride:e=>{t(n=>n.newSessionDraft?.open?{newSessionDraft:{...n.newSessionDraft,preserveDirectoryOverride:e}}:n)},createSession:async(e,n,o)=>{const i=r().newSessionDraft.targetFolderId;r().closeNewSessionDraft();const a=await q.getState().createSession(e,n,o);if(a?.id){await r().setCurrentSession(a.id);const l=n||r().lastLoadedDirectory||a.directory;i&&l&&As.getState().addSessionToFolder(l,i,a.id)}return a},createSessionFromAssistantMessage:async e=>{if(!e)return;const n=ee.getState(),{messages:o,lastUsedProvider:s}=n;let i,a;if(o.forEach((h,v)=>{const b=h.find(D=>D.info?.id===e);b&&!i&&(i=b,a=v)}),!i||i.info.role!=="assistant")return;const l=gg(i.parts);if(!l.trim())return;const c=q.getState(),d=Aa(c.sessions,a??null,c.getWorktreeMetadata),u=await r().createSession(void 0,d??null,null);if(!u)return;const{currentProviderId:f,currentModelId:m,currentAgentName:p}=ke.getState(),g=f||s?.providerID,S=m||s?.modelID;!g||!S||await O.sendMessage({id:u.id,providerID:g,modelID:S,text:l,prefaceText:$c,agent:p??void 0})},deleteSession:(e,n)=>q.getState().deleteSession(e,n),deleteSessions:(e,n)=>q.getState().deleteSessions(e,n),archiveSession:e=>q.getState().archiveSession(e),archiveSessions:(e,n)=>q.getState().archiveSessions(e,n),updateSessionTitle:(e,n)=>q.getState().updateSessionTitle(e,n),shareSession:e=>q.getState().shareSession(e),unshareSession:e=>q.getState().unshareSession(e),setCurrentSession:async e=>{e&&r().closeNewSessionDraft();const n=q.getState().currentSessionId,o=Aa(q.getState().sessions,e,q.getState().getWorktreeMetadata),s=O.getDirectory()??be.getState().currentDirectory??null,i=o??s;try{O.setDirectory(i??void 0)}catch(a){console.warn("Failed to set OpenCode directory for session switch:",a)}if(n&&n!==e&&!r().sessionMemoryState.get(n)?.isStreaming){const l=r().messages.get(n)||[];l.length>0&&r().updateViewportAnchor(n,l.length-1)}if(q.getState().setCurrentSession(e),e){const a=r().messages.get(e),l=r().sessionHistoryMeta.get(e),c=!l||typeof l.complete!="boolean";(!a||c)&&await r().loadMessages(e);const d=r().messages.get(e);if(d&&d.length>0){const u=ke.getState().agents;if(u.length>0){const f=Mg(d);if(Ia.get(e)===f)return;try{await ne.getState().analyzeAndSaveExternalSessionChoices(e,u,r().messages),Ia.set(e,f)}catch(m){console.warn("Failed to analyze session choices:",m)}}}}},loadMessages:(e,n)=>ee.getState().loadMessages(e,n),sendMessage:async(e,n,o,s,i,a,l,c,d="normal")=>{const u=r().newSessionDraft,f=typeof s=="string"&&s.trim().length>0?s.trim():void 0,m=(b,D)=>{t(I=>{const M=new Map(I.sessionStatus??new Map);return M.set(b,{type:D}),{sessionStatus:M}})};if(u?.open){const b=u.targetFolderId;let D=u.bootstrapPendingDirectory??u.directoryOverride??null;const I=u.selectedProjectId??null;u.pendingWorktreeRequestId&&(D=await Sg(u.pendingWorktreeRequestId),r().resolvePendingDraftWorktreeTarget(u.pendingWorktreeRequestId,D));const M=await q.getState().createSession(u.title,D,u.parentID??null);if(!M?.id)throw new Error("Failed to create session");Vr({projectId:I,directory:ie(D??M.directory??null)});const C=ke.getState(),k=C.currentAgentName,T=f??k,_=C.currentProviderId,$=C.currentModelId;if(_&&$)try{ne.getState().saveSessionModelSelection(M.id,_,$)}catch{}if(T){try{ne.getState().saveSessionAgentSelection(M.id,T)}catch{}if(_&&$){try{ne.getState().saveAgentModelForSession(M.id,T,_,$)}catch{}try{ne.getState().saveAgentModelVariantForSession(M.id,T,_,$,c)}catch{}}}try{q.getState().initializeNewOpenChamberSession(M.id,C.agents)}catch{}const U=u.syntheticParts;if(r().closeNewSessionDraft(),await r().setCurrentSession(M.id),b){const L=D||M.directory||null;L&&As.getState().addSessionToFolder(L,b,M.id)}m(M.id,"busy");const E=U?.length?[...l||[],...U]:l,j=ie(D??M.directory??null);j&&await cs(j);try{return Da(M.id),await ee.getState().sendMessage(e,n,o,T,M.id,i,a,E,c,d)}catch(L){throw m(M.id,"idle"),L}}const p=q.getState().currentSessionId,g=p?ne.getState().getSessionAgentSelection(p):null,S=ke.getState().currentAgentName,h=f||g||S||void 0;if(p&&h){try{ne.getState().saveSessionAgentSelection(p,h)}catch{}try{ne.getState().saveAgentModelVariantForSession(p,h,n,o,c)}catch{}}if(p){m(p,"busy");const b=r().sessionMemoryState.get(p);if(!b||!b.lastUserMessageAt){const D=r().sessionMemoryState,I=new Map(D);I.set(p,{viewportAnchor:b?.viewportAnchor??0,isStreaming:b?.isStreaming??!1,lastAccessedAt:Date.now(),backgroundMessageCount:b?.backgroundMessageCount??0,lastUserMessageAt:Date.now()}),t({sessionMemoryState:I})}}const v=p?ie(q.getState().getDirectoryForSession(p)):null;v&&await cs(v),p&&fetch(`/api/sessions/${p}/message-sent`,{method:"POST"}).catch(()=>{});try{return p&&Da(p),await ee.getState().sendMessage(e,n,o,h,p||void 0,i,a,l,c,d)}catch(b){throw p&&m(p,"idle"),b}},abortCurrentOperation:e=>{const n=e||q.getState().currentSessionId;return ee.getState().abortCurrentOperation(n||void 0)},armAbortPrompt:(e=3e3)=>{const n=q.getState().currentSessionId;if(!n)return null;const o=Date.now()+e;return t({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{t({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:e=>{e&&ee.getState().acknowledgeSessionAbort(e)},addStreamingPart:(e,n,o,s)=>{const a=q.getState().currentSessionId||e;return ee.getState().addStreamingPart(e,n,o,s,a)},applyPartDelta:(e,n,o,s,i,a)=>{const c=q.getState().currentSessionId||e;return ee.getState().applyPartDelta(e,n,o,s,i,a,c)},completeStreamingMessage:(e,n)=>ee.getState().completeStreamingMessage(e,n),markMessageStreamSettled:e=>ee.getState().markMessageStreamSettled(e),updateMessageInfo:(e,n,o)=>ee.getState().updateMessageInfo(e,n,o),updateSessionCompaction:(e,n)=>ee.getState().updateSessionCompaction(e,n??null),addPermission:e=>nn.getState().addPermission(e),respondToPermission:(e,n,o)=>nn.getState().respondToPermission(e,n,o),dismissPermission:(e,n)=>nn.getState().dismissPermission(e,n),addQuestion:e=>wr.getState().addQuestion(e),dismissQuestion:(e,n)=>wr.getState().dismissQuestion(e,n),respondToQuestion:(e,n,o)=>wr.getState().respondToQuestion(e,n,o),rejectQuestion:(e,n)=>wr.getState().rejectQuestion(e,n),clearError:()=>q.getState().clearError(),getSessionsByDirectory:e=>q.getState().getSessionsByDirectory(e),getDirectoryForSession:e=>q.getState().getDirectoryForSession(e),getLastMessageModel:e=>ee.getState().getLastMessageModel(e),getCurrentAgent:e=>ne.getState().getCurrentAgent(e),syncMessages:(e,n,o)=>ee.getState().syncMessages(e,n,o),applySessionMetadata:(e,n)=>q.getState().applySessionMetadata(e,n),addAttachedFile:e=>Xt.getState().addAttachedFile(e),addServerFile:(e,n,o)=>Xt.getState().addServerFile(e,n,o),removeAttachedFile:e=>Xt.getState().removeAttachedFile(e),clearAttachedFiles:()=>Xt.getState().clearAttachedFiles(),updateViewportAnchor:(e,n)=>ee.getState().updateViewportAnchor(e,n),loadMoreMessages:(e,n)=>ee.getState().loadMoreMessages(e,n),saveSessionModelSelection:(e,n,o)=>ne.getState().saveSessionModelSelection(e,n,o),getSessionModelSelection:e=>ne.getState().getSessionModelSelection(e),saveSessionAgentSelection:(e,n)=>ne.getState().saveSessionAgentSelection(e,n),getSessionAgentSelection:e=>ne.getState().getSessionAgentSelection(e),saveAgentModelForSession:(e,n,o,s)=>ne.getState().saveAgentModelForSession(e,n,o,s),getAgentModelForSession:(e,n)=>ne.getState().getAgentModelForSession(e,n),saveAgentModelVariantForSession:(e,n,o,s,i)=>ne.getState().saveAgentModelVariantForSession(e,n,o,s,i),getAgentModelVariantForSession:(e,n,o,s)=>ne.getState().getAgentModelVariantForSession(e,n,o,s),analyzeAndSaveExternalSessionChoices:(e,n)=>{const o=ee.getState().messages;return ne.getState().analyzeAndSaveExternalSessionChoices(e,n,o)},isOpenChamberCreatedSession:e=>q.getState().isOpenChamberCreatedSession(e),markSessionAsOpenChamberCreated:e=>q.getState().markSessionAsOpenChamberCreated(e),initializeNewOpenChamberSession:(e,n)=>q.getState().initializeNewOpenChamberSession(e,n),setWorktreeMetadata:(e,n)=>q.getState().setWorktreeMetadata(e,n),setSessionDirectory:(e,n)=>q.getState().setSessionDirectory(e,n),getWorktreeMetadata:e=>q.getState().getWorktreeMetadata(e),getContextUsage:(e,n)=>{if(r().newSessionDraft?.open)return null;const o=q.getState().currentSessionId;if(!o)return null;const s=ee.getState().messages;return ne.getState().getContextUsage(o,e,n,s)},updateSessionContextUsage:(e,n,o)=>{const s=ee.getState().messages;return ne.getState().updateSessionContextUsage(e,n,o,s)},initializeSessionContextUsage:(e,n,o)=>{const s=ee.getState().messages;return ne.getState().initializeSessionContextUsage(e,n,o,s)},debugSessionMessages:async e=>{const n=vm(ee.getState().messages.get(e)||[]),o=q.getState().sessions.find(s=>s.id===e);console.log(`Debug session ${e}:`,{session:o,messageCount:n.length,messages:n.map(s=>({id:s.info.id,role:s.info.role,parts:s.parts.length,tokens:s.info.tokens}))})},pollForTokenUpdates:(e,n,o)=>{const s=ee.getState().messages;return ne.getState().pollForTokenUpdates(e,n,s,o)},updateSession:e=>q.getState().updateSession(e),removeSessionFromStore:e=>q.getState().removeSessionFromStore(e),revertToMessage:async(e,n)=>{const s=(ee.getState().messages.get(e)||[]).find(d=>d.info.id===n);let i="";s&&s.info.role==="user"&&(i=s.parts.filter(u=>u.type==="text").map(u=>{const f=u;return f.text||f.content||""}).join(`
47
47
  `).trim());const a=await O.revertSession(e,n);q.getState().updateSession(a);const l=ee.getState().messages.get(e)||[],c=a.revert?.messageID;if(c){let d=l.findIndex(u=>u.info.id===c);if(d===-1&&(d=l.findIndex(u=>u.info.id===n)),d!==-1){const u=l.slice(0,d);ee.getState().syncMessages(e,u,{replace:!0})}}i&&t({pendingInputText:i,pendingInputMode:"replace"})},handleSlashUndo:async e=>{const o=(r().messages.get(e)||[]).filter(f=>f.info.role==="user"),i=r().sessions.find(f=>f.id===e);if(o.length===0)return;const a=i?.revert?.messageID;let l;if(a){const f=o.findIndex(m=>m.info.id===a);l=o[f+1]}else l=o[o.length-1];if(!l)return;const c=l.parts.find(f=>f.type==="text"),d=typeof c=="object"&&c&&"text"in c?String(c.text).slice(0,50)+(String(c.text).length>50?"...":""):"[No text]";await r().revertToMessage(e,l.info.id);const{toast:u}=await qe(async()=>{const{toast:f}=await import("./vendor-.bun-HTKwyaEM.js").then(m=>m.fE);return{toast:f}},__vite__mapDeps([0,1]));u.success(`Undid to: ${d}`)},handleSlashRedo:async e=>{const s=r().sessions.find(d=>d.id===e)?.revert?.messageID;if(!s)return;const a=(r().messages.get(e)||[]).filter(d=>d.info.role==="user"),l=a.findIndex(d=>d.info.id===s),c=a[l-1];if(c){const d=c.parts.find(m=>m.type==="text"),u=typeof d=="object"&&d&&"text"in d?String(d.text).slice(0,50)+(String(d.text).length>50?"...":""):"[No text]";await r().revertToMessage(e,c.info.id);const{toast:f}=await qe(async()=>{const{toast:m}=await import("./vendor-.bun-HTKwyaEM.js").then(p=>p.fE);return{toast:m}},__vite__mapDeps([0,1]));f.success(`Redid to: ${u}`)}else{const d=await O.unrevertSession(e);await q.getState().updateSession(d),await r().loadMessages(e);const{toast:u}=await qe(async()=>{const{toast:f}=await import("./vendor-.bun-HTKwyaEM.js").then(m=>m.fE);return{toast:f}},__vite__mapDeps([0,1]));u.success("Restored all messages")}},forkFromMessage:async(e,n)=>{const s=r().sessions.find(i=>i.id===e);if(s)try{const i=await O.forkSession(e,n);if(!i||!i.id){const{toast:u}=await qe(async()=>{const{toast:f}=await import("./vendor-.bun-HTKwyaEM.js").then(m=>m.fE);return{toast:f}},__vite__mapDeps([0,1]));u.error("Failed to fork session");return}const l=(r().messages.get(e)||[]).find(u=>u.info.id===n);if(!l){const{toast:u}=await qe(async()=>{const{toast:f}=await import("./vendor-.bun-HTKwyaEM.js").then(m=>m.fE);return{toast:f}},__vite__mapDeps([0,1]));u.error("Message not found");return}let c="";for(const u of l.parts)u.type==="text"&&!u.synthetic&&!u.ignored&&(c+=u.text||"");r().setCurrentSession(i.id),c&&t({pendingInputText:c,pendingInputMode:"replace"}),await r().loadMessages(i.id);const{toast:d}=await qe(async()=>{const{toast:u}=await import("./vendor-.bun-HTKwyaEM.js").then(f=>f.fE);return{toast:u}},__vite__mapDeps([0,1]));d.success(`Forked from ${s.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:a}=await qe(async()=>{const{toast:l}=await import("./vendor-.bun-HTKwyaEM.js").then(c=>c.fE);return{toast:l}},__vite__mapDeps([0,1]));a.error("Failed to fork session")}},setPendingInputText:(e,n="replace")=>{t({pendingInputText:e,pendingInputMode:n})},consumePendingInputText:()=>{const e=r().pendingInputText,n=r().pendingInputMode;return e!==null&&t({pendingInputText:null,pendingInputMode:"replace"}),e===null?null:{text:e,mode:n}},setPendingSyntheticParts:e=>{t({pendingSyntheticParts:e})},consumePendingSyntheticParts:()=>{const e=r().pendingSyntheticParts;return e!==null&&t({pendingSyntheticParts:null}),e}}),{name:"composed-session-store"}));let zn=null,Hn=null;q.subscribe((t,r)=>{if(t.sessions===r.sessions&&t.archivedSessions===r.archivedSessions&&t.sessionsByDirectory===r.sessionsByDirectory&&t.currentSessionId===r.currentSessionId&&t.lastLoadedDirectory===r.lastLoadedDirectory&&t.isLoading===r.isLoading&&t.error===r.error&&t.webUICreatedSessions===r.webUICreatedSessions&&t.worktreeMetadata===r.worktreeMetadata&&t.availableWorktrees===r.availableWorktrees&&t.availableWorktreesByProject===r.availableWorktreesByProject)return;const e=V.getState().newSessionDraft?.open;V.setState({sessions:t.sessions,archivedSessions:t.archivedSessions,sessionsByDirectory:t.sessionsByDirectory,currentSessionId:e?null:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,isLoading:t.isLoading,error:t.error,webUICreatedSessions:t.webUICreatedSessions,worktreeMetadata:t.worktreeMetadata,availableWorktrees:t.availableWorktrees,availableWorktreesByProject:t.availableWorktreesByProject})});ee.subscribe((t,r)=>{t.messages===r.messages&&t.sessionMemoryState===r.sessionMemoryState&&t.sessionHistoryMeta===r.sessionHistoryMeta&&t.messageStreamStates===r.messageStreamStates&&t.sessionCompactionUntil===r.sessionCompactionUntil&&t.sessionAbortFlags===r.sessionAbortFlags&&t.streamingMessageIds===r.streamingMessageIds&&t.abortControllers===r.abortControllers&&t.lastUsedProvider===r.lastUsedProvider&&t.isSyncing===r.isSyncing||(zn!==null&&cancelAnimationFrame(zn),zn=requestAnimationFrame(()=>{zn=null;const e=ee.getState();V.setState({messages:e.messages,sessionMemoryState:e.sessionMemoryState,sessionHistoryMeta:e.sessionHistoryMeta,messageStreamStates:e.messageStreamStates,sessionCompactionUntil:e.sessionCompactionUntil,sessionAbortFlags:e.sessionAbortFlags,streamingMessageIds:e.streamingMessageIds,abortControllers:e.abortControllers,lastUsedProvider:e.lastUsedProvider,isSyncing:e.isSyncing}),Hn!==null&&clearTimeout(Hn),Hn=setTimeout(()=>{Hn=null;const n=ee.getState(),o=new Map;n.messages.forEach((s,i)=>{if(!(!Array.isArray(s)||s.length===0))for(let a=s.length-1;a>=0;a-=1){const l=s[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const f=c.time&&typeof c.time.created=="number"?c.time.created:null;o.set(i,{title:u,createdAt:f});break}}}}}),V.setState({userSummaryTitles:o})},500)}))});Xt.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&V.setState({attachedFiles:t.attachedFiles})});ne.subscribe((t,r)=>{t.sessionModelSelections===r.sessionModelSelections&&t.sessionAgentSelections===r.sessionAgentSelections&&t.sessionAgentModelSelections===r.sessionAgentModelSelections&&t.currentAgentContext===r.currentAgentContext&&t.sessionContextUsage===r.sessionContextUsage&&t.sessionAgentEditModes===r.sessionAgentEditModes||V.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});nn.subscribe((t,r)=>{t.permissions!==r.permissions&&V.setState({permissions:t.permissions})});wr.subscribe((t,r)=>{t.questions!==r.questions&&V.setState({questions:t.questions})});be.subscribe((t,r)=>{const e=ie(t.currentDirectory??null),n=ie(r.currentDirectory??null);if(e===n)return;const o=V.getState().newSessionDraft;if(!o?.open||o.pendingWorktreeRequestId||o.bootstrapPendingDirectory||o.preserveDirectoryOverride)return;const s=ie(o.directoryOverride);if(s&&s!==n)return;const i=et.getState().projects,a=Kr(i,V.getState().availableWorktreesByProject,e);V.setState(l=>({newSessionDraft:{...l.newSessionDraft,selectedProjectId:a?.id??l.newSessionDraft.selectedProjectId??null,directoryOverride:e,parentID:null}})),Vr({projectId:a?.id??o.selectedProjectId??null,directory:e})});const vg=V.getState().newSessionDraft?.open;V.setState({sessions:q.getState().sessions,currentSessionId:vg?null:q.getState().currentSessionId,lastLoadedDirectory:q.getState().lastLoadedDirectory,isLoading:q.getState().isLoading,error:q.getState().error,webUICreatedSessions:q.getState().webUICreatedSessions,worktreeMetadata:q.getState().worktreeMetadata,availableWorktrees:q.getState().availableWorktrees,availableWorktreesByProject:q.getState().availableWorktreesByProject,messages:ee.getState().messages,sessionMemoryState:ee.getState().sessionMemoryState,sessionHistoryMeta:ee.getState().sessionHistoryMeta,messageStreamStates:ee.getState().messageStreamStates,sessionCompactionUntil:ee.getState().sessionCompactionUntil,sessionAbortFlags:ee.getState().sessionAbortFlags,streamingMessageIds:ee.getState().streamingMessageIds,abortControllers:ee.getState().abortControllers,lastUsedProvider:ee.getState().lastUsedProvider,isSyncing:ee.getState().isSyncing,permissions:nn.getState().permissions,questions:wr.getState().questions,attachedFiles:Xt.getState().attachedFiles,sessionModelSelections:ne.getState().sessionModelSelections,sessionAgentSelections:ne.getState().sessionAgentSelections,sessionAgentModelSelections:ne.getState().sessionAgentModelSelections,currentAgentContext:ne.getState().currentAgentContext,sessionContextUsage:ne.getState().sessionContextUsage,sessionAgentEditModes:ne.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=V);const el=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),Dg=Me()(ve((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async e=>{if(e){t({isLoading:!0});try{const n=V.getState().getDirectoryForSession(e),s=(n?await O.withDirectory(n,()=>O.getSessionTodos(e)):await O.getSessionTodos(e)).map(el);t(i=>{const a=new Map(i.sessionTodos);return a.set(e,s),{sessionTodos:a,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),t({isLoading:!1})}}},updateTodos:(e,n)=>{t(o=>{const s=new Map(o.sessionTodos);return s.set(e,n),{sessionTodos:s}})},getTodosForSession:e=>r().sessionTodos.get(e)||[],clearTodos:e=>{t(n=>{const o=new Map(n.sessionTodos);return o.delete(e),{sessionTodos:o}})}}),{name:"todo-store"})),Ig=(t,r)=>{const e=r.map(el);Dg.getState().updateTodos(t,e)},Ag={},an=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const e=r.replace(/\\/g,"/");return e.length>1?e.replace(/\/+$/,""):e},Pa=t=>an(t)??"__global__",ts=t=>{const r=an(t);return r?O.getScopedApiClient(r):O.getApiClient()},xy=t=>{const r=Object.entries(t??{}),e=r.filter(([,i])=>i?.status==="connected").length,n=r.length,o=r.some(([,i])=>i?.status==="failed"),s=r.some(([,i])=>i?.status==="needs_auth"||i?.status==="needs_client_registration");return{connected:e,total:n,hasFailed:o,hasAuthRequired:s}},Pg=Me()(ve((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:e=>{const n=Pa(e??be.getState().currentDirectory);return r().byDirectory[n]??Ag},refresh:async e=>{const n=an(e?.directory??be.getState().currentDirectory),o=Pa(n);e?.silent||t(s=>({loadingKeys:{...s.loadingKeys,[o]:!0},lastErrorKeys:{...s.lastErrorKeys,[o]:null}}));try{const a=(await ts(n).mcp.status()).data??{};t(l=>({byDirectory:{...l.byDirectory,[o]:a},loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:null}}))}catch(s){const i=s instanceof Error?s.message:"Failed to load MCP status";t(a=>({loadingKeys:{...a.loadingKeys,[o]:!1},lastErrorKeys:{...a.lastErrorKeys,[o]:i}}))}},connect:async(e,n)=>{const o=an(n??be.getState().currentDirectory);await ts(o).mcp.connect({name:e},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(e,n)=>{const o=an(n??be.getState().currentDirectory);await ts(o).mcp.disconnect({name:e},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function rs(...t){return vl(Dl(t))}const tl=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),_y=t=>tl()&&Ke()?t.metaKey:t.ctrlKey,Ry=()=>tl()&&Ke()?"⌘":"Ctrl",Oy=(t,r)=>{const e=t??"",n=Math.max(16,r?.maxLength??45);if(e.length<=n)return e;const o=e.split("/");if(o.length<=1)return e;const s=o.pop()??"";if(!s)return e;const i=Math.max(0,n-(s.length+2));if(i<=0)return`…/${s}`;let a="";for(const l of o){if(!l)continue;const c=a?`${a}/${l}`:l;if(c.length>i)break;a=c}if(!a){const l=o[0]??"";a=l?l.slice(0,i):""}return a?`${a}…/${s}`:`…/${s}`},po=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function jy(t,r){if(!t)return"";const e=po(t);if(e==="/")return"/";const n=r?po(r):void 0;if(n&&n!=="/"){if(e===n)return"~";if(e.startsWith(`${n}/`)){const o=e.slice(n.length+1);return o?`~/${o}`:"~"}}return e}function Fy(t,r){if(!t)return"/";const e=po(t);if(!e||e==="/")return"/";const n=r?po(r):void 0;return n&&n!=="/"&&e===n?"~":e.split("/").pop()||e||"/"}function Ly(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new Il([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}const Ta=(t,r)=>{const e=t.trim();return e.length<=r?e:`${e.slice(0,Math.max(0,r-3))}...`},Tg=({sessionTitle:t,permissionBody:r,disabled:e=!1,onOnce:n,onAlways:o,onDeny:s})=>{const[i,a]=R.useState(!1),l=t.trim().length>0?` for ${t}`:"",c=Ta(t,64)||"Session",d=Ta(r,120)||"Permission details unavailable",u=async f=>{if(!(i||e)){a(!0);try{await f()}finally{a(!1)}}};return ht.jsxs("div",{className:"min-w-0",children:[ht.jsxs("div",{className:"mb-1.5 min-w-0 space-y-0.5",children:[ht.jsxs("p",{className:"typography-meta text-muted-foreground",title:t,children:["Session:"," ",ht.jsx("span",{className:"inline-block max-w-[280px] align-bottom truncate text-foreground",children:c})]}),ht.jsxs("p",{className:"typography-meta text-muted-foreground",title:r,children:["Permission:"," ",ht.jsx("span",{className:"inline-block max-w-[280px] align-bottom truncate",children:d})]})]}),ht.jsxs("div",{className:"flex items-center gap-1.5",children:[ht.jsx("button",{onClick:()=>u(n),disabled:e||i,"aria-label":`Approve once${l}`,className:rs("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:"Once"}),ht.jsx("button",{onClick:()=>u(o),disabled:e||i,"aria-label":`Approve always${l}`,className:rs("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:"Always"}),ht.jsx("button",{onClick:()=>u(s),disabled:e||i,"aria-label":`Deny permission${l}`,className:rs("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:f=>{f.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:f=>{f.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:"Deny"})]})]})},de=(t,r)=>{if(!t||typeof t!="object")return null;const e=t;for(let n=0;n<r.length;n++){const o=e[r[n]];if(typeof o=="string"&&o.length>0)return o}return null},ka=t=>Array.isArray(t)?t.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0):[],Ca=t=>{if(!t||typeof t!="object")return null;const r=t,e=de(r,["id"]),n=de(r,["sessionID"]);if(!e||!n)return null;const o=typeof r.permission=="string"?r.permission:"",s=ka(r.patterns),i=typeof r.metadata=="object"&&r.metadata!==null?r.metadata:{},a=ka(r.always),l=r.tool,c=l&&typeof l=="object"?{messageID:de(l,["messageID"])??"",callID:de(l,["callID"])??""}:void 0;return{id:e,sessionID:n,permission:o,patterns:s,metadata:i,always:a,tool:c&&c.messageID.length>0&&c.callID.length>0?c:void 0}},kg=t=>{const r=["command","cmd","script","path","filePath","filepath","file_path","directory","working_directory","cwd","url","uri","endpoint","description","action","operation"];for(let n=0;n<r.length;n++){const o=t[r[n]];if(typeof o=="string"){const s=o.trim();if(s.length>0)return s;continue}if(typeof o=="number"||typeof o=="boolean")return String(o);if(Array.isArray(o)){const s=o.filter(i=>typeof i=="string"&&i.trim().length>0).slice(0,3).join(", ").trim();if(s.length>0)return s}}if(Object.entries(t).length===0)return"";try{return JSON.stringify(t)}catch{return""}},Cg=t=>{const e=(Array.isArray(t.patterns)?t.patterns:[]).filter(i=>typeof i=="string"&&i.trim().length>0).join(", ").trim(),n=typeof t.metadata=="object"&&t.metadata!==null?t.metadata:{},o=kg(n);if(e.length>0&&o.length>0)return`${e} | ${o}`;if(e.length>0)return e;if(o.length>0)return o;const s=typeof t.permission=="string"?t.permission.trim():"";return s.length>0?s:"Permission details unavailable"};function rl(){if(typeof window>"u")return{subscribe:()=>()=>{},publish:()=>{}};if(window.__openCodeEventBus)return window.__openCodeEventBus;const t=new Set,r={subscribe:e=>(t.add(e),()=>{t.delete(e)}),publish:e=>{for(const n of t)try{n(e)}catch(o){console.warn("[EventBus] Subscriber error:",o)}}};return window.__openCodeEventBus=r,r}const Eg=1800,xg=3e3,_g=3e3,Ea=2500,Rg=5e3,Og=new Set(["edit","multiedit","apply_patch","write","file_write","create","bash"]),jg=new Set(["completed","complete","failed","error","cancelled","canceled"]),ns=t=>de(t,["directory"])??"global",Fg=500,Lg=100,Yt=new Map,xa=(t,r)=>{const e=`${t}:${r}`,n=Yt.get(e);if(n&&n.sessionId===t)return n.message;const i=(V.getState().messages.get(t)||[]).find(a=>a.info.id===r)||null;if(Yt.size>=Fg){let a=0;for(const l of Yt.keys()){if(a++>=Lg)break;Yt.delete(l)}}return Yt.set(e,{sessionId:t,message:i}),i},_a=(t,r)=>(V.getState().messages.get(t)||[]).find(o=>o.info.id===r)||null,Ny=t=>{const r=t?.enabled??!0,{addStreamingPart:e,applyPartDelta:n,completeStreamingMessage:o,updateMessageInfo:s,updateSessionCompaction:i,addPermission:a,dismissPermission:l,addQuestion:c,dismissQuestion:d,currentSessionId:u,applySessionMetadata:f,getWorktreeMetadata:m,loadMessages:p,loadSessions:g,updateSession:S,removeSessionFromStore:h}=V(),{checkConnection:v}=ke(),b=be(A=>A.currentDirectory),D=R.useMemo(()=>{if(!u)return;try{const H=m?.(u);if(H?.path)return H.path}catch(H){console.warn("Failed to inspect worktree metadata for session directory:",H)}const y=V.getState().sessions.find(H=>H.id===u);if(y&&typeof y.directory=="string"&&y.directory.trim().length>0)return y.directory.trim()},[u,m]),I=R.useMemo(()=>{if(D&&D.length>0)return D;if(typeof b=="string"&&b.trim().length>0)return b.trim()},[D,b]),M=R.useCallback(async()=>{try{const y=et.getState().projects.map(B=>B.path),w=V.getState().sessions.map(B=>B.directory),P=[I,...y,...w],F=await O.listPendingQuestions({directories:P});if(F.length===0)return;for(const B of F)c(B)}catch{}},[c,I]),C=R.useRef(0),k=R.useCallback((A=!1)=>{const y=Date.now();!A&&y-C.current<xg||(C.current=y,M())},[M]),T=R.useCallback(async()=>{try{const y=et.getState().projects.map(B=>B.path),w=V.getState().sessions.map(B=>B.directory),P=[I,...y,...w],F=await O.listPendingPermissions({directories:P});if(F.length===0)return;for(const B of F){const x=Ca(B);x&&a(x)}}catch{}},[a,I]),_=R.useRef(0),$=R.useCallback((A=!1)=>{const y=Date.now();!A&&y-_.current<_g||(_.current=y,T())},[T]),U=R.useRef($);R.useEffect(()=>{U.current=$},[$]),R.useEffect(()=>{r&&($(!0),k(!0))},[r,$,k]);const E=R.useCallback(A=>{if(typeof A!="string")return null;const y=A.trim();if(!y)return null;const H=y.replace(/\\/g,"/");return H.length>1?H.replace(/\/+$/,""):H},[]),j=R.useCallback(A=>{if(!A)return null;try{const w=m?.(A),P=E(w?.path??null);if(P)return P}catch{}const H=V.getState().sessions.find(w=>w.id===A);return E(H?.directory??null)},[m,E]),L=Oe(A=>A.setEventStreamStatus),z=R.useRef(null),W=R.useCallback((A,y)=>{const H=y??null,w=z.current;if(!(w&&w.status===A&&w.hint===H)){if(z.current={status:A,hint:H},we()){const F={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[A]??"[INFO]",B=H?`${F} SSE ${A}: ${H}`:`${F} SSE ${A}`;console.info(B)}L(A,H)}},[L]),fe=R.useCallback((A,y,H)=>{if(!A)return Promise.resolve();const w=Date.now();if(Ut.current)return Ut.current;if(w-kr.current<Eg)return Promise.resolve();const P=p(A,H).catch(F=>{console.warn(`[useEventStream] Failed to resync messages (${y}):`,F)}).finally(()=>{Ut.current=null,kr.current=Date.now()});return Ut.current=P,P},[p]),re=R.useCallback(async A=>{we()&&console.info("[useEventStream] Bootstrapping state:",A);try{const y=kt();await Promise.all([g(),u?fe(u,A,y):Promise.resolve()])}catch(y){console.warn("[useEventStream] Bootstrap failed:",A,y)}},[u,g,fe]),Ae=R.useCallback((A,y,H=kt())=>{if(!A)return Promise.resolve();const P=V.getState().sessionMemoryState.get(A)?.streamingCooldownUntil,F=Date.now();if(typeof P=="number"&&P>F){const B=Math.min(3e3,Math.max(0,P-F));return new Promise(x=>{setTimeout(()=>{fe(A,y,H).finally(x)},B)})}return fe(A,y,H)},[fe]);R.useEffect(()=>{Ao.current=Ae},[Ae]);const oe=R.useCallback((A,y,H)=>{we()&&console.debug(`[MessageTracker] ${A}: ${y}`,H)},[]),ut=R.useCallback(A=>{we()&&console.debug(`[MessageTracker] ${A}: reported`)},[]),Q=R.useRef(null),se=R.useRef(null),Z=R.useRef(0),ce=R.useRef(new Set),De=R.useRef(new Map),he=R.useRef(null),je=R.useRef(!1),Ut=R.useRef(null),kr=R.useRef(0),Cr=R.useRef(new Set),yn=R.useRef(new Set),bt=R.useRef(new Set),Et=R.useRef(new Set),nt=R.useRef(!1),Er=R.useRef(new Set),hn=R.useRef(new Map),ft=R.useCallback(()=>{if(typeof document>"u")return"visible";const A=document.visibilityState;return A==="hidden"&&document.hasFocus()?"visible":A},[]),pt=R.useRef(ft()),Bt=R.useRef(typeof navigator>"u"?!0:navigator.onLine),Fe=R.useRef(!1),Do=R.useRef(null),or=R.useRef(null),Mt=R.useRef(Date.now()),xr=R.useRef(new Map),ot=R.useRef(new Map),zs=R.useRef(new Map),Io=R.useRef(new Map),_r=R.useRef(new Map),xt=R.useRef(new Map),Hs=R.useRef(0),Sn=R.useRef(null),Ws=R.useRef(0),Gs=R.useRef(0),Rr=R.useRef(new Map),Ao=R.useRef(()=>Promise.resolve()),qs=R.useRef(()=>{}),wn=R.useCallback((A,y)=>{const H=Io.current;if(H.set(A,y),H.size>4e3){const w=H.keys().next().value;typeof w=="string"&&H.delete(w)}},[]),Vs=R.useCallback(A=>pt.current==="hidden"?!0:A&&typeof document<"u"?!document.hasFocus():!1,[]),sr=R.useCallback(A=>{const y=Nt();if(!y?.notifications)return;const H=typeof A.title=="string"?A.title.trim():"";if(!H)return;const w=Oe.getState();if(!w.nativeNotificationsEnabled)return;const P=!!y.runtime?.isVSCode;(A.requireHidden||w.notificationMode==="hidden-only")&&!Vs(P)||y.notifications.notifyAgentCompletion({title:H,body:typeof A.body=="string"?A.body:"",tag:typeof A.tag=="string"?A.tag:void 0})},[Vs]),bn=R.useCallback(A=>{const y=Date.now();y-Mt.current>25e3&&(re(A),Mt.current=y)},[re]),Ks=R.useCallback(A=>{if(typeof window>"u")return;const y=`${A.sessionId}:${A.messageId}:${A.partId??"unknown"}:${A.toolName}:${A.toolState}`,H=Date.now(),w=Rr.current.get(y)??0;if(!(H-w<Rg)){if(Rr.current.set(y,H),Rr.current.size>600){const P=Rr.current.keys().next().value;typeof P=="string"&&Rr.current.delete(P)}window.dispatchEvent(new CustomEvent("archcoder:git-refresh-hint",{detail:{directory:A.directory,sessionId:A.sessionId,messageId:A.messageId,toolName:A.toolName,toolState:A.toolState}}))}},[]),Je=R.useRef(u),Js=R.useRef(null),Qs=R.useRef(null);R.useEffect(()=>{Je.current=u},[u]);const mt=R.useCallback((A,y)=>{if(!A)return;const H=Date.now(),w=De.current,P=w.get(A);if(P&&H-P<3e3)return;w.set(A,H);const F=B=>{if(typeof y=="string"&&y.trim().length>0)return y.trim();try{const G=m?.(B);if(G?.path)return G.path}catch{}const N=V.getState().sessions.find(G=>G.id===B);return N&&typeof N.directory=="string"&&N.directory.trim().length>0?N.directory.trim():null};setTimeout(async()=>{try{const B=F(A),x=B?await O.withDirectory(B,()=>O.getSession(A)):await O.getSession(A);if(x){const N={};typeof x.title=="string"&&x.title.length>0&&(N.title=x.title),x.summary!==void 0&&(N.summary=x.summary),Object.keys(N).length>0&&f(A,N)}}catch(B){console.warn("Failed to refresh session metadata:",B)}},100)},[f,m]),Ee=R.useCallback((A,y,H="unknown")=>{if(!A)return;const P=V.getState().sessionStatus?.get(A)?.type??"idle",F=y?.type??"idle",B=P==="idle"&&(F==="busy"||F==="retry");if(F==="idle"){const G=ot.current.get(A);G&&(clearTimeout(G),ot.current.delete(A))}if(B){const G=ot.current.get(A);G&&(clearTimeout(G),ot.current.delete(A));const J=Date.now(),te=setTimeout(()=>{const Se=V.getState().sessionStatus?.get(A);if(Se?.type!=="busy"&&Se?.type!=="retry")return;const ue=zs.current.get(A)??0;Date.now()-ue<15e3||(xr.current.get(A)??0)>=J||(zs.current.set(A,Date.now()),Ao.current(A,"status_busy_no_message",kt()).finally(()=>{qs.current("No message events after busy status")}))},2e3);ot.current.set(A,te)}const N=new Map(V.getState().sessionStatus??new Map);if(F==="idle")N.set(A,{...y,confirmedAt:Date.now()});else{const G=N.get(A);G?.confirmedAt?N.set(A,{...y,confirmedAt:G.confirmedAt}):N.set(A,y)}V.setState({sessionStatus:N})},[]),st=R.useCallback((A,y,H="unknown",w)=>{if(!A)return;const P=w?.syncStatus!==!1;if(xt.current.get(A)===y)return;const B=_r.current.get(A);B&&(clearTimeout(B),_r.current.delete(A));const x=new Map(xt.current);if(x.set(A,y),xt.current=x,!!P){if(y==="idle"){Ee(A,{type:"idle"},`${H}:idle`);return}if(Ee(A,{type:"busy"},`${H}:${y}`),y==="cooldown"){const N=setTimeout(()=>{if(_r.current.delete(A),xt.current.get(A)!=="cooldown")return;const G=new Map(xt.current);G.set(A,"idle"),xt.current=G,Ee(A,{type:"idle"},`${H}:cooldown_timeout`)},2e3);_r.current.set(A,N)}}},[Ee]),Po=R.useCallback(async()=>{const A=Date.now();if(Sn.current)return Sn.current;if(A-Hs.current<1500)return;Hs.current=A;const y=w=>{const P=new Set,F=V.getState().sessions,B=new Set(F.map(x=>x.id));for(const[x,N]of Object.entries(w)){if(!x||!N)continue;P.add(x);const G=N.type==="cooldown"?"cooldown":N.type==="busy"||N.type==="retry"?"busy":"idle";st(x,G,"snapshot")}for(const[x,N]of xt.current.entries())B.has(x)&&(N==="busy"||N==="cooldown")&&!P.has(x)&&st(x,"idle","snapshot_missing")},H=(async()=>{try{const w=await O.getWebServerSessionActivity();if(w&&Object.keys(w).length>0){y(w);return}const P=await O.getGlobalSessionStatus();P&&Object.keys(P).length>0&&y(P)}catch{}})().finally(()=>{Sn.current=null});return Sn.current=H,H},[st]),Ys=R.useCallback(()=>{const A=_r.current;for(const y of A.values())clearTimeout(y);A.clear(),xt.current.clear()},[]),xe=R.useCallback((A,y)=>{const H=y?.refreshActivity!==!1,w=y?.pollStatus!==!1,P=y?.immediate===!0,F=Date.now();we()&&console.debug("[useEventStream] Repairing derived session state",{reason:A,refreshActivity:H,pollStatus:w,immediate:P}),H&&(P||F-Ws.current>=Ea)&&(Ws.current=F,Po()),w&&(P||F-Gs.current>=Ea)&&(Gs.current=F,Fc())},[Po]);R.useEffect(()=>{const A=u??null,y=Js.current,H=j(A),w=Qs.current;y&&A&&y!==A&&(Yt.clear(),w&&H&&w!==H&&xe("session_switch_directory")),Js.current=A,Qs.current=H},[u,xe,j]);const To=R.useCallback(A=>{if(Mt.current=Date.now(),we()&&console.debug("[useEventStream] Received event:",A.type,A.properties),rl().publish(A),!A.properties)return;const y=A.properties;if(!new Set(["session.abort","session.error"]).has(A.type)){const w=(typeof y.session=="object"&&y.session!==null?y.session:null)||(typeof y.sessionInfo=="object"&&y.sessionInfo!==null?y.sessionInfo:null);if(w){const P=w,F=typeof P.id=="string"&&P.id.length>0?P.id:typeof P.sessionID=="string"&&P.sessionID.length>0?P.sessionID:typeof y.sessionID=="string"&&y.sessionID.length>0?y.sessionID:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(F){const B=typeof P.title=="string"?P.title:typeof y.title=="string"?y.title:void 0,x=typeof P.summary=="object"&&P.summary!==null?P.summary:typeof y.summary=="object"&&y.summary!==null?y.summary:void 0;if(B!==void 0||x!==void 0){const N={};B!==void 0&&(N.title=B),x!==void 0&&(N.summary=x),f(F,N)}}}}switch(A.type){case"server.connected":v();break;case"global.disposed":case"server.instance.disposed":{re("server_disposed_event");break}case"mcp.tools.changed":{const w=typeof y.directory=="string"?y.directory:I;Pg.getState().refresh({directory:w??null,silent:!0});break}case"session.status":{const w=de(y,["sessionID","sessionId"]),P=y.status,F=typeof P=="object"&&P!==null?P:null,B=typeof P=="string"?P:typeof F?.type=="string"?F.type:typeof F?.status=="string"?F.status:typeof y.type=="string"?y.type:typeof y.phase=="string"?y.phase:typeof y.state=="string"?y.state:null,x=F??{},N=y.metadata,G=typeof N=="object"&&N!==null?N:null;w&&B&&(B==="busy"?(Ee(w,{type:"busy"},"sse:session.status"),st(w,"busy","sse:session.status",{syncStatus:!1})):B==="retry"?(Ee(w,{type:"retry",attempt:typeof x.attempt=="number"?x.attempt:typeof y.attempt=="number"?y.attempt:typeof G?.attempt=="number"?G.attempt:void 0,message:typeof x.message=="string"?x.message:typeof y.message=="string"?y.message:typeof G?.message=="string"?G.message:void 0,next:typeof x.next=="number"?x.next:typeof y.next=="number"?y.next:typeof G?.next=="number"?G.next:void 0},"sse:session.status"),st(w,"busy","sse:session.status",{syncStatus:!1})):(Ee(w,{type:"idle"},"sse:session.status"),st(w,"idle","sse:session.status",{syncStatus:!1}),xe("session.status_idle",{refreshActivity:!1})),mt(w,typeof y.directory=="string"?y.directory:null))}break;case"archcoder:session-activity":{const w=de(y,["sessionId","sessionID"]),P=typeof y.phase=="string"?y.phase:null;w&&(P==="idle"||P==="busy"||P==="cooldown")&&(st(w,P,"sse:archcoder:session-activity"),mt(w,typeof y.directory=="string"?y.directory:null))}break;case"archcoder:session-status":{const w=de(y,["sessionId","sessionID"]),P=typeof y.status=="string"?y.status:null,F=typeof y.needsAttention=="boolean"?y.needsAttention:!1,B=typeof y.timestamp=="number"?y.timestamp:Date.now();if(w&&P){if(P==="busy")Ee(w,{type:"busy"},"sse:archcoder:session-status"),st(w,"busy","sse:archcoder:session-status",{syncStatus:!1});else if(P==="retry"){const J=typeof y.metadata=="object"&&y.metadata!==null?y.metadata:{};Ee(w,{type:"retry",attempt:typeof J.attempt=="number"?J.attempt:void 0,message:typeof J.message=="string"?J.message:void 0,next:typeof J.next=="number"?J.next:void 0},"sse:archcoder:session-status"),st(w,"busy","sse:archcoder:session-status",{syncStatus:!1})}else Ee(w,{type:"idle"},"sse:archcoder:session-status"),st(w,"idle","sse:archcoder:session-status",{syncStatus:!1}),F&&xe("archcoder.session-status_attention_idle",{refreshActivity:!1});const x=V.getState().sessionAttentionStates||new Map,N=new Map(x),G=N.get(w);N.set(w,{needsAttention:F,lastStatusChangeAt:B,lastUserMessageAt:G?.lastUserMessageAt??null,status:P,isViewed:G?.isViewed??!1}),V.setState({sessionAttentionStates:N})}}break;case"message.part.updated":{const w=typeof y.part=="object"&&y.part!==null?y.part:null;if(!w)break;const P=w,F=typeof y.info=="object"&&y.info!==null?y.info:y,B=de(F,["sessionID","sessionId"]),x=de(P,["sessionID","sessionId"])||B||de(y,["sessionID","sessionId"]),N=de(F,["messageID","messageId","id"]),G=de(P,["messageID","messageId"])||N||de(y,["messageID","messageId"]);if(!x||!G){we()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:P.sessionID??B??y.sessionID,messageID:P.messageID??N??y.messageID});break}const J=x,te=G;xr.current.set(J,Date.now());const Se=ot.current.get(J);Se&&(clearTimeout(Se),ot.current.delete(J));const ue=pe=>{const Ot=typeof pe=="string"?pe.trim():"";return Ot?Ot.startsWith("User has requested to enter plan mode")||Ot.startsWith("The plan at ")||Ot.startsWith("The following tool was executed by the user"):!1},Qe=()=>{const pe=typeof P.type=="string"?P.type:"";if(pe==="subtask"||pe==="agent"||pe==="file")return!0;if(pe==="text"&&P.synthetic===!0){const Ot=P.text;return ue(Ot)}return!1};let Le="assistant";const Dt=_a(J,te),gt=Dt?.parts?.find(pe=>pe?.id===P.id),cr=typeof gt?.type=="string"?gt.type:void 0;if(F&&typeof F.role=="string")Le=F.role;else if(Dt){const pe=Dt.info.role;typeof pe=="string"&&(Le=pe)}if(Le!=="user"&&Qe()&&(Le="user"),oe(te,"part_received",{role:Le}),Le==="user"&&P.synthetic===!0){const pe=P.text;if(!ue(pe)){oe(te,"skipped_synthetic_user_part");break}}const lr=de(P,["id","partID","partId"]),Or=ns(y),Rt=lr?`${Or}:${te}:${lr}`:null,Mn=Rt?Io.current.get(Rt):void 0,zt=w.type||cr||Mn||"text",It={...{...w,type:zt}};if(Rt&&typeof zt=="string"&&zt.length>0&&wn(Rt,zt),Le==="assistant"){const pe=It.type,jr=typeof It.time?.end=="number",dr=It.state?.status,At=typeof dr=="string"?dr.toLowerCase():null,ur=typeof It.tool=="string"?It.tool.toLowerCase():null,Co=It.text;if(pe==="tool"&&ur&&Og.has(ur)&&At&&jg.has(At)&&Ks({directory:Or,sessionId:J,messageId:te,partId:lr,toolName:ur,toolState:At}),pe==="tool"&&ur==="question"&&k(),pe==="tool"?At==="running"||At==="pending":pe==="reasoning"?!jr:pe==="text"?typeof Co=="string"&&Co.trim().length>0&&!jr:pe==="step-start"){const Pe=V.getState().sessionStatus?.get(J),We=Pe?.type==="idle"&&typeof Pe.confirmedAt=="number"&&Date.now()-Pe.confirmedAt<1200;(!Pe||Pe.type==="idle")&&(We||Ee(J,{type:"busy"},"sse:message.part.updated"))}}oe(te,"addStreamingPart_called"),e(J,te,It,Le);break}case"message.part.delta":{const w=de(y,["sessionID","sessionId"]),P=de(y,["messageID","messageId"]),F=de(y,["partID","partId"]),B=de(y,["field"]),x=typeof y.delta=="string"?y.delta:null;if(!w||!P||!F||!B||x===null){we()&&console.debug("[useEventStream] Skipping message.part.delta with missing payload",{sessionID:y.sessionID,messageID:y.messageID,partID:y.partID,field:y.field});break}xr.current.set(w,Date.now());const N=ot.current.get(w);N&&(clearTimeout(N),ot.current.delete(w));const G=_a(w,P),J=G?.parts?.find(ue=>ue?.id===F),te=G?.info?.role,Se=typeof te=="string"?te:"assistant";if(!J){if(B==="text"||B==="content"||B==="value"){const ue=ns(y),Qe=de(y,["partType","type","part_type"])||de(y,["kind"]),Le=`${ue}:${P}:${F}`,Dt=Io.current.get(Le),gt=typeof Qe=="string"&&Qe.trim().length>0?Qe:typeof Dt=="string"&&Dt.trim().length>0?Dt:"text",cr={id:F,type:gt,sessionID:w,messageID:P,delta:x,[B]:""};typeof gt=="string"&&gt.length>0&&wn(Le,gt),e(w,P,cr,Se)}break}if(Se==="assistant"&&x.length>0){const ue=V.getState().sessionStatus?.get(w),Qe=ue?.type==="idle"&&typeof ue.confirmedAt=="number"&&Date.now()-ue.confirmedAt<1200;(!ue||ue.type==="idle")&&(Qe||Ee(w,{type:"busy"},"sse:message.part.delta"))}oe(P,"part_delta_received",{role:Se,field:B}),n(w,P,F,B,x,Se);break}case"message.updated":{const w=typeof y.info=="object"&&y.info!==null?y.info:y,P=w,F=de(P,["sessionID","sessionId"])||de(y,["sessionID","sessionId"]),B=de(P,["messageID","messageId","id"])||de(y,["messageID","messageId"]);if(!F||!B){we()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:P.sessionID??y.sessionID,messageID:P.id??y.messageID});break}const x=F,N=B;xr.current.set(x,Date.now());const G=ot.current.get(x);if(G&&(clearTimeout(G),ot.current.delete(x)),we())try{const He=y.parts||P.parts||[],We=(Array.isArray(He)?He.filter(me=>me?.type==="text"):[]).map(me=>{const yt=me;return typeof yt?.text=="string"?yt.text:typeof yt?.content=="string"?yt.content:""}).join(`
48
- `);console.info("[STREAM-TRACE] message.updated",{messageId:N,role:P.role,status:P.status,textLen:We.length,textPreview:We.slice(0,120),partsCount:Array.isArray(He)?He.length:0})}catch{}if(oe(N,"message_updated",{role:P.role}),P.role==="user"){const{sessionMemoryState:He}=ee.getState(),Pe=He.get(x);if(Pe){const ae=new Map(He);ae.set(x,{...Pe,lastUserMessageAt:Date.now()}),ee.setState({sessionMemoryState:ae})}const We=y.parts||P.parts,me=Array.isArray(We)?We:[],yt=xa(x,N),ge=(()=>{const ae=P.agent;if(typeof ae=="string"&&ae.trim().length>0)return ae.trim();const le=P.mode;return typeof le=="string"&&le.trim().length>0?le.trim():""})(),Ht=(()=>{const le=P.time?.created;return typeof le=="number"?le:null})(),fr=me.length>0&&me.every(ae=>ae?.synthetic===!0),ni=(()=>{if(!ge)return!1;if(fr&&(ge==="plan"||ge==="build"))return!0;if(Je.current===x){const le=ne.getState().getSessionAgentSelection(x);if(le&&le!==ge){const _e=V.getState().sessionStatus?.get(x);if(_e?.type==="busy"||_e?.type==="retry")return!1}}const ae=hn.current.get(x);return ae?Ht===null?!1:N===ae.messageId?!0:Ht>=ae.created:!0})();if(ge&&ni)try{const ae=ke.getState().agents;if(Array.isArray(ae)&&ae.some(le=>le?.name===ge)){const le=ne.getState();if(le.saveSessionAgentSelection(x,ge),hn.current.set(x,{created:Ht??Date.now(),messageId:N}),Je.current===x)try{ke.getState().setAgent(ge)}catch{}const _e=P.model,Wt=typeof _e?.providerID=="string"?_e.providerID:null,it=typeof _e?.modelID=="string"?_e.modelID:null;if(Wt&&it){le.saveSessionModelSelection(x,Wt,it),le.saveAgentModelForSession(x,ge,Wt,it);const vn=typeof P.variant=="string"?P.variant:void 0;if(le.saveAgentModelVariantForSession(x,ge,Wt,it,vn),Je.current===x)try{ke.getState().setProvider(Wt),ke.getState().setModel(it)}catch{}}}}catch{}if(fr&&(ge==="plan"||ge==="build")&&Je.current===x){const ae=`${x}:${N}:${ge}`;Er.current.has(ae)||(Er.current.add(ae),qe(async()=>{const{toast:le}=await import("./vendor-.bun-HTKwyaEM.js").then(_e=>_e.fE);return{toast:le}},__vite__mapDeps([0,1])).then(({toast:le})=>{le.info(ge==="plan"?"Plan mode active":"Build mode active",{description:ge==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const Fr={...w,userMessageMarker:!0,clientRole:"user",...ge?{mode:ge}:{}};if(s(x,N,Fr),!yt&&me.length===0){const ae=`${x}:${N}`;ce.current.has(ae)||(ce.current.add(ae),O.getSessionMessages(x).then(le=>{V.getState().syncMessages(x,le)}).catch(()=>{}))}if(me.length>0){const ae=ns(y);for(let le=0;le<me.length;le++){const _e=me[le];if(_e.synthetic===!0){const vn=_e.text,Eo=typeof vn=="string"?vn.trim():"";if(!(Eo.startsWith("User has requested to enter plan mode")||Eo.startsWith("The plan at ")||Eo.startsWith("The following tool was executed by the user")))continue}const it={..._e,type:_e?.type||"text",sessionID:_e?.sessionID||x,messageID:_e?.messageID||N};typeof it.id=="string"&&typeof it.type=="string"&&wn(`${ae}:${N}:${it.id}`,it.type),e(x,N,it,"user")}}oe(N,"user_message_created_from_event",{partsCount:me.length});break}const te=xa(x,N)?.info?.finish==="stop",Se=y.parts||P.parts,Qe=(Array.isArray(Se)?Se:[]).length>0,Dt=typeof(P.time||{})?.completed=="number",gt=w.status,cr=typeof gt=="string"?gt.toLowerCase():null,lr=cr==="completed"||cr==="complete",Or=w.finish,Rt=typeof Or=="string"?Or:null,Mn=Rt==="stop",zt=Rt==="error";if(!Qe&&!Dt&&!lr&&!Mn&&!zt)break;const ko={...P};delete ko.parts,s(x,N,ko);const It=typeof w.role=="string"?w.role:null;if(!!Nt()?.runtime?.isVSCode&&!nt.current&&It==="assistant"){const He=Oe.getState(),Pe=V.getState().sessions.find(me=>me.id===x),We=typeof Pe?.title=="string"?Pe.title.trim():"";if(Mn&&He.notifyOnCompletion!==!1){const me=!!Pe?.parentID;if(!(He.notifyOnSubtasks===!1&&me)){const yt=`ready:${x}:${N}`;bt.current.has(yt)||(bt.current.add(yt),sr({title:"Agent is ready",body:We||"Task completed",tag:`ready-${x}`}))}}if(zt&&He.notifyOnError!==!1){const me=`error:${x}:${N}`;bt.current.has(me)||(bt.current.add(me),sr({title:"Tool error",body:We||"An error occurred",tag:`error-${x}`}))}}const jr=w.time,dr=jr?.completed,At=typeof dr=="number"&&Number.isFinite(dr),ur=Rt==="stop"||te;if(w.role==="assistant"&&(At||lr||ur)&&w.role==="assistant"){const Pe=V.getState().messages.get(x)||[];let We=null,me="";for(let Fr=0;Fr<Pe.length;Fr++){const ae=Pe[Fr];ae.info.role==="assistant"&&ae.info.id>me&&(me=ae.info.id,We=ae.info.id)}if(u===x&&N!==We)break;const ge=At?dr:Date.now();At||s(x,N,{...w,time:{...jr??{},completed:ge}}),oe(N,"completed",{timeCompleted:ge}),ut(N),yu(x,N,ge),o(x,N),xe("assistant_message_completed");const Ht=w.sessionID,fr=typeof Ht=="string"&&Ht.length>0?Ht:x;mt(fr,typeof y.directory=="string"?y.directory:null),w.summary&&typeof fr=="string"&&i(fr,null)}break}case"session.created":case"session.updated":{const w=typeof y.info=="object"&&y.info!==null?y.info:typeof y.sessionInfo=="object"&&y.sessionInfo!==null?y.sessionInfo:typeof y.session=="object"&&y.session!==null?y.session:y,P=typeof w.id=="string"&&w.id.length>0?w.id:typeof w.sessionID=="string"&&w.sessionID.length>0?w.sessionID:typeof y.sessionID=="string"&&y.sessionID.length>0?y.sessionID:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(P){const F=typeof w.time=="object"&&w.time!==null?w.time:typeof y.time=="object"&&y.time!==null?y.time:null,B=F&&typeof F.compacting=="number"?F.compacting:null;i(P,B);const x=typeof w.directory=="string"?w.directory:typeof y.directory=="string"?y.directory:null,N={...w,id:P,...x?{directory:x}:{}};S(N)}break}case"session.deleted":{const w=typeof y.sessionID=="string"?y.sessionID:typeof y.id=="string"?y.id:null;w&&h(w);break}case"session.abort":{const w=typeof y.sessionID=="string"&&y.sessionID.length>0?y.sessionID:null,P=typeof y.messageID=="string"&&y.messageID.length>0?y.messageID:null;w&&Ee(w,{type:"idle"},"sse:session.abort"),w&&P&&o(w,P);break}case"permission.asked":{const w=Ca(y);if(!w)break;if(a(w),Nt()?.runtime?.isVSCode&&!nt.current&&Oe.getState().notifyOnQuestion!==!1){const x=`permission:${w.sessionID}:${w.id}`;if(!Et.current.has(x)){Et.current.add(x);const N=V.getState().sessions.find(G=>G.id===w.sessionID)?.title||"Agent is waiting for your approval";sr({title:"Permission required",body:N,tag:`permission-${w.sessionID}:${w.id}`})}}const F=`${w.sessionID}:${w.id}`;Cr.current.has(F)||setTimeout(()=>{const B=Je.current;if(B===w.sessionID)return;const x=V.getState().sessions.find(te=>te.id===w.sessionID);if(x?.parentID&&x.parentID===B||!V.getState().permissions.get(w.sessionID)?.some(te=>te.id===w.id))return;Cr.current.add(F);const G=V.getState().sessions.find(te=>te.id===w.sessionID)?.title||"Session",J=Cg(w);qe(async()=>{const{toast:te}=await import("./vendor-.bun-HTKwyaEM.js").then(Se=>Se.fE);return{toast:te}},__vite__mapDeps([0,1])).then(({toast:te})=>{Oe.getState().isMobile?te.warning("Permission required",{id:F,description:G,duration:3e4,action:{label:"Open",onClick:()=>{Oe.getState().setActiveMainTab("chat"),V.getState().setCurrentSession(w.sessionID)}}}):te.warning("Permission required",{id:F,description:R.createElement(Tg,{sessionTitle:G,permissionBody:J,onOnce:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"once"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}},onAlways:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"always"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}},onDeny:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"reject"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}}}),duration:3e4})})},0);break}case"permission.replied":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:typeof y.id=="string"?y.id:null;w&&P&&l(w,P);break}case"question.asked":{if(!("sessionID"in y)||typeof y.sessionID!="string")break;const w=y;if(c(w),Nt()?.runtime?.isVSCode&&!nt.current&&Oe.getState().notifyOnQuestion!==!1){const x=`question:${w.sessionID}:${w.id}`;if(!Et.current.has(x)){Et.current.add(x);const N=Array.isArray(w.questions)?w.questions[0]:void 0,G=typeof N?.header=="string"?N.header.trim():"",J=typeof N?.question=="string"?N.question.trim():"";sr({title:G||"Input needed",body:J||"Agent is waiting for your response",tag:`question-${w.sessionID}:${w.id}`})}}const F=`${w.sessionID}:${w.id}`;yn.current.has(F)||setTimeout(()=>{const B=Je.current;if(B===w.sessionID)return;const x=V.getState().sessions.find(J=>J.id===w.sessionID);if(x?.parentID&&x.parentID===B||!V.getState().questions.get(w.sessionID)?.some(J=>J.id===w.id))return;yn.current.add(F);const G=V.getState().sessions.find(J=>J.id===w.sessionID)?.title||"Session";qe(async()=>{const{toast:J}=await import("./vendor-.bun-HTKwyaEM.js").then(te=>te.fE);return{toast:J}},__vite__mapDeps([0,1])).then(({toast:J})=>{J.info("Input needed",{id:F,description:G,duration:3e4,action:{label:"Open",onClick:()=>{Oe.getState().setActiveMainTab("chat"),V.getState().setCurrentSession(w.sessionID)}}})})},0);break}case"question.replied":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:null;w&&P&&d(w,P);break}case"question.rejected":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:null;w&&P&&d(w,P);break}case"archcoder:notification":{nt.current=!0;const w=typeof y.title=="string"?y.title:"",P=typeof y.body=="string"?y.body:"",F=typeof y.tag=="string"?y.tag:void 0,B=!!y.requireHidden;if(dt()&&y.desktopStdoutActive)break;sr({title:w,body:P,tag:F,requireHidden:B});break}case"todo.updated":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=Array.isArray(y.todos)?y.todos:null;w&&P&&Ig(w,P);break}}},[u,e,n,o,s,a,l,c,d,v,mt,i,f,oe,ut,k,S,h,re,I,Ee,st,xe,sr,Ks,wn]),Xs=R.useRef(To);R.useEffect(()=>{Xs.current=To},[To]);const Zs=R.useRef(re);R.useEffect(()=>{Zs.current=re},[re]);const ei=R.useCallback(A=>{Xs.current(A)},[]),ti=R.useCallback(A=>Zs.current(A),[]),ir=R.useCallback(()=>{const A=ft();return pt.current=A,A==="visible"&&Bt.current},[ft]),ri=R.useCallback(()=>{we()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!Q.current,currentSessionId:Je.current,effectiveDirectory:I,onlineStatus:Bt.current,visibilityState:pt.current,lastEventTimestamp:Mt.current,reconnectAttempts:Z.current})},[I]),vt=R.useCallback(()=>{if(je.current){we()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(je.current=!0,se.current&&(clearTimeout(se.current),se.current=null),Q.current){const A=Q.current;Q.current=null;try{A()}catch(y){console.warn("[useEventStream] Error during unsubscribe:",y)}}je.current=!1},[]),_t=R.useCallback(async A=>{if(ri(),!ir()){Fe.current=!0,Bt.current?W("paused","Paused while hidden"):W("offline","Waiting for network");return}A?.resetAttempts&&(Z.current=0),vt(),Mt.current=Date.now(),W("connecting",null),we()&&console.info("[useEventStream] Starting event stream...");const y=w=>{console.warn("Event stream error:",w)},H=()=>{const w=Fe.current;if(Z.current=0,Fe.current=!1,Mt.current=Date.now(),W("connected",null),v(),xe("stream_open"),U.current(w),w)ti("sse_reconnected");else{const P=Je.current;P&&setTimeout(()=>{Ao.current(P,"sse_reconnected",kt()).then(()=>mt(P)).catch(F=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",F)})},0)}};if(we()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:I,isCleaningUp:je.current}),je.current){we()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const w=O.subscribeToGlobalEvents(F=>{const B=F.payload,x=F.payload,N=typeof x.properties=="object"&&x.properties!==null?x.properties:{},G=F.directory&&F.directory!=="global"?{...N,directory:F.directory}:N;ei({type:typeof B.type=="string"?B.type:"",properties:G})},y,H),P=()=>{try{w()}catch(F){console.warn("[useEventStream] Error during unsubscribe:",F)}};je.current?P():Q.current=P}catch(w){console.error("[useEventStream] Error during subscription:",w),y(w)}},[ir,vt,W,v,mt,ei,ti,xe,I,ri]),ar=R.useCallback(A=>{if(!ir()){Fe.current=!0,vt(),Bt.current?W("paused","Paused while hidden"):W("offline","Waiting for network");return}if(se.current)return;const y=Z.current+1;Z.current=y;const H=A??`Retrying (${y})`;W("reconnecting",H);const w=y<=3?Math.min(1e3*Math.pow(2,y-1),8e3):Math.min(2e3*Math.pow(2,y-3),32e3),P=Math.floor(Math.random()*250),F=w+P;se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{_t({resetAttempts:!1})},F)},[ir,vt,W,_t]);R.useEffect(()=>{qs.current=ar},[ar]),R.useEffect(()=>{if(!r){vt(),W("idle",null);return}typeof window<"u"&&(window.__messageTracker=oe);const A=()=>{Do.current&&(clearTimeout(Do.current),Do.current=null)},y=()=>{if(pt.current=ft(),pt.current!=="visible")return;if(A(),bn("visibility_restore"),xe("visibility_restore"),Date.now()-Mt.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),Fe.current=!0),Fe.current||!Q.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const J=Je.current;J&&(Ae(J,"visibility_restore",kt()),mt(J)),U.current(!1),xe("visibility_restore_resume"),W("connecting","Resuming stream"),_t({resetAttempts:!0})}},H=()=>{if(pt.current=ft(),pt.current==="visible"&&(A(),bn("window_focus"),xe("window_focus"),Date.now()-Mt.current>45e3&&(Fe.current=!0),Fe.current||!Q.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const J=Je.current;J&&(mt(J),Ae(J,"window_focus",kt())),U.current(!1),xe("window_focus_resume"),W("connecting","Resuming stream"),_t({resetAttempts:!0})}},w=()=>{Bt.current=!0,bn("network_restored"),xe("network_restored"),U.current(!1),(Fe.current||!Q.current)&&(W("connecting","Network restored"),_t({resetAttempts:!0}))},P=()=>{Bt.current=!1,Fe.current=!0,W("offline","Waiting for network"),vt()},F=()=>{Fe.current=!0,vt(),W("paused","Paused while hidden")},B=G=>{if(Fe.current=Fe.current||!!G.persisted,pt.current=ft(),pt.current==="visible"){const J=Je.current;J&&(Ae(J,"page_show",kt()),mt(J)),U.current(!1),xe("page_show"),_t({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",y),typeof window<"u"&&(window.addEventListener("online",w),window.addEventListener("offline",P),window.addEventListener("focus",H),window.addEventListener("pagehide",F),window.addEventListener("pageshow",B));const x=setTimeout(()=>{_t({resetAttempts:!0})},100);or.current&&clearInterval(or.current),or.current=setInterval(()=>{if(!ir())return;const G=Date.now();Array.from(V.getState().sessionStatus?.values?.()??[]).some(te=>te?.type==="busy"||te?.type==="retry")&&xe("stale_check_busy_sessions"),G-Mt.current>45e3&&Promise.resolve().then(async()=>{try{if(!await O.checkHealth()){ar("Refreshing stalled stream");return}ar("Refreshing stalled stream")}catch(te){console.warn("Health check after stale stream failed:",te),ar("Refreshing stalled stream")}})},1e4);const N=setInterval(()=>{const G=V.getState().sessionStatus;if(!G)return;const J=Date.now();G.forEach((te,Se)=>{if(te.type!=="busy"&&te.type!=="retry")return;const ue=xr.current.get(Se)??0,Qe=J-ue>gm,Le=J-ue>6e4;Qe&&Le&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Se),Ee(Se,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(x),clearInterval(N),typeof document<"u"&&document.removeEventListener("visibilitychange",y),typeof window<"u"&&(window.removeEventListener("online",w),window.removeEventListener("offline",P),window.removeEventListener("focus",H),window.removeEventListener("pagehide",F),window.removeEventListener("pageshow",B)),A(),or.current&&(clearInterval(or.current),or.current=null),Ys(),Yt.clear(),bt.current.clear(),Et.current.clear(),nt.current=!1,Fe.current=!1,pt.current=ft(),Bt.current=typeof navigator>"u"?!0:navigator.onLine,vt(),he.current&&(clearTimeout(he.current),he.current=null),W("idle",null)}},[r,I,oe,ft,vt,W,_t,ar,p,mt,Po,Ys,xe,ir,g,bn,fe,Ae,Ee])};window.__OPENCHAMBER_RUNTIME_APIS__=jd();rl();Fd({onRegisterError(t){console.warn("[PWA] service worker registration failed:",t)}});qe(()=>import("./main-B6oiMU86.js").then(t=>t.F),__vite__mapDeps([2,0,1,3]));export{ee as $,Qu as A,qg as B,Vg as C,Oy as D,wo as E,mn as F,Ly as G,ne as H,Dg as I,Zg as J,mc as K,cf as L,Fy as M,Ud as N,Yg as O,Xg as P,gy as Q,ny as R,vc as S,vy as T,pp as U,ky as V,ay as W,yy as X,Cy as Y,Ey as Z,em as _,Ze as a,Iy as a$,O as a0,q as a1,nn as a2,Qd as a3,Pn as a4,Lo as a5,gg as a6,Ay as a7,sa as a8,oa as a9,jy as aA,My as aB,ry as aC,Ou as aD,$d as aE,_u as aF,qd as aG,Wd as aH,Gd as aI,Bd as aJ,Dy as aK,wy as aL,Sy as aM,Op as aN,Rp as aO,As as aP,zd as aQ,Hd as aR,Ap as aS,we as aT,kt as aU,hm as aV,ym as aW,Wg as aX,Hg as aY,Kg as aZ,Ny as a_,Py as aa,Ty as ab,aa as ac,rl as ad,uy as ae,dy as af,ly as ag,fy as ah,py as ai,cy as aj,lo as ak,sy as al,my as am,oy as an,iy as ao,Ry as ap,lt as aq,Xr as ar,ze as as,xs as at,Vf as au,ty as av,ey as aw,Bf as ax,jc as ay,hy as az,ye as b,Jg as b0,Qg as b1,Gg as b2,vu as b3,Ug as b4,Bg as b5,rs as c,Ke as d,rr as e,be as f,Nt as g,Pg as h,nr as i,xy as j,tl as k,Nd as l,dt as m,Jd as n,Kd as o,Vd as p,zg as q,$l as r,by as s,ke as t,Oe as u,V as v,et as w,_y as x,Eu as y,Xt as z};
48
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:N,role:P.role,status:P.status,textLen:We.length,textPreview:We.slice(0,120),partsCount:Array.isArray(He)?He.length:0})}catch{}if(oe(N,"message_updated",{role:P.role}),P.role==="user"){const{sessionMemoryState:He}=ee.getState(),Pe=He.get(x);if(Pe){const ae=new Map(He);ae.set(x,{...Pe,lastUserMessageAt:Date.now()}),ee.setState({sessionMemoryState:ae})}const We=y.parts||P.parts,me=Array.isArray(We)?We:[],yt=xa(x,N),ge=(()=>{const ae=P.agent;if(typeof ae=="string"&&ae.trim().length>0)return ae.trim();const le=P.mode;return typeof le=="string"&&le.trim().length>0?le.trim():""})(),Ht=(()=>{const le=P.time?.created;return typeof le=="number"?le:null})(),fr=me.length>0&&me.every(ae=>ae?.synthetic===!0),ni=(()=>{if(!ge)return!1;if(fr&&(ge==="plan"||ge==="build"))return!0;if(Je.current===x){const le=ne.getState().getSessionAgentSelection(x);if(le&&le!==ge){const _e=V.getState().sessionStatus?.get(x);if(_e?.type==="busy"||_e?.type==="retry")return!1}}const ae=hn.current.get(x);return ae?Ht===null?!1:N===ae.messageId?!0:Ht>=ae.created:!0})();if(ge&&ni)try{const ae=ke.getState().agents;if(Array.isArray(ae)&&ae.some(le=>le?.name===ge)){const le=ne.getState();if(le.saveSessionAgentSelection(x,ge),hn.current.set(x,{created:Ht??Date.now(),messageId:N}),Je.current===x)try{ke.getState().setAgent(ge)}catch{}const _e=P.model,Wt=typeof _e?.providerID=="string"?_e.providerID:null,it=typeof _e?.modelID=="string"?_e.modelID:null;if(Wt&&it){le.saveSessionModelSelection(x,Wt,it),le.saveAgentModelForSession(x,ge,Wt,it);const vn=typeof P.variant=="string"?P.variant:void 0;if(le.saveAgentModelVariantForSession(x,ge,Wt,it,vn),Je.current===x)try{ke.getState().setProvider(Wt),ke.getState().setModel(it)}catch{}}}}catch{}if(fr&&(ge==="plan"||ge==="build")&&Je.current===x){const ae=`${x}:${N}:${ge}`;Er.current.has(ae)||(Er.current.add(ae),qe(async()=>{const{toast:le}=await import("./vendor-.bun-HTKwyaEM.js").then(_e=>_e.fE);return{toast:le}},__vite__mapDeps([0,1])).then(({toast:le})=>{le.info(ge==="plan"?"Plan mode active":"Build mode active",{description:ge==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const Fr={...w,userMessageMarker:!0,clientRole:"user",...ge?{mode:ge}:{}};if(s(x,N,Fr),!yt&&me.length===0){const ae=`${x}:${N}`;ce.current.has(ae)||(ce.current.add(ae),O.getSessionMessages(x).then(le=>{V.getState().syncMessages(x,le)}).catch(()=>{}))}if(me.length>0){const ae=ns(y);for(let le=0;le<me.length;le++){const _e=me[le];if(_e.synthetic===!0){const vn=_e.text,Eo=typeof vn=="string"?vn.trim():"";if(!(Eo.startsWith("User has requested to enter plan mode")||Eo.startsWith("The plan at ")||Eo.startsWith("The following tool was executed by the user")))continue}const it={..._e,type:_e?.type||"text",sessionID:_e?.sessionID||x,messageID:_e?.messageID||N};typeof it.id=="string"&&typeof it.type=="string"&&wn(`${ae}:${N}:${it.id}`,it.type),e(x,N,it,"user")}}oe(N,"user_message_created_from_event",{partsCount:me.length});break}const te=xa(x,N)?.info?.finish==="stop",Se=y.parts||P.parts,Qe=(Array.isArray(Se)?Se:[]).length>0,Dt=typeof(P.time||{})?.completed=="number",gt=w.status,cr=typeof gt=="string"?gt.toLowerCase():null,lr=cr==="completed"||cr==="complete",Or=w.finish,Rt=typeof Or=="string"?Or:null,Mn=Rt==="stop",zt=Rt==="error";if(!Qe&&!Dt&&!lr&&!Mn&&!zt)break;const ko={...P};delete ko.parts,s(x,N,ko);const It=typeof w.role=="string"?w.role:null;if(!!Nt()?.runtime?.isVSCode&&!nt.current&&It==="assistant"){const He=Oe.getState(),Pe=V.getState().sessions.find(me=>me.id===x),We=typeof Pe?.title=="string"?Pe.title.trim():"";if(Mn&&He.notifyOnCompletion!==!1){const me=!!Pe?.parentID;if(!(He.notifyOnSubtasks===!1&&me)){const yt=`ready:${x}:${N}`;bt.current.has(yt)||(bt.current.add(yt),sr({title:"Agent is ready",body:We||"Task completed",tag:`ready-${x}`}))}}if(zt&&He.notifyOnError!==!1){const me=`error:${x}:${N}`;bt.current.has(me)||(bt.current.add(me),sr({title:"Tool error",body:We||"An error occurred",tag:`error-${x}`}))}}const jr=w.time,dr=jr?.completed,At=typeof dr=="number"&&Number.isFinite(dr),ur=Rt==="stop"||te;if(w.role==="assistant"&&(At||lr||ur)&&w.role==="assistant"){const Pe=V.getState().messages.get(x)||[];let We=null,me="";for(let Fr=0;Fr<Pe.length;Fr++){const ae=Pe[Fr];ae.info.role==="assistant"&&ae.info.id>me&&(me=ae.info.id,We=ae.info.id)}if(u===x&&N!==We)break;const ge=At?dr:Date.now();At||s(x,N,{...w,time:{...jr??{},completed:ge}}),oe(N,"completed",{timeCompleted:ge}),ut(N),yu(x,N,ge),o(x,N),xe("assistant_message_completed");const Ht=w.sessionID,fr=typeof Ht=="string"&&Ht.length>0?Ht:x;mt(fr,typeof y.directory=="string"?y.directory:null),w.summary&&typeof fr=="string"&&i(fr,null)}break}case"session.created":case"session.updated":{const w=typeof y.info=="object"&&y.info!==null?y.info:typeof y.sessionInfo=="object"&&y.sessionInfo!==null?y.sessionInfo:typeof y.session=="object"&&y.session!==null?y.session:y,P=typeof w.id=="string"&&w.id.length>0?w.id:typeof w.sessionID=="string"&&w.sessionID.length>0?w.sessionID:typeof y.sessionID=="string"&&y.sessionID.length>0?y.sessionID:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(P){const F=typeof w.time=="object"&&w.time!==null?w.time:typeof y.time=="object"&&y.time!==null?y.time:null,B=F&&typeof F.compacting=="number"?F.compacting:null;i(P,B);const x=typeof w.directory=="string"?w.directory:typeof y.directory=="string"?y.directory:null,N={...w,id:P,...x?{directory:x}:{}};S(N)}break}case"session.deleted":{const w=typeof y.sessionID=="string"?y.sessionID:typeof y.id=="string"?y.id:null;w&&h(w);break}case"session.abort":{const w=typeof y.sessionID=="string"&&y.sessionID.length>0?y.sessionID:null,P=typeof y.messageID=="string"&&y.messageID.length>0?y.messageID:null;w&&Ee(w,{type:"idle"},"sse:session.abort"),w&&P&&o(w,P);break}case"permission.asked":{const w=Ca(y);if(!w)break;if(a(w),Nt()?.runtime?.isVSCode&&!nt.current&&Oe.getState().notifyOnQuestion!==!1){const x=`permission:${w.sessionID}:${w.id}`;if(!Et.current.has(x)){Et.current.add(x);const N=V.getState().sessions.find(G=>G.id===w.sessionID)?.title||"Agent is waiting for your approval";sr({title:"Permission required",body:N,tag:`permission-${w.sessionID}:${w.id}`})}}const F=`${w.sessionID}:${w.id}`;Cr.current.has(F)||setTimeout(()=>{const B=Je.current;if(B===w.sessionID)return;const x=V.getState().sessions.find(te=>te.id===w.sessionID);if(x?.parentID&&x.parentID===B||!V.getState().permissions.get(w.sessionID)?.some(te=>te.id===w.id))return;Cr.current.add(F);const G=V.getState().sessions.find(te=>te.id===w.sessionID)?.title||"Session",J=Cg(w);qe(async()=>{const{toast:te}=await import("./vendor-.bun-HTKwyaEM.js").then(Se=>Se.fE);return{toast:te}},__vite__mapDeps([0,1])).then(({toast:te})=>{Oe.getState().isMobile?te.warning("Permission required",{id:F,description:G,duration:3e4,action:{label:"Open",onClick:()=>{Oe.getState().setActiveMainTab("chat"),V.getState().setCurrentSession(w.sessionID)}}}):te.warning("Permission required",{id:F,description:R.createElement(Tg,{sessionTitle:G,permissionBody:J,onOnce:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"once"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}},onAlways:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"always"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}},onDeny:async()=>{try{await V.getState().respondToPermission(w.sessionID,w.id,"reject"),te.dismiss(F)}catch(ue){console.error("Failed to respond to permission:",ue)}}}),duration:3e4})})},0);break}case"permission.replied":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:typeof y.id=="string"?y.id:null;w&&P&&l(w,P);break}case"question.asked":{if(!("sessionID"in y)||typeof y.sessionID!="string")break;const w=y;if(c(w),Nt()?.runtime?.isVSCode&&!nt.current&&Oe.getState().notifyOnQuestion!==!1){const x=`question:${w.sessionID}:${w.id}`;if(!Et.current.has(x)){Et.current.add(x);const N=Array.isArray(w.questions)?w.questions[0]:void 0,G=typeof N?.header=="string"?N.header.trim():"",J=typeof N?.question=="string"?N.question.trim():"";sr({title:G||"Input needed",body:J||"Agent is waiting for your response",tag:`question-${w.sessionID}:${w.id}`})}}const F=`${w.sessionID}:${w.id}`;yn.current.has(F)||setTimeout(()=>{const B=Je.current;if(B===w.sessionID)return;const x=V.getState().sessions.find(J=>J.id===w.sessionID);if(x?.parentID&&x.parentID===B||!V.getState().questions.get(w.sessionID)?.some(J=>J.id===w.id))return;yn.current.add(F);const G=V.getState().sessions.find(J=>J.id===w.sessionID)?.title||"Session";qe(async()=>{const{toast:J}=await import("./vendor-.bun-HTKwyaEM.js").then(te=>te.fE);return{toast:J}},__vite__mapDeps([0,1])).then(({toast:J})=>{J.info("Input needed",{id:F,description:G,duration:3e4,action:{label:"Open",onClick:()=>{Oe.getState().setActiveMainTab("chat"),V.getState().setCurrentSession(w.sessionID)}}})})},0);break}case"question.replied":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:null;w&&P&&d(w,P);break}case"question.rejected":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=typeof y.requestID=="string"?y.requestID:null;w&&P&&d(w,P);break}case"archcoder:notification":{nt.current=!0;const w=typeof y.title=="string"?y.title:"",P=typeof y.body=="string"?y.body:"",F=typeof y.tag=="string"?y.tag:void 0,B=!!y.requireHidden;if(dt()&&y.desktopStdoutActive)break;sr({title:w,body:P,tag:F,requireHidden:B});break}case"todo.updated":{const w=typeof y.sessionID=="string"?y.sessionID:null,P=Array.isArray(y.todos)?y.todos:null;w&&P&&Ig(w,P);break}}},[u,e,n,o,s,a,l,c,d,v,mt,i,f,oe,ut,k,S,h,re,I,Ee,st,xe,sr,Ks,wn]),Xs=R.useRef(To);R.useEffect(()=>{Xs.current=To},[To]);const Zs=R.useRef(re);R.useEffect(()=>{Zs.current=re},[re]);const ei=R.useCallback(A=>{Xs.current(A)},[]),ti=R.useCallback(A=>Zs.current(A),[]),ir=R.useCallback(()=>{const A=ft();return pt.current=A,A==="visible"&&Bt.current},[ft]),ri=R.useCallback(()=>{we()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!Q.current,currentSessionId:Je.current,effectiveDirectory:I,onlineStatus:Bt.current,visibilityState:pt.current,lastEventTimestamp:Mt.current,reconnectAttempts:Z.current})},[I]),vt=R.useCallback(()=>{if(je.current){we()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(je.current=!0,se.current&&(clearTimeout(se.current),se.current=null),Q.current){const A=Q.current;Q.current=null;try{A()}catch(y){console.warn("[useEventStream] Error during unsubscribe:",y)}}je.current=!1},[]),_t=R.useCallback(async A=>{if(ri(),!ir()){Fe.current=!0,Bt.current?W("paused","Paused while hidden"):W("offline","Waiting for network");return}A?.resetAttempts&&(Z.current=0),vt(),Mt.current=Date.now(),W("connecting",null),we()&&console.info("[useEventStream] Starting event stream...");const y=w=>{console.warn("Event stream error:",w)},H=()=>{const w=Fe.current;if(Z.current=0,Fe.current=!1,Mt.current=Date.now(),W("connected",null),v(),xe("stream_open"),U.current(w),w)ti("sse_reconnected");else{const P=Je.current;P&&setTimeout(()=>{Ao.current(P,"sse_reconnected",kt()).then(()=>mt(P)).catch(F=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",F)})},0)}};if(we()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:I,isCleaningUp:je.current}),je.current){we()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const w=O.subscribeToGlobalEvents(F=>{const B=F.payload,x=F.payload,N=typeof x.properties=="object"&&x.properties!==null?x.properties:{},G=F.directory&&F.directory!=="global"?{...N,directory:F.directory}:N;ei({type:typeof B.type=="string"?B.type:"",properties:G})},y,H),P=()=>{try{w()}catch(F){console.warn("[useEventStream] Error during unsubscribe:",F)}};je.current?P():Q.current=P}catch(w){console.error("[useEventStream] Error during subscription:",w),y(w)}},[ir,vt,W,v,mt,ei,ti,xe,I,ri]),ar=R.useCallback(A=>{if(!ir()){Fe.current=!0,vt(),Bt.current?W("paused","Paused while hidden"):W("offline","Waiting for network");return}if(se.current)return;const y=Z.current+1;Z.current=y;const H=A??`Retrying (${y})`;W("reconnecting",H);const w=y<=3?Math.min(1e3*Math.pow(2,y-1),8e3):Math.min(2e3*Math.pow(2,y-3),32e3),P=Math.floor(Math.random()*250),F=w+P;se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{_t({resetAttempts:!1})},F)},[ir,vt,W,_t]);R.useEffect(()=>{qs.current=ar},[ar]),R.useEffect(()=>{if(!r){vt(),W("idle",null);return}typeof window<"u"&&(window.__messageTracker=oe);const A=()=>{Do.current&&(clearTimeout(Do.current),Do.current=null)},y=()=>{if(pt.current=ft(),pt.current!=="visible")return;if(A(),bn("visibility_restore"),xe("visibility_restore"),Date.now()-Mt.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),Fe.current=!0),Fe.current||!Q.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const J=Je.current;J&&(Ae(J,"visibility_restore",kt()),mt(J)),U.current(!1),xe("visibility_restore_resume"),W("connecting","Resuming stream"),_t({resetAttempts:!0})}},H=()=>{if(pt.current=ft(),pt.current==="visible"&&(A(),bn("window_focus"),xe("window_focus"),Date.now()-Mt.current>45e3&&(Fe.current=!0),Fe.current||!Q.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const J=Je.current;J&&(mt(J),Ae(J,"window_focus",kt())),U.current(!1),xe("window_focus_resume"),W("connecting","Resuming stream"),_t({resetAttempts:!0})}},w=()=>{Bt.current=!0,bn("network_restored"),xe("network_restored"),U.current(!1),(Fe.current||!Q.current)&&(W("connecting","Network restored"),_t({resetAttempts:!0}))},P=()=>{Bt.current=!1,Fe.current=!0,W("offline","Waiting for network"),vt()},F=()=>{Fe.current=!0,vt(),W("paused","Paused while hidden")},B=G=>{if(Fe.current=Fe.current||!!G.persisted,pt.current=ft(),pt.current==="visible"){const J=Je.current;J&&(Ae(J,"page_show",kt()),mt(J)),U.current(!1),xe("page_show"),_t({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",y),typeof window<"u"&&(window.addEventListener("online",w),window.addEventListener("offline",P),window.addEventListener("focus",H),window.addEventListener("pagehide",F),window.addEventListener("pageshow",B));const x=setTimeout(()=>{_t({resetAttempts:!0})},100);or.current&&clearInterval(or.current),or.current=setInterval(()=>{if(!ir())return;const G=Date.now();Array.from(V.getState().sessionStatus?.values?.()??[]).some(te=>te?.type==="busy"||te?.type==="retry")&&xe("stale_check_busy_sessions"),G-Mt.current>45e3&&Promise.resolve().then(async()=>{try{if(!await O.checkHealth()){ar("Refreshing stalled stream");return}ar("Refreshing stalled stream")}catch(te){console.warn("Health check after stale stream failed:",te),ar("Refreshing stalled stream")}})},1e4);const N=setInterval(()=>{const G=V.getState().sessionStatus;if(!G)return;const J=Date.now();G.forEach((te,Se)=>{if(te.type!=="busy"&&te.type!=="retry")return;const ue=xr.current.get(Se)??0,Qe=J-ue>gm,Le=J-ue>6e4;Qe&&Le&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Se),Ee(Se,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(x),clearInterval(N),typeof document<"u"&&document.removeEventListener("visibilitychange",y),typeof window<"u"&&(window.removeEventListener("online",w),window.removeEventListener("offline",P),window.removeEventListener("focus",H),window.removeEventListener("pagehide",F),window.removeEventListener("pageshow",B)),A(),or.current&&(clearInterval(or.current),or.current=null),Ys(),Yt.clear(),bt.current.clear(),Et.current.clear(),nt.current=!1,Fe.current=!1,pt.current=ft(),Bt.current=typeof navigator>"u"?!0:navigator.onLine,vt(),he.current&&(clearTimeout(he.current),he.current=null),W("idle",null)}},[r,I,oe,ft,vt,W,_t,ar,p,mt,Po,Ys,xe,ir,g,bn,fe,Ae,Ee])};window.__OPENCHAMBER_RUNTIME_APIS__=jd();rl();Fd({onRegisterError(t){console.warn("[PWA] service worker registration failed:",t)}});qe(()=>import("./main-DAvs5z8b.js").then(t=>t.F),__vite__mapDeps([2,0,1,3]));export{ee as $,Qu as A,qg as B,Vg as C,Oy as D,wo as E,mn as F,Ly as G,ne as H,Dg as I,Zg as J,mc as K,cf as L,Fy as M,Ud as N,Yg as O,Xg as P,gy as Q,ny as R,vc as S,vy as T,pp as U,ky as V,ay as W,yy as X,Cy as Y,Ey as Z,em as _,Ze as a,Iy as a$,O as a0,q as a1,nn as a2,Qd as a3,Pn as a4,Lo as a5,gg as a6,Ay as a7,sa as a8,oa as a9,jy as aA,My as aB,ry as aC,Ou as aD,$d as aE,_u as aF,qd as aG,Wd as aH,Gd as aI,Bd as aJ,Dy as aK,wy as aL,Sy as aM,Op as aN,Rp as aO,As as aP,zd as aQ,Hd as aR,Ap as aS,we as aT,kt as aU,hm as aV,ym as aW,Wg as aX,Hg as aY,Kg as aZ,Ny as a_,Py as aa,Ty as ab,aa as ac,rl as ad,uy as ae,dy as af,ly as ag,fy as ah,py as ai,cy as aj,lo as ak,sy as al,my as am,oy as an,iy as ao,Ry as ap,lt as aq,Xr as ar,ze as as,xs as at,Vf as au,ty as av,ey as aw,Bf as ax,jc as ay,hy as az,ye as b,Jg as b0,Qg as b1,Gg as b2,vu as b3,Ug as b4,Bg as b5,rs as c,Ke as d,rr as e,be as f,Nt as g,Pg as h,nr as i,xy as j,tl as k,Nd as l,dt as m,Jd as n,Kd as o,Vd as p,zg as q,$l as r,by as s,ke as t,Oe as u,V as v,et as w,_y as x,Eu as y,Xt as z};