@algochad/archcoder 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -0
- package/bin/cli-entry.js +55 -0
- package/bin/cli-output.js +145 -0
- package/bin/cli.js +5108 -0
- package/bin/cli.test.js +56 -0
- package/dist/apple-touch-icon-120x120.png +0 -0
- package/dist/apple-touch-icon-152x152.png +0 -0
- package/dist/apple-touch-icon-167x167.png +0 -0
- package/dist/apple-touch-icon-180x180.png +0 -0
- package/dist/apple-touch-icon.png +0 -0
- package/dist/apple-touch-icon.svg +67 -0
- package/dist/assets/MultiRunWindow-BZp3MjJP.js +1 -0
- package/dist/assets/SettingsWindow-DoGYXpX7.js +1 -0
- package/dist/assets/TerminalView-BN7BR5Ff.js +3 -0
- package/dist/assets/TimelineDialog-ZQ33oVQR.js +1 -0
- package/dist/assets/ToolOutputDialog-Blv3pnug.js +16 -0
- package/dist/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
- package/dist/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
- package/dist/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
- package/dist/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
- package/dist/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
- package/dist/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
- package/dist/assets/index-CtCEGYrr.css +1 -0
- package/dist/assets/index-o_d2wtWC.js +48 -0
- package/dist/assets/main-5QGBtzdq.css +1 -0
- package/dist/assets/main-B6oiMU86.js +8033 -0
- package/dist/assets/vendor--DbVqbJpV.css +1 -0
- package/dist/assets/vendor-.bun-HTKwyaEM.js +10086 -0
- package/dist/assets/wasm-CG6Dc4jp.js +1 -0
- package/dist/assets/worker-bqd4RMrj.js +155 -0
- package/dist/favicon-16.png +0 -0
- package/dist/favicon-32.png +0 -0
- package/dist/favicon.png +0 -0
- package/dist/favicon.svg +67 -0
- package/dist/index.html +533 -0
- package/dist/logo-dark-192x192.png +0 -0
- package/dist/logo-dark-512x512.svg +16 -0
- package/dist/logo-light-192x192.png +0 -0
- package/dist/logo-light-512x512.svg +16 -0
- package/dist/pwa-192.png +0 -0
- package/dist/pwa-512.png +0 -0
- package/dist/pwa-maskable-192.png +0 -0
- package/dist/pwa-maskable-512.png +0 -0
- package/dist/site.webmanifest +22 -0
- package/dist/sw.js +1 -0
- package/package.json +107 -0
- package/public/apple-touch-icon-120x120.png +0 -0
- package/public/apple-touch-icon-152x152.png +0 -0
- package/public/apple-touch-icon-167x167.png +0 -0
- package/public/apple-touch-icon-180x180.png +0 -0
- package/public/apple-touch-icon.png +0 -0
- package/public/apple-touch-icon.svg +67 -0
- package/public/favicon-16.png +0 -0
- package/public/favicon-32.png +0 -0
- package/public/favicon.png +0 -0
- package/public/favicon.svg +67 -0
- package/public/logo-dark-192x192.png +0 -0
- package/public/logo-dark-512x512.svg +16 -0
- package/public/logo-light-192x192.png +0 -0
- package/public/logo-light-512x512.svg +16 -0
- package/public/pwa-192.png +0 -0
- package/public/pwa-512.png +0 -0
- package/public/pwa-maskable-192.png +0 -0
- package/public/pwa-maskable-512.png +0 -0
- package/public/site.webmanifest +22 -0
- package/server/TERMINAL_INPUT_WS_PROTOCOL.md +44 -0
- package/server/index.d.ts +37 -0
- package/server/index.js +14694 -0
- package/server/lib/cloudflare-tunnel.js +650 -0
- package/server/lib/git/DOCUMENTATION.md +146 -0
- package/server/lib/git/credentials.js +74 -0
- package/server/lib/git/identity-storage.js +110 -0
- package/server/lib/git/index.js +6 -0
- package/server/lib/git/service.js +3117 -0
- package/server/lib/github/DOCUMENTATION.md +170 -0
- package/server/lib/github/auth.js +307 -0
- package/server/lib/github/device-flow.js +50 -0
- package/server/lib/github/index.js +24 -0
- package/server/lib/github/octokit.js +10 -0
- package/server/lib/github/pr-status.js +478 -0
- package/server/lib/github/repo/index.js +55 -0
- package/server/lib/installer/desktop.js +289 -0
- package/server/lib/installer/download.js +208 -0
- package/server/lib/installer/index.js +45 -0
- package/server/lib/installer/platform.js +100 -0
- package/server/lib/notifications/DOCUMENTATION.md +61 -0
- package/server/lib/notifications/index.js +1 -0
- package/server/lib/notifications/message.js +49 -0
- package/server/lib/notifications/message.test.js +59 -0
- package/server/lib/opencode/DOCUMENTATION.md +59 -0
- package/server/lib/opencode/agents.js +634 -0
- package/server/lib/opencode/auth.js +81 -0
- package/server/lib/opencode/commands.js +339 -0
- package/server/lib/opencode/index.js +66 -0
- package/server/lib/opencode/mcp.js +206 -0
- package/server/lib/opencode/providers.js +96 -0
- package/server/lib/opencode/shared.js +527 -0
- package/server/lib/opencode/skills.js +480 -0
- package/server/lib/opencode/tunnel-auth.js +591 -0
- package/server/lib/opencode/ui-auth.js +510 -0
- package/server/lib/package-manager.js +505 -0
- package/server/lib/quota/DOCUMENTATION.md +55 -0
- package/server/lib/quota/index.js +24 -0
- package/server/lib/quota/providers/claude.js +107 -0
- package/server/lib/quota/providers/codex.js +113 -0
- package/server/lib/quota/providers/copilot.js +165 -0
- package/server/lib/quota/providers/google/api.js +92 -0
- package/server/lib/quota/providers/google/auth.js +108 -0
- package/server/lib/quota/providers/google/index.js +124 -0
- package/server/lib/quota/providers/google/transforms.js +109 -0
- package/server/lib/quota/providers/index.js +152 -0
- package/server/lib/quota/providers/interface.js +55 -0
- package/server/lib/quota/providers/kimi.js +108 -0
- package/server/lib/quota/providers/minimax-cn-coding-plan.js +15 -0
- package/server/lib/quota/providers/minimax-coding-plan.js +15 -0
- package/server/lib/quota/providers/minimax-shared.js +136 -0
- package/server/lib/quota/providers/nanogpt.js +124 -0
- package/server/lib/quota/providers/ollama-cloud.js +112 -0
- package/server/lib/quota/providers/openai.js +91 -0
- package/server/lib/quota/providers/openrouter.js +92 -0
- package/server/lib/quota/providers/zai.js +91 -0
- package/server/lib/quota/utils/auth.js +46 -0
- package/server/lib/quota/utils/formatters.js +76 -0
- package/server/lib/quota/utils/index.js +10 -0
- package/server/lib/quota/utils/transformers.js +55 -0
- package/server/lib/skills-catalog/DOCUMENTATION.md +178 -0
- package/server/lib/skills-catalog/cache.js +32 -0
- package/server/lib/skills-catalog/clawdhub/api.js +158 -0
- package/server/lib/skills-catalog/clawdhub/index.js +30 -0
- package/server/lib/skills-catalog/clawdhub/install.js +238 -0
- package/server/lib/skills-catalog/clawdhub/scan.js +113 -0
- package/server/lib/skills-catalog/curated-sources.js +21 -0
- package/server/lib/skills-catalog/git.js +77 -0
- package/server/lib/skills-catalog/index.js +42 -0
- package/server/lib/skills-catalog/install.js +294 -0
- package/server/lib/skills-catalog/scan.js +221 -0
- package/server/lib/skills-catalog/source.js +85 -0
- package/server/lib/terminal/DOCUMENTATION.md +114 -0
- package/server/lib/terminal/index.js +12 -0
- package/server/lib/terminal/input-ws-protocol.js +66 -0
- package/server/lib/terminal/input-ws-protocol.test.js +138 -0
- package/server/lib/tts/DOCUMENTATION.md +134 -0
- package/server/lib/tts/index.js +16 -0
- package/server/lib/tts/service.js +162 -0
- package/server/lib/tts/summarization.js +171 -0
- package/server/lib/tunnels/index.js +166 -0
- package/server/lib/tunnels/providers/cloudflare.js +260 -0
- package/server/lib/tunnels/registry.js +51 -0
- package/server/lib/tunnels/types.js +219 -0
- package/server/lib/utils/lru.js +107 -0
- package/server/lib/utils/sse.js +121 -0
|
@@ -0,0 +1,48 @@
|
|
|
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]);
|
|
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
|
+
// 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
|
+
|
|
5
|
+
Return JSON with exactly this shape:
|
|
6
|
+
{"subject": string, "highlights": string[]}
|
|
7
|
+
|
|
8
|
+
Rules:
|
|
9
|
+
- subject format: <type>: <summary>
|
|
10
|
+
- allowed types: feat, fix, refactor, perf, docs, test, build, ci, chore, style, revert
|
|
11
|
+
- no scope in subject
|
|
12
|
+
- keep subject concise and user-facing
|
|
13
|
+
- highlights: 0-3 concise user-facing points
|
|
14
|
+
|
|
15
|
+
Selected files:
|
|
16
|
+
${r.map(i=>`- ${i}`).join(`
|
|
17
|
+
`)}`;try{const i=await Ic({directory:t,prompt:s,generationSession:o,schema:{type:"object",additionalProperties:!1,properties:{subject:{type:"string",description:"Conventional commit subject line."},highlights:{type:"array",items:{type:"string",description:"Short user-facing highlight."},maxItems:3,description:"Optional short user-facing highlights."}},required:["subject","highlights"]},kind:"commit"}),a=typeof i.subject=="string"?i.subject.trim():"",l=Array.isArray(i.highlights)?i.highlights.filter(d=>typeof d=="string").map(d=>d.trim()).filter(Boolean).slice(0,3):[];if(!a)throw new Error("Structured output missing subject");const c={message:{subject:a,highlights:l}};return console.info("[git-generation][browser] success",{transport:"session",kind:"commit",elapsedMs:Date.now()-n,subjectLength:c.message.subject.length,highlightsCount:c.message.highlights.length}),c}catch(i){throw console.error("[git-generation][browser] failed",{transport:"session",kind:"commit",elapsedMs:Date.now()-n,message:i instanceof Error?i.message:String(i),error:i}),i}}async function sy(t,r){const e=Date.now(),n=Dc();if(!n)throw new Error("Select existing session for generation");const o=await wp(t,{from:r.base,to:r.head,maxCount:50}),s=(Array.isArray(o?.all)?o.all:[]).filter(c=>typeof c?.hash=="string"&&c.hash.length>0).map(c=>({hash:c.hash,subject:typeof c.message=="string"?c.message.trim():""}));if(s.length===0)throw new Error(`No commits found in range ${r.base}...${r.head}`);const i=new Set;await Promise.all(s.map(async c=>{try{const d=await bp(t,c.hash),u=Array.isArray(d?.files)?d.files:[];for(const f of u)typeof f?.path=="string"&&f.path.trim().length>0&&i.add(f.path.trim())}catch(d){console.warn("[git-generation][browser] failed to collect commit files",{hash:c.hash,error:d instanceof Error?d.message:String(d)})}}));const a=Array.from(i).sort().slice(0,300);console.info("[git-generation][browser] request",{transport:"session",kind:"pr",directory:t,sessionId:n.sessionId,providerId:n.providerID,modelId:n.modelID,agent:n.agent,base:r.base,head:r.head,commits:s.length,changedFiles:a.length});const l=`You are drafting GitHub Pull Request title and body using session context, commit list, and changed files.
|
|
18
|
+
|
|
19
|
+
Return JSON with exactly this shape:
|
|
20
|
+
{"title": string, "body": string}
|
|
21
|
+
|
|
22
|
+
Rules:
|
|
23
|
+
- title: concise, outcome-first, conventional style
|
|
24
|
+
- body: markdown with sections: ## Summary, ## Why, ## Testing
|
|
25
|
+
- keep output concrete and user-facing
|
|
26
|
+
|
|
27
|
+
Base branch: ${r.base}
|
|
28
|
+
Head branch: ${r.head}
|
|
29
|
+
|
|
30
|
+
Commits in range (base...head):
|
|
31
|
+
${s.map(c=>`- ${c.hash.slice(0,7)} ${c.subject||"(no subject)"}`).join(`
|
|
32
|
+
`)}
|
|
33
|
+
|
|
34
|
+
Files changed across these commits:
|
|
35
|
+
${a.length>0?a.map(c=>`- ${c}`).join(`
|
|
36
|
+
`):"- none detected"}
|
|
37
|
+
${r.context?.trim()?`
|
|
38
|
+
Additional context:
|
|
39
|
+
${r.context.trim()}`:""}`;try{const c=await Ic({directory:t,prompt:l,generationSession:n,schema:{type:"object",additionalProperties:!1,properties:{title:{type:"string",description:"Pull request title."},body:{type:"string",description:"Pull request markdown description."}},required:["title","body"]},kind:"pr"}),d={title:typeof c.title=="string"?c.title.trim():"",body:typeof c.body=="string"?c.body.trim():""};return console.info("[git-generation][browser] success",{transport:"session",kind:"pr",elapsedMs:Date.now()-e,titleLength:d.title.length,bodyLength:d.body.length}),d}catch(c){throw console.error("[git-generation][browser] failed",{transport:"session",kind:"pr",elapsedMs:Date.now()-e,message:c instanceof Error?c.message:String(c),error:c}),c}}const Dc=()=>{const t=V.getState().currentSessionId;if(!t)return null;const r=ne.getState(),e=ke.getState(),n=r.getSessionAgentSelection(t)||e.currentAgentName||void 0,o=r.getSessionModelSelection(t),i=(n?r.getAgentModelForSession(t,n):null)||o||(e.currentProviderId&&e.currentModelId?{providerId:e.currentProviderId,modelId:e.currentModelId}:null);return!i?.providerId||!i?.modelId?null:{sessionId:t,providerID:i.providerId,modelID:i.modelId,agent:n}},Ic=async({directory:t,prompt:r,generationSession:e,schema:n,kind:o})=>{const s=Date.now();console.info("[git-generation][browser] runStructuredGenerationInActiveSession start",{kind:o,directory:t,sessionId:e.sessionId,providerID:e.providerID,modelID:e.modelID,agent:e.agent});const i=typeof t=="string"?t.trim():"",a=r.indexOf(`
|
|
40
|
+
`),l=(a===-1?r:r.slice(0,a)).trim(),c=(a===-1?"":r.slice(a+1)).trim(),d=[];l&&d.push({type:"text",text:l,synthetic:!1}),c&&d.push({type:"text",text:c,synthetic:!0}),d.length===0&&d.push({type:"text",text:r,synthetic:!1});const u=await O.withDirectory(t,async()=>O.getApiClient().session.prompt({sessionID:e.sessionId,...i.length>0?{directory:i}:{},model:{providerID:e.providerID,modelID:e.modelID},...e.agent?{agent:e.agent}:{},format:{type:"json_schema",schema:n,retryCount:2},parts:d})),f=u?.error;if(!u?.data)throw new Error(f?.message||`Failed to generate ${o} output`);const m=u.data.info,p=m?.structured_output||m?.structured;if(!p||typeof p!="object"||Array.isArray(p))throw console.error("[git-generation][browser] invalid structured output",{kind:o,sessionId:e.sessionId,elapsedMs:Date.now()-s,finish:m?.finish,messageInfo:u.data.info,messageParts:u.data.parts}),new Error("No structured output returned by session");return p};async function gp(t){const r=Ie();return r?.worktree?.list?r.worktree.list(t):r?r.listGitWorktrees(t):os(t)}async function yp(t,r){const e=Ie();return e?.worktree?.validate?e.worktree.validate(t,r):e?.validateGitWorktree?e.validateGitWorktree(t,r):ss(t,r)}async function iy(t){const r=Ie();return r?.worktree?.bootstrapStatus?r.worktree.bootstrapStatus(t):r?.getGitWorktreeBootstrapStatus?r.getGitWorktreeBootstrapStatus(t):Wa(t)}async function ay(t,r){const e=Ie();return e?.worktree?.preview?e.worktree.preview(t,r):e?.previewGitWorktree?e.previewGitWorktree(t,r):td(t,r)}async function hp(t,r){const e=Ie();return e?.worktree?.create?e.worktree.create(t,r):e?.createGitWorktree?e.createGitWorktree(t,r):is(t,r)}async function Sp(t,r){const e=Ie();return e?.worktree?.remove?e.worktree.remove(t,r):e?.deleteGitWorktree?e.deleteGitWorktree(t,r):as(t,r)}const bo={worktree:{list:gp,validate:yp,create:hp,remove:Sp}};async function wp(t,r={}){const e=Ie();return e?e.getGitLog(t,r):Ga(t,r)}async function bp(t,r){const e=Ie();return e?e.getCommitFiles(t,r):qa(t,r)}async function cy(){const t=Ie();return t?t.getGitIdentities():Va()}async function ly(t){const r=Ie();return r?r.createGitIdentity(t):Ka(t)}async function dy(t,r){const e=Ie();return e?e.updateGitIdentity(t,r):Ja(t,r)}async function uy(t){const r=Ie();return r?r.deleteGitIdentity(t):Qa(t)}async function fy(){const t=Ie();return t?.discoverGitCredentials?t.discoverGitCredentials():pd()}async function py(){const t=Ie();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():ud()}async function my(t){const r=Ie();return r?.getConflictDetails?r.getConflictDetails(t):Ya(t)}const qo="/api",Mp=()=>(qo.startsWith("/"),qo);function vp(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}async function Dp(t,r){const e=vp();if(e?.execCommands)return e.execCommands(t,r);const n=await fetch(`${Mp()}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:t,cwd:r,background:!1})});if(!n.ok){const s=await n.json().catch(()=>({error:n.statusText}));throw new Error(s.error||"Command exec failed")}const o=await n.json().catch(()=>null);return{success:!!o?.success,results:Array.isArray(o?.results)?o.results:[]}}async function lo(t,r){const e=await Dp([t],r),n=e.results[0];return n||{command:t,success:e.success}}const Zt=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ip=(t,r)=>{const e=Zt(t),n=Zt(r);if(!n)return e;if(n.startsWith("/"))return n;const o=e.split("/").filter(Boolean),s=n.split("/").filter(Boolean);for(const i of s)if(i!=="."){if(i===".."){o.pop();continue}o.push(i)}return`/${o.join("/")}`},qi=t=>{const r=Zt(t);if(!r)return null;if(r.endsWith("/.git"))return r.slice(0,-5)||null;const n=r.indexOf("/.git/worktrees/");return n>0&&r.slice(0,n)||null};async function Ap(t){const r=Zt(t),e=await vc(r);return{isDirty:!e.isClean,ahead:e.ahead,behind:e.behind,upstream:e.tracking}}async function gy(t){const r=Zt(t);if(!r)return"HEAD";const e=async n=>{const o=await lo("git rev-parse --absolute-git-dir",n),s=Zt((o.stdout||"").trim());if(o.success&&s){const d=qi(s);if(d)return d}const i=await lo("git rev-parse --git-common-dir",n),a=Zt((i.stdout||"").trim());if(!i.success||!a)return n;const l=Ip(n,a),c=qi(l);return c||n};try{const n=await e(r).catch(()=>r),o=await vc(n);return(typeof o.current=="string"?o.current.trim():"")||"HEAD"}catch{return"HEAD"}}const Pp="openchamber.json",Tp=".openchamber",kp=[".config","openchamber"],Cp=[".config","openchamber","projects"],Ep="settings.json",Vo=new Map,Vi=t=>/^[A-Za-z0-9._-]+$/.test(t),xp=t=>{let r="";for(const e of t)r+=e.toString(16).padStart(2,"0");return r},_p=async t=>{try{if(typeof crypto>"u"||!crypto.subtle)return null;const e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-1",e);return xp(new Uint8Array(n))}catch{return null}};function Mo(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Rp=1e3,Op=120,jp=80,Fp=4e3,Lp=2e3,Np=300,$p=new Set(["macos","linux","windows"]),fn=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ir=(t,r)=>{const e=fn(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!e||e==="/"?`/${n}`:`${e}/${n}`},Ac=t=>Ir(Ir(t,Tp),Pp),gn=()=>{const t="/api";return t.startsWith("/"),t},Rs=async(t,r)=>{try{const e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return e.ok?{ok:!0,data:await e.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},Up=async t=>{const r=Mo();if(r?.createDirectory)try{if((await r.createDirectory(t))?.success)return!0}catch{}return!!(await Rs(`${gn()}/fs/mkdir`,{path:t})).ok},Pc=async t=>{const r=Mo();if(r?.readFile)try{const e=await r.readFile(t);return typeof e?.content=="string"?e.content:""}catch{return null}try{const e=await fetch(`${gn()}/fs/read?path=${encodeURIComponent(t)}`);return e.ok?await e.text():null}catch{return null}},Bp=async(t,r)=>{const e=Mo();if(e?.writeFile)try{if((await e.writeFile(t,r))?.success)return!0}catch{}return!!(await Rs(`${gn()}/fs/write`,{path:t,content:r})).ok},Tc=async()=>{if(!nr()){const t=await mo().catch(()=>null);if(t&&t.trim().length>0)return fn(t)}try{const t=await fetch(`${gn()}/fs/home`);if(!t.ok)return null;const r=await t.json().catch(()=>null),e=typeof r?.home=="string"?r.home.trim():"";return e?fn(e):null}catch{return null}},zp=async()=>{const t=await Tc();return t?kp.reduce((r,e)=>Ir(r,e),t):null},kc=async()=>{const t=await Tc();return t?Cp.reduce((r,e)=>Ir(r,e),t):null},Hp=async()=>{const t=await zp();return t?Ir(t,Ep):null},Wp=async t=>{const r=typeof t?.path=="string"?t.path.trim():"",e=r?fn(r):"",n=typeof t?.id=="string"?t.id.trim():"";if(n&&Vi(n))return n;if(e){const s=Vo.get(e);if(s)return s}const o=await Hp();if(o&&e){const s=await Pc(o);if(s)try{const i=JSON.parse(s),a=Array.isArray(i?.projects)?i.projects:[];for(const l of a){if(!l||typeof l!="object")continue;const c=l,d=typeof c.id=="string"?c.id.trim():"",u=typeof c.path=="string"?fn(c.path.trim()):"";if(d&&Vi(d)&&u&&u===e)return Vo.set(e,d),d}}catch{}}if(e){const s=await _p(e),i=s?`path_${s}`:`path_${e.replace(/[^A-Za-z0-9._-]+/g,"_")}`;return Vo.set(e,i),i}return null},Cc=async t=>{const r=await kc();if(!r)return null;const e=await Wp(t);return e?Ir(r,`${e}.json`):null},Sr=(t,r)=>t.length<=r?t:t.slice(0,r),Gp=t=>typeof t!="string"?"":Sr(t,Rp),qp=t=>{if(!Array.isArray(t))return[];const r=[];for(const e of t){if(!e||typeof e!="object")continue;const n=e,o=typeof n.id=="string"?n.id.trim():"",s=typeof n.text=="string"?n.text:"",i=Sr(s.trim(),Op);if(!o||!i)continue;const a=!!n.completed,l=typeof n.createdAt=="number"&&Number.isFinite(n.createdAt)&&n.createdAt>=0?n.createdAt:Date.now();r.push({id:o,text:i,completed:a,createdAt:l})}return r},Vp=t=>{if(!Array.isArray(t))return[];const r=[],e=new Set;for(const n of t){if(typeof n!="string")continue;const o=n.trim().toLowerCase();!$p.has(o)||e.has(o)||(e.add(o),r.push(o))}return r},Kp=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=Sr(typeof o.name=="string"?o.name.trim():"",jp),a=Sr(typeof o.command=="string"?o.command.trim():"",Fp);if(!s||!i||!a||e.has(s))continue;e.add(s);const l=typeof o.icon=="string"?o.icon.trim():"",c=Vp(o.platforms),d=o.autoOpenUrl===!0,u=typeof o.openUrl=="string"?o.openUrl.trim():"",f=Sr(u,Lp),m=typeof o.desktopOpenSshForward=="string"?o.desktopOpenSshForward.trim():"",p=Sr(m,Np);r.push({id:s,name:i,command:a,icon:l||null,...d?{autoOpenUrl:!0}:{},...f?{openUrl:f}:{},...p?{desktopOpenSshForward:p}:{},...c.length>0?{platforms:c}:{}})}return r},Ec=t=>{const r=Kp(t?.actions),e=typeof t?.primaryActionId=="string"?t.primaryActionId.trim():"",n=e&&r.some(o=>o.id===e)?e:null;return{actions:r,primaryActionId:n}},xc=t=>({notes:Gp(t?.notes),todos:qp(t?.todos)});async function vo(t){const r=typeof t?.path=="string"?t.path.trim():"";if(!r)return null;const e=await Cc(t),n=async a=>{const l=await Pc(a);return l===null?null:l},o=a=>{if(typeof a!="string")return null;const l=a.trim();if(!l)return null;try{const c=JSON.parse(l);return!c||typeof c!="object"?null:c}catch{return null}};if(e){const a=o(await n(e));if(a)return a}const s=Ac(r),i=o(await n(s));if(!i)return null;try{await _c(t,i)&&await Qp(r)}catch{}return i}async function _c(t,r){if(!(typeof t?.path=="string"?t.path.trim():""))return!1;const n=await kc(),o=await Cc(t);if(!n||!o)return!1;try{if(!await Up(n))return!1;const i=JSON.stringify(r,null,2);return await Bp(o,i)}catch(s){return console.error("Failed to write openchamber config:",s),!1}}async function Os(t,r){const n={...await vo(t)||{},...r};return _c(t,n)}async function yy(t){return(await vo(t))?.["setup-worktree"]??[]}async function hy(t,r){const e=r.filter(n=>n.trim().length>0);return Os(t,{"setup-worktree":e})}async function Sy(t){const r=await vo(t);return xc({notes:r?.projectNotes,todos:r?.projectTodos})}async function wy(t,r){const e=xc({notes:r.notes,todos:r.todos});return Os(t,{projectNotes:e.notes,projectTodos:e.todos})}async function by(t){const r=await vo(t);return Ec({actions:r?.projectActions,primaryActionId:r?.projectActionsPrimaryId})}async function My(t,r){const e=Ec({actions:r.actions,primaryActionId:r.primaryActionId});return Os(t,{projectActions:e.actions,projectActionsPrimaryId:e.primaryActionId??void 0})}function Jp(t,r){return t.replace(/\$ROOT_PROJECT_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_PROJECT_PATH\}/g,r.rootWorktreePath).replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}async function Qp(t){const r=Ac(t),e=Mo();if(e?.delete)try{await e.delete(r);return}catch{}try{await Rs(`${gn()}/fs/delete`,{path:r})}catch{}}const Ve=t=>{const r=t.replace(/\\/g,"/");return r==="/"?"/":r.length>1?r.replace(/\/+$/,""):r},Yp=(t,r)=>{const e=Ve(t),n=Ve(r);if(!n)return e;if(n.startsWith("/"))return n;const o=e.split("/").filter(Boolean),s=n.split("/").filter(Boolean);for(const i of s)if(i!=="."){if(i===".."){o.pop();continue}o.push(i)}return`/${o.join("/")}`},Ki=t=>{const r=Ve(t);if(!r)return null;if(r.endsWith("/.git"))return r.slice(0,-5)||null;const n=r.indexOf("/.git/worktrees/");return n>0&&r.slice(0,n)||null},Rc=async t=>{const r=Ve(t),e=await lo("git rev-parse --absolute-git-dir",r),n=Ve((e.stdout||"").trim());if(e.success&&n){const l=Ki(n);if(l)return l}const o=await lo("git rev-parse --git-common-dir",r),s=Ve((o.stdout||"").trim());if(!o.success||!s)return r;const i=Yp(r,s),a=Ki(i);return a||r},Xp=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,"").split("/").join("-").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),Ji=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,""),Qi=t=>{const r=Ve(t),e=r.split("/").filter(Boolean);return e[e.length-1]??r},Zp=t=>{const r=[];for(const n of t.setupCommands){const o=n.trim();o&&r.push(Jp(o,{rootWorktreePath:t.projectDirectory}))}const e=r.filter(Boolean).join(" && ");return e.trim().length>0?e:void 0},Oc=(t,r)=>{const e=t.mode==="existing"?"existing":"new",n=t.worktreeName??t.preferredName??"",o=Xp(n),s=t.branchName??(e==="new"?t.preferredName:void 0)??"",i=Ji(s),a=Ji(t.existingBranch??t.branchName??""),l=(t.startRef||"").trim(),c=Array.isArray(t.setupCommands)?t.setupCommands:[],d=Zp({projectDirectory:r,setupCommands:c});return{mode:e,...o?{worktreeName:o}:{},...i?{branchName:i}:{},...a?{existingBranch:a}:{},...l?{startRef:l}:{},...d?{startCommand:d}:{},...t.setUpstream?{setUpstream:!0}:{},...t.upstreamRemote?{upstreamRemote:t.upstreamRemote}:{},...t.upstreamBranch?{upstreamBranch:t.upstreamBranch}:{},...t.ensureRemoteName?{ensureRemoteName:t.ensureRemoteName}:{},...t.ensureRemoteUrl?{ensureRemoteUrl:t.ensureRemoteUrl}:{}}};async function jc(t){const r=Ve(t.path),e=await Rc(r).catch(()=>r),n=Ve(r);return(await bo.worktree.list(r).catch(()=>[])).filter(i=>typeof i.path=="string"&&i.path.trim().length>0).map(i=>{const a=Ve(i.path),l=(i.branch||"").replace(/^refs\/heads\//,"").trim(),c=(i.name||"").trim();return{source:"sdk",name:c||Qi(a),path:a,projectDirectory:e,branch:l,label:l||c||Qi(a)}}).filter(i=>Ve(i.path)!==n).sort((i,a)=>{const l=(i.label||i.branch||i.path).toLowerCase(),c=(a.label||a.branch||a.path).toLowerCase();return l.localeCompare(c)})}async function vy(t,r){const e=Ve(t.path),n=await Rc(e).catch(()=>e),o=Oc(r,e),s=await bo.worktree.create(e,o),i=typeof s?.name=="string"?s.name:"",a=typeof s?.branch=="string"?s.branch:"",l=typeof s?.path=="string"?s.path:"";if(!i||!l)throw new Error("Worktree create missing name/path");const c={source:"sdk",name:i,path:Ve(l),projectDirectory:n,branch:a,label:a||i};return tu(c.path),c}async function Dy(t,r){const e=t.path,n=Oc(r,e);return bo.worktree.validate(e,n)}async function em(t,r,e){const n=t.path,o=!!e?.deleteRemoteBranch,s=e?.deleteLocalBranch===!0,i=e?.remoteName;if(!(await bo.worktree.remove(n,{directory:r.path,deleteLocalBranch:s}))?.success)throw new Error("Worktree removal failed");ru(r.path);const l=(r.branch||"").replace(/^refs\/heads\//,"").trim();o&&l&&await mp(n,{branch:l,remote:i}).catch(()=>{})}const Yi=150,tm=1100,Xi=1200,rm=5e3;let Zr=null;const Fc=()=>{Zr&&Zr()};function Iy(t){const r=t?.enabled??!0,e=R.useRef(!1),n=R.useRef(!1),o=R.useRef(0),s=R.useRef(0),i=R.useRef(0),a=R.useRef(null),l=R.useRef(null),c=R.useCallback(async(u=!1)=>{const f=Date.now();if(!(!u&&f-o.current<1e3)&&!(u&&f-o.current<600)){if(e.current){u&&(n.current=!0);return}e.current=!0,o.current=f;try{const[m,p]=await Promise.allSettled([fetch("/api/sessions/snapshot",{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}).then(async E=>{if(!E.ok)throw console.warn("[useServerSessionStatus] API returned",E.status),E.status===401&&console.warn("[useServerSessionStatus] Authentication required - session may have expired"),new Error(String(E.status));return await E.json()}),O.getGlobalSessionStatus()]),g=m.status==="fulfilled"?m.value:null,S=g?.statusSessions??{},h=g?.attentionSessions??{},v=p.status==="fulfilled"?p.value??{}:{},b=V.getState().sessionStatus||new Map;let D=null;const I=()=>(D||(D=new Map(b)),D);for(const[E,j]of Object.entries(S)){const L=b.get(E);(!L||L.type!==j.status||L.attempt!==j.metadata?.attempt||L.message!==j.metadata?.message||L.next!==j.metadata?.next||L.confirmedAt!==j.lastUpdateAt)&&I().set(E,{type:j.status,confirmedAt:j.lastUpdateAt,attempt:j.metadata?.attempt,message:j.metadata?.message,next:j.metadata?.next})}for(const[E,j]of Object.entries(v)){const L=(D??b).get(E);(!L||L.type!==j.type||L.attempt!==j.attempt||L.message!==j.message||L.next!==j.next)&&I().set(E,{type:j.type,confirmedAt:Date.now(),attempt:j.attempt,message:j.message,next:j.next})}const M=new Set(Object.keys(S)),C=new Set(Object.keys(v));for(const[E,j]of D??b)(j.type==="busy"||j.type==="retry")&&!M.has(E)&&!C.has(E)&&I().set(E,{type:"idle",confirmedAt:Date.now()});const k=V.getState().sessionAttentionStates||new Map;let T=null;const _=()=>(T||(T=new Map(k)),T);let $=!1;for(const[E,j]of Object.entries(h)){const L=k.get(E),z=j;(!L||L.needsAttention!==z.needsAttention||L.lastUserMessageAt!==z.lastUserMessageAt||L.lastStatusChangeAt!==z.lastStatusChangeAt||L.status!==z.status||L.isViewed!==z.isViewed)&&(_().set(E,z),$=!0)}for(const E of(T??k).keys()){const j=!!S[E],L=!!h[E];!j&&!L&&(_().delete(E),$=!0)}const U=D!==null;(U||$)&&V.setState({...U&&D?{sessionStatus:D}:{},...$&&T?{sessionAttentionStates:T}:{}})}catch(m){console.warn("[useServerSessionStatus] Error fetching session status:",m)}finally{e.current=!1,n.current&&(n.current=!1,setTimeout(()=>{c(!0)},120))}}},[]),d=R.useCallback(()=>{const u=Date.now(),f=u-s.current;if(s.current=u,!a.current){const m=f>=Xi?Yi:Math.max(Yi,Xi-f);a.current=setTimeout(()=>{a.current=null,c(!0)},m)}!l.current&&u-i.current>=rm&&(i.current=u,l.current=setTimeout(()=>{l.current=null,c(!0)},tm))},[c]);return R.useEffect(()=>{if(r)return c(!0),()=>{a.current&&clearTimeout(a.current),l.current&&clearTimeout(l.current)}},[r,c]),R.useEffect(()=>{if(!r)return;const u=()=>{document.visibilityState==="visible"&&d()};return document.addEventListener("visibilitychange",u),()=>{document.removeEventListener("visibilitychange",u)}},[r,d]),R.useEffect(()=>{if(!r){Zr=null;return}return Zr=d,()=>{Zr=null}},[r,d]),{fetchSessionStatus:c,triggerImmediatePoll:d}}const nm=t=>{if(!t)return null;const r=Number(t);return Number.isFinite(r)?r:null},om=(t,r)=>{if(!t||typeof t!="object")return null;const n=t.headers;if(!n||typeof n!="object")return null;const o=n;if(typeof o.get=="function")return o.get(r);const s=n,i=s[r]??s[r.toLowerCase()];return typeof i=="string"?i:null},Ko=t=>nm(om(t,"x-next-cursor")),sm=t=>{if(!t||typeof t!="object")return!1;const r=t;return(r.status??r.response?.status??r.cause?.status??r.cause?.response?.status)===404},js=ye(),Fs="oc.sessionSelectionByDirectory",im=()=>{try{const t=js.getItem(Fs);if(!t)return{};const r=JSON.parse(t);return!r||typeof r!="object"?{}:Object.entries(r).reduce((e,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(e[n]=o),e),{})}catch{return{}}};let Vn=null,Zi=0,zr=null,Jo=!1,Ss,en=null;const am=12e4,ws=new Map,uo=new Map,cm=(t,r)=>{const e=K(t)??t;ws.set(e,{cachedAt:Date.now(),result:r})},lm=t=>{const r=new Set;for(const e of t){const n=K(e)??e;n&&r.add(n)}for(const e of ws.keys())r.has(e)||ws.delete(e);for(const e of uo.keys())r.has(e)||uo.delete(e)},dm=async t=>{const r=K(t)??t,e=uo.get(r);if(e&&Date.now()-e.cachedAt<=am)return e.isGitRepo;const n=await pp(r).catch(()=>!1);return uo.set(r,{cachedAt:Date.now(),isGitRepo:n}),n},Ls=()=>(Vn||(Vn=im()),Vn),Lc=t=>{Vn=t,en=t,clearTimeout(Ss),Ss=setTimeout(()=>{try{js.setItem(Fs,JSON.stringify(t)),en=null}catch{}},300)};typeof window<"u"&&window.addEventListener("beforeunload",()=>{if(en!==null){clearTimeout(Ss);try{js.setItem(Fs,JSON.stringify(en))}catch{}en=null}});const Nc=t=>{if(!t)return null;const e=Ls()[t];return typeof e=="string"?e:null},Pt=(t,r)=>{if(!t)return;const e={...Ls()};r?e[t]=r:delete e[t],Lc(e)},um=(t,r)=>{if(!t)return;const e=Nc(t);if(!e)return;if(!new Set(r).has(e)){const o={...Ls()};delete o[t],Lc(o)}},ea=async(t,r)=>{const e=t.status??await Ap(t.path).catch(()=>{}),n=et.getState().projects,o=K(t.projectDirectory)??t.projectDirectory,i={id:n.find(a=>K(a.path)===o)?.id??`path:${o}`,path:o};await em(i,e?{...t}:t,{deleteRemoteBranch:r?.deleteRemoteBranch,deleteLocalBranch:r?.deleteLocalBranch,remoteName:r?.remoteName})},ta=async(t,r)=>{const e=O.getApiClient(),n=K(r??null);return!!(await e.session.delete({sessionID:t,...n?{directory:n}:{}})).data},fm=async(t,r,e)=>{const n=O.getApiClient(),o=K(e??null);return(await n.session.update({sessionID:t,...o?{directory:o}:{},time:{archived:r}})).data??null},K=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const e=r.replace(/\\/g,"/").replace(/^([a-z]):\//,(n,o)=>`${o.toUpperCase()}:/`).replace(/^\/([a-z]):\//,(n,o)=>`/${o.toUpperCase()}:/`);return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},ra=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return K(r)},pm=()=>typeof window>"u"?!1:!!(window.__ARCHCODER_RUNTIME_APIS__?.runtime||window.__OPENCHAMBER_RUNTIME_APIS__?.runtime)?.isVSCode,na=(...t)=>{we()&&pm()&&console.log("[ArchCoder][VSCode][sessions]",...t)},Te=t=>{const r=new Map;return t.forEach(e=>{if(!e||typeof e.id!="string"||e.id.length===0)return;const n=r.get(e.id);if(!n){r.set(e.id,e);return}const o=n.time?.updated??0;(e.time?.updated??0)>o&&r.set(e.id,e)}),Array.from(r.values())},Ye=t=>{const r=new Map;t.forEach(e=>{const n=K(e.directory??null);if(!n)return;const o=r.get(n);o?o.push(e):r.set(n,[e])});for(const[e,n]of r.entries())r.set(e,Te(n));return r},Kt=(t,r)=>{const e=t.find(n=>n.id===r);return e?K(e.directory??null):null},mm=async(t,r,e,n)=>{const o=K(r);if(!o||t.length===0)return null;const s=t.map(u=>({id:u.id,directory:K(u.directory)})).filter(u=>!!u.directory);if(s.length===0)return null;let i;if(Array.isArray(n))i=n;else try{i=await jc({id:`path:${o}`,path:o})}catch(u){return console.debug("Failed to hydrate worktree metadata from worktree list:",u),null}if(!Array.isArray(i)||i.length===0){let u=!1;const f=new Map(e);return s.forEach(({id:m})=>{f.delete(m)&&(u=!0)}),u?f:null}const a=new Map;i.forEach(u=>{const f=K(u.path)??u.path;f!==o&&a.set(f,u)});let l=!1;const c=new Map(e),d=(u,f)=>f?{...f,...u,branch:u.branch||f.branch,label:u.label||f.label,name:u.name||f.name,projectDirectory:u.projectDirectory||f.projectDirectory,createdFromBranch:u.createdFromBranch||f.createdFromBranch,kind:u.kind||f.kind,status:u.status||f.status}:u;return s.forEach(({id:u,directory:f})=>{const m=a.get(f);if(!m){c.delete(u)&&(l=!0);return}const p=c.get(u),g=d(m,p);(!p||p.path!==g.path||p.branch!==g.branch||p.label!==g.label||p.name!==g.name||p.projectDirectory!==g.projectDirectory||p.createdFromBranch!==g.createdFromBranch||p.kind!==g.kind||p.source!==g.source)&&(c.set(u,g),l=!0)}),l?c:null},q=Me()(ve(tt((t,r)=>({sessions:[],archivedSessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{if(zr)return Jo=!0,zr;const e=(async()=>{const n=++Zi,o=()=>n===Zi;t({isLoading:!0,error:null});try{const s=be.getState(),i=et.getState(),a=O.getApiClient(),l=ra(),c=!!l;na("loadSessions:start",{workspace:l,currentDirectory:s.currentDirectory,clientDirectory:O.getDirectory(),projectsCount:i.projects.length,activeProjectId:i.activeProjectId});const d=K(s.currentDirectory??O.getDirectory()??null),u=i.projects.find(M=>M.id===i.activeProjectId)??null,f=K(u?.path??null),m=f??d??null,p=i.projects.length>0?i.projects:m?[{id:"legacy",path:m}]:[],g=M=>{const C=K(M.directory??null);return C||K(M.project?.worktree??null)},S=(M,C)=>M?M===C?!0:c&&M.startsWith(`${C}/`):!1,h=async(M,C)=>{const k=new Map;M.forEach(Q=>{Q.projectPath&&Q.validPaths.forEach(se=>{const Z=K(se)??se,ce=Q.sessions.filter(De=>(K(De.directory??null)??Z)===Z);k.set(Z,Te(ce))})});const T=Te(Array.from(k.values()).flat()),_=r();let $=_.worktreeMetadata;for(const Q of M)if(Q.projectPath)try{const se=await mm(Q.sessions,Q.projectPath,$,Q.discoveredWorktrees);se&&($=se)}catch(se){console.debug("Failed to refresh worktree metadata during session load:",se)}const U=new Map;M.forEach(Q=>{Q.projectPath&&U.set(Q.projectPath,Q.discoveredWorktrees)});const E=new Set;M.forEach(Q=>{Q.validPaths.forEach(se=>{const Z=K(se)??se;Z&&E.add(Z)})});const j=d??f??null,L=j&&E.has(j)?j:f??j,z=L?k.get(L)??[]:T,W=new Set(T.map(Q=>Q.id));for(const[Q,se]of k.entries())um(Q,se.map(Z=>Z.id));const fe=(L??null)!==(_.lastLoadedDirectory??null);let re=_.currentSessionId;const Ae=!!(re&&z.some(Q=>Q.id===re));if((!re||!W.has(re)||fe&&!Ae)&&(re=z[0]?.id??T[0]?.id??null),L){const Q=Nc(L);Q&&W.has(Q)&&(re=Q)}const oe=(()=>{if(!re)return L??null;const Q=$.get(re)?.path;if(Q)return K(Q)??Q;const se=Kt(T,re);return se||(L??null)})();if(!o())return;try{O.setDirectory(oe??void 0)}catch(Q){console.warn("Failed to sync OpenCode directory after session load:",Q)}const ut=f?M.find(Q=>Q.projectPath===f)?.discoveredWorktrees??[]:[];t({sessions:T,archivedSessions:C,sessionsByDirectory:k,currentSessionId:re,lastLoadedDirectory:L??null,isLoading:!1,worktreeMetadata:$,availableWorktrees:ut,availableWorktreesByProject:U}),L&&Pt(L,re),oe&&oe!==L&&Pt(oe,re)};if(p.length===0){if(!o())return;t({sessions:[],archivedSessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}lm(p.map(M=>M.path));const v=async M=>Promise.all(p.map(async C=>{const k=K(C.path);if(!k)return{projectId:C.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const T=await dm(k);let _=[];const $=new Set([k]);T&&(_=await jc({id:C.id,path:k}).catch(()=>[]),_.forEach(j=>{j?.path&&$.add(K(j.path)??j.path)}));const U=Te(M.filter(j=>{const L=g(j);if(!L)return!1;for(const z of $)if(S(L,z))return!0;return!1})),E={projectId:C.id,projectPath:k,sessions:U,discoveredWorktrees:_,validPaths:$};return cm(k,E),E}));try{const C=Te(r().archivedSessions),k=await a.experimental.session.list({limit:500,archived:!1});let T=Te(Array.isArray(k.data)?k.data:[]),_=[],$=!1;const U=async()=>{if(!o())return;const j=await v(T),L=$?Te(_):C;await h(j,L)};await U(),(async()=>{let j=Ko(k)??void 0;for(;j&&o();){const z=await a.experimental.session.list({limit:500,cursor:j,archived:!1}),W=Array.isArray(z.data)?z.data:[];if(W.length===0)break;T=Te([...T,...W]),await U(),j=Ko(z)??void 0}let L;for(;o();){const z=await a.experimental.session.list({limit:500,archived:!0,...L?{cursor:L}:{}}),W=Array.isArray(z.data)?z.data.filter(re=>!!re.time?.archived):[];W.length>0&&($=!0,_=Te([..._,...W]),await U());const fe=Ko(z);if(!fe)break;L=fe}!$&&o()&&($=!0,_=[],await U())})().catch(j=>{console.debug("Failed to load additional global sessions:",j)});return}catch(M){if(!sm(M))throw M;console.debug("Global session endpoint unavailable, using legacy loader")}const b=await a.session.list(void 0),D=Te(Array.isArray(b.data)?b.data:[]),I=await v(D);await h(I,[])}catch(s){if(!o())return;t({error:s instanceof Error?s.message:"Failed to load sessions",isLoading:!1})}})();zr=e;try{await e}finally{zr===e&&(zr=null),Jo&&(Jo=!1,r().loadSessions())}},createSession:async(e,n,o)=>{t({error:null});const s=be.getState(),i=K(s.currentDirectory),a=ra(),l=a??K(n??O.getDirectory()??i);na("createSession:start",{title:e,parentID:o,targetDirectory:l,vscodeWorkspaceDirectory:a});const c=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,d=r(),u=new Set(d.sessions.map(g=>g.id)),f={id:c,title:e||"New session",parentID:o??void 0,directory:l??null,projectID:d.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(t(g=>{const S=[f,...g.sessions],h=new Map(g.sessionsByDirectory);if(l){const v=h.get(l)??[];h.set(l,Te([f,...v]))}return{sessions:S,sessionsByDirectory:h,currentSessionId:c,webUICreatedSessions:new Set([...g.webUICreatedSessions,c]),isLoading:!1}}),l)try{O.setDirectory(l)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const m=g=>{const S=l??null,h=S?{...g,directory:S}:g;t(v=>{const b=v.sessions.map(I=>I.id===c?h:I),D=new Map(v.sessionsByDirectory);if(l){const M=(D.get(l)??[]).map(C=>C.id===c?h:C);D.set(l,Te(M))}return{sessions:b,sessionsByDirectory:Ye(b),currentSessionId:h.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(I=>I!==c),h.id])}}),Pt(l??null,h.id)},p=async()=>{const g=O.getApiClient(),S=20;for(let h=0;h<S;h+=1){try{const v=await g.session.list(l?{directory:l}:void 0),D=(Array.isArray(v.data)?v.data:[]).find(I=>!(u.has(I.id)||e&&I.title&&I.title!==e));if(D)return D}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const g=()=>O.createSession({title:e,parentID:o??void 0});let S=null;try{S=l?await O.withDirectory(l,g):await g()}catch(h){console.warn("Direct session create failed or timed out, falling back to polling:",h)}return S||(S=await p()),S?(m(S),S):(t(h=>({sessions:h.sessions.filter(v=>v.id!==c),currentSessionId:d.currentSessionId,webUICreatedSessions:new Set(Array.from(h.webUICreatedSessions).filter(v=>v!==c)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return t(S=>({sessions:S.sessions.filter(h=>h.id!==c),currentSessionId:d.currentSessionId,webUICreatedSessions:new Set(Array.from(S.webUICreatedSessions).filter(h=>h!==c)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(e,n)=>{t({isLoading:!0,error:null});const o=r().worktreeMetadata.get(e),s=typeof o?.path=="string"?o.path:null,i=typeof o?.projectDirectory=="string"?o.projectDirectory:null,a=r(),l=Kt([...a.sessions,...a.archivedSessions],e),c=K(i)??K(l)??K(O.getDirectory()??null)??null;let d=!1;try{if(!await ta(e,c))return t({isLoading:!1,error:"Failed to delete session"}),!1;if(o&&n?.archiveWorktree)try{await ea(o,{deleteRemoteBranch:n?.deleteRemoteBranch,deleteLocalBranch:n?.deleteLocalBranch,remoteName:n?.remoteName}),d=!0}catch(p){const g=p instanceof Error?p.message:"Failed to delete worktree";t({error:g})}let f=null;t(p=>{const g=p.sessions.filter(I=>I.id!==e),S=p.archivedSessions.filter(I=>I.id!==e);f=p.currentSessionId===e?null:p.currentSessionId;const h=new Map(p.worktreeMetadata);h.delete(e);const v=!!(s&&n?.archiveWorktree&&d),b=v?p.availableWorktrees.filter(I=>K(I.path)!==K(s)):p.availableWorktrees,D=new Map(p.availableWorktreesByProject);if(v&&i){const I=K(i)??i,M=D.get(I)??[];D.set(I,M.filter(C=>K(C.path)!==K(s)))}return{sessions:g,archivedSessions:S,sessionsByDirectory:Ye(g),currentSessionId:f,isLoading:!1,worktreeMetadata:h,availableWorktrees:b,availableWorktreesByProject:D}});const m=K(l)??K(O.getDirectory()??null)??null;return Pt(m,f),!0}catch(u){const f=u instanceof Error?u.message:"Failed to delete session";return t({error:f,isLoading:!1}),!1}},deleteSessions:async(e,n)=>{const o=Array.from(new Set(e.filter(h=>typeof h=="string"&&h.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const s=n?.silent===!0;s||t({isLoading:!0,error:null});const i=[],a=[],l=new Map,c=new Set;for(const h of o)try{const v=r().worktreeMetadata.get(h),b=Kt([...r().sessions,...r().archivedSessions],h),D=K(v?.projectDirectory??null)??K(b)??K(O.getDirectory()??null)??null;if(v&&n?.archiveWorktree){const M=K(v.path)??v.path;c.has(M)||(c.add(M),l.set(M,v))}await ta(h,D)?i.push(h):a.push(h)}catch{a.push(h)}const d=[],u=[];if(n?.archiveWorktree&&l.size>0)for(const h of l.values())try{await ea(h,{deleteRemoteBranch:n?.deleteRemoteBranch,deleteLocalBranch:n?.deleteLocalBranch,remoteName:n?.remoteName}),d.push({path:h.path,projectDirectory:h.projectDirectory})}catch(v){const b=v instanceof Error?v.message:"Failed to delete worktree";u.push(b)}u.length>0&&t({error:u[0]});const f=be.getState();d.forEach(({path:h,projectDirectory:v})=>{f.currentDirectory===h&&f.setDirectory(v,{showOverlay:!1})});const m=new Set(i),p=a.length>0?a.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let g=null;t(h=>{const v=h.sessions.filter(k=>!m.has(k.id)),b=h.archivedSessions.filter(k=>!m.has(k.id));h.currentSessionId&&m.has(h.currentSessionId)?g=null:g=h.currentSessionId;const D=new Map(h.worktreeMetadata);for(const k of m)D.delete(k);const I=new Set(d.map(k=>K(k.path)).filter(k=>!!k)),M=I.size>0?h.availableWorktrees.filter(k=>!I.has(K(k.path)??k.path)):h.availableWorktrees,C=new Map(h.availableWorktreesByProject);return d.length>0&&d.reduce((T,_)=>{const $=K(_.projectDirectory)??_.projectDirectory,U=K(_.path)??_.path;return T.has($)||T.set($,new Set),T.get($)?.add(U),T},new Map).forEach((T,_)=>{const U=(C.get(_)??[]).filter(E=>!T.has(K(E.path)??E.path));C.set(_,U)}),{sessions:v,archivedSessions:b,sessionsByDirectory:Ye(v),currentSessionId:g,...s?{}:{isLoading:!1,error:p},worktreeMetadata:D,availableWorktrees:M,availableWorktreesByProject:C}});const S=O.getDirectory()??null;return Pt(S,g),{deletedIds:i,failedIds:a}},archiveSession:async e=>{const{archivedIds:n,failedIds:o}=await r().archiveSessions([e]);return n.length===1&&o.length===0},archiveSessions:async(e,n)=>{const o=Array.from(new Set(e.filter(u=>typeof u=="string"&&u.length>0)));if(o.length===0)return{archivedIds:[],failedIds:[]};const s=n?.silent===!0;s||t({isLoading:!0,error:null});const i=[],a=[];for(const u of o)try{const f=r().worktreeMetadata.get(u),m=Kt([...r().sessions,...r().archivedSessions],u),p=K(f?.projectDirectory??null)??K(m)??K(O.getDirectory()??null)??null;if(!await fm(u,Date.now(),p)){a.push(u);continue}i.push(u)}catch{a.push(u)}const l=new Set(i);let c=null;const d=a.length>0?a.length===o.length?"Failed to archive sessions":"Failed to archive some sessions":null;return t(u=>{if(l.size===0)return s?u:{...u,isLoading:!1,error:d};const f=u.sessions.filter(g=>l.has(g.id)).map(g=>({...g,time:{...g.time,archived:Date.now()}})),m=u.sessions.filter(g=>!l.has(g.id)),p=Te([...f,...u.archivedSessions]);return u.currentSessionId&&l.has(u.currentSessionId)?c=m[0]?.id??null:c=u.currentSessionId,{sessions:m,archivedSessions:p,sessionsByDirectory:Ye(m),currentSessionId:c,...s?{}:{isLoading:!1,error:d}}}),!s&&l.size===0&&t({isLoading:!1,error:d}),{archivedIds:i,failedIds:a}},updateSessionTitle:async(e,n)=>{try{const o=Kt(r().sessions,e),s=r().worktreeMetadata.get(e),i=()=>O.updateSession(e,n),a=s?.path??o,l=a?await O.withDirectory(a,i):await i();t(c=>{const d=c.sessions.map(u=>u.id===e?l:u);return{sessions:d,sessionsByDirectory:Ye(d)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async e=>{try{const n=Kt(r().sessions,e),o=O.getApiClient(),i=r().worktreeMetadata.get(e)?.path??n,a=async()=>{const c=n??O.getDirectory();return o.session.share({sessionID:e,...c?{directory:c}:{}})},l=i?await O.withDirectory(i,a):await a();return l.data?(t(c=>{const d=c.sessions.map(u=>u.id===e?l.data:u);return{sessions:d,sessionsByDirectory:Ye(d)}}),l.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async e=>{try{const n=Kt(r().sessions,e),o=O.getApiClient(),i=r().worktreeMetadata.get(e)?.path??n,a=async()=>{const c=n??O.getDirectory();return o.session.unshare({sessionID:e,...c?{directory:c}:{}})},l=i?await O.withDirectory(i,a):await a();return l.data?(t(c=>{const d=c.sessions.map(u=>u.id===e?l.data:u);return{sessions:d,sessionsByDirectory:Ye(d)}}),l.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:e=>{const n=r().currentSessionId;t({currentSessionId:e,error:null}),n&&n!==e&&fetch(`/api/sessions/${n}/unview`,{method:"POST"}).catch(()=>{}),e&&fetch(`/api/sessions/${e}/view`,{method:"POST"}).catch(()=>{}),Fc();const o=O.getDirectory()??null;Pt(o,e)},clearError:()=>{t({error:null})},getSessionsByDirectory:e=>{const n=K(e)??e,{sessionsByDirectory:o,sessions:s}=r(),i=o.get(n);return i||s.filter(a=>(K(a.directory??null)??n)===n)},getDirectoryForSession:e=>{if(!e)return null;const n=r().worktreeMetadata.get(e);if(n?.path)return K(n.path)??n.path;const o=r().sessions.find(i=>i.id===e);return K(o?.directory??null)},applySessionMetadata:(e,n)=>{!e||!n||t(o=>{const s=o.sessions.findIndex(m=>m.id===e);if(s===-1)return o;const i=o.sessions[s],a=n.time?{...i.time,...n.time}:i.time,l=n.summary===void 0?i.summary:n.summary||void 0,c=n.share===void 0?i.share:n.share||void 0,d={...i,...n,time:a,summary:l,share:c},u=d.title!==i.title||d.parentID!==i.parentID||d.directory!==i.directory||d.version!==i.version||d.projectID!==i.projectID||a!==i.time&&JSON.stringify(a)!==JSON.stringify(i.time)||l!==i.summary&&JSON.stringify(l??null)!==JSON.stringify(i.summary??null)||c!==i.share&&JSON.stringify(c??null)!==JSON.stringify(i.share??null),f=[...o.sessions];return f[s]=u?d:i,{sessions:f,sessionsByDirectory:Ye(f)}})},isOpenChamberCreatedSession:e=>{const{webUICreatedSessions:n}=r();return n.has(e)},markSessionAsOpenChamberCreated:e=>{t(n=>{const o=new Set(n.webUICreatedSessions);return o.add(e),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:e=>{const{markSessionAsOpenChamberCreated:n}=r();n(e)},setWorktreeMetadata:(e,n)=>{e&&t(o=>{const s=new Map(o.worktreeMetadata);return n?s.set(e,n):s.delete(e),{worktreeMetadata:s}})},getWorktreeMetadata:e=>{if(e)return r().worktreeMetadata.get(e)},setSessionDirectory:(e,n)=>{if(!e)return;const o=r().sessions,s=o.findIndex(c=>c.id===e);if(s===-1)return;const a=o[s].directory??null,l=n??void 0;a!==(l??null)&&(t(c=>{const d=[...c.sessions],u={...d[s]};return l!==void 0?u.directory=l:delete u.directory,d[s]=u,{sessions:d,sessionsByDirectory:Ye(d)}}),a&&Pt(a,null),n&&Pt(n,e))},updateSession:e=>{t(n=>{const o=n.sessions.findIndex(u=>u.id===e.id),s=n.archivedSessions.findIndex(u=>u.id===e.id),i=!!e.time?.archived,a=o===-1?i?n.sessions:[e,...n.sessions]:n.sessions.map(u=>u.id===e.id?e:u),l=s===-1?i?[e,...n.archivedSessions]:n.archivedSessions:n.archivedSessions.map(u=>u.id===e.id?e:u),c=Te(a.filter(u=>!u.time?.archived)),d=Te(l.filter(u=>!!u.time?.archived));return{sessions:c,archivedSessions:d,sessionsByDirectory:Ye(c)}})},removeSessionFromStore:e=>{e&&t(n=>{const o=[...n.sessions,...n.archivedSessions].find(d=>d.id===e),s=K(o?.directory??null),i=n.sessions.filter(d=>d.id!==e),a=n.archivedSessions.filter(d=>d.id!==e);if(i.length===n.sessions.length&&a.length===n.archivedSessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(e);const c=n.currentSessionId===e?null:n.currentSessionId;return s&&Pt(s,null),{sessions:i,archivedSessions:a,sessionsByDirectory:Ye(i),currentSessionId:c,worktreeMetadata:l}})}}),{name:"session-store",storage:rt(()=>ye()),partialize:t=>({currentSessionId:t.currentSessionId,sessions:t.sessions,archivedSessions:t.archivedSessions,lastLoadedDirectory:t.lastLoadedDirectory,webUICreatedSessions:Array.from(t.webUICreatedSessions),worktreeMetadata:Array.from(t.worktreeMetadata.entries()),availableWorktrees:t.availableWorktrees,availableWorktreesByProject:Array.from(t.availableWorktreesByProject.entries())}),merge:(t,r)=>{if(!(g=>typeof g=="object"&&g!==null)(t))return r;const n=Array.isArray(t.sessions)?t.sessions:r.sessions,o=Array.isArray(t.archivedSessions)?t.archivedSessions:r.archivedSessions,s=typeof t.currentSessionId=="string"||t.currentSessionId===null?t.currentSessionId:r.currentSessionId,i=Array.isArray(t.webUICreatedSessions)?t.webUICreatedSessions:[],a=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],l=Array.isArray(t.availableWorktrees)?t.availableWorktrees:r.availableWorktrees,c=Array.isArray(t.availableWorktreesByProject)?t.availableWorktreesByProject:[],d=new Map(c),u=typeof t.lastLoadedDirectory=="string"?t.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Te(n),m=Te(o);return{...r,...t,sessions:f,archivedSessions:m,sessionsByDirectory:Ye(f),currentSessionId:s,webUICreatedSessions:new Set(i),worktreeMetadata:new Map(a),availableWorktrees:l,availableWorktreesByProject:d.size>0?d:r.availableWorktreesByProject,lastLoadedDirectory:u}}}),{name:"session-store"})),$c="This message comes from an AI assistant in another session. The user wants you to respond according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed. Always clearly state what you understand your task to be, and wait for the user's approval of your conclusions before taking any further actions.",Ay="This message bellow comes from an AI agent in another session. I want you to act according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed; if it is a bug description, find the root cause and fix it. Proceed with actions right away based on your understanding of the task. Here is the content of the message: ",Qo=t=>typeof t=="string"&&t.trim()===$c.trim(),oa="Authentication failed for this provider. Please re-authenticate and retry.",sa=t=>{if(typeof t!="string")return!1;const r=t.toLowerCase().trim();if(!r)return!1;if(r.includes("token refresh failed")||r.includes("unauthorized")||r.includes("invalid token")||r.includes("expired token"))return!0;const e=r.includes("oauth"),n=r.includes("failed")||r.includes("invalid")||r.includes("expired");if(e&&n)return!0;const o=/\b401\b/.test(r),s=r.includes("auth")||r.includes("token")||r.includes("unauthorized");return o&&s},Kn=200,gm=300*1e3,ia={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},kt=()=>Kn,ym=()=>Math.round(kt()*.6),Uc={MAX_SESSIONS:ia.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(Kn*.6),HISTORICAL_MESSAGES:Kn,FETCH_BUFFER:20,HISTORY_CHUNK:Kn,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:ia.ZOMBIE_TIMEOUT},aa=()=>{const t=kt(),r=ym();return{...Uc,HISTORICAL_MESSAGES:t,VIEWPORT_MESSAGES:r,HISTORY_CHUNK:t}},hm=Uc,Rn=(t,r)=>{const e=Date.now(),n=t.get(r),o=new Map(t);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??e,lastUpdateAt:e}),o},Yo=(t,r)=>{const e=Array.from(r);if(!e.some(s=>t.has(s)))return t;const o=new Map(t);return e.forEach(s=>{o.delete(s)}),o},ca=new Map,Bc=t=>{const r=ca.get(t);r&&(clearTimeout(r),ca.delete(t))},Hr=t=>{for(const r of t)Bc(r)},Sm=new Set(["completed","complete","error","failed","aborted","timeout","timedout","done","cancelled","canceled"]),wm=t=>{if(typeof t!="string")return;const r=t.toLowerCase().trim().replace(/[\s_-]+/g,"");return r.length>0?r:void 0},la=t=>{const r=wm(t);return r?Sm.has(r):!1},Xe=t=>!!t&&typeof t=="object"&&!Array.isArray(t),On=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,zc=(t,r)=>{const e=Xe(t)?t:void 0,n=Xe(r)?r:void 0,o=[On(e?.start),On(n?.start)].filter(a=>typeof a=="number"),s=[On(e?.end),On(n?.end)].filter(a=>typeof a=="number");if(o.length===0&&s.length===0)return;const i={};return o.length>0&&(i.start=Math.min(...o)),s.length>0&&(i.end=Math.max(...s)),i},bm=(t,r)=>{const e=Xe(t)?t:void 0,n=Xe(r)?r:void 0;if(!e&&!n)return;const o=e?.status,s=n?.status,i=typeof o=="string"&&la(o),a=typeof s=="string"&&la(s),l={...e??{},...n??{}};i&&!a&&typeof s=="string"&&(l.status=o);const c=zc(e?.time,n?.time);return c&&(l.time=c),(Xe(e?.metadata)||Xe(n?.metadata))&&(l.metadata={...Xe(e?.metadata)?e.metadata:{},...Xe(n?.metadata)?n.metadata:{}}),(Xe(e?.input)||Xe(n?.input))&&(l.input={...Xe(e?.input)?e.input:{},...Xe(n?.input)?n.input:{}}),l},pn=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>pn(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>pn(r)).join("")}return""},Ct=t=>{if(!t)return"";const r=t,e=s=>typeof s=="string"?s:Array.isArray(s)?s.map(i=>{if(typeof i=="string")return i;if(i&&typeof i=="object"){const a=i;return e(a.text)||e(a.content)||e(a.value)||pn(a.delta)}return""}).join(""):"",n=[e(r.text),e(r.content),e(r.value),pn(r.delta)];let o="";for(const s of n)s.length>o.length&&(o=s);return o},Wr=(t,r)=>{const e={...r,...t},n=typeof r?.type=="string"?r.type:void 0;if(e.type=e.type||n||"text",e.type==="text"||e.type==="reasoning"){const i=r??{},a=Ct(r),l=Ct(t),c=pn(t.delta);let d="";const f=(typeof e.text=="string"?"text":typeof e.content=="string"?"content":typeof e.value=="string"?"value":null)??(typeof i.text=="string"?"text":typeof i.content=="string"?"content":typeof i.value=="string"?"value":"text");c?d=a?`${a}${c}`:c:l?d=l:d=a,e[f]=d,f!=="text"&&(e.text=d),delete e.delta}const s=zc(r?.time,t?.time);if(s&&(e.time=s),e.type==="tool"){const i=bm(r?.state,t?.state);i&&(e.state=i)}return e},Mm=t=>{const r=t.clientRole??t.role;return typeof r=="string"?r:""},Jn=t=>{const r=Mm(t);return{...t,clientRole:r,...r==="user"?{userMessageMarker:!0}:{}}},vm=t=>t.map(r=>({...r,info:Jn(r.info),parts:Array.isArray(r.parts)?r.parts:[]})),da=(t,r)=>{if(!r)return t;const e=t.findIndex(n=>n.info.id===r);return e<0?t:t.slice(0,e)},Dm=50*1024*1024,Im=t=>{const r=(t||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"application/octet-stream"}},Am=t=>{if(t.type&&t.type.trim().length>0)return t.type;const r=(t.name||"").toLowerCase(),e=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(e){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},bs=t=>t.replace(/\\/g,"/").trim(),Pm=t=>{const r=bs(t);if(r.startsWith("file://"))return r;const e=r.startsWith("/")?r:`/${r}`;return`file://${encodeURI(e)}`},Tm=async t=>{const r=await fetch(`/api/fs/raw?path=${encodeURIComponent(t)}`);if(!r.ok)throw new Error(`Failed to read raw file: ${r.status}`);const e=await r.blob();return await new Promise((n,o)=>{const s=new FileReader;s.onload=()=>n(s.result),s.onerror=o,s.readAsDataURL(e)})},Xt=Me()(ve(tt((t,r)=>({attachedFiles:[],addAttachedFile:async e=>{const{attachedFiles:n}=r();if(n.some(p=>p.filename===e.name&&p.size===e.size)){console.log(`File "${e.name}" is already attached`);return}const s=Dm;if(e.size>s)throw new Error(`File "${e.name}" is too large. Maximum size is 50MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],a=Am(e);!i.some(p=>a.startsWith(p)||a===p||a==="")&&a!==""&&console.warn(`File type "${a}" might not be supported`);const c=new FileReader,d=await new Promise((p,g)=>{c.onload=()=>p(c.result),c.onerror=g,c.readAsDataURL(e)}),u=d.startsWith("data:")?d.replace(/^data:[^;]*/,`data:${a}`):d,f=p=>{const g=p.replace(/\\/g,"/").split("/");return g[g.length-1]||p},m={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:e,dataUrl:u,mimeType:a,filename:f(e.name),size:e.size,source:"local"};t(p=>({attachedFiles:[...p.attachedFiles,m]}))},addServerFile:async(e,n,o)=>{const s=bs(e),{attachedFiles:i}=r();if(i.some(g=>bs(g.serverPath||"")===s&&g.source==="server")){console.log(`Server file "${n}" is already attached`);return}const l=Im(n),c=l&&l.trim().length>0?l:"application/octet-stream",d=c!=="text/plain"&&c!=="application/x-directory";let u=Pm(s);if(d)try{u=await Tm(s)}catch(g){console.warn("Failed to inline binary server file, falling back to file://",g)}const f=typeof o=="string"?new TextEncoder().encode(o).length:0,m=new File([],n,{type:c}),p={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:m,dataUrl:u,mimeType:c,filename:n,size:f,source:"server",serverPath:s};t(g=>({attachedFiles:[...g.attachedFiles,p]}))},removeAttachedFile:e=>{t(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==e)}))},clearAttachedFiles:()=>{t({attachedFiles:[]})}}),{name:"file-store",storage:rt(()=>ye()),version:3,migrate:t=>{const r=t;return{attachedFiles:Array.isArray(r?.attachedFiles)?r.attachedFiles:[]}},partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),ua=(t,r)=>{const e=new Map(t);return e.delete(r),e},km=3e4,Jt=new Map,jn=new Map,hr=new Map,Fn=new Map,Xo=new Map,Ar=new Map,Ue=[];let Qn=!1,tn=null;const Cm=2500,Pr=new Map,Be=[];let Yn=!1,rn=null;const Em=3500,Hc=120,Xn=()=>{tn!==null&&(clearTimeout(tn),tn=null),Qn=!1},xm=t=>{const r=Ms(t.part)??`${t.part.type??"unknown"}`,e=typeof t.role=="string"?t.role:"";return`${t.sessionId}:${t.messageId}:${e}:${r}`},_m=t=>{const r=xm(t);Ar.has(r)||Ue.push(r),Ar.set(r,t)},Ns=(t,r)=>{if(Ue.length===0){Xn();return}const e=[],n=[];for(const o of Ue){const s=Ar.get(o);if(s){if(r&&!r(s)){n.push(o);continue}e.push(s),Ar.delete(o)}}if(Ue.length=0,Ue.push(...n),e.length===0){Ue.length===0&&Xn();return}for(const o of e)t(o.sessionId,o.messageId,o.part,o.role,o.currentSessionId);Ue.length===0&&Xn()},Rm=(t,r)=>{Ns(t,e=>e.sessionId===r)},Om=(t,r,e)=>{Ns(t,n=>n.sessionId===r&&n.messageId===e)},jm=t=>{if(Ue.length!==0){for(let r=Ue.length-1;r>=0;r-=1){const e=Ue[r],n=Ar.get(e);if(!n){Ue.splice(r,1);continue}n.sessionId===t&&(Ar.delete(e),Ue.splice(r,1))}Ue.length===0&&Xn()}},Fm=t=>{Qn||(Qn=!0,tn=setTimeout(()=>{tn=null,Qn&&t()},Hc))},Zn=()=>{rn!==null&&(clearTimeout(rn),rn=null),Yn=!1},Lm=t=>{const r=typeof t.role=="string"?t.role:"";return`${t.sessionId}:${t.messageId}:${t.partId}:${t.field}:${r}`},Nm=t=>{const r=Lm(t),e=Pr.get(r);if(e){e.delta+=t.delta,!e.currentSessionId&&t.currentSessionId&&(e.currentSessionId=t.currentSessionId);return}Pr.set(r,{...t}),Be.push(r)},$s=(t,r)=>{if(Be.length===0){Zn();return}const e=[],n=[];for(const o of Be){const s=Pr.get(o);if(s){if(r&&!r(s)){n.push(o);continue}e.push(s),Pr.delete(o)}}if(Be.length=0,Be.push(...n),e.length===0){Be.length===0&&Zn();return}for(const o of e)t(o.sessionId,o.messageId,o.partId,o.field,o.delta,o.role,o.currentSessionId);Be.length===0&&Zn()},$m=(t,r)=>{$s(t,e=>e.sessionId===r)},Um=(t,r,e)=>{$s(t,n=>n.sessionId===r&&n.messageId===e)},Bm=t=>{if(Be.length!==0){for(let r=Be.length-1;r>=0;r-=1){const e=Be[r],n=Pr.get(e);if(!n){Be.splice(r,1);continue}n.sessionId===t&&(Pr.delete(e),Be.splice(r,1))}Be.length===0&&Zn()}},zm=t=>{Yn||(Yn=!0,rn=setTimeout(()=>{rn=null,Yn&&t()},Hc))},Hm=t=>!t||typeof t.type!="string"?!1:t.type==="tool"?!0:t.type==="text"||t.type==="reasoning"?Oe.getState().chatRenderMode==="sorted":!1,Wm=(t,r,e,n)=>{const o=t.get(r);if(!o||o.length===0)return!1;const s=Qt(r,e,o);if(s===-1)return!1;const a=o[s].parts.find(l=>l?.id===n);return a?.type==="tool"?!0:a?.type==="text"||a?.type==="reasoning"?Oe.getState().chatRenderMode==="sorted":!1},Gm=15e3,qm=10,fa=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const e=r.indexOf("_"),n=e>=0?r.slice(e+1):r;return!n||n.length<qm?null:n},Vm=t=>{let r=0;for(const e of t)(e.info.clientRole??e.info.role)==="user"&&(r+=1);return r},pa=(t,r)=>{const e=typeof t?.info?.id=="string"?t.info.id:"",n=typeof r?.info?.id=="string"?r.info.id:"";if(e&&n){const i=fa(e),a=fa(n);if(i&&a&&i.length===a.length&&i!==a)return i<a?-1:1;if(e!==n)return e.localeCompare(n)}const o=typeof t?.info?.time?.created=="number"?t.info.time.created:0,s=typeof r?.info?.time?.created=="number"?r.info.time.created:0;return o-s},ma=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("archcoder_stream_debug")==="1"}catch{return!1}},ga=t=>{const r=t.replace(/\\/g,"/").trim();if(r.startsWith("file://"))return r;const e=r.startsWith("/")?r:`/${r}`;return`file://${encodeURI(e)}`},Ms=t=>{if(t){if(typeof t.id=="string"&&t.id.length>0)return t.id;if(t.type){const r=t.reason,e=typeof t.tool=="string"?t.tool:"",n=t.callID,o=t.tool,s=o&&typeof o=="object"?o.callID:void 0,i=n??s;return`${t.type}-${e}-${r??""}-${i??""}`}}},Ln=(t,r)=>{if(!Array.isArray(t)||t.length===0)return-1;if(typeof r.id=="string"&&r.id.length>0){const n=t.findIndex(o=>o?.id===r.id);return n!==-1?n:-1}const e=Ms(r);return e?t.findIndex(n=>Ms(n)===e):-1},Nn=new Set,Km=(t,r)=>({...r,info:{...t.info,...r.info},parts:Array.isArray(r.parts)?r.parts:[]}),ya=t=>{const r=[],e=new Map;for(const n of t){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const s=e.get(o);if(s===void 0){e.set(o,r.length),r.push(n);continue}r[s]=Km(r[s],n)}return r},Tt=(t,r,e)=>{if(t.get(r)===e)return t;const o=new Map(t);return e?o.set(r,e):o.delete(r),o},Gr=(t,r,e)=>{if(t.get(r)===e)return t;const o=new Map(t);return o.set(r,e),o},fo=new Map,Jm=t=>{const r=new Map;for(let e=0;e<t.length;e+=1){const n=t[e]?.info?.id;typeof n=="string"&&n.length>0&&r.set(n,e)}return r},$n=(t,r)=>{fo.set(t,Jm(r))},vs=(t,r,e)=>{let n=fo.get(t);n||(n=new Map,fo.set(t,n)),n.set(r,e)},Qt=(t,r,e)=>{const n=fo.get(t),o=n?.get(r);if(typeof o=="number"&&o>=0&&o<e.length&&e[o]?.info?.id===r)return o;const s=e.findIndex(i=>i.info.id===r);return s!==-1?vs(t,r,s):n&&n.delete(r),s},ha=(t,r)=>{const e=new Map(t);let n=!1;for(const o of r)e.delete(o)&&(n=!0);return n?e:t},Qm=(t,r)=>{const e=new Set,n=t.streamingMessageIds.get(r);return n&&e.add(n),t.messageStreamStates.forEach((o,s)=>{t.messageSessionIndex.get(s)===r&&e.add(s)}),e},Sa=(t,r,e)=>t.streamingMessageIds.get(r)===e?!0:t.messageSessionIndex.get(e)===r&&t.messageStreamStates.has(e),Ym=async t=>{if(t)try{return q.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},wa=t=>{if(!t)return null;try{return q.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},ba=async(t,r)=>{const e=await Ym(t);return e?O.withDirectory(e,r):r()},ee=Me()(ve(tt((t,r)=>({messages:new Map,sessionMemoryState:new Map,sessionHistoryMeta:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingUserMessageMetaBySession:new Map,loadMessages:async(e,n)=>{const o=Fn.get(e);if(o)return o;const s=(Xo.get(e)??0)+1;Xo.set(e,s);const i=()=>Xo.get(e)===s,a=(async()=>{const l=aa(),c=n===1/0,d=r().sessionMemoryState.get(e),u=r().sessionHistoryMeta.get(e);if(u?.loading)return;const f=u?.limit??l.HISTORICAL_MESSAGES,m=typeof n=="number"&&Number.isFinite(n)?n:f,p=Math.max(f,m);t(g=>{if(!i())return g;const S=new Map(g.sessionHistoryMeta),h=S.get(e);return S.set(e,{limit:h?.limit??f,complete:h?.complete??!1,loading:!0}),{sessionHistoryMeta:S}});try{const g=c?void 0:p,S=await ba(e,()=>O.getSessionMessages(e,g));if(!i())return;const h=wa(e),b=[...da(S,h)].sort(pa),D=typeof g=="number"?b.length>=p:!1,I=b.slice(-p);t(M=>{if(!i())return M;const C=M.messages.get(e)||[],k=I.map(Z=>{const ce=Jn(Z.info),De=(Array.isArray(Z.parts)?Z.parts:[]).map(he=>{if(he?.type==="text"){const je=he.text??he.content??"";if(Qo(je))return{...he,synthetic:!0}}return he});return{...Z,info:ce,parts:De}}),T=ya(k),_=M.sessionMemoryState.get(e)??d,$=!!M.streamingMessageIds.get(e),U=typeof _?.lastUserMessageAt=="number"&&Date.now()-_.lastUserMessageAt<Gm;if(T.length===0&&C.length>0&&($||_?.isStreaming===!0||U)){const Z=new Map(M.sessionMemoryState),ce=Z.get(e)??d??{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};Z.set(e,{...ce,lastAccessedAt:Date.now(),historyLoading:!1,historyLimit:p});const De=new Map(M.sessionHistoryMeta),he=De.get(e);return De.set(e,{limit:p,complete:he?.complete??!1,loading:!1}),{sessionMemoryState:Z,sessionHistoryMeta:De}}const j=Vm(T),L=new Set(C.map(Z=>Z.info.id)),z=new Set(T.map(Z=>Z.info.id)),W=[];L.forEach(Z=>{z.has(Z)||W.push(Z)});const fe=new Map(M.messages);fe.set(e,T),$n(e,T);const re=new Map(M.sessionMemoryState);re.set(e,{...d,viewportAnchor:T.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:d?.totalAvailableMessages,loadedTurnCount:j,hasMoreAbove:D,hasMoreTurnsAbove:D,historyLoading:!1,historyComplete:!D,historyLimit:p,streamingCooldownUntil:void 0});const Ae=new Map(M.sessionHistoryMeta);Ae.set(e,{limit:p,complete:!D,loading:!1});const oe={messages:fe,sessionMemoryState:re,sessionHistoryMeta:Ae};Hr(W);const ut=Yo(M.messageStreamStates,W);if(ut!==M.messageStreamStates&&(oe.messageStreamStates=ut),W.length>0){const Z=M.streamingMessageIds.get(e);Z&&W.includes(Z)&&(oe.streamingMessageIds=Tt(oe.streamingMessageIds??M.streamingMessageIds,e,null))}if(W.length>0){const Z=ha(oe.messageSessionIndex??M.messageSessionIndex,W);Z!==(oe.messageSessionIndex??M.messageSessionIndex)&&(oe.messageSessionIndex=Z)}if(W.length>0){const Z=new Map(M.pendingAssistantParts);let ce=!1;W.forEach(De=>{Z.delete(De)&&(ce=!0)}),ce&&(oe.pendingAssistantParts=Z)}const Q=oe.messageSessionIndex??M.messageSessionIndex;let se=Q;return T.forEach(Z=>{const ce=Z?.info?.id;typeof ce=="string"&&ce.length>0&&(se=Gr(se,ce,e))}),se!==Q&&(oe.messageSessionIndex=se),oe})}finally{t(g=>{if(!i())return g;const S=g.sessionHistoryMeta.get(e);if(!S?.loading)return g;const h=new Map(g.sessionHistoryMeta);return h.set(e,{...S,loading:!1}),{sessionHistoryMeta:h}})}})();Fn.set(e,a);try{await a}finally{Fn.get(e)===a&&Fn.delete(e)}},sendMessage:async(e,n,o,s,i,a,l,c,d,u="normal",f)=>{if(!i)throw new Error("No session selected");const m=i;r().sessionAbortFlags.has(m)&&t(p=>{const g=new Map(p.sessionAbortFlags);return g.delete(m),{sessionAbortFlags:g}}),await ba(m,async()=>{try{const p=e.trimStart(),g=(()=>{if(!p.startsWith("/"))return!1;const b=p.search(/\s/),D=b===-1?p:p.slice(0,b);return!(D.length<=1||!D.slice(1).includes("/"))})(),S=(()=>{if(u==="shell"||!p.startsWith("/")||g)return null;const b=p.indexOf(`
|
|
41
|
+
`),D=b===-1?p:p.slice(0,b),[I,...M]=D.split(" "),C=I.slice(1).trim();if(C.toLowerCase()==="shell"||!C)return null;const k=b===-1?"":p.slice(b+1),T=M.join(" ").trim(),_=k?T?`${T}
|
|
42
|
+
${k}`:k:T;return{command:C,arguments:_}})(),h=(()=>{if(u!=="shell")return null;const b=e.trim();return b.trim()?{command:b}:null})(),v=(()=>{if(!p.startsWith("/")||g)return null;const b=p.indexOf(`
|
|
43
|
+
`),D=b===-1?p:p.slice(0,b),[I,...M]=D.split(" ");if(I.slice(1).trim().toLowerCase()!=="shell")return null;const k=b===-1?"":p.slice(b+1),T=M.join(" ").trim(),_=k?T?`${T}
|
|
44
|
+
${k}`:k:T;return _.trim()?{command:_}:null})();t({lastUsedProvider:{providerID:n,modelID:o}}),t(b=>{const D=b.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},I=hr.get(m);I&&(clearTimeout(I),hr.delete(m));const M=new Map(b.sessionMemoryState);return M.set(m,{...D,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:M}});try{const b=new AbortController;t(k=>{const T=new Map(k.abortControllers);return T.set(m,b),{abortControllers:T}});const D=(a??[]).map(k=>({type:"file",mime:k.mimeType,filename:k.filename,url:k.source==="server"&&k.serverPath&&(k.mimeType==="text/plain"||k.mimeType==="application/x-directory")?ga(k.serverPath):k.dataUrl}));t(k=>{const T=new Map(k.pendingUserMessageMetaBySession);return T.set(m,{mode:typeof s=="string"&&s.trim().length>0?s.trim():void 0,providerID:n,modelID:o,variant:typeof d=="string"&&d.trim().length>0?d:void 0}),{pendingUserMessageMetaBySession:T}});const I=c?.map(k=>({text:k.text,synthetic:k.synthetic,files:k.attachments?.map(T=>({type:"file",mime:T.mimeType,filename:T.filename,url:T.source==="server"&&T.serverPath&&(T.mimeType==="text/plain"||T.mimeType==="application/x-directory")?ga(T.serverPath):T.dataUrl}))})),M=O.getApiClient(),C=O.getDirectory();if(h||v?await M.session.shell({sessionID:m,...C?{directory:C}:{},...s?{agent:s}:{},model:{providerID:n,modelID:o},command:(h??v).command}):S&&S.command.toLowerCase()==="compact"?await M.session.summarize({sessionID:m,...C?{directory:C}:{},providerID:n,modelID:o}):S?await O.sendCommand({id:m,providerID:n,modelID:o,command:S.command,arguments:S.arguments,agent:s,variant:d,files:D.length>0?D:void 0}):(f&&console.info("[git-generation][browser] dispatch structured sendMessage",{sessionId:m,providerID:n,modelID:o,agent:s,variant:d,directory:C,formatType:f.type}),await O.sendMessage({id:m,providerID:n,modelID:o,text:e,agent:s,variant:d,...f?{format:f}:{},files:D.length>0?D:void 0,additionalParts:I&&I.length>0?I:void 0,agentMentions:l?[{name:l}]:void 0})),D.length>0)try{Xt.getState().clearAttachedFiles()}catch(k){console.error("Failed to clear attached files after send",k)}t(k=>{const T=new Map(k.abortControllers);return T.delete(m),{abortControllers:T}})}catch(b){let D="Network error while sending message. The message may still be processing.";if(b.name==="AbortError")D="Request timed out. The message may still be processing.";else if(b.message?.includes("504")||b.message?.includes("Gateway")){D="Gateway timeout - your message is being processed. Please wait for response.",t(I=>{const M=new Map(I.abortControllers);return M.delete(m),{abortControllers:M}});return}else sa(b.message)?D=oa:b.message&&(D=b.message);throw t(I=>{const M=new Map(I.abortControllers);M.delete(m);const C=new Map(I.pendingUserMessageMetaBySession);return C.delete(m),{abortControllers:M,pendingUserMessageMetaBySession:C}}),new Error(D)}}catch(p){let g="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?g="Request timed out. The message may still be processing.":p.response?.status===401?g="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?g="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?g="Gateway timeout - your message is being processed. Please wait for response.":sa(p.message)?g=oa:p.message&&(g=p.message),t(S=>{const h=new Map(S.abortControllers);h.delete(m);const v=new Map(S.pendingUserMessageMetaBySession);return v.delete(m),{abortControllers:h,pendingUserMessageMetaBySession:v}}),new Error(g)}})},abortCurrentOperation:async e=>{if(!e)return;jm(e),Bm(e);const n=r(),{abortControllers:o,messages:s}=n;o.get(e)?.abort();const a=Qm(n,e);if(a.size===0){const c=e?s.get(e)??[]:[];let d=null;for(let u=c.length-1;u>=0;u-=1){const f=c[u];if(!f||f.info.role!=="assistant")continue;if(d||(d=f.info.id),(f.parts??[]).some(p=>p.type==="reasoning"||p.type==="tool"||p.type==="step-start")){a.add(f.info.id);break}}a.size===0&&d&&a.add(d)}for(const c of a){const d=Jt.get(c);d&&(clearTimeout(d),Jt.delete(c),jn.delete(c))}a.size>0&&Hr(a);const l=Date.now();t(c=>{const d=Yo(c.messageStreamStates,a),u=c.messages.get(e)??[];let f=!1,m=c.messages;if(u.length>0&&a.size>0){const h=u.map(v=>{if(!a.has(v.info.id)&&a.size>0)return v;const b=(v.parts??[]).map(D=>{if(D.type==="reasoning"){const I=D,M={...I.time??{}};return typeof M.end!="number"&&(M.end=l),{...I,time:M}}if(D.type==="tool"){const I=D,M={...I.state??{}};return(M.status==="running"||M.status==="pending")&&(M.status="aborted"),{...I,state:M}}return D.type==="step-start"?{...D,type:"step-finish",aborted:!0}:D});return f=!0,{...v,info:{...v.info,abortedAt:l,streaming:!1,status:"aborted"},parts:b}});f&&(m=new Map(c.messages),m.set(e,h))}const p=c.sessionMemoryState.get(e);let g=c.sessionMemoryState;if(p){const h=new Map(c.sessionMemoryState);h.set(e,{...p,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=h}const S=new Map(c.sessionAbortFlags);return S.set(e,{timestamp:l,acknowledged:!1}),{messageStreamStates:d,sessionMemoryState:g,sessionAbortFlags:S,abortControllers:(()=>{const h=new Map(c.abortControllers);return h.delete(e),h})(),streamingMessageIds:Tt(c.streamingMessageIds,e,null),...f?{messages:m}:{}}}),O.abortSession(e).catch(c=>{console.warn("Abort request failed:",c)})},_addStreamingPartImmediate:(e,n,o,s,i)=>{const a=r();if(Nn.has(n))return;const l=a.messages.get(e)||[],c=Qt(e,n,l),d=c>=0?l[c]:void 0,u=s==="user"||d?.info.role==="user"?"user":s||d?.info.role||"assistant",f=r().sessionMemoryState.get(e);if(f?.streamStartTime&&Date.now()-f.streamStartTime>hm.ZOMBIE_TIMEOUT){f.isZombie||t(p=>{const g=new Map(p.sessionMemoryState);return g.set(e,{...f,isZombie:!0}),{sessionMemoryState:g}}),setTimeout(()=>{r().completeStreamingMessage(e,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(m=>{const g=[...m.messages.get(e)||[]],S={},h=Gr(m.messageSessionIndex,n,e);h!==m.messageSessionIndex&&(S.messageSessionIndex=h);const v=T=>{if(!((u==="assistant"||u==="user")&&m.sessionAbortFlags.has(e)))return T;const $=new Map(m.sessionAbortFlags);return $.delete(e),{...T,sessionAbortFlags:$}},b=T=>{const _=T||"",$=jn.get(n);if(_&&$===_){const j=r();if(Sa(j,e,n)){const L=Jt.get(n);L&&(clearTimeout(L),Jt.delete(n)),setTimeout(()=>{const z=r();typeof z.forceCompleteMessage=="function"&&z.forceCompleteMessage(e,n,"timeout"),z.completeStreamingMessage(e,n)},100)}}jn.set(n,_);const U=Jt.get(n);U&&clearTimeout(U);const E=setTimeout(()=>{const j=r();typeof j.forceCompleteMessage=="function"&&j.forceCompleteMessage(e,n,"timeout"),Sa(j,e,n)&&j.completeStreamingMessage(e,n),Jt.delete(n),jn.delete(n)},8e3);Jt.set(n,E)},D=e!==i,I=m.sessionMemoryState.get(e);if(D&&I?.isStreaming){const T=new Map(m.sessionMemoryState);T.set(e,{...I,backgroundMessageCount:(I.backgroundMessageCount||0)+1}),S.sessionMemoryState=T}if(u==="assistant"){const T=S.sessionMemoryState??m.sessionMemoryState,_=T.get(e);if(_){const $=Date.now(),U=new Map(T);U.set(e,{..._,isStreaming:!0,streamStartTime:_.streamStartTime??$,lastAccessedAt:$,isZombie:!1}),S.sessionMemoryState=U}}const M=Ct(o);if(Qo(M)&&(o.synthetic=!0),ma()&&u==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,partId:o?.id,role:u,type:o?.type||"text",textLen:M.length,snapshotParts:l.length})}catch{}const C=S.streamingMessageIds??m.streamingMessageIds;if(u==="assistant"){const T=Tt(C,e,n);T!==C&&(S.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set_latest"))}const k=Qt(e,n,g);if(k!==-1&&u==="user"){const T=g[k],_=Ln(T.parts,o);if(o.synthetic===!0){const L=Ct(o).trim();if(!(L.startsWith("User has requested to enter plan mode")||L.startsWith("The plan at ")||L.startsWith("The following tool was executed by the user")))return window.__messageTracker?.(n,"skipped_synthetic_user_part"),m}const $=Wr(o,_!==-1?T.parts[_]:void 0);window.__messageTracker?.(n,`user_part_type:${$.type||"unknown"}`);const U={...T};_!==-1?U.parts=U.parts.map((L,z)=>z===_?$:L):U.parts=[...U.parts,$];const E=[...g];E[k]=U;const j=new Map(m.messages);return j.set(e,E),v({messages:j,...S})}if(u==="assistant"&&k!==-1){const T=g[k],_=Ln(T.parts,o),$=Wr(o,_!==-1?T.parts[_]:void 0);window.__messageTracker?.(n,`part_type:${$.type||"unknown"}`);const U={...T};_!==-1?U.parts=U.parts.map((z,W)=>W===_?$:z):U.parts=[...U.parts,$];const E=[...g];E[k]=U;const j=new Map(m.messages);j.set(e,E),S.messageStreamStates=Rn(m.messageStreamStates,n);const L=Tt(S.streamingMessageIds??m.streamingMessageIds,e,n);return L!==(S.streamingMessageIds??m.streamingMessageIds)&&(S.streamingMessageIds=L,window.__messageTracker?.(n,"streamingId_set")),$.type==="text"?b($.text||""):b(""),v({messages:j,...S})}if(k===-1){if(u==="user"){if(o.synthetic===!0){const nt=Ct(o).trim();if(!(nt.startsWith("User has requested to enter plan mode")||nt.startsWith("The plan at ")||nt.startsWith("The following tool was executed by the user")))return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),m}const ce=Wr(o);window.__messageTracker?.(n,`new_user_part_type:${ce.type||"unknown"}`);const De=m.pendingUserMessageMetaBySession.get(e),he=ne.getState(),je=De?.mode??he.getSessionAgentSelection(e)??he.getCurrentAgent(e),Ut=typeof je=="string"&&je.trim().length>0?je.trim():void 0,kr=De?.providerID??(m.lastUsedProvider?.providerID||void 0),Cr=De?.modelID??(m.lastUsedProvider?.modelID||void 0);De&&(S.pendingUserMessageMetaBySession=ua(m.pendingUserMessageMetaBySession,e));const yn={info:{id:n,sessionID:e,role:"user",clientRole:"user",userMessageMarker:!0,...Ut?{mode:Ut}:{},...kr?{providerID:kr}:{},...Cr?{modelID:Cr}:{},time:{created:Date.now()}},parts:[ce]},bt=[...g,yn];bt.sort((nt,Er)=>{const hn=nt.info?.time?.created||0,ft=Er.info?.time?.created||0;return hn-ft});const Et=new Map(m.messages);return Et.set(e,bt),$n(e,bt),v({messages:Et,...S})}if(o?.type==="text"){const ce=Ct(o).trim();if(ce.length>0){const De=[...g].reverse().find(he=>he.info.role==="user");if(De){const he=De.parts.map(je=>Ct(je)).join("").trim();if(he.length>0&&he===ce)return Nn.size>1e3&&Nn.clear(),Nn.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),m}}}const T=m.pendingAssistantParts.get(n),_=T?[...T.parts]:[],$=Ln(_,o),U=$!==-1?_[$]:void 0,E=Wr(o,U);if(window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`),E.type==="text"?b(E.text||""):b(""),$!==-1){const ce=E;ce.type==="tool"&&typeof U?.id=="string"&&U.id.length>0&&(ce.id=U.id),_[$]=ce}else _.push(E);const j=new Map(m.pendingAssistantParts);j.set(n,{sessionId:e,parts:_});const L=m.lastUsedProvider?.providerID||"",z=m.lastUsedProvider?.modelID||"",W=Date.now(),fe=O.getDirectory()??"/",re=ne.getState(),Ae=re.getSessionAgentSelection(e)??re.getCurrentAgent(e),oe=typeof Ae=="string"&&Ae.trim().length>0?Ae.trim():void 0,Q={info:u==="user"?{id:n,sessionID:e,role:"user",time:{created:W},agent:oe||"default",model:{providerID:L,modelID:z},clientRole:u,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:e,role:"assistant",time:{created:W},parentID:n,modelID:z,providerID:L,mode:oe||"default",path:{cwd:fe,root:fe},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:u,animationSettled:!1,streaming:!0},parts:_},se=[...g,Q],Z=new Map(m.messages);if(Z.set(e,se),vs(e,n,se.length-1),u==="assistant"){S.messageStreamStates=Rn(m.messageStreamStates,n);const ce=Tt(S.streamingMessageIds??m.streamingMessageIds,e,n);ce!==(S.streamingMessageIds??m.streamingMessageIds)&&(S.streamingMessageIds=ce,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:Z,pendingAssistantParts:j,...S})}else{const T=g[k],_=Ln(T.parts,o),$=_!==-1?T.parts[_]:void 0,U=Wr(o,$);U.type==="tool"&&typeof $?.id=="string"&&$.id.length>0&&(U.id=$.id),window.__messageTracker?.(n,`part_type:${U.type||"unknown"}`);const E={...T};_!==-1?E.parts=E.parts.map((z,W)=>W===_?U:z):E.parts=[...E.parts,U];const j=[...g];j[k]=E;const L=new Map(m.messages);if(L.set(e,j),E.info.role==="assistant"){S.messageStreamStates=Rn(m.messageStreamStates,n);const z=Tt(S.streamingMessageIds??m.streamingMessageIds,e,n);z!==(S.streamingMessageIds??m.streamingMessageIds)&&(S.streamingMessageIds=z,window.__messageTracker?.(n,"streamingId_set"))}return U.type==="text"?b(U.text||""):b(""),v({messages:L,...S})}})},addStreamingPart:(e,n,o,s,i)=>{if(!Hm(o)){r()._addStreamingPartImmediate(e,n,o,s,i);return}_m({sessionId:e,messageId:n,part:o,role:s,currentSessionId:i});const a=()=>{Ns(r()._addStreamingPartImmediate)};if(Ue.length>=Cm){a();return}Fm(a)},_applyPartDeltaImmediate:(e,n,o,s,i,a,l)=>{t(c=>{const d=c.messages.get(e)||[],u=Qt(e,n,d);if(u===-1)return c;const f=d[u],m=f.parts.findIndex(k=>k?.id===o);if(m===-1)return c;const p=f.parts[m],g=p[s],S=`${typeof g=="string"?g:""}${i}`,h={...p,[s]:S},v=[...f.parts];v[m]=h;const b={...f,parts:v},D=[...d];D[u]=b;const I=new Map(c.messages);I.set(e,D);const M=a==="user"||b.info.role==="user"?"user":a||b.info.role||"assistant",C={messages:I};if(ma()&&M==="assistant")try{const k=Ct(p),T=Ct(h);console.info("[STREAM-TRACE] delta_apply",{messageId:n,partId:o,field:s,deltaLen:i.length,prevFieldLen:typeof g=="string"?g.length:0,nextFieldLen:S.length,prevTextLen:k.length,nextTextLen:T.length,partType:typeof p.type=="string"?p.type:"unknown"})}catch{}if(M==="assistant"){C.messageStreamStates=Rn(c.messageStreamStates,n);const k=l||e,T=Tt(c.streamingMessageIds,e,n);if(T!==c.streamingMessageIds&&(C.streamingMessageIds=T),k!==e){const _=c.sessionMemoryState.get(e);if(_){const $=Date.now(),U=new Map(c.sessionMemoryState);U.set(e,{..._,isStreaming:!0,streamStartTime:_.streamStartTime??$,lastAccessedAt:$,isZombie:!1}),C.sessionMemoryState=U}}}return C})},applyPartDelta:(e,n,o,s,i,a,l)=>{if(!Wm(r().messages,e,n,o)){r()._applyPartDeltaImmediate(e,n,o,s,i,a,l);return}Nm({sessionId:e,messageId:n,partId:o,field:s,delta:i,role:a,currentSessionId:l});const c=()=>{$s(r()._applyPartDeltaImmediate)};if(Be.length>=Em){c();return}zm(c)},forceCompleteMessage:(e,n,o="timeout")=>{const s=i=>{if(e)return e;const a=i.messageSessionIndex.get(n);if(a)return a;for(const[l,c]of i.messages.entries())if(c.some(d=>d.info.id===n))return l;return null};t(i=>{const a=s(i);if(!a)return i;const l=i.messages.get(a)??[],c=Qt(a,n,l);if(c===-1)return i;const d=l[c];if(!d)return i;const u=Date.now(),f=d.info,m=typeof f?.time?.completed=="number"&&f.time.completed>0;let p=!1;const g={...f};m||(g.time={...f.time??{},completed:u},p=!0),g.status!=="completed"&&(g.status="completed",p=!0),g.streaming&&(g.streaming=!1,p=!0);let S=!1;const h=d.parts.map(I=>{if(!I)return I;if(I.type==="tool"){const M=I.state;if(!M)return I;const C=M.status,k=C==="running"||C==="pending"||C==="started",T=!M.time||typeof M.time?.end!="number";if(k||T){const _={...M};return k&&(_.status="completed"),T&&(_.time={...M.time??{},end:u}),S=!0,{...I,state:_}}return I}if(I.type==="reasoning"){const M=I.time;return!M||typeof M.end!="number"?(S=!0,{...I,time:{...M??{},end:u}}):I}if(I.type==="text"){const M=I.time;return M&&typeof M.end!="number"?(S=!0,{...I,time:{...M,end:u}}):I}return I});if(!p&&!S)return i;window.__messageTracker?.(n,`force_complete:${o}`);const v={...d,info:g,parts:S?h:d.parts},b=[...l];b[c]=v;const D=new Map(i.messages);return D.set(a,b),{messages:D}})},markMessageStreamSettled:e=>{t(n=>{Bc(e);const o=new Map(n.messageStreamStates);o.delete(e);let s=n.messages,i=!1;const a=n.messageSessionIndex.get(e),l=a?[a,...Array.from(n.messages.keys()).filter(d=>d!==a)]:Array.from(n.messages.keys());for(const d of l){const u=n.messages.get(d);if(!u)continue;const f=Qt(d,e,u);if(f===-1)continue;const m=u[f];if(m.info?.animationSettled)break;const p={...m,info:{...m.info,animationSettled:!0}},g=[...u];g[f]=p;const S=new Map(n.messages);S.set(d,g),s=S,i=!0;break}return{messageStreamStates:o,...i?{messages:s}:{}}}),Hr([e])},updateMessageInfo:(e,n,o)=>{t(a=>{const c=[...a.messages.get(e)??[]],d=Qt(e,n,c),u=a.pendingAssistantParts.get(n),f=I=>I&&Jn(I);if(d===-1){if(c.length>0){const E=c[0]?.info,j=typeof E?.time?.created=="number"?E.time.created:null,L=typeof E?.id=="string"?E.id:null,z=o,W=typeof z?.time?.created=="number"?z.time.created:null,fe=typeof z?.id=="string"?z.id:n;let re=!1;if(W!==null&&j!==null&&(re=W<j),!re&&fe&&L&&(re=fe.localeCompare(L)<0),re)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const I=f(o);if(I&&I.role==="user"){const U=u?.parts??[],E=a.pendingUserMessageMetaBySession.get(e),j={info:{...I,userMessageMarker:!0,clientRole:"user",...E?.mode?{mode:E.mode}:{},...E?.providerID?{providerID:E.providerID}:{},...E?.modelID?{modelID:E.modelID}:{}},parts:U.length>0?[...U]:[]},L=new Map(a.messages),z=[...c,j];z.sort((re,Ae)=>{const oe=re.info?.time?.created||0,ut=Ae.info?.time?.created||0;return oe-ut}),L.set(e,z),$n(e,z);const W={messages:L,...E?{pendingUserMessageMetaBySession:ua(a.pendingUserMessageMetaBySession,e)}:{}},fe=Gr(W.messageSessionIndex??a.messageSessionIndex,n,e);if(fe!==(W.messageSessionIndex??a.messageSessionIndex)&&(W.messageSessionIndex=fe),u){const re=new Map(a.pendingAssistantParts);re.delete(n),W.pendingAssistantParts=re}return W}if(!I||I.role!=="assistant")return a;const M=u?.parts??[],C={info:{...I,animationSettled:I?.animationSettled??!1},parts:M.length>0?[...M]:[]},k=new Map(a.messages),T=[...c,C];k.set(e,T),vs(e,n,T.length-1);const _={messages:k},$=Gr(_.messageSessionIndex??a.messageSessionIndex,n,e);if($!==(_.messageSessionIndex??a.messageSessionIndex)&&(_.messageSessionIndex=$),u){const U=new Map(a.pendingAssistantParts);U.delete(n),_.pendingAssistantParts=U}return _}const m=c[d],p=m.info;if(p.userMessageMarker===!0||p.clientRole==="user"||p.role==="user"){const I={...m.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:p.providerID||void 0,modelID:p.modelID||void 0},M=a.pendingUserMessageMetaBySession.get(e);M&&!I.mode&&M.mode&&(I.mode=M.mode);const C={...m,info:I},k=new Map(a.messages),T=[...c];if(T[d]=C,k.set(e,T),M){const _=new Map(a.pendingUserMessageMetaBySession);return _.delete(e),{messages:k,pendingUserMessageMetaBySession:_}}return{messages:k}}const S={...m.info,...o};o.role&&o.role!==m.info.role&&(S.role=m.info.role),S.clientRole=S.clientRole??m.info.clientRole??m.info.role,S.clientRole==="user"&&(S.userMessageMarker=!0);const h={...m,info:S,parts:m.parts},v=new Map(a.messages),b=[...c];b[d]=h,v.set(e,b);const D={messages:v};if(u){const I=new Map(a.pendingAssistantParts);I.delete(n),D.pendingAssistantParts=I}return D});const s=o?.finish,i=o?.role;typeof s=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(e,n)},0)},completeStreamingMessage:(e,n)=>{Om(r()._addStreamingPartImmediate,e,n),Um(r()._applyPartDeltaImmediate,e,n);const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(e)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(e,n,"cooldown");const s=o.streamingMessageIds.get(e)===n;s?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(s&&(i.streamingMessageIds=Tt(o.streamingMessageIds,e,null),i.abortControllers=(()=>{const l=new Map(o.abortControllers);return l.delete(e),l})()),o.messageStreamStates.has(n)){const l=new Map(o.messageStreamStates);l.delete(n),i.messageStreamStates=l}Object.keys(i).length>0&&t(i),o.pendingAssistantParts.has(n)&&t(l=>{if(!l.pendingAssistantParts.has(n))return l;const c=new Map(l.pendingAssistantParts);return c.delete(n),{pendingAssistantParts:c}}),Hr([n]);let a=!1;if(t(l=>{const c=l.sessionMemoryState.get(e);if(!c||!c.isStreaming)return l;const d=new Map(l.sessionMemoryState),u=Date.now(),f={...c,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:u,streamingCooldownUntil:u+2e3};return d.set(e,f),a=!0,{sessionMemoryState:d}}),a){const l=hr.get(e);l&&(clearTimeout(l),hr.delete(e));const c=setTimeout(()=>{t(d=>{const u=d.sessionMemoryState.get(e);if(!u||u.isStreaming)return d;const f=new Map(d.sessionMemoryState),{streamingCooldownUntil:m,...p}=u;return f.set(e,p),{sessionMemoryState:f}}),hr.delete(e)},2e3);hr.set(e,c)}},syncMessages:(e,n,o)=>{Rm(r()._addStreamingPartImmediate,e),$m(r()._applyPartDeltaImmediate,e);const s=wa(e),a=da(n,s),l=o?.replace===!0;t(c=>{const d=new Map(c.messages),u=c.messages.get(e)||[],f=a.map(C=>{const k={...Jn(C.info),animationSettled:C.info.role==="assistant"?C.info?.animationSettled??!0:C.info?.animationSettled},T=(Array.isArray(C.parts)?C.parts:[]).map(_=>{if(_?.type==="text"){const $=_.text??_.content??"";if(Qo($))return{..._,synthetic:!0}}return _});return{...C,info:k,parts:T}}),m=new Set(f.map(C=>C?.info?.id).filter(C=>typeof C=="string"&&C.length>0)),p=l?[]:u.filter(C=>{const k=C?.info?.id;return typeof k=="string"&&k.length>0?!m.has(k):!0}),g=ya([...p,...f]).sort(pa),S=new Set(u.map(C=>C.info.id)),h=new Set(g.map(C=>C.info.id)),v=[];S.forEach(C=>{h.has(C)||v.push(C)}),d.set(e,g),$n(e,g);const b={messages:d,isSyncing:!0};Hr(v);const D=Yo(c.messageStreamStates,v);if(D!==c.messageStreamStates&&(b.messageStreamStates=D),v.length>0){const C=c.streamingMessageIds.get(e);C&&v.includes(C)&&(b.streamingMessageIds=Tt(b.streamingMessageIds??c.streamingMessageIds,e,null))}if(v.length>0){const C=ha(b.messageSessionIndex??c.messageSessionIndex,v);C!==(b.messageSessionIndex??c.messageSessionIndex)&&(b.messageSessionIndex=C)}if(v.length>0){const C=new Map(c.pendingAssistantParts);let k=!1;v.forEach(T=>{C.delete(T)&&(k=!0)}),k&&(b.pendingAssistantParts=C)}const I=b.messageSessionIndex??c.messageSessionIndex;let M=I;return g.forEach(C=>{const k=C?.info?.id;typeof k=="string"&&k.length>0&&(M=Gr(M,k,e))}),M!==I&&(b.messageSessionIndex=M),b}),setTimeout(()=>{t({isSyncing:!1})},100)},updateSessionCompaction:(e,n)=>{t(o=>{const s=new Map(o.sessionCompactionUntil);if(!n||n<=0)return s.has(e)?(s.delete(e),{sessionCompactionUntil:s}):o;const i=n+km;return s.get(e)===i?o:(s.set(e,i),{sessionCompactionUntil:s})})},acknowledgeSessionAbort:e=>{e&&t(n=>{const o=n.sessionAbortFlags.get(e);if(!o||o.acknowledged)return n;const s=new Map(n.sessionAbortFlags);return s.set(e,{...o,acknowledged:!0}),{sessionAbortFlags:s}})},updateViewportAnchor:(e,n)=>{t(o=>{const s=o.sessionMemoryState.get(e)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(s.viewportAnchor===n)return o;const i=new Map(o.sessionMemoryState);return i.set(e,{...s,viewportAnchor:n}),{sessionMemoryState:i}})},loadMoreMessages:async(e,n="up")=>{const o=r(),s=o.messages.get(e),i=o.sessionMemoryState.get(e),a=o.sessionHistoryMeta.get(e);if(!s||!i||a?.loading||a?.complete)return;const l=aa(),c=a?.limit??l.HISTORICAL_MESSAGES,d=n==="up"?c+l.HISTORY_CHUNK:c;d<=c||await r().loadMessages(e,d)},getLastMessageModel:e=>{const{messages:n}=r(),o=n.get(e);if(!o||o.length===0)return null;for(let s=o.length-1;s>=0;s--){const i=o[s];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:rt(()=>ye()),partialize:t=>({lastUsedProvider:t.lastUsedProvider,sessionMemoryState:Array.from(t.sessionMemoryState.entries()).map(([r,e])=>[r,{viewportAnchor:e.viewportAnchor,lastAccessedAt:e.lastAccessedAt,totalAvailableMessages:e.totalAvailableMessages,loadedTurnCount:e.loadedTurnCount,hasMoreAbove:e.hasMoreAbove,hasMoreTurnsAbove:e.hasMoreTurnsAbove,historyLoading:e.historyLoading,historyComplete:e.historyComplete,historyLimit:e.historyLimit}]),sessionAbortFlags:Array.from(t.sessionAbortFlags.entries()).map(([r,e])=>[r,{timestamp:e.timestamp,acknowledged:e.acknowledged}])}),merge:(t,r)=>{if(!t)return r;let e=r.sessionMemoryState;Array.isArray(t.sessionMemoryState)&&(e=new Map(t.sessionMemoryState.map(o=>{const[s,i]=o;return[s,{...i,isStreaming:!1,backgroundMessageCount:typeof i.backgroundMessageCount=="number"?i.backgroundMessageCount:0,hasMoreAbove:void 0,hasMoreTurnsAbove:void 0,historyComplete:void 0,historyLimit:void 0,historyLoading:!1}]})));let n=r.sessionAbortFlags;return Array.isArray(t.sessionAbortFlags)&&(n=new Map(t.sessionAbortFlags)),{...r,lastUsedProvider:t.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:e,sessionAbortFlags:n}}}),{name:"message-store"})),Zo=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(/\/+$/g,""):e},Ma=t=>typeof t=="object"&&t!==null,Xm=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(e=>{if(!Array.isArray(e)||e.length!==2)return;const[n,o]=e;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},Wc=async(t,r)=>{try{const n=q.getState().getDirectoryForSession(t);if(n)return O.withDirectory(n,r);console.warn("Permission handling: session directory not resolved, proceeding without directory context:",{sessionId:t})}catch(e){console.warn("Failed to resolve session directory for permission handling:",{sessionId:t,error:e})}return r()},Zm=(t,r)=>{const e=new Map;for(const i of r)e.set(i.id,i);const n=[],o=new Set;let s=t;for(;s&&!o.has(s);)o.add(s),n.push(s),s=e.get(s)?.parentID;return n},Gc=(t,r,e)=>{for(const n of Zm(e,r))if(n in t)return t[n]===!0;return!1},qc=(t,r)=>{if(!t?.sessionID)return!1;const n=q.getState().sessions;return Gc(r,n,t.sessionID)},eg=t=>{const r=q.getState(),e=new Set,n=Zo(t);n&&e.add(n);const o=Zo(O.getDirectory());o&&e.add(o);for(const s of r.sessions){const i=Zo(s.directory);i&&e.add(i)}return Array.from(e)},tg=async(t,r)=>{const e=eg(r);if(e.length===0)return;const n=await O.listPendingPermissions({directories:e});if(n.length!==0){for(const o of n)if(!(!o?.sessionID||!o?.id)&&qc(o,t))try{await Wc(o.sessionID,()=>O.replyToPermission(o.id,"once"))}catch{}}},nn=Me()(ve(tt((t,r)=>({permissions:new Map,autoAccept:{},addPermission:e=>{const n=e.sessionID;if(!(!n||r().permissions.get(n)?.some(s=>s.id===e.id))){if(qc(e,r().autoAccept)){r().respondToPermission(n,e.id,"once").catch(()=>{});return}t(s=>{const i=s.permissions.get(n)||[],a=new Map(s.permissions);return a.set(n,[...i,e]),{permissions:a}})}},respondToPermission:async(e,n,o)=>{try{if(!await Wc(e,()=>O.replyToPermission(n,o)))throw console.error("Permission response rejected by server:",{sessionId:e,requestId:n,response:o}),new Error("Server rejected permission response");o==="reject"&&await ee.getState().abortCurrentOperation(e),t(i=>{const l=(i.permissions.get(e)||[]).filter(d=>d.id!==n),c=new Map(i.permissions);return c.set(e,l),{permissions:c}})}catch(s){throw console.error("Permission response failed:",{sessionId:e,requestId:n,response:o,error:s instanceof Error?s.message:s}),s}},dismissPermission:(e,n)=>{t(o=>{const i=(o.permissions.get(e)||[]).filter(l=>l.id!==n),a=new Map(o.permissions);return a.set(e,i),{permissions:a}})},isSessionAutoAccepting:e=>{if(!e)return!1;const n=q.getState().sessions;return Gc(r().autoAccept,n,e)},setSessionAutoAccept:async(e,n)=>{if(!e||(t(s=>({autoAccept:{...s.autoAccept,[e]:n}})),!n))return;const o=q.getState().getDirectoryForSession(e);tg(r().autoAccept,o)}}),{name:"permission-store",storage:rt(()=>ye()),partialize:t=>({permissions:Array.from(t.permissions.entries()),autoAccept:t.autoAccept}),merge:(t,r)=>{if(!Ma(t))return r;const e=Xm(t.permissions),n=Ma(t.autoAccept)?Object.fromEntries(Object.entries(t.autoAccept).filter(o=>typeof o[0]=="string"&&typeof o[1]=="boolean")):{};return{...r,permissions:new Map(e),autoAccept:n}}}),{name:"permission-store"})),rg=t=>typeof t=="object"&&t!==null,ng=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(e=>{if(!Array.isArray(e)||e.length!==2)return;const[n,o]=e;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},va=async(t,r)=>{try{const n=q.getState().getDirectoryForSession(t);if(n)return O.withDirectory(n,r)}catch(e){console.warn("Failed to resolve session directory for question handling:",e)}return r()},wr=Me()(ve(tt((t,r)=>({questions:new Map,addQuestion:e=>{const n=e.sessionID;!n||r().questions.get(n)?.some(s=>s.id===e.id)||t(s=>{const i=s.questions.get(n)||[],a=new Map(s.questions);return a.set(n,[...i,e]),{questions:a}})},dismissQuestion:(e,n)=>{!e||!n||t(o=>{const i=(o.questions.get(e)||[]).filter(l=>l.id!==n),a=new Map(o.questions);return a.set(e,i),{questions:a}})},respondToQuestion:async(e,n,o)=>{await va(e,()=>O.replyToQuestion(n,o)),r().dismissQuestion(e,n)},rejectQuestion:async(e,n)=>{await va(e,()=>O.rejectQuestion(n)),r().dismissQuestion(e,n)}}),{name:"question-store",storage:rt(()=>ye()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!rg(t))return r;const e=ng(t.questions);return{...r,questions:new Map(e)}}}),{name:"question-store"})),Us="oc.sessions.folders",Bs="oc.sessions.folderCollapse",og=".config/openchamber/sessions-directories.json",sg=250,ig="__archived__:",er=ye();let Un=null,qr=!1,Bn=!1,Ds,Is,on=null,sn=null;const Vc=()=>typeof window>"u"?!1:nr()?!0:window.__VSCODE_CONFIG__!==void 0,Kc=()=>{const t=be.getState(),r=typeof t.homeDirectory=="string"&&t.homeDirectory.length>0?t.homeDirectory:er.getItem("homeDirectory")||"";return r?`${r.replace(/\/$/,"")}/${og}`:null},ag=t=>{const r=t.lastIndexOf("/");return r<=0?null:t.slice(0,r)},cg=(t,r)=>{if(typeof window>"u"||Vc())return;Un&&clearTimeout(Un);const e=JSON.parse(JSON.stringify(t)),n=Array.from(r);Un=setTimeout(()=>{Un=null,(async()=>{const o=Nt()?.files;if(!o?.writeFile)return;const s=Kc();if(!s)return;const i=ag(s);i&&await o.createDirectory(i).catch(()=>{});const a={version:1,foldersMap:e,collapsedFolderIds:n,updatedAt:Date.now()};await o.writeFile(s,JSON.stringify(a,null,2)).catch(()=>{})})()},sg)},lg=()=>{try{const t=er.getItem(Us);if(!t)return{};const r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))return{};const e={};for(const[n,o]of Object.entries(r)){if(!Array.isArray(o))continue;const s=[];for(const i of o){if(!i||typeof i!="object")continue;const a=i,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.name=="string"?a.name.trim():"",d=typeof a.createdAt=="number"?a.createdAt:0;if(!l||!c)continue;const u=Array.isArray(a.sessionIds)?a.sessionIds.filter(m=>typeof m=="string"&&m.trim().length>0):[],f=typeof a.parentId=="string"?a.parentId:null;s.push({id:l,name:c,sessionIds:u,createdAt:d,parentId:f})}s.length>0&&(e[n]=s)}return e}catch{return{}}},dg=()=>{try{const t=er.getItem(Bs);if(!t)return new Set;const r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(e=>typeof e=="string")):new Set}catch{return new Set}},Jc=t=>{on=t,clearTimeout(Ds),Ds=setTimeout(()=>{try{er.setItem(Us,JSON.stringify(t)),on=null}catch{}},300)},Qc=t=>{sn=t,clearTimeout(Is),Is=setTimeout(()=>{try{er.setItem(Bs,JSON.stringify(Array.from(t))),sn=null}catch{}},300)};typeof window<"u"&&window.addEventListener("beforeunload",()=>{if(on!==null){clearTimeout(Ds);try{er.setItem(Us,JSON.stringify(on))}catch{}on=null}if(sn!==null){clearTimeout(Is);try{er.setItem(Bs,JSON.stringify(Array.from(sn)))}catch{}sn=null}});const Lt=(t,r)=>{Jc(t),Qc(r),cg(t,r)},ug=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,es=(t,r,e)=>{const n=new Set(r.map(s=>s.id));let o=null;for(const s of t)!n.has(s.id)&&e.has(s.id)&&(o||(o=new Set(e)),o.delete(s.id));return o},fg=(t,r)=>t.startsWith(ig)?r.filter(e=>e.sessionIds.length>0):r,As=Me()(ve((t,r)=>({foldersMap:lg(),collapsedFolderIds:dg(),getFoldersForScope:e=>e?r().foldersMap[e]??[]:[],createFolder:(e,n,o)=>{const s=n.trim()||"New folder",i={id:ug(),name:s,sessionIds:[],createdAt:Date.now(),parentId:o??null},a=r().foldersMap,l=a[e]??[],c={...a,[e]:[...l,i]};return t({foldersMap:c}),Lt(c,r().collapsedFolderIds),i},renameFolder:(e,n,o)=>{const s=o.trim();if(!s||!e)return;const i=r().foldersMap,a=i[e];if(!a)return;const l=a.map(d=>d.id===n?{...d,name:s}:d),c={...i,[e]:l};t({foldersMap:c}),Lt(c,r().collapsedFolderIds)},deleteFolder:(e,n)=>{if(!e)return;const o=r().foldersMap,s=o[e];if(!s)return;const i=new Set([n]);let a=!0;for(;a;){a=!1;for(const f of s)f.parentId&&i.has(f.parentId)&&!i.has(f.id)&&(i.add(f.id),a=!0)}const l=s.filter(f=>!i.has(f.id)),c={...o,[e]:l};t({foldersMap:c}),Lt(c,r().collapsedFolderIds);const d=r().collapsedFolderIds;if(Array.from(i).some(f=>d.has(f))){const f=new Set(d);i.forEach(m=>f.delete(m)),t({collapsedFolderIds:f}),Lt(c,f)}},addSessionToFolder:(e,n,o)=>{if(!e||!n||!o)return;const s=r().foldersMap,i=s[e];if(!i)return;const a=i.map(d=>{const u=d.sessionIds.filter(f=>f!==o);return d.id===n?{...d,sessionIds:[...u,o]}:u.length!==d.sessionIds.length?{...d,sessionIds:u}:d}),l={...s,[e]:a},c=es(i,a,r().collapsedFolderIds);t(c?{foldersMap:l,collapsedFolderIds:c}:{foldersMap:l}),Lt(l,c??r().collapsedFolderIds)},removeSessionFromFolder:(e,n)=>{if(!e||!n)return;const o=r().foldersMap,s=o[e];if(!s)return;let i=!1;const a=s.map(d=>{const u=d.sessionIds.filter(f=>f!==n);return u.length!==d.sessionIds.length?(i=!0,{...d,sessionIds:u}):d});if(!i)return;const l={...o,[e]:a},c=es(s,a,r().collapsedFolderIds);t(c?{foldersMap:l,collapsedFolderIds:c}:{foldersMap:l}),Lt(l,c??r().collapsedFolderIds)},toggleFolderCollapse:e=>{const n=r().collapsedFolderIds,o=new Set(n);o.has(e)?o.delete(e):o.add(e),t({collapsedFolderIds:o}),Lt(r().foldersMap,o)},cleanupSessions:(e,n)=>{if(!e)return;const o=r().foldersMap,s=o[e];if(!s||s.length===0)return;let i=!1;const a=s.map(u=>{const f=u.sessionIds.filter(m=>n.has(m));return f.length!==u.sessionIds.length?(i=!0,{...u,sessionIds:f}):u}),l=fg(e,a);if(l.length!==a.length&&(i=!0),!i)return;const c={...o,[e]:l},d=es(s,l,r().collapsedFolderIds);t(d?{foldersMap:c,collapsedFolderIds:d}:{foldersMap:c}),Lt(c,d??r().collapsedFolderIds)},getSessionFolderId:(e,n)=>{if(!e||!n)return null;const o=r().foldersMap[e];if(!o)return null;for(const s of o)if(s.sessionIds.includes(n))return s.id;return null}}),{name:"session-folders-store"})),pg=async()=>{if(qr||Bn||typeof window>"u")return;if(Vc()){qr=!0;return}const t=Nt()?.files;if(!t?.readFile)return;const r=Kc();if(!r)return;Bn=!0;const e=await t.readFile(r).catch(()=>null);if(!e?.content){Bn=!1,qr=!0;return}try{const n=JSON.parse(e.content),o=n?.foldersMap&&typeof n.foldersMap=="object"?n.foldersMap:{},s=Array.isArray(n?.collapsedFolderIds)?new Set(n.collapsedFolderIds.filter(a=>typeof a=="string")):new Set;if(!(Object.keys(o).length>0||s.size>0))return;As.setState({foldersMap:o,collapsedFolderIds:s}),Jc(o),Qc(s)}catch{}finally{Bn=!1,qr=!0}},mg=()=>{if(typeof window>"u")return;let t=0;const r=20,e=()=>{t+=1,pg(),!(qr||t>=r)&&setTimeout(e,500)};e()};mg();const vr=new Map,Da=t=>{vr.set(t,(vr.get(t)??0)+1)},Py=t=>(vr.get(t)??0)>0,Ty=t=>{const r=vr.get(t)??0;return r<=0?!1:(r===1?vr.delete(t):vr.set(t,r-1),!0)},gg=t=>t.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
45
|
+
`).replace(/\n\s*\n+/g,`
|
|
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
|
+
`).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"&>.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};
|