@openchambery/web 1.18.2-beta.39 → 1.18.2-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/assets/{AgentAvatar-SFzXgOdv.js → AgentAvatar-OmE7AspO.js} +1 -1
  2. package/dist/assets/{AssistantView-CvYXAhVR.js → AssistantView-1qhaLhHt.js} +1 -1
  3. package/dist/assets/{ChatContainer-Be1DHzgc.js → ChatContainer-CEXwPvOE.js} +4 -4
  4. package/dist/assets/{DiagramView-D0COpV7w.js → DiagramView-zedL3sNZ.js} +1 -1
  5. package/dist/assets/{FadeInOnReveal-9uJN0g-H.js → FadeInOnReveal-EygBOzfu.js} +1 -1
  6. package/dist/assets/{Icon-CBdklpKH.js → Icon-C0dydAmx.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-DzZY5lYZ.js → MarkdownRendererImpl-CbBKHgg_.js} +1 -1
  8. package/dist/assets/{MobileDetailNavigation-DnkLVrVy.js → MobileDetailNavigation-BuGHMy3o.js} +1 -1
  9. package/dist/assets/{MobileShareBridge-C_m49-E6.js → MobileShareBridge-DwJRFCl2.js} +2 -2
  10. package/dist/assets/{MobileSurface-DPBYd_9L.js → MobileSurface-BBWgxzyI.js} +1 -1
  11. package/dist/assets/{MultiRunWindow-DPm1lQmo.js → MultiRunWindow-DJu-y4fb.js} +1 -1
  12. package/dist/assets/{OnboardingScreen-C1kAHsU9.js → OnboardingScreen-Ck8vLrCb.js} +1 -1
  13. package/dist/assets/{OverlayScrollbar-iaMCjwrs.js → OverlayScrollbar-DMQhwzR3.js} +1 -1
  14. package/dist/assets/{SettingsView-jKwiCthd.js → SettingsView-BzZTiaDd.js} +1 -1
  15. package/dist/assets/{SettingsWindow-YVW1K0vh.js → SettingsWindow-Biji-Bb4.js} +1 -1
  16. package/dist/assets/{TerminalView-CiyuM0im.js → TerminalView-BKCM76aM.js} +1 -1
  17. package/dist/assets/{ToolOutputDialog-DMHFrQtf.js → ToolOutputDialog-6lL_lCmU.js} +1 -1
  18. package/dist/assets/{appThemeRegistry-CBs9rFM0.js → appThemeRegistry-DUeCYxWD.js} +2 -2
  19. package/dist/assets/{button-DimCg1lF.js → button-Iv9uULki.js} +1 -1
  20. package/dist/assets/{clipboard-mzqrY_n2.js → clipboard-DH0BvKYH.js} +1 -1
  21. package/dist/assets/{collapsible-CF7TDu-T.js → collapsible-C46kU7ea.js} +1 -1
  22. package/dist/assets/{context-menu-ZC-7T9D6.js → context-menu-BWKM1gKq.js} +1 -1
  23. package/dist/assets/{desktopHosts-Tqz56Y0u.js → desktopHosts-DV_01iQq.js} +1 -1
  24. package/dist/assets/{desktopRelayRestore-DgHC01I5.js → desktopRelayRestore-DhQzRu4d.js} +1 -1
  25. package/dist/assets/{diagram-DObb9lfm.js → diagram-CqOdzPLy.js} +1 -1
  26. package/dist/assets/{dialog-DDrJKIhd.js → dialog-BPXCMWcj.js} +1 -1
  27. package/dist/assets/{fileQueries-BjL2dHDF.js → fileQueries-EAHC6GsF.js} +1 -1
  28. package/dist/assets/{gitApi-CdLpItUF.js → gitApi-4LIdr-v1.js} +1 -1
  29. package/dist/assets/{input-BNj7D6h_.js → input-7arjRNdx.js} +1 -1
  30. package/dist/assets/{insertionBoundaries-Dx-FimZn.js → insertionBoundaries-Dbq-aDBu.js} +1 -1
  31. package/dist/assets/{main-B2Qp731c.js → main-C-5guI2W.js} +2 -2
  32. package/dist/assets/{main-Dq04PAJw.js → main-CyVIqNNp.js} +4 -4
  33. package/dist/assets/{markdown-worker-CJ8ooXEK.js → markdown-worker-sIoCa792.js} +1 -1
  34. package/dist/assets/{markdownTheme-CziN3c9i.js → markdownTheme-QtXMKzKz.js} +1 -1
  35. package/dist/assets/{miniChat-XD8besP9.js → miniChat-DjAmMQNF.js} +2 -2
  36. package/dist/assets/mobile-B72TTAxF.js +2 -0
  37. package/dist/assets/{multirun-CgKdqjlp.js → multirun-hsF95duc.js} +1 -1
  38. package/dist/assets/{persistence-ZSrLIR97.js → persistence-Cm9DnxXq.js} +1 -1
  39. package/dist/assets/{platform-BiSk9jV3.js → platform-BrOZ1tqx.js} +1 -1
  40. package/dist/assets/{projectMeta-jWxWbDkQ.js → projectMeta-r5NAkHfX.js} +1 -1
  41. package/dist/assets/{radio-BArg8rN7.js → radio-G_YvD3ft.js} +1 -1
  42. package/dist/assets/{renderElectronMiniChatApp-CcHll5HJ.js → renderElectronMiniChatApp-YPzmrpPR.js} +2 -2
  43. package/dist/assets/{renderMobileApp-z9BLmg-1.js → renderMobileApp-CIKcbD89.js} +4 -4
  44. package/dist/assets/{runtimeConfig-o7VOqbIv.js → runtimeConfig-EBmDM9YF.js} +1 -1
  45. package/dist/assets/{runtimeEndpointReset-ZQl4KUPA.js → runtimeEndpointReset-m802uRQ1.js} +1 -1
  46. package/dist/assets/{sortable-tabs-strip-CBs61Gj9.js → sortable-tabs-strip-OO0ijdmq.js} +1 -1
  47. package/dist/assets/{terminalApi-CkknnXhV.js → terminalApi-BunCJZ0A.js} +1 -1
  48. package/dist/assets/{tooltip-BE6WDmtb.js → tooltip-CO8qCWXw.js} +1 -1
  49. package/dist/assets/{url-DQDmlZku.js → url-CM2fyKko.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BnAqVzvs.js → useAppFontEffects-BApC_Nk8.js} +2 -2
  51. package/dist/assets/{useAssistantUIStore-Bq3cPj2x.js → useAssistantUIStore-B9YvQgXU.js} +1 -1
  52. package/dist/assets/{useDesktopWindowControlsLayout-DW06JgtH.js → useDesktopWindowControlsLayout-CPOQ6w0N.js} +1 -1
  53. package/dist/assets/{useEffectiveDirectory-Cxk960zS.js → useEffectiveDirectory-Bc-cEAh0.js} +1 -1
  54. package/dist/assets/{useFontPreferences-ZvBF445N.js → useFontPreferences-DKIVD8RE.js} +1 -1
  55. package/dist/assets/{useMobileNavigationStore-7SQlIaRN.js → useMobileNavigationStore-f5hodHkc.js} +2 -2
  56. package/dist/assets/{useSessionAutoCleanup-fCB4vS1c.js → useSessionAutoCleanup-EKU0ZYhf.js} +1 -1
  57. package/dist/assets/{useUIStore-5agS8bsW.js → useUIStore-CL06MzOk.js} +1 -1
  58. package/dist/assets/{useWorkerHighlightedLines-Dur8-7lm.js → useWorkerHighlightedLines-DBz6RbGf.js} +1 -1
  59. package/dist/assets/{utils-Dh7UZFrA.js → utils-DlvuQ5yV.js} +1 -1
  60. package/dist/index.html +8 -8
  61. package/dist/mini-chat.html +8 -8
  62. package/dist/mobile.html +8 -8
  63. package/package.json +1 -1
  64. package/dist/assets/mobile-B-urUzQ2.js +0 -2
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CUPf3g2A.js","assets/rolldown-runtime-C0FnF6B9.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,D as n,E as r,F as i,H as a,T as o,X as s,b as c,et as l,j as u,nt as d}from"./useUIStore-5agS8bsW.js";import{$t as f,Mt as p,Pt as m,Xt as h,kn as g,nt as ee,ot as te,pt as ne,r as _,st as v,xn as re,zt as ie}from"./persistence-ZSrLIR97.js";import{a as ae,r as oe}from"./vendor-zustand-B4dlGEM2.js";import{t as se}from"./vendor-opencode-sdk-C07HQypa.js";import{i as ce}from"./vendor-pathe-vBmvQE8f.js";import{o as le}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";var ue=(e,t)=>e!==t,de=new Set([`image/heic`,`image/heif`]),fe=!1,pe=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},me=e=>de.has((e.type||``).toLowerCase()),he=async e=>{let t=new Uint8Array(await e.arrayBuffer()),n=``,r=32768;for(let e=0;e<t.byteLength;e+=r){let i=t.subarray(e,Math.min(e+r,t.byteLength));n+=String.fromCharCode(...i)}return btoa(n)},ge=(e,t)=>{let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new Blob([r],{type:t})},_e=async e=>{if(!me(e)||fe)return null;let t=pe();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.OpenChamberMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await he(e),mime:e.type.toLowerCase(),quality:.9});if(typeof t?.data!=`string`||!t.data)return null;let r=typeof t.mime==`string`&&t.mime?t.mime:`image/jpeg`;return ge(t.data,r)}catch(e){return fe=!0,console.warn(`Native HEIC transcode failed`,e),null}},ve=e=>e.trim().toLowerCase(),ye=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,be=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(ve)),r=[],i=0;for(;i<e.length;){let t=e.indexOf(`[`,i);if(t===-1)break;let a=e.indexOf(`]`,t+1);if(a===-1)break;if(e[a+1]!==`(`){let i=ne(e.slice(t+1,a)).trim();n.has(ve(i))&&r.push({start:t,end:a+1})}i=a+1}return r},xe=(e,t)=>{let n=t.start,r=t.end;return r<e.length&&/\s/.test(e[r])?r+=1:n>0&&/\s/.test(e[n-1])&&--n,{start:n,end:r}},Se=(e,t,n,r)=>{let i=be(e,t);if(i.length===0)return{text:e,mentions:[...n],composerReferences:r===void 0?void 0:[...r],changed:!1};let a=e,o=[...n],s=r===void 0?[]:[...r];for(let e=i.length-1;e>=0;--e){let{start:t,end:n}=xe(a,i[e]),r=n-t;a=`${a.slice(0,t)}${a.slice(n)}`,o=o.flatMap(e=>e.range.end<=t?[e]:e.range.start>=n?[{...e,range:{start:e.range.start-r,end:e.range.end-r}}]:[]),s=s.flatMap(e=>e.end<=t?[e]:e.start>=n?[{...e,start:e.start-r,end:e.end-r}]:[])}return{text:a,mentions:o,composerReferences:r===void 0?void 0:s,changed:!0}},Ce=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),we={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/heic":`heic`,"image/heif":`heif`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/png":`png`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/webp":`webp`},y=e=>e.trim().toLowerCase(),Te=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Ee=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>Te(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},De=e=>we[e?.trim().toLowerCase()??``]??`png`,Oe=e=>{let t=Ee(e.name),n=De(e.type),r=t.lastIndexOf(`.`);if(r>0&&r<t.length-1){let e=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(e))return{base:t.slice(0,r).trim()||`image`,ext:e}}return{base:t.trim()||`image`,ext:n}},ke=e=>{let{base:t}=Oe({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(Ce.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&Ce.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},b=(e,t)=>`${e}.${t}`,Ae=(e,t,n)=>{let r=b(e,t);if(!n.has(y(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=b(`${e}-${r}`,t);if(!n.has(y(i)))return i}return b(`${e}-${Date.now()}`,t)},je=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=b(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(y(r)))return r}return b(`image-${Date.now()}`,e)},Me=(e,t)=>{let n=new Set(t.map(y));return e.map(e=>{let{base:t,ext:r}=Oe(e),i=ke(b(t,r))?je(r,n):Ae(t,r,n);return n.add(y(i)),i})},Ne=e=>e.map(e=>v(e)).join(` `),Pe=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[v(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},Fe=e=>e.replaceAll(`[${te}`,`[`),Ie=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Le=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Re=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Le(t)||!Ie.test(t)&&!Ie.test(r))continue;let i=`[${r}]`;n=n.split(v(t)).join(i).split(`[${t}]`).join(i)}return n},ze=(e,t)=>{let n=e;for(let e of t??[]){if(e.source!==`vscode`||e.vscodeSource!==`selection`||!e.vscodePath)continue;let t=e.filename.match(/:(\d+(?:-\d+)?)$/)?.[1];if(!t)continue;let r=`[${e.vscodePath}:${t}]`;n=n.split(v(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Be=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Ve=`application/x-directory`,He=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Ue=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),We=(e,t,n)=>{if(t===`Backspace`){let t=n;for(;t>0&&/\s/.test(e[t-1]);)--t;for(;t>0&&!/\s/.test(e[t-1]);)--t;return{start:t,end:n}}let r=n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;for(;r<e.length&&!/\s/.test(e[r]);)r+=1;return{start:n,end:r}},Ge=(e,t,n)=>{let r=Math.max(0,Math.min(n.selectionStart,e.length)),i=Math.max(r,Math.min(n.selectionEnd,e.length)),a;if(a=r===i?n.altKey?We(e,n.key,r):n.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(e.length,r+1)}:{start:r,end:i},a.start===a.end)return null;let o=be(e,t).filter(e=>e.start<a.end&&e.end>a.start);if(o.length===0)return null;let s=Math.min(a.start,...o.map(e=>e.start)),c=Math.max(a.end,...o.map(e=>e.end));return c<e.length&&/\s/.test(e[c])&&(s===0||/\s/.test(e[s-1]))?c+=1:c===e.length&&s>0&&/\s/.test(e[s-1])&&--s,{text:`${e.slice(0,s)}${e.slice(c)}`,caret:s,removedFilenames:o.map(t=>ne(e.slice(t.start+1,t.end-1)).trim())}},x=class extends Error{status;code;constructor(e,t,n=`Failed to upload prompt attachment`){super(n),this.name=`PromptAttachmentUploadError`,this.status=e,this.code=t}},S=`file://`,Ke=e=>{let t=e.trim();if(t.toLowerCase().startsWith(S))return t;let n=ce(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${S}/${n}`:`${S}${n}`},qe=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(S))return t;let n=t.slice(7);n.toLowerCase().startsWith(`localhost/`)&&(n=n.slice(9));let r=n.split(`/`).map(e=>{if(/^[A-Za-z]:$/.test(e))return e;try{return decodeURIComponent(e)}catch{return e}}).join(`/`);return/^\/[A-Za-z]:/.test(r)?r.slice(1):r},Je=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),Ye=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Xe=async e=>{let t;try{t=await e.json()}catch{throw new x(e.status,`unavailable`)}if(!Ye(t)||typeof t.path!=`string`||!t.path)throw new x(e.status,`unavailable`);let n=typeof t.mime==`string`&&t.mime?t.mime:`application/octet-stream`,r=typeof t.size==`number`&&Number.isSafeInteger(t.size)?t.size:0,i=typeof t.sha256==`string`?t.sha256:``;return{path:t.path,url:Ke(t.path),mime:n,size:r,sha256:i}},Ze=e=>{let t=typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n=e?.replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,32);return n?`att-${t}-${n}`:`att-${t}`},Qe=(e,t)=>{if(!e.startsWith(`data:`))return null;let n=e.indexOf(`,`);if(n===-1)return null;let r=e.slice(5,n),i=e.slice(n+1),a=r.split(`;`,1)[0]?.trim()||t||`application/octet-stream`;try{if(r.toLowerCase().includes(`;base64`)){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([t],{type:a})}return new Blob([decodeURIComponent(i)],{type:a})}catch{return null}},$e=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),et=async e=>{let t=e.mime||e.body.type||`application/octet-stream`,n=e.body.type===t?e.body:new Blob([e.body],{type:t});if(!Number.isSafeInteger(n.size)||n.size<0||n.size>26214400)throw new x(413,`too-large`);let r=await Je(n),i=Ze(e.filename),a;try{a=await g(`/api/fs/prompt-attachments/${encodeURIComponent(i)}`,{method:`PUT`,headers:{"Content-Type":t,"Content-Length":String(n.size),"X-OpenChamber-Content-Length":String(n.size),"X-OpenChamber-Sha256":r,"X-OpenChamber-Mime":t,...e.filename?{"X-OpenChamber-Filename":encodeURIComponent(e.filename)}:{}},body:n,signal:e.signal})}catch{throw new x(0,`unavailable`)}if(a.status===413)throw new x(413,`too-large`);if(!a.ok)throw new x(a.status,a.status>=500||a.status===0?`unavailable`:`rejected`);let o=await Xe(a);if(o.size!==n.size)throw new x(a.status,`unavailable`);return{...o,mime:t}},tt=500,nt=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`OPENCHAMBER_STARTUP_TRACE`)===`1`}catch{return!1}},rt=()=>nt(),C=(e,t)=>{if(!nt())return;let n=typeof performance<`u`?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>tt&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-tt)};typeof window<`u`&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var it=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();C(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return C(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw C(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},at=3,ot=3e4,st=32e3,ct=36e5,lt=6e5,ut=new Set([429,502,503,504]),w=new Map;function dt(){let e=Date.now();for(let[t,n]of w)n.consecutiveErrors===0&&e-n.lastErrorAt>ct&&w.delete(t)}typeof setInterval<`u`&&setInterval(dt,lt).unref?.();function ft(e){let t=w.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:ot},w.set(e,t)),t}function pt(e){if(!e)return;let t=w.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function mt(e,t){if(!e)return;let n=ft(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),ht(t)&&n.consecutiveErrors>=at&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function ht(e){return e!==void 0&&ut.has(e)}function gt(e){let t=w.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,st*4),!1):!0:!1}function _t(e){if(!(!e||!gt(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var vt=`/api`,yt=1e4,bt=4e3,xt=3e3,St=1e3,Ct=12e3;function T(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function E(e,t){if(e.error){let n=e.response?.status,r=Error(`${t} failed${n?` (${n})`:``}: ${T(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw Error(`${t} failed: empty response`);return e.data}function D(e,t){if(e.error){let n=e.response?.status,r=Error(`${t} failed${n?` (${n})`:``}: ${T(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}var wt=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Tt=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(wt.test(t)||typeof window>`u`)return t;let n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(e){return console.warn(`Failed to normalize OpenCode base URL:`,e),t}},Et=()=>{try{return i().api(`/api`)}catch{return null}},Dt=()=>{try{return i().api(`/`)}catch{return null}},Ot=e=>{let t=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof t?.timeout==`function`)return{signal:t.timeout(e),cleanup:()=>void 0};let n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},kt=e=>{let t=e.filter(e=>e!=null);if(t.length===0)return{signal:new AbortController().signal,cleanup:()=>void 0};if(t.length===1)return{signal:t[0],cleanup:()=>void 0};let n=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof n?.any==`function`)return{signal:n.any(t),cleanup:()=>void 0};let r=new AbortController,i=()=>r.abort();for(let e of t){if(e.aborted){r.abort();break}e.addEventListener(`abort`,i)}return{signal:r.signal,cleanup:()=>{for(let e of t)e.removeEventListener(`abort`,i)}}},O=e=>se({...e,fetch:g}),At=e=>typeof e.mime==`string`&&e.mime.startsWith(`image/`)?!0:typeof e.filename==`string`&&/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i.test(e.filename),jt=e=>{let t=[];for(let n of e){if(!At(n))continue;let e=typeof n.filename==`string`?n.filename.trim():``,r=typeof n.url==`string`?n.url:``;if(!e||!r.toLowerCase().startsWith(`file://`))continue;let i=qe(r).trim();i&&t.push({filename:e,path:i})}return t},Mt=async(e,t)=>{let n=[],r=e.files?.length?await Promise.all(e.files.map(e=>t(e))):[],i=e.additionalParts?.length?await Promise.all(e.additionalParts.map(async e=>({text:e.text,synthetic:e.synthetic,files:e.files?.length?await Promise.all(e.files.map(e=>t(e))):[]}))):[],a=e=>Re(e,jt([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files)}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},k=e=>e.replace(/\\/g,`/`),Nt=400,Pt=()=>{let e=re();return e&&e.runtime?.isDesktop&&e.files?e.files:null},A=new class{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;healthInFlight=new Map;healthCache=new Map;healthCacheGeneration=0;constructor(e=vt){let t=Et()||e;this.baseUrl=Tt(t),this.client=O({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){let e=Tt(Et()||vt);e!==this.baseUrl&&(this.baseUrl=e,this.client=O({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache())}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}getScopedApiClient(e){let t=this.normalizeCandidatePath(e)??e,n=t||``,r=this.scopedClients.get(n);if(r)return r;let i=O({baseUrl:this.baseUrl,directory:t});return this.scopedClients.set(n,i),i}normalizeCandidatePath(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return(n.length>1?n.replace(/\/+$/,``):n)||null}deriveHomeDirectory(e){let t=e.match(/^([A-Za-z]:)(?:\/|$)/);if(t){let n=t[1],r=e.slice(n.length+ +(e.charAt(n.length)===`/`)).split(`/`).filter(Boolean);return r.length>=2?{homeDirectory:`${n}/${r[0]}/${r[1]}`,username:r[1]}:r.length===1?{homeDirectory:`${n}/${r[0]}`,username:r[0]}:{homeDirectory:n,username:void 0}}let n=e.startsWith(`/`),r=e.split(`/`).filter(Boolean);return r.length>=2&&(r[0]===`Users`||r[0]===`home`)?{homeDirectory:`${n?`/`:``}${r[0]}/${r[1]}`,username:r[1]}:n?r.length===0?{homeDirectory:`/`,username:void 0}:{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:r.length>0?{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:{homeDirectory:`/`,username:void 0}}setDirectory(e){let t=this.normalizeCandidatePath(e)??e;this.currentDirectory!==t&&C(`opencodeClient:setDirectory`,{previous:this.currentDirectory??null,next:t??null}),this.currentDirectory=t}getDirectory(){return this.currentDirectory}async withDirectory(e,t){let n=async()=>{if(e==null)return t();let n=this.currentDirectory,r=this.normalizeCandidatePath(e)??e;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory===r&&(this.currentDirectory=n)}},r=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=r.then(()=>void 0,()=>void 0),r}getApiClient(){return this.client}async getSystemInfo(){let e=new Set,t=t=>{let n=this.normalizeCandidatePath(t);n&&e.add(n)};try{let e=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;e&&(t(e.directory),t(e.worktree),t(e.state))}catch{}if(!e.size)try{t((await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data?.worktree)}catch{}if(!e.size)try{(await this.listSessions()).forEach(e=>t(e.directory))}catch{}if(t(this.currentDirectory),typeof window<`u`)try{t(p(`lastDirectory`)),t(p(`homeDirectory`))}catch{}if(!e.size&&typeof process<`u`&&typeof process.cwd==`function`&&t(process.cwd()),!e.size)return{homeDirectory:`/`,username:void 0};let[n]=Array.from(e);return this.deriveHomeDirectory(n)}async probeDirectory(e){let t=this.normalizeCandidatePath(e);if(!t)return!1;try{let e=(await this.client.path.get({directory:t})).data,n=typeof e?.directory==`string`?e.directory:null;return!!(n&&n.trim().length>0)}catch{return!1}}async listSessions(){let e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return E(await this.client.session.create({...n?{directory:n}:{},parentID:e?.parentID,title:e?.title,metadata:e?.metadata}),`session.create`)}async getSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return E(await this.client.session.get({sessionID:e,...n?{directory:n}:{}}),`session.get`)}async deleteSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return D(await this.client.session.delete({sessionID:e,...n?{directory:n}:{}}),`session.delete`)===!0}async deleteSessionMessage(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory;return D(await this.client.session.deleteMessage({sessionID:e,messageID:t,...r?{directory:r}:{}}),`session.deleteMessage`)===!0}async updateSession(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory,i={...t.title===void 0?{}:{title:t.title},...t.metadata===void 0?{}:{metadata:t.metadata},...t.time?.archived!==void 0&&t.time.archived!==null?{time:{archived:t.time.archived}}:{}};return E(await this.client.session.update({sessionID:e,...r?{directory:r}:{},...i}),`session.update`)}async getSessionMessages(e,t){return E(await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof t==`number`?{limit:t}:{}}),`session.messages`)}async getSessionDiff(e,t){let n=this.normalizeCandidatePath(e.directory)??this.currentDirectory,r=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():void 0,i={sessionID:e.sessionID,...n?{directory:n}:{},...r?{messageID:r}:{}};return E(t?.signal?await this.client.session.diff(i,{signal:t.signal}):await this.client.session.diff(i),`session.diff`)}async getSessionTodos(e){try{let t=await this.client.session.todo({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(t.error)return[];let n=t.data;return!n||!Array.isArray(n)?[]:n}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`text/`)&&t!==`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(t)}isHeicMime(e){if(!e)return!1;let t=e.toLowerCase();return t===`image/heic`||t===`image/heif`}async convertHeicToJpeg(t){try{let n=Qe(t.url,t.mime);if(!n)return t;let r=await _e(n)??await(await le(async()=>{let{default:t}=await import(`./vendor-heic2any-CUPf3g2A.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e){let t=await this.normalizeFilePart(e),n=t.url;if($e(n)){let e=Qe(n,t.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${t.filename??`file`}`);n=(await et({body:e,mime:t.mime,filename:t.filename})).url}return{...e.id?{id:e.id}:{},type:`file`,mime:t.mime,filename:t.filename,url:n}}async buildMessageParts(e){return Mt(e,e=>this.toNormalizedFilePartInput(e))}async sendMessage(e){let t=e.messageId??ee(`msg`),n=await this.buildMessageParts({text:e.text,prefaceText:e.prefaceText,prefaceTextSynthetic:e.prefaceTextSynthetic,files:e.files,additionalParts:e.additionalParts,agentMentions:e.agentMentions}),r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;e.format&&(e.id,e.providerID,e.modelID,e.agent,e.variant,this.baseUrl,e.format.type),_t(e.providerID);let i;try{let a=await this.client.session.promptAsync({sessionID:e.id,...r?{directory:r}:{},model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,messageID:t,...e.delivery?{delivery:e.delivery}:{},...e.format?{format:e.format}:{},parts:n});if(a.response instanceof Response)i=a.response;else if(a.error){let e=a.response?.status;if(!e)throw Error(`Message send transport failure: ${T(a.error)}`);i=new Response(JSON.stringify(a.error),{status:e})}else i=new Response(JSON.stringify(a.data??!0),{status:200})}catch(t){throw mt(e.providerID),t}if(i.ok)return pt(e.providerID),t;let a=``;try{a=await i.text()}catch{}let o=a&&a.trim().length>0?`: ${a.trim()}`:``,s=Error(`Failed to send message (${i.status})${o}`);throw s.status=i.status,mt(e.providerID,i.status),s}async sendCommand(e){let t=e.messageId??ee(`msg`),n=[];if(e.files&&e.files.length>0)for(let t of e.files)n.push(await this.toNormalizedFilePartInput(t));let r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;return D(await this.client.session.command({sessionID:e.id,...r?{directory:r}:{},command:e.command,arguments:e.arguments??``,model:`${e.providerID}/${e.modelID}`,agent:e.agent,variant:e.variant,...n.length>0?{parts:n}:{},messageID:t}),`session.command`),t}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(e){let t=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;return E(await this.client.session.shell({sessionID:e.sessionId,...t?{directory:t}:{},messageID:e.messageId,agent:e.agent,model:e.model,command:e.command}),`session.shell`)}async revertSession(e,t,n,r){let i=this.normalizeCandidatePath(r)??this.currentDirectory;return E(await this.client.session.revert({sessionID:e,...i?{directory:i}:{},messageID:t,partID:n}),`session.revert`)}async summarizeSession(e,t,n,r){let i=this.normalizeCandidatePath(r)??this.currentDirectory;return D(await this.client.session.summarize({sessionID:e,...i?{directory:i}:{},providerID:t,modelID:n}),`session.summarize`)===!0}async unrevertSession(e){return E(await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`session.unrevert`)}async forkSession(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory,i=E(await this.client.session.fork({sessionID:e,...r?{directory:r}:{},messageID:t}),`session.fork`);return i.id,i}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e,t){try{let n=typeof e==`string`?e.trim():``,r=await this.client.session.status(n?{directory:n}:void 0,t?{signal:t}:void 0);return r.error||!r.data||typeof r.data!=`object`?null:r.data}catch{return null}}async getSessionActive(e){try{let t=await O({baseUrl:Tt(Dt()||`/`)}).v2.session.active(e?{signal:e}:void 0),n=t.response?.status;if(t.error||n!==void 0&&n!==200)return n===404||n===405||n===501?{state:`unsupported`}:{state:`unknown`};let r=t.data,i=r&&typeof r==`object`&&`data`in r&&r.data!==void 0?r.data:r;if(!i||typeof i!=`object`||Array.isArray(i))return{state:`unknown`};let a={};for(let[e,t]of Object.entries(i)){if(typeof e!=`string`||e.length===0||!t||typeof t!=`object`||t.type!==`running`)return{state:`unknown`};a[e]={type:`running`}}return{state:`supported`,membership:a}}catch{return{state:`unknown`}}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{let e=await g(`/api/session-activity`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json().catch(()=>null);return!t||typeof t!=`object`?null:t}catch{return null}}async listToolIds(e){try{let t=typeof e?.directory==`string`?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():``;return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(e=>typeof e==`string`&&e!==`invalid`)}catch{return[]}}async replyToPermission(e,t,n){let r=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory;return D(await this.client.permission.reply({requestID:e,...r?{directory:r}:{},reply:t,...n?.message?{message:n.message}:{}}),`permission.reply`)===!0}async createPermission(e,t,n,r){try{let i=await this.client.v2.session.permission.create({sessionID:e,action:t,resources:n,...r?.id?{id:r.id}:{},...r?.save?{save:r.save}:{},...r?.metadata?{metadata:r.metadata}:{},...r?.source?{source:r.source}:{},...r?.agent?{agent:r.agent}:{}});if(i.error!==void 0)return null;let a=i.data?.data;return a===void 0?null:{id:a.id,effect:a.effect}}catch{return null}}async fetchPermission(e,t){try{let n=await this.client.v2.session.permission.get({sessionID:e,requestID:t});if(n.error===void 0){let e=n.data?.data;if(e!==void 0)return{state:`ok`,permission:e}}return n.response?.status===404?{state:`resolved`}:{state:`unknown`}}catch{return{state:`unknown`}}}async listPendingPermissions(e){let t=[],n=async e=>{let t=typeof e==`string`?e.trim():``,n=await this.client.permission.list(t?{directory:t}:void 0);if(n.error)throw Error(`permission.list failed: ${T(n.error)}`);return n.data||[]};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}async replyToQuestion(e,t,n){let r=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t],i=this.normalizeCandidatePath(n)??this.currentDirectory;return D(await this.client.question.reply({requestID:e,...i?{directory:i}:{},answers:r}),`question.reply`)===!0}async rejectQuestion(e){return D(await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`question.reject`)===!0}async listPendingQuestions(e){let t=[],n=async e=>{let t=typeof e==`string`?e.trim():``,n=await this.client.question.list(t?{directory:t}:void 0);if(n.error)throw Error(`question.list failed: ${T(n.error)}`);return n.data||[]};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}clearHealthCache(){this.healthCacheGeneration+=1,this.healthInFlight.clear(),this.healthCache.clear()}async getConfig(e){let t=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,n=t??``,r=this.configCache.get(n);if(r&&r.expiresAt>Date.now())return C(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return C(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{C(`opencodeClient.getConfig:start`,{directory:t??null});let e=typeof performance<`u`?performance.now():Date.now(),r=await(t?this.getScopedApiClient(t):this.client).config.get();if(!r.data)throw Error(`Failed to get config`);let i=typeof performance<`u`?performance.now():Date.now();return C(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(i-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:r.data,expiresAt:Date.now()+yt}),r.data})();this.configInFlight.set(n,o);try{return await o}finally{this.configInFlight.get(n)===o&&this.configInFlight.delete(n)}}async updateConfig(e){let t=E(await this.client.config.update({config:e}),`global.config.update`);return this.clearConfigCache(),t}async updateConfigPartial(e){let t=e(await this.getConfig());return await this.updateConfig(t)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){let t=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,n=t??``,r=this.configProvidersInFlight.get(n);if(r)return r;let i=(async()=>E(await this.client.config.providers(t?{directory:t}:void 0),`config.providers`))();this.configProvidersInFlight.set(n,i);try{return await i}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:`0.0.3`,config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e,t){let n=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,r=n??``;if(!t){let e=this.listAgentsInFlight.get(r);if(e)return e}let i=(async()=>{let e=Ot(Ct),r=kt(t?[t,e.signal]:[e.signal]);try{let e=n?{directory:n}:void 0,t=await this.client.app.agents(e,{signal:r.signal});if(!t.error&&Array.isArray(t.data)&&t.data.length>0)return t.data;let i=await g(`/api/agent`,{...n?{query:{directory:n}}:{},signal:r.signal});if(!i.ok)throw t.error?Error(`app.agents failed${t.response?.status?` (${t.response.status})`:``}: ${T(t.error)}`):Error(`agent.list failed (${i.status})`);let a=await i.json().catch(()=>null);if(!Array.isArray(a))throw Error(`agent.list failed: invalid response`);return a}finally{e.cleanup(),r.cleanup()}})();if(t)return i;this.listAgentsInFlight.set(r,i);try{return await i}finally{this.listAgentsInFlight.delete(r)}}async readFile(e){try{let t=await this.client.file.read({path:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(E(t,`file.read`))}catch{return`// Content of ${e}\n// This would be loaded from the server`}}async listFiles(e){try{let t=e||this.currentDirectory||`/`,n=E(await this.client.file.list({path:t,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`file.list`);return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){return(E(await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0),`command.list`)||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model,source:e.source}))}async listCommandsWithDetails(){return(E(await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0),`command.list`)||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model,source:e.source,template:e.template}))}async listSkillsWithDetails(){try{let e=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n.name==`string`?n.name.trim():``,r=typeof n.location==`string`?n.location:``;if(!e||!r)continue;let i={name:e,location:r};typeof n.description==`string`&&(i.description=n.description),typeof n.content==`string`&&(i.content=n.content),t.push(i)}return t}catch{return[]}}async getCommandDetails(e){try{let t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){let n=t.data.find(t=>t.name===e);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(){let e=r(),t=this.healthCache.get(e);if(t&&t.expiresAt>Date.now())return t.healthy;let n=this.healthInFlight.get(e);if(n)return n;let i=this.healthCacheGeneration,a=(async()=>{let t=!1;try{let e=this.baseUrl.endsWith(`/`)?this.baseUrl.replace(/\/+$/,``):this.baseUrl,n=e===`/api`||e.endsWith(`/api`)?`/api/opencode/health`:`${e}/opencode/health`;C(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:n});let r=Ot(bt),i=await g(n,{signal:r.signal}).finally(r.cleanup);if(C(`opencodeClient.checkHealth:response`,{status:i.status}),i.ok){let e=await i.json();C(`opencodeClient.checkHealth:result`,{healthy:e?.healthy}),t=e?.healthy===!0}}catch{t=!1}return i!==this.healthCacheGeneration||e!==r()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?xt:St)}),t)})();this.healthInFlight.set(e,a);try{return await a}finally{this.healthInFlight.get(e)===a&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=Pt();if(n?.createDirectory)try{return await n.createDirectory(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(t||`Failed to create directory`)}let r={path:e,...t?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await g(`${this.baseUrl}/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to create directory`}));throw Error(e.error||`Failed to create directory`)}return await i.json()}async cloneRepository(e){let t=await g(`${this.baseUrl}/fs/clone`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to clone repository`}));throw Error(e.error||`Failed to clone repository`)}return await t.json()}async listLocalDirectory(e,t){let n=`${typeof e==`string`?k(e.trim()):``}|${t?.respectGitignore?`1`:`0`}`,r=Date.now(),i=this.listDirectoryCache.get(n);if(i&&i.expiresAt>r)return i.entries;let a=this.listDirectoryInFlight.get(n);if(a)return a;let o=(async()=>{let r=Pt();if(r)try{let i=await r.listDirectory(e||``,t);if(!i||!Array.isArray(i.entries))return[];let a=i.entries.map(e=>({name:e.name,path:k(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+Nt}),a}catch(e){throw console.error(`Failed to list directory contents:`,e),e}try{let r=new URLSearchParams;e&&e.trim().length>0&&r.set(`path`,e),t?.respectGitignore&&r.set(`respectGitignore`,`true`);let i=r.toString(),a=await g(`${this.baseUrl}/fs/list${i?`?${i}`:``}`);if(!a.ok){let e=await a.json().catch(()=>({})),t=typeof e.error==`string`?e.error:`Failed to list directory`;throw Error(t)}let o=await a.json();if(!o||!Array.isArray(o.entries))return[];let s=o.entries;return this.listDirectoryCache.set(n,{entries:s,expiresAt:Date.now()+Nt}),s}catch(e){throw console.error(`Failed to list directory contents:`,e),e}})().finally(()=>{this.listDirectoryInFlight.get(n)===o&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,o),o}async searchFiles(e,t){let n=typeof t?.directory==`string`&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,r=n?k(n):null,i=n?this.getScopedApiClient(n):this.client;try{let n=await i.find.files({query:e,limit:typeof t?.limit==`number`&&Number.isFinite(t.limit)?t.limit:void 0,dirs:t?.dirs===!1||t?.type===`file`?`false`:`true`,type:t?.type});return(Array.isArray(n?.data)?n.data:[]).map(e=>{let t=k(e),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:k(r?`${r}/${t}`:t),relativePath:t,extension:n.includes(`.`)?n.split(`.`).pop()?.toLowerCase():void 0}})}catch(e){throw console.error(`Failed to search files:`,e),e}}async getFilesystemHome(){let e=r();if(!e||e===`local`){let e=await ie();if(e)return e}try{let e=await g(`${this.baseUrl}/fs/home`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok){let t=await e.json().catch(()=>({})),n=typeof t.error==`string`&&t.error.length>0?t.error:`Failed to resolve home directory`;throw Error(n)}let t=await e.json();return t&&typeof t.home==`string`&&t.home.length>0?t.home:null}catch(e){return console.warn(`Failed to resolve filesystem home directory:`,e),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!=`string`||!e.trim())return console.warn(`[OpencodeClient] setOpenCodeWorkingDirectory: invalid path`,e),null;let t=`${this.baseUrl}/opencode/directory`;try{let n=await g(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})}),r=await n.json().catch(()=>null);if(!n.ok){let e=r??{},t=typeof e.error==`string`&&e.error.length>0?e.error:`Failed to update OpenCode working directory`;throw Error(t)}return r&&typeof r==`object`?r:{success:!0,restarted:!1,path:e}}catch(e){throw console.warn(`Failed to update OpenCode working directory:`,e),e}}},Ft=3e4,It=40,Lt=60,Rt=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},zt=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},Bt=ae()(oe((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=Lt,a){if(!n||n.trim().length===0)return[];let o=n.trim(),s=typeof r==`string`?r.trim():``,c=!!a?.includeHidden,l=a?.respectGitignore??!0,u=a?.type===`directory`?`directory`:`file`,d=Rt(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<Ft)return p.files;let m=t().inFlight[d];if(m)return m;let h=A.searchFiles(s,{directory:o,limit:i,includeHidden:c,respectGitignore:l,dirs:u!==`file`,type:u}).then(t=>(e(e=>{if(e.inFlight[d]!==h)return e;let n={...e.cache,[d]:{files:t,timestamp:Date.now()}},r=e.cacheKeys.filter(e=>e!==d);for(r.push(d);r.length>It;){let e=r.shift();e&&delete n[e]}return{cache:n,cacheKeys:r}}),t)).finally(()=>{e(e=>{if(e.inFlight[d]!==h)return e;let t={...e.inFlight};return delete t[d],{inFlight:t}})});return e(e=>({inFlight:{...e.inFlight,[d]:h}})),h},invalidateDirectory(t){if(!t||t.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}let n=t.trim();e(e=>{let t={...e.cache},r=e.cacheKeys.filter(e=>!zt(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!zt(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Vt=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`openchamber_stream_debug`)===`1`}catch{return!1}},Ht=`openchamber_stream_perf`,j=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(Ht)===`1`}catch{return!1}},Ut=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),Wt=()=>{if(!j()||typeof window>`u`)return null;if(!window.__openchamberStreamPerfState){let e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Gt=e=>Array.from(e.entries()).map(([e,t])=>({metric:e,count:t.count,avg:t.count>0?Number((t.total/t.count).toFixed(3)):0,max:Number(t.max.toFixed(3)),total:Number(t.total.toFixed(3)),last:Number(t.last.toFixed(3))})).sort((e,t)=>t.total-e.total||t.count-e.count),Kt=(e,t)=>{let n=Wt();if(!n)return;let r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},qt=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(Ht,`1`),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Ht),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Jt=()=>{typeof window>`u`||(j()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Yt=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberStreamPerfState;return!j()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Gt(e.counters)}},Xt=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberVsCodeStreamPerfState;if(!j()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let t=typeof e.startedAt==`number`?e.startedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:typeof e.lastUpdatedAt==`number`?e.lastUpdatedAt:null,durationMs:t?Math.max(0,Date.now()-t):0,entries:Gt(e.counters)}},Zt=(e,t=1)=>{Kt(e,t)},Qt=(e,t)=>{Kt(e,t)},$t=(e,t)=>{if(!j())return t();let n=Ut();try{return t()}finally{Kt(e,Ut()-n)}},M=null,en=0,N=c(),tn=p(`lastDirectory`,{storage:N}),nn=typeof tn==`string`&&tn.length>0,P=e=>{try{Bt.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},F=e=>{let t=e.trim();if(!t)return t;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return n.length>1?n.replace(/\/+$/,``):n},rn=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},I=(e,t)=>F(rn(e,t)),an=()=>{let e=p(`homeDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},on=()=>{let e=p(`lastDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},sn=()=>{if(typeof process>`u`)return null;let e={},t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t==`string`&&t.trim().length>0){let e=F(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=F(n);return e.length>0?e:null}return null},L=()=>{if(typeof window<`u`){if(M)return M;let e=typeof window.__OPENCHAMBER_HOME__==`string`&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return M=e,m(`homeDirectory`,e,{storage:N}),e;let t=an();if(t&&!f())return M=t,t}return sn()||`/`},cn=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);if(n.length>1){let e=n.replace(/\/+$/,``);if(e&&e.length>0)return e===`/`?null:e}return n===`/`||n.length===0?null:n},ln=e=>(M=e,typeof window<`u`&&m(`homeDirectory`,e,{storage:N}),_({homeDirectory:e}),e),un=async()=>{let e=e=>{let t=cn(e);return t?ln(t):null};try{let t=e(await A.getFilesystemHome());if(t)return t}catch(e){console.warn(`Failed to obtain filesystem home directory:`,e)}try{let t=e((await A.getSystemInfo())?.homeDirectory);if(t)return t}catch(e){console.warn(`Failed to get home directory from system info:`,e)}try{let t=e(await ie());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=L();return e(t)||t},R=(()=>{if(!f())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null})()||L(),z=(()=>{let e=on();return e&&!f()?I(e,R):R})();z&&A.setDirectory(z);var dn=!!(R&&R!==`/`),B=ae()(oe((e,t)=>({currentDirectory:z,directoryHistory:[z],historyIndex:0,homeDirectory:R,hasPersistedDirectory:nn,isHomeReady:dn,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=I(n,M||t().homeDirectory||p(`homeDirectory`,{storage:N}));Vt(),ue(t().currentDirectory,i)&&(A.setDirectory(i),P(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return m(`lastDirectory`,i,{storage:N}),_({lastDirectory:i}),{currentDirectory:i,directoryHistory:t,historyIndex:t.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}}))},goBack:()=>{let n=t();if(n.historyIndex>0){let t=n.historyIndex-1,r=n.directoryHistory[t];A.setDirectory(r),P(),m(`lastDirectory`,r,{storage:N}),_({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{let n=t();if(n.historyIndex<n.directoryHistory.length-1){let t=n.historyIndex+1,r=n.directoryHistory[t];A.setDirectory(r),P(),m(`lastDirectory`,r,{storage:N}),_({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{let{currentDirectory:e,setDirectory:n}=t();if(e===(M||t().homeDirectory||L())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?M||L():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=M||t().homeDirectory||await un();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;M=i;let a=r.homeDirectory!==i,o=p(`lastDirectory`,{storage:N}),s=typeof o==`string`&&o.length>0,c=!s&&(r.currentDirectory===`/`||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||e({isHomeReady:!0});return}let l=typeof i==`string`&&i!==``&&i!==`/`,u=r.currentDirectory?I(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>I(e,i)),f=d.some((e,t)=>e!==r.directoryHistory[t]),h=!!(u&&u!==r.currentDirectory),g={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(g.currentDirectory=i,g.directoryHistory=[i],g.historyIndex=0,g.isSwitchingDirectory=!1):(h||f)&&(g.currentDirectory=u,g.directoryHistory=d,g.historyIndex=Math.min(r.historyIndex,d.length-1),g.isSwitchingDirectory=!1),e(()=>g),(c||h)&&l){let e=c?i:u;A.setDirectory(e),P(),m(`lastDirectory`,e,{storage:N}),_({lastDirectory:e})}_({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(un().then(e=>{B.getState().synchronizeHomeDirectory(e)}),u(e=>{M=null;let n=++en;if(t(e)){let e=an(),t=on(),n=e||`/`,r=t||n;M=e,B.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(A.setDirectory(r),P())}un().then(e=>{n===en&&B.getState().synchronizeHomeDirectory(e)})}));var fn=`x-openchamber-target-port`,pn=()=>{let e=a();for(let[t,n]of Object.entries(e)){if(t.trim().toLowerCase()!==fn)continue;let e=n.trim();return e?{[fn]:e}:void 0}},mn=(e,t)=>{let n=s();return n?n.openWebSocket(d(e),t,pn()):l(t?new WebSocket(e,t):new WebSocket(e))},V=`/api/git`,hn=1200,gn=5e3,_n=2,vn=5e3,yn=`${V}/worktrees/queue-activation`,bn=`message_queue_activation_pending`,xn=`worktree_lifecycle_busy`,Sn=`worktree_activation_stale`,Cn=5e3,wn=3e4,Tn=[0,500,1e3,2e3,4e3,8e3,14e3],H=new Map,U=new Map,En=new Map,W=new Map,G=new Map,K=new Map,q=new Map,Dn=new Map,J=new Map,On=new Map,kn=new Set,Y=0,An=[],jn=()=>Y<_n?(Y+=1,Promise.resolve()):new Promise(e=>{An.push(e)}),Mn=()=>{let e=An.shift();if(e){e();return}Y=Math.max(0,Y-1)},Nn=async e=>{await jn();try{return await e()}finally{Mn()}},Pn=Symbol.for(`openchamber.git.discoveryGated`),Fn=e=>(Object.defineProperty(e,Pn,{value:!0,configurable:!0}),e),In=e=>typeof e==`function`&&e[Pn]===!0,X=e=>e.trim(),Ln=(e,t)=>t===`light`?`${X(e)}::light`:X(e),Rn=e=>En.get(X(e))??0,Z=e=>{let t=X(e);En.set(t,Rn(e)+1);for(let e of Array.from(H.keys()))(e===t||e.startsWith(`${t}::`))&&H.delete(e);for(let e of Array.from(U.keys()))(e===t||e.startsWith(`${t}::`))&&U.delete(e)},zn=e=>On.get(X(e))??0,Q=e=>{let t=X(e);t&&(On.set(t,zn(e)+1),Dn.delete(t),J.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),i().api(e,r)}var Bn=(e,t,n)=>{let r=X(e);if(!r)return;let i=Date.now()+vn;W.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;K.set(r,{value:{root:a},expiresAt:i})};async function Vn(e){let t=Array.from(new Set(e.map(e=>X(e)).filter(Boolean))),n=new Map;if(t.length===0)return n;let r=Date.now(),a=[];for(let e of t){let t=W.get(e),i=K.get(e);if(t&&t.expiresAt>r&&i&&i.expiresAt>r){n.set(e,{isGitRepository:t.value,primaryRoot:i.value.root});continue}a.push(e)}if(a.length===0)return n;let o=e=>{for(let t of e){let e=typeof t.directory==`string`?X(t.directory):``;if(!e)continue;let r=!!t.isGitRepository,i=typeof t.primaryRoot==`string`&&t.primaryRoot?t.primaryRoot:null;Bn(e,r,i),n.set(e,{isGitRepository:r,primaryRoot:i})}},s=async e=>{await Promise.all(e.map(async e=>{try{let[t,r]=await Promise.all([Hn(e),Wn(e).then(e=>e.root).catch(()=>e)]);Bn(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Bn(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Nn(async()=>{let e=new URLSearchParams;for(let t of a)e.append(`directories`,t);let t=i().api(`${V}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await g(r);if(s.status===501||!s.ok)throw Error(`Batch git discover unavailable: ${s.status} ${s.statusText}`);let c=await s.json().catch(()=>null),l=Array.isArray(c)?c:[];if(l.length===0&&a.length>0)throw Error(`Batch git discover returned empty payload`);o(l)})}catch{}let c=a.filter(e=>!n.has(e));return c.length>0&&await s(c),n}async function Hn(e){let t=X(e),n=Date.now(),r=W.get(t);if(r&&r.expiresAt>n)return r.value;let i=G.get(t);if(i)return i;let a=(async()=>{let n=await g($(`${V}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return W.set(t,{value:r,expiresAt:Date.now()+gn}),r})();G.set(t,a);try{return await a}finally{G.get(t)===a&&G.delete(t)}}async function Un(e,t){let n=t?.mode,r=Ln(e,n),i=Date.now(),a=H.get(r);if(a&&a.expiresAt>i)return a.value;let o=U.get(r);if(o)return o;let s=(async()=>{let t=Rn(e),i=await g($(`${V}/status`,e,n?{mode:n}:void 0));if(!i.ok)throw Error(`Failed to get git status: ${i.statusText}`);let a=await i.json();return Rn(e)===t&&H.set(r,{value:a,expiresAt:Date.now()+hn}),a})();U.set(r,s);try{return await s}finally{U.get(r)===s&&U.delete(r)}}async function Wn(e){let t=X(e),n=Date.now(),r=K.get(t);if(r&&r.expiresAt>n)return r.value;let i=q.get(t);if(i)return i;let a=Nn(async()=>{let n=await g($(`${V}/primary-root`,e));if(!n.ok)throw Error(`Failed to resolve git primary root: ${n.statusText}`);let r=await n.json().catch(()=>({})),i={root:typeof r.root==`string`&&r.root?r.root:e};return K.set(t,{value:i,expiresAt:Date.now()+vn}),i});q.set(t,a);try{return await a}finally{q.get(t)===a&&q.delete(t)}}async function Gn(e){let t=await g($(`${V}/toplevel`,e));if(!t.ok)throw Error(`Failed to resolve git toplevel: ${t.statusText}`);let n=await t.json().catch(()=>({}));return{root:typeof n.root==`string`&&n.root?n.root:e}}async function Kn(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await g($(`${V}/diff`,e,{path:n,staged:r?`true`:void 0,context:i}));if(!a.ok)throw Error(`Failed to get git diff: ${a.statusText}`);return a.json()}async function qn(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await g($(`${V}/file-diff`,e,{path:n,staged:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get git file diff: ${i.statusText}`);return i.json()}async function Jn(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await g($(`${V}/revert`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to revert git changes`)}Z(e)}async function Yn(e,t){await Xn(e,[t])}async function Xn(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to stage git changes`);let r=await g($(`${V}/stage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to stage git changes`)}Z(e)}async function Zn(e,t){await Qn(e,[t])}async function Qn(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to unstage git changes`);let r=await g($(`${V}/unstage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to unstage git changes`)}Z(e)}async function $n(e,t,n){await nr(e,t,n,`stage`)}async function er(e,t,n){await nr(e,t,n,`unstage`)}async function tr(e,t,n){await nr(e,t,n,`discard`)}async function nr(e,t,n,r){if(!t)throw Error(`path is required to apply a git hunk`);if(typeof n!=`string`||!n.trim())throw Error(`patch is required to apply a git hunk`);let i=await g($(`${V}/apply-hunk`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,patch:n,action:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to apply git hunk`)}Z(e)}async function rr(e){if(!e)return!1;let t=await g($(`${V}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function ir(e,t){let n=await g($(`${V}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function ar(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await g($(`${V}/branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete branch`)}return n.json()}async function or(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await g($(`${V}/remote-branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete remote branch`)}return n.json()}async function sr(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await g($(`${V}/remotes`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remote:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to remove remote`)}return r.json()}async function cr(e,t,n){if(!Array.isArray(t)||t.length===0)throw Error(`No files provided to generate commit message`);let r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);let i=await g($(`${V}/commit-message`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));console.error(`[git-generation][browser] http error`,{status:i.status,statusText:i.statusText,error:e});let t=typeof e?.traceId==`string`&&e.traceId?` (traceId: ${e.traceId})`:``;throw Error(`${e.error||`Failed to generate commit message`}${t}`)}let a=await i.json();if(!a?.message||typeof a.message!=`object`)throw Error(`Malformed commit generation response`);return{message:{subject:typeof a.message.subject==`string`&&a.message.subject.trim().length>0?a.message.subject.trim():``,highlights:Array.isArray(a.message.highlights)?a.message.highlights.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()):[]}}}async function lr(e,t){let{base:n,head:r,context:i,zenModel:a,providerId:o,modelId:s}=t;if(!n||!r)throw Error(`base and head are required`);let c={base:n,head:r};i?.trim()&&(c.context=i.trim()),a&&(c.zenModel=a),o&&(c.providerId=o),s&&(c.modelId=s);let l=await g($(`${V}/pr-description`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c)});if(!l.ok){let e=await l.json().catch(()=>({error:l.statusText}));throw Error(e.error||`Failed to generate PR description`)}let u=await l.json().catch(()=>null),d=typeof u?.title==`string`?u.title:``,f=typeof u?.body==`string`?u.body:``;if(!d&&!f)throw Error(`Malformed PR description response`);return{title:d,body:f}}async function ur(e){let t=X(e),n=Date.now(),r=Dn.get(t);if(r&&r.expiresAt>n)return r.value;let i=J.get(t);if(i)return i;let a=zn(e),o=Nn(async()=>{let n=await g($(`${V}/worktrees`,e));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to list worktrees`)}let r=await n.json();return a===zn(e)&&Dn.set(t,{value:r,expiresAt:Date.now()+vn}),r});J.set(t,o);try{return await o}finally{J.get(t)===o&&J.delete(t)}}Fn(ur);async function dr(e,t){let n=await g($(`${V}/worktrees/validate`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to validate worktree`)}return n.json()}async function fr(e){let t=await g($(`${V}/worktrees/bootstrap-status`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to get worktree bootstrap status`)}return t.json()}async function pr(e,t){let n=await g($(`${V}/worktrees/preview`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to preview worktree`)}return n.json()}var mr=e=>typeof e==`string`&&e.length>0,hr=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!mr(t.name)||!mr(t.path))return null;let n={head:typeof t.head==`string`?t.head:``,name:t.name,branch:typeof t.branch==`string`?t.branch:``,path:t.path};return t.directoryCreated===!0&&(n.directoryCreated=!0),t.bootstrapStatus&&typeof t.bootstrapStatus==`object`&&(n.bootstrapStatus=t.bootstrapStatus),n},gr=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==bn)return null;let i=hr(r.worktree);if(!i)return null;let a=r.repair;if(!a||typeof a!=`object`)return null;let o=a;if(o.method!==`POST`||o.path!==yn)return null;let s=o.body;if(!s||typeof s!=`object`)return null;let c=s;return c.projectDirectory!==n||c.directory!==i.path?null:i},_r=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,vr=e=>new Promise(t=>{setTimeout(t,e)}),yr=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===xn||t?.code===Sn}return e.status===503&&(await e.json().catch(()=>null))?.code===bn},br=e=>e===400||e===401||e===403||e===501,xr=(e,t)=>{let r=n(),i=o(),a=_r(r,i,e,t);if(kn.has(a))return;kn.add(a);let s=()=>n()===r&&o()===i;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<wn;){if(!s())return;let i=Tn[Math.min(r,Tn.length-1)]??0;if(i>0){let e=wn-(Date.now()-n);if(e<=0||(await vr(Math.min(i,e)),!s()))return}let a=new AbortController,o=setTimeout(()=>a.abort(),Cn);try{let n=await g($(yn,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:a.signal});if(n.ok||br(n.status))return;if(await yr(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(o)}}})().catch(()=>{}).finally(()=>{kn.delete(a)})};async function Sr(e,t){let n=await g($(`${V}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=hr(r);if(t)return Q(e),t;if(r&&typeof r==`object`)return Q(e),r;throw Error(`Failed to create worktree`)}let i=gr(n.status,r,e);if(i)return Q(e),xr(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function Cr(e,t){let n=await g($(`${V}/worktrees`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete worktree`)}let r=await n.json();return Q(e),r}async function wr(e,t,n={}){let r=await g($(`${V}/commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create commit`)}let i=await r.json();return Z(e),i}async function Tr(e,t={}){let n=await g($(`${V}/push`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to push`)}let r=await n.json();return Z(e),r}async function Er(e,t={}){let n=await g($(`${V}/pull`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to pull`)}let r=await n.json();return Z(e),r}async function Dr(e,t={}){let n=await g($(`${V}/fetch`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to fetch`)}let r=await n.json();return Z(e),r}async function Or(e){let t=await g($(`${V}/stashes`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to list stashes`)}return t.json()}async function kr(e,t){let n=await g($(`${V}/stashes/file-counts`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refs:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to count stash files`)}return n.json()}async function Ar(e,t={}){let n=await g($(`${V}/stash`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to stash changes`)}return n.json()}var jr=async(e,t,n)=>{let r=await g($(`${V}/${t}`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to ${t}`)}return r.json()},Mr=(e,t)=>jr(e,`stash/apply`,t),Nr=(e,t)=>jr(e,`stash/pop`,t),Pr=(e,t)=>jr(e,`stash/drop`,t);async function Fr(e,t){let n=await g($(`${V}/checkout`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({branch:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout branch`)}return n.json()}async function Ir(e,t,n){let r=await g($(`${V}/branches`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create branch`)}return r.json()}async function Lr(e,t,n){let r=await g($(`${V}/branches/rename`,e),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename branch`)}return r.json()}async function Rr(e,t={}){let n=await g($(`${V}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?`true`:void 0}));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(`Failed to get git log: ${e.error||n.statusText}`)}return n.json()}async function zr(e,t){let n=await g($(`${V}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Br(e,t,n,r){let i=await g($(`${V}/commit-file-diff`,e,{hash:t,path:n,binary:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function Vr(){let e=await g($(`${V}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Hr(e){let t=await g($(`${V}/identities`,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to create git identity`)}return t.json()}async function Ur(e,t){let n=await g($(`${V}/identities/${e}`,void 0),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to update git identity`)}return n.json()}async function Wr(e){let t=await g($(`${V}/identities/${e}`,void 0),{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to delete git identity`)}}async function Gr(e){if(!e)return null;let t=await g($(`${V}/current-identity`,e));if(!t.ok)throw Error(`Failed to get current git identity: ${t.statusText}`);let n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Kr(e){if(!e)return!1;let t=await g($(`${V}/has-local-identity`,e));if(!t.ok)throw Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function qr(){let e=await g($(`${V}/global-identity`,void 0));if(!e.ok)throw Error(`Failed to get global git identity: ${e.statusText}`);let t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Jr(e,t){let n=await g($(`${V}/set-identity`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profileId:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to set git identity`)}return n.json()}async function Yr(){let e=await g($(`${V}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Xr(e,t){let n=await g($(`${V}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function Zr(e,t){let n=await g($(`${V}/rebase`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to rebase`)}return n.json()}async function Qr(e){let t=await g($(`${V}/rebase/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort rebase`)}return t.json()}async function $r(e,t){let n=await g($(`${V}/merge`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to merge`)}return n.json()}async function ei(e,t){let n=await g($(`${V}/checkout-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout commit`)}return n.json()}async function ti(e,t){let n=await g($(`${V}/cherry-pick`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to cherry-pick`)}return n.json()}async function ni(e,t){let n=await g($(`${V}/revert-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to revert commit`)}return n.json()}async function ri(e,t,n,r){let i=await g($(`${V}/reset-to-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t,mode:n,force:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to reset`)}return i.json()}async function ii(e){let t=await g($(`${V}/merge/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort merge`)}return t.json()}async function ai(e){let t=await g($(`${V}/rebase/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue rebase`)}return t.json()}async function oi(e){let t=await g($(`${V}/merge/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue merge`)}return t.json()}async function si(e,t){return await Ar(e,{message:t?.message}),{success:!0}}async function ci(e){return await Nr(e,{ref:`stash@{0}`}),{success:!0}}async function li(e){let t=await g($(`${V}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function ui(e,t){let n=await g(`${V}/validate-directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function di(e){let t=await g(`${V}/canonicalize-worktree-state`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e})});if(!t.ok)throw Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}var fi=()=>typeof window>`u`?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol===`capacitor:`,pi=()=>{if(typeof window>`u`||!fi()||mi()!==`ios`)return!1;let e=navigator.userAgent||``,t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},mi=()=>{if(typeof window<`u`){let e=window.Capacitor?.getPlatform?.();if(e===`ios`||e===`android`)return e}return f()?`vscode`:h()?`desktop`:`web`};export{Zr as $,li as A,$t as At,Xr as B,Pe as Bt,Yr as C,B as Ct,lr as D,qt as Dt,cr as E,Jt as Et,Vr as F,it as Ft,Q as G,Ge as Gt,Er as H,Be as Ht,Rr as I,rt as It,Or as J,ye as Jt,In as K,Fe as Kt,Un as L,Ve as Lt,ir as M,Bt as Mt,Kn as N,A as Nt,Br as O,Vt as Ot,qn as P,C as Pt,pr as Q,fr as R,Me as Rt,or as S,mn as St,Pr as T,Xt as Tt,Tr as U,He as Ut,Dr as V,ze as Vt,Kr as W,Ue as Wt,$r as X,ur as Y,Se as Yt,Nr as Z,Hr as _,er as _t,Qr as a,ni as at,Wr as b,ui as bt,Hn as c,Jr as ct,ti as d,$n as dt,sr as et,oi as f,si as ft,wr as g,Qn as gt,Ir as h,Zn as ht,ii as i,Gn as it,Gr as j,Qt as jt,zr as k,Zt as kt,Fr as l,Yn as lt,kr as m,ci as mt,fi as n,ri as nt,Mr as o,Jn as ot,ai as p,Ar as pt,rr as q,be as qt,pi as r,Wn as rt,di as s,tr as st,mi as t,Lr as tt,ei as u,Xn as ut,Sr as v,Ur as vt,Vn as w,Yt as wt,Cr as x,Nn as xt,ar as y,dr as yt,qr as z,Ne as zt};
2
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,D as n,E as r,F as i,H as a,T as o,X as s,b as c,et as l,j as u,nt as d}from"./useUIStore-CL06MzOk.js";import{$t as f,Mt as p,Pt as m,Xt as h,kn as g,nt as ee,ot as te,pt as ne,r as _,st as v,xn as re,zt as ie}from"./persistence-Cm9DnxXq.js";import{a as ae,r as oe}from"./vendor-zustand-B4dlGEM2.js";import{t as se}from"./vendor-opencode-sdk-C07HQypa.js";import{i as ce}from"./vendor-pathe-vBmvQE8f.js";import{o as le}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";var ue=(e,t)=>e!==t,de=new Set([`image/heic`,`image/heif`]),fe=!1,pe=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},me=e=>de.has((e.type||``).toLowerCase()),he=async e=>{let t=new Uint8Array(await e.arrayBuffer()),n=``,r=32768;for(let e=0;e<t.byteLength;e+=r){let i=t.subarray(e,Math.min(e+r,t.byteLength));n+=String.fromCharCode(...i)}return btoa(n)},ge=(e,t)=>{let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new Blob([r],{type:t})},_e=async e=>{if(!me(e)||fe)return null;let t=pe();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.OpenChamberMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await he(e),mime:e.type.toLowerCase(),quality:.9});if(typeof t?.data!=`string`||!t.data)return null;let r=typeof t.mime==`string`&&t.mime?t.mime:`image/jpeg`;return ge(t.data,r)}catch(e){return fe=!0,console.warn(`Native HEIC transcode failed`,e),null}},ve=e=>e.trim().toLowerCase(),ye=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,be=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(ve)),r=[],i=0;for(;i<e.length;){let t=e.indexOf(`[`,i);if(t===-1)break;let a=e.indexOf(`]`,t+1);if(a===-1)break;if(e[a+1]!==`(`){let i=ne(e.slice(t+1,a)).trim();n.has(ve(i))&&r.push({start:t,end:a+1})}i=a+1}return r},xe=(e,t)=>{let n=t.start,r=t.end;return r<e.length&&/\s/.test(e[r])?r+=1:n>0&&/\s/.test(e[n-1])&&--n,{start:n,end:r}},Se=(e,t,n,r)=>{let i=be(e,t);if(i.length===0)return{text:e,mentions:[...n],composerReferences:r===void 0?void 0:[...r],changed:!1};let a=e,o=[...n],s=r===void 0?[]:[...r];for(let e=i.length-1;e>=0;--e){let{start:t,end:n}=xe(a,i[e]),r=n-t;a=`${a.slice(0,t)}${a.slice(n)}`,o=o.flatMap(e=>e.range.end<=t?[e]:e.range.start>=n?[{...e,range:{start:e.range.start-r,end:e.range.end-r}}]:[]),s=s.flatMap(e=>e.end<=t?[e]:e.start>=n?[{...e,start:e.start-r,end:e.end-r}]:[])}return{text:a,mentions:o,composerReferences:r===void 0?void 0:s,changed:!0}},Ce=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),we={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/heic":`heic`,"image/heif":`heif`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/png":`png`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/webp":`webp`},y=e=>e.trim().toLowerCase(),Te=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Ee=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>Te(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},De=e=>we[e?.trim().toLowerCase()??``]??`png`,Oe=e=>{let t=Ee(e.name),n=De(e.type),r=t.lastIndexOf(`.`);if(r>0&&r<t.length-1){let e=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(e))return{base:t.slice(0,r).trim()||`image`,ext:e}}return{base:t.trim()||`image`,ext:n}},ke=e=>{let{base:t}=Oe({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(Ce.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&Ce.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},b=(e,t)=>`${e}.${t}`,Ae=(e,t,n)=>{let r=b(e,t);if(!n.has(y(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=b(`${e}-${r}`,t);if(!n.has(y(i)))return i}return b(`${e}-${Date.now()}`,t)},je=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=b(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(y(r)))return r}return b(`image-${Date.now()}`,e)},Me=(e,t)=>{let n=new Set(t.map(y));return e.map(e=>{let{base:t,ext:r}=Oe(e),i=ke(b(t,r))?je(r,n):Ae(t,r,n);return n.add(y(i)),i})},Ne=e=>e.map(e=>v(e)).join(` `),Pe=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[v(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},Fe=e=>e.replaceAll(`[${te}`,`[`),Ie=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Le=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Re=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Le(t)||!Ie.test(t)&&!Ie.test(r))continue;let i=`[${r}]`;n=n.split(v(t)).join(i).split(`[${t}]`).join(i)}return n},ze=(e,t)=>{let n=e;for(let e of t??[]){if(e.source!==`vscode`||e.vscodeSource!==`selection`||!e.vscodePath)continue;let t=e.filename.match(/:(\d+(?:-\d+)?)$/)?.[1];if(!t)continue;let r=`[${e.vscodePath}:${t}]`;n=n.split(v(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Be=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Ve=`application/x-directory`,He=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Ue=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),We=(e,t,n)=>{if(t===`Backspace`){let t=n;for(;t>0&&/\s/.test(e[t-1]);)--t;for(;t>0&&!/\s/.test(e[t-1]);)--t;return{start:t,end:n}}let r=n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;for(;r<e.length&&!/\s/.test(e[r]);)r+=1;return{start:n,end:r}},Ge=(e,t,n)=>{let r=Math.max(0,Math.min(n.selectionStart,e.length)),i=Math.max(r,Math.min(n.selectionEnd,e.length)),a;if(a=r===i?n.altKey?We(e,n.key,r):n.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(e.length,r+1)}:{start:r,end:i},a.start===a.end)return null;let o=be(e,t).filter(e=>e.start<a.end&&e.end>a.start);if(o.length===0)return null;let s=Math.min(a.start,...o.map(e=>e.start)),c=Math.max(a.end,...o.map(e=>e.end));return c<e.length&&/\s/.test(e[c])&&(s===0||/\s/.test(e[s-1]))?c+=1:c===e.length&&s>0&&/\s/.test(e[s-1])&&--s,{text:`${e.slice(0,s)}${e.slice(c)}`,caret:s,removedFilenames:o.map(t=>ne(e.slice(t.start+1,t.end-1)).trim())}},x=class extends Error{status;code;constructor(e,t,n=`Failed to upload prompt attachment`){super(n),this.name=`PromptAttachmentUploadError`,this.status=e,this.code=t}},S=`file://`,Ke=e=>{let t=e.trim();if(t.toLowerCase().startsWith(S))return t;let n=ce(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${S}/${n}`:`${S}${n}`},qe=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(S))return t;let n=t.slice(7);n.toLowerCase().startsWith(`localhost/`)&&(n=n.slice(9));let r=n.split(`/`).map(e=>{if(/^[A-Za-z]:$/.test(e))return e;try{return decodeURIComponent(e)}catch{return e}}).join(`/`);return/^\/[A-Za-z]:/.test(r)?r.slice(1):r},Je=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),Ye=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Xe=async e=>{let t;try{t=await e.json()}catch{throw new x(e.status,`unavailable`)}if(!Ye(t)||typeof t.path!=`string`||!t.path)throw new x(e.status,`unavailable`);let n=typeof t.mime==`string`&&t.mime?t.mime:`application/octet-stream`,r=typeof t.size==`number`&&Number.isSafeInteger(t.size)?t.size:0,i=typeof t.sha256==`string`?t.sha256:``;return{path:t.path,url:Ke(t.path),mime:n,size:r,sha256:i}},Ze=e=>{let t=typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n=e?.replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,32);return n?`att-${t}-${n}`:`att-${t}`},Qe=(e,t)=>{if(!e.startsWith(`data:`))return null;let n=e.indexOf(`,`);if(n===-1)return null;let r=e.slice(5,n),i=e.slice(n+1),a=r.split(`;`,1)[0]?.trim()||t||`application/octet-stream`;try{if(r.toLowerCase().includes(`;base64`)){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([t],{type:a})}return new Blob([decodeURIComponent(i)],{type:a})}catch{return null}},$e=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),et=async e=>{let t=e.mime||e.body.type||`application/octet-stream`,n=e.body.type===t?e.body:new Blob([e.body],{type:t});if(!Number.isSafeInteger(n.size)||n.size<0||n.size>26214400)throw new x(413,`too-large`);let r=await Je(n),i=Ze(e.filename),a;try{a=await g(`/api/fs/prompt-attachments/${encodeURIComponent(i)}`,{method:`PUT`,headers:{"Content-Type":t,"Content-Length":String(n.size),"X-OpenChamber-Content-Length":String(n.size),"X-OpenChamber-Sha256":r,"X-OpenChamber-Mime":t,...e.filename?{"X-OpenChamber-Filename":encodeURIComponent(e.filename)}:{}},body:n,signal:e.signal})}catch{throw new x(0,`unavailable`)}if(a.status===413)throw new x(413,`too-large`);if(!a.ok)throw new x(a.status,a.status>=500||a.status===0?`unavailable`:`rejected`);let o=await Xe(a);if(o.size!==n.size)throw new x(a.status,`unavailable`);return{...o,mime:t}},tt=500,nt=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`OPENCHAMBER_STARTUP_TRACE`)===`1`}catch{return!1}},rt=()=>nt(),C=(e,t)=>{if(!nt())return;let n=typeof performance<`u`?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>tt&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-tt)};typeof window<`u`&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var it=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();C(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return C(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw C(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},at=3,ot=3e4,st=32e3,ct=36e5,lt=6e5,ut=new Set([429,502,503,504]),w=new Map;function dt(){let e=Date.now();for(let[t,n]of w)n.consecutiveErrors===0&&e-n.lastErrorAt>ct&&w.delete(t)}typeof setInterval<`u`&&setInterval(dt,lt).unref?.();function ft(e){let t=w.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:ot},w.set(e,t)),t}function pt(e){if(!e)return;let t=w.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function mt(e,t){if(!e)return;let n=ft(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),ht(t)&&n.consecutiveErrors>=at&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function ht(e){return e!==void 0&&ut.has(e)}function gt(e){let t=w.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,st*4),!1):!0:!1}function _t(e){if(!(!e||!gt(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var vt=`/api`,yt=1e4,bt=4e3,xt=3e3,St=1e3,Ct=12e3;function T(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function E(e,t){if(e.error){let n=e.response?.status,r=Error(`${t} failed${n?` (${n})`:``}: ${T(e.error)}`);throw n!==void 0&&(r.status=n),r}if(e.data===void 0||e.data===null)throw Error(`${t} failed: empty response`);return e.data}function D(e,t){if(e.error){let n=e.response?.status,r=Error(`${t} failed${n?` (${n})`:``}: ${T(e.error)}`);throw n!==void 0&&(r.status=n),r}return e.data}var wt=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Tt=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(wt.test(t)||typeof window>`u`)return t;let n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(e){return console.warn(`Failed to normalize OpenCode base URL:`,e),t}},Et=()=>{try{return i().api(`/api`)}catch{return null}},Dt=()=>{try{return i().api(`/`)}catch{return null}},Ot=e=>{let t=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof t?.timeout==`function`)return{signal:t.timeout(e),cleanup:()=>void 0};let n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},kt=e=>{let t=e.filter(e=>e!=null);if(t.length===0)return{signal:new AbortController().signal,cleanup:()=>void 0};if(t.length===1)return{signal:t[0],cleanup:()=>void 0};let n=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof n?.any==`function`)return{signal:n.any(t),cleanup:()=>void 0};let r=new AbortController,i=()=>r.abort();for(let e of t){if(e.aborted){r.abort();break}e.addEventListener(`abort`,i)}return{signal:r.signal,cleanup:()=>{for(let e of t)e.removeEventListener(`abort`,i)}}},O=e=>se({...e,fetch:g}),At=e=>typeof e.mime==`string`&&e.mime.startsWith(`image/`)?!0:typeof e.filename==`string`&&/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i.test(e.filename),jt=e=>{let t=[];for(let n of e){if(!At(n))continue;let e=typeof n.filename==`string`?n.filename.trim():``,r=typeof n.url==`string`?n.url:``;if(!e||!r.toLowerCase().startsWith(`file://`))continue;let i=qe(r).trim();i&&t.push({filename:e,path:i})}return t},Mt=async(e,t)=>{let n=[],r=e.files?.length?await Promise.all(e.files.map(e=>t(e))):[],i=e.additionalParts?.length?await Promise.all(e.additionalParts.map(async e=>({text:e.text,synthetic:e.synthetic,files:e.files?.length?await Promise.all(e.files.map(e=>t(e))):[]}))):[],a=e=>Re(e,jt([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files)}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},k=e=>e.replace(/\\/g,`/`),Nt=400,Pt=()=>{let e=re();return e&&e.runtime?.isDesktop&&e.files?e.files:null},A=new class{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;healthInFlight=new Map;healthCache=new Map;healthCacheGeneration=0;constructor(e=vt){let t=Et()||e;this.baseUrl=Tt(t),this.client=O({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){let e=Tt(Et()||vt);e!==this.baseUrl&&(this.baseUrl=e,this.client=O({baseUrl:this.baseUrl}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache())}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}getScopedApiClient(e){let t=this.normalizeCandidatePath(e)??e,n=t||``,r=this.scopedClients.get(n);if(r)return r;let i=O({baseUrl:this.baseUrl,directory:t});return this.scopedClients.set(n,i),i}normalizeCandidatePath(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return(n.length>1?n.replace(/\/+$/,``):n)||null}deriveHomeDirectory(e){let t=e.match(/^([A-Za-z]:)(?:\/|$)/);if(t){let n=t[1],r=e.slice(n.length+ +(e.charAt(n.length)===`/`)).split(`/`).filter(Boolean);return r.length>=2?{homeDirectory:`${n}/${r[0]}/${r[1]}`,username:r[1]}:r.length===1?{homeDirectory:`${n}/${r[0]}`,username:r[0]}:{homeDirectory:n,username:void 0}}let n=e.startsWith(`/`),r=e.split(`/`).filter(Boolean);return r.length>=2&&(r[0]===`Users`||r[0]===`home`)?{homeDirectory:`${n?`/`:``}${r[0]}/${r[1]}`,username:r[1]}:n?r.length===0?{homeDirectory:`/`,username:void 0}:{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:r.length>0?{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:{homeDirectory:`/`,username:void 0}}setDirectory(e){let t=this.normalizeCandidatePath(e)??e;this.currentDirectory!==t&&C(`opencodeClient:setDirectory`,{previous:this.currentDirectory??null,next:t??null}),this.currentDirectory=t}getDirectory(){return this.currentDirectory}async withDirectory(e,t){let n=async()=>{if(e==null)return t();let n=this.currentDirectory,r=this.normalizeCandidatePath(e)??e;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory===r&&(this.currentDirectory=n)}},r=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=r.then(()=>void 0,()=>void 0),r}getApiClient(){return this.client}async getSystemInfo(){let e=new Set,t=t=>{let n=this.normalizeCandidatePath(t);n&&e.add(n)};try{let e=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;e&&(t(e.directory),t(e.worktree),t(e.state))}catch{}if(!e.size)try{t((await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data?.worktree)}catch{}if(!e.size)try{(await this.listSessions()).forEach(e=>t(e.directory))}catch{}if(t(this.currentDirectory),typeof window<`u`)try{t(p(`lastDirectory`)),t(p(`homeDirectory`))}catch{}if(!e.size&&typeof process<`u`&&typeof process.cwd==`function`&&t(process.cwd()),!e.size)return{homeDirectory:`/`,username:void 0};let[n]=Array.from(e);return this.deriveHomeDirectory(n)}async probeDirectory(e){let t=this.normalizeCandidatePath(e);if(!t)return!1;try{let e=(await this.client.path.get({directory:t})).data,n=typeof e?.directory==`string`?e.directory:null;return!!(n&&n.trim().length>0)}catch{return!1}}async listSessions(){let e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return E(await this.client.session.create({...n?{directory:n}:{},parentID:e?.parentID,title:e?.title,metadata:e?.metadata}),`session.create`)}async getSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return E(await this.client.session.get({sessionID:e,...n?{directory:n}:{}}),`session.get`)}async deleteSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;return D(await this.client.session.delete({sessionID:e,...n?{directory:n}:{}}),`session.delete`)===!0}async deleteSessionMessage(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory;return D(await this.client.session.deleteMessage({sessionID:e,messageID:t,...r?{directory:r}:{}}),`session.deleteMessage`)===!0}async updateSession(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory,i={...t.title===void 0?{}:{title:t.title},...t.metadata===void 0?{}:{metadata:t.metadata},...t.time?.archived!==void 0&&t.time.archived!==null?{time:{archived:t.time.archived}}:{}};return E(await this.client.session.update({sessionID:e,...r?{directory:r}:{},...i}),`session.update`)}async getSessionMessages(e,t){return E(await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof t==`number`?{limit:t}:{}}),`session.messages`)}async getSessionDiff(e,t){let n=this.normalizeCandidatePath(e.directory)??this.currentDirectory,r=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():void 0,i={sessionID:e.sessionID,...n?{directory:n}:{},...r?{messageID:r}:{}};return E(t?.signal?await this.client.session.diff(i,{signal:t.signal}):await this.client.session.diff(i),`session.diff`)}async getSessionTodos(e){try{let t=await this.client.session.todo({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(t.error)return[];let n=t.data;return!n||!Array.isArray(n)?[]:n}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`text/`)&&t!==`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(t)}isHeicMime(e){if(!e)return!1;let t=e.toLowerCase();return t===`image/heic`||t===`image/heif`}async convertHeicToJpeg(t){try{let n=Qe(t.url,t.mime);if(!n)return t;let r=await _e(n)??await(await le(async()=>{let{default:t}=await import(`./vendor-heic2any-CUPf3g2A.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e){let t=await this.normalizeFilePart(e),n=t.url;if($e(n)){let e=Qe(n,t.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${t.filename??`file`}`);n=(await et({body:e,mime:t.mime,filename:t.filename})).url}return{...e.id?{id:e.id}:{},type:`file`,mime:t.mime,filename:t.filename,url:n}}async buildMessageParts(e){return Mt(e,e=>this.toNormalizedFilePartInput(e))}async sendMessage(e){let t=e.messageId??ee(`msg`),n=await this.buildMessageParts({text:e.text,prefaceText:e.prefaceText,prefaceTextSynthetic:e.prefaceTextSynthetic,files:e.files,additionalParts:e.additionalParts,agentMentions:e.agentMentions}),r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;e.format&&(e.id,e.providerID,e.modelID,e.agent,e.variant,this.baseUrl,e.format.type),_t(e.providerID);let i;try{let a=await this.client.session.promptAsync({sessionID:e.id,...r?{directory:r}:{},model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,messageID:t,...e.delivery?{delivery:e.delivery}:{},...e.format?{format:e.format}:{},parts:n});if(a.response instanceof Response)i=a.response;else if(a.error){let e=a.response?.status;if(!e)throw Error(`Message send transport failure: ${T(a.error)}`);i=new Response(JSON.stringify(a.error),{status:e})}else i=new Response(JSON.stringify(a.data??!0),{status:200})}catch(t){throw mt(e.providerID),t}if(i.ok)return pt(e.providerID),t;let a=``;try{a=await i.text()}catch{}let o=a&&a.trim().length>0?`: ${a.trim()}`:``,s=Error(`Failed to send message (${i.status})${o}`);throw s.status=i.status,mt(e.providerID,i.status),s}async sendCommand(e){let t=e.messageId??ee(`msg`),n=[];if(e.files&&e.files.length>0)for(let t of e.files)n.push(await this.toNormalizedFilePartInput(t));let r=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;return D(await this.client.session.command({sessionID:e.id,...r?{directory:r}:{},command:e.command,arguments:e.arguments??``,model:`${e.providerID}/${e.modelID}`,agent:e.agent,variant:e.variant,...n.length>0?{parts:n}:{},messageID:t}),`session.command`),t}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async shellSession(e){let t=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory;return E(await this.client.session.shell({sessionID:e.sessionId,...t?{directory:t}:{},messageID:e.messageId,agent:e.agent,model:e.model,command:e.command}),`session.shell`)}async revertSession(e,t,n,r){let i=this.normalizeCandidatePath(r)??this.currentDirectory;return E(await this.client.session.revert({sessionID:e,...i?{directory:i}:{},messageID:t,partID:n}),`session.revert`)}async summarizeSession(e,t,n,r){let i=this.normalizeCandidatePath(r)??this.currentDirectory;return D(await this.client.session.summarize({sessionID:e,...i?{directory:i}:{},providerID:t,modelID:n}),`session.summarize`)===!0}async unrevertSession(e){return E(await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`session.unrevert`)}async forkSession(e,t,n){let r=this.normalizeCandidatePath(n)??this.currentDirectory,i=E(await this.client.session.fork({sessionID:e,...r?{directory:r}:{},messageID:t}),`session.fork`);return i.id,i}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e,t){try{let n=typeof e==`string`?e.trim():``,r=await this.client.session.status(n?{directory:n}:void 0,t?{signal:t}:void 0);return r.error||!r.data||typeof r.data!=`object`?null:r.data}catch{return null}}async getSessionActive(e){try{let t=await O({baseUrl:Tt(Dt()||`/`)}).v2.session.active(e?{signal:e}:void 0),n=t.response?.status;if(t.error||n!==void 0&&n!==200)return n===404||n===405||n===501?{state:`unsupported`}:{state:`unknown`};let r=t.data,i=r&&typeof r==`object`&&`data`in r&&r.data!==void 0?r.data:r;if(!i||typeof i!=`object`||Array.isArray(i))return{state:`unknown`};let a={};for(let[e,t]of Object.entries(i)){if(typeof e!=`string`||e.length===0||!t||typeof t!=`object`||t.type!==`running`)return{state:`unknown`};a[e]={type:`running`}}return{state:`supported`,membership:a}}catch{return{state:`unknown`}}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{let e=await g(`/api/session-activity`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json().catch(()=>null);return!t||typeof t!=`object`?null:t}catch{return null}}async listToolIds(e){try{let t=typeof e?.directory==`string`?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():``;return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(e=>typeof e==`string`&&e!==`invalid`)}catch{return[]}}async replyToPermission(e,t,n){let r=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory;return D(await this.client.permission.reply({requestID:e,...r?{directory:r}:{},reply:t,...n?.message?{message:n.message}:{}}),`permission.reply`)===!0}async createPermission(e,t,n,r){try{let i=await this.client.v2.session.permission.create({sessionID:e,action:t,resources:n,...r?.id?{id:r.id}:{},...r?.save?{save:r.save}:{},...r?.metadata?{metadata:r.metadata}:{},...r?.source?{source:r.source}:{},...r?.agent?{agent:r.agent}:{}});if(i.error!==void 0)return null;let a=i.data?.data;return a===void 0?null:{id:a.id,effect:a.effect}}catch{return null}}async fetchPermission(e,t){try{let n=await this.client.v2.session.permission.get({sessionID:e,requestID:t});if(n.error===void 0){let e=n.data?.data;if(e!==void 0)return{state:`ok`,permission:e}}return n.response?.status===404?{state:`resolved`}:{state:`unknown`}}catch{return{state:`unknown`}}}async listPendingPermissions(e){let t=[],n=async e=>{let t=typeof e==`string`?e.trim():``,n=await this.client.permission.list(t?{directory:t}:void 0);if(n.error)throw Error(`permission.list failed: ${T(n.error)}`);return n.data||[]};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}async replyToQuestion(e,t,n){let r=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t],i=this.normalizeCandidatePath(n)??this.currentDirectory;return D(await this.client.question.reply({requestID:e,...i?{directory:i}:{},answers:r}),`question.reply`)===!0}async rejectQuestion(e){return D(await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`question.reject`)===!0}async listPendingQuestions(e){let t=[],n=async e=>{let t=typeof e==`string`?e.trim():``,n=await this.client.question.list(t?{directory:t}:void 0);if(n.error)throw Error(`question.list failed: ${T(n.error)}`);return n.data||[]};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}clearHealthCache(){this.healthCacheGeneration+=1,this.healthInFlight.clear(),this.healthCache.clear()}async getConfig(e){let t=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,n=t??``,r=this.configCache.get(n);if(r&&r.expiresAt>Date.now())return C(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return C(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{C(`opencodeClient.getConfig:start`,{directory:t??null});let e=typeof performance<`u`?performance.now():Date.now(),r=await(t?this.getScopedApiClient(t):this.client).config.get();if(!r.data)throw Error(`Failed to get config`);let i=typeof performance<`u`?performance.now():Date.now();return C(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(i-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:r.data,expiresAt:Date.now()+yt}),r.data})();this.configInFlight.set(n,o);try{return await o}finally{this.configInFlight.get(n)===o&&this.configInFlight.delete(n)}}async updateConfig(e){let t=E(await this.client.config.update({config:e}),`global.config.update`);return this.clearConfigCache(),t}async updateConfigPartial(e){let t=e(await this.getConfig());return await this.updateConfig(t)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){let t=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,n=t??``,r=this.configProvidersInFlight.get(n);if(r)return r;let i=(async()=>E(await this.client.config.providers(t?{directory:t}:void 0),`config.providers`))();this.configProvidersInFlight.set(n,i);try{return await i}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:`0.0.3`,config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e,t){let n=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,r=n??``;if(!t){let e=this.listAgentsInFlight.get(r);if(e)return e}let i=(async()=>{let e=Ot(Ct),r=kt(t?[t,e.signal]:[e.signal]);try{let e=n?{directory:n}:void 0,t=await this.client.app.agents(e,{signal:r.signal});if(!t.error&&Array.isArray(t.data)&&t.data.length>0)return t.data;let i=await g(`/api/agent`,{...n?{query:{directory:n}}:{},signal:r.signal});if(!i.ok)throw t.error?Error(`app.agents failed${t.response?.status?` (${t.response.status})`:``}: ${T(t.error)}`):Error(`agent.list failed (${i.status})`);let a=await i.json().catch(()=>null);if(!Array.isArray(a))throw Error(`agent.list failed: invalid response`);return a}finally{e.cleanup(),r.cleanup()}})();if(t)return i;this.listAgentsInFlight.set(r,i);try{return await i}finally{this.listAgentsInFlight.delete(r)}}async readFile(e){try{let t=await this.client.file.read({path:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});return String(E(t,`file.read`))}catch{return`// Content of ${e}\n// This would be loaded from the server`}}async listFiles(e){try{let t=e||this.currentDirectory||`/`,n=E(await this.client.file.list({path:t,...this.currentDirectory?{directory:this.currentDirectory}:{}}),`file.list`);return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){return(E(await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0),`command.list`)||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model,source:e.source}))}async listCommandsWithDetails(){return(E(await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0),`command.list`)||[]).map(e=>({name:e.name,description:e.description,agent:e.agent,model:e.model,source:e.source,template:e.template}))}async listSkillsWithDetails(){try{let e=(await this.client.app.skills(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n.name==`string`?n.name.trim():``,r=typeof n.location==`string`?n.location:``;if(!e||!r)continue;let i={name:e,location:r};typeof n.description==`string`&&(i.description=n.description),typeof n.content==`string`&&(i.content=n.content),t.push(i)}return t}catch{return[]}}async getCommandDetails(e){try{let t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){let n=t.data.find(t=>t.name===e);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(){let e=r(),t=this.healthCache.get(e);if(t&&t.expiresAt>Date.now())return t.healthy;let n=this.healthInFlight.get(e);if(n)return n;let i=this.healthCacheGeneration,a=(async()=>{let t=!1;try{let e=this.baseUrl.endsWith(`/`)?this.baseUrl.replace(/\/+$/,``):this.baseUrl,n=e===`/api`||e.endsWith(`/api`)?`/api/opencode/health`:`${e}/opencode/health`;C(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:n});let r=Ot(bt),i=await g(n,{signal:r.signal}).finally(r.cleanup);if(C(`opencodeClient.checkHealth:response`,{status:i.status}),i.ok){let e=await i.json();C(`opencodeClient.checkHealth:result`,{healthy:e?.healthy}),t=e?.healthy===!0}}catch{t=!1}return i!==this.healthCacheGeneration||e!==r()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?xt:St)}),t)})();this.healthInFlight.set(e,a);try{return await a}finally{this.healthInFlight.get(e)===a&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=Pt();if(n?.createDirectory)try{return await n.createDirectory(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(t||`Failed to create directory`)}let r={path:e,...t?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await g(`${this.baseUrl}/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to create directory`}));throw Error(e.error||`Failed to create directory`)}return await i.json()}async cloneRepository(e){let t=await g(`${this.baseUrl}/fs/clone`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to clone repository`}));throw Error(e.error||`Failed to clone repository`)}return await t.json()}async listLocalDirectory(e,t){let n=`${typeof e==`string`?k(e.trim()):``}|${t?.respectGitignore?`1`:`0`}`,r=Date.now(),i=this.listDirectoryCache.get(n);if(i&&i.expiresAt>r)return i.entries;let a=this.listDirectoryInFlight.get(n);if(a)return a;let o=(async()=>{let r=Pt();if(r)try{let i=await r.listDirectory(e||``,t);if(!i||!Array.isArray(i.entries))return[];let a=i.entries.map(e=>({name:e.name,path:k(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+Nt}),a}catch(e){throw console.error(`Failed to list directory contents:`,e),e}try{let r=new URLSearchParams;e&&e.trim().length>0&&r.set(`path`,e),t?.respectGitignore&&r.set(`respectGitignore`,`true`);let i=r.toString(),a=await g(`${this.baseUrl}/fs/list${i?`?${i}`:``}`);if(!a.ok){let e=await a.json().catch(()=>({})),t=typeof e.error==`string`?e.error:`Failed to list directory`;throw Error(t)}let o=await a.json();if(!o||!Array.isArray(o.entries))return[];let s=o.entries;return this.listDirectoryCache.set(n,{entries:s,expiresAt:Date.now()+Nt}),s}catch(e){throw console.error(`Failed to list directory contents:`,e),e}})().finally(()=>{this.listDirectoryInFlight.get(n)===o&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,o),o}async searchFiles(e,t){let n=typeof t?.directory==`string`&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,r=n?k(n):null,i=n?this.getScopedApiClient(n):this.client;try{let n=await i.find.files({query:e,limit:typeof t?.limit==`number`&&Number.isFinite(t.limit)?t.limit:void 0,dirs:t?.dirs===!1||t?.type===`file`?`false`:`true`,type:t?.type});return(Array.isArray(n?.data)?n.data:[]).map(e=>{let t=k(e),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:k(r?`${r}/${t}`:t),relativePath:t,extension:n.includes(`.`)?n.split(`.`).pop()?.toLowerCase():void 0}})}catch(e){throw console.error(`Failed to search files:`,e),e}}async getFilesystemHome(){let e=r();if(!e||e===`local`){let e=await ie();if(e)return e}try{let e=await g(`${this.baseUrl}/fs/home`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok){let t=await e.json().catch(()=>({})),n=typeof t.error==`string`&&t.error.length>0?t.error:`Failed to resolve home directory`;throw Error(n)}let t=await e.json();return t&&typeof t.home==`string`&&t.home.length>0?t.home:null}catch(e){return console.warn(`Failed to resolve filesystem home directory:`,e),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!=`string`||!e.trim())return console.warn(`[OpencodeClient] setOpenCodeWorkingDirectory: invalid path`,e),null;let t=`${this.baseUrl}/opencode/directory`;try{let n=await g(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})}),r=await n.json().catch(()=>null);if(!n.ok){let e=r??{},t=typeof e.error==`string`&&e.error.length>0?e.error:`Failed to update OpenCode working directory`;throw Error(t)}return r&&typeof r==`object`?r:{success:!0,restarted:!1,path:e}}catch(e){throw console.warn(`Failed to update OpenCode working directory:`,e),e}}},Ft=3e4,It=40,Lt=60,Rt=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},zt=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},Bt=ae()(oe((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=Lt,a){if(!n||n.trim().length===0)return[];let o=n.trim(),s=typeof r==`string`?r.trim():``,c=!!a?.includeHidden,l=a?.respectGitignore??!0,u=a?.type===`directory`?`directory`:`file`,d=Rt(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<Ft)return p.files;let m=t().inFlight[d];if(m)return m;let h=A.searchFiles(s,{directory:o,limit:i,includeHidden:c,respectGitignore:l,dirs:u!==`file`,type:u}).then(t=>(e(e=>{if(e.inFlight[d]!==h)return e;let n={...e.cache,[d]:{files:t,timestamp:Date.now()}},r=e.cacheKeys.filter(e=>e!==d);for(r.push(d);r.length>It;){let e=r.shift();e&&delete n[e]}return{cache:n,cacheKeys:r}}),t)).finally(()=>{e(e=>{if(e.inFlight[d]!==h)return e;let t={...e.inFlight};return delete t[d],{inFlight:t}})});return e(e=>({inFlight:{...e.inFlight,[d]:h}})),h},invalidateDirectory(t){if(!t||t.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}let n=t.trim();e(e=>{let t={...e.cache},r=e.cacheKeys.filter(e=>!zt(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!zt(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Vt=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`openchamber_stream_debug`)===`1`}catch{return!1}},Ht=`openchamber_stream_perf`,j=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(Ht)===`1`}catch{return!1}},Ut=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),Wt=()=>{if(!j()||typeof window>`u`)return null;if(!window.__openchamberStreamPerfState){let e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Gt=e=>Array.from(e.entries()).map(([e,t])=>({metric:e,count:t.count,avg:t.count>0?Number((t.total/t.count).toFixed(3)):0,max:Number(t.max.toFixed(3)),total:Number(t.total.toFixed(3)),last:Number(t.last.toFixed(3))})).sort((e,t)=>t.total-e.total||t.count-e.count),Kt=(e,t)=>{let n=Wt();if(!n)return;let r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},qt=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(Ht,`1`),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Ht),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Jt=()=>{typeof window>`u`||(j()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Yt=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberStreamPerfState;return!j()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Gt(e.counters)}},Xt=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberVsCodeStreamPerfState;if(!j()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let t=typeof e.startedAt==`number`?e.startedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:typeof e.lastUpdatedAt==`number`?e.lastUpdatedAt:null,durationMs:t?Math.max(0,Date.now()-t):0,entries:Gt(e.counters)}},Zt=(e,t=1)=>{Kt(e,t)},Qt=(e,t)=>{Kt(e,t)},$t=(e,t)=>{if(!j())return t();let n=Ut();try{return t()}finally{Kt(e,Ut()-n)}},M=null,en=0,N=c(),tn=p(`lastDirectory`,{storage:N}),nn=typeof tn==`string`&&tn.length>0,P=e=>{try{Bt.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},F=e=>{let t=e.trim();if(!t)return t;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return n.length>1?n.replace(/\/+$/,``):n},rn=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},I=(e,t)=>F(rn(e,t)),an=()=>{let e=p(`homeDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},on=()=>{let e=p(`lastDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},sn=()=>{if(typeof process>`u`)return null;let e={},t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t==`string`&&t.trim().length>0){let e=F(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=F(n);return e.length>0?e:null}return null},L=()=>{if(typeof window<`u`){if(M)return M;let e=typeof window.__OPENCHAMBER_HOME__==`string`&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return M=e,m(`homeDirectory`,e,{storage:N}),e;let t=an();if(t&&!f())return M=t,t}return sn()||`/`},cn=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);if(n.length>1){let e=n.replace(/\/+$/,``);if(e&&e.length>0)return e===`/`?null:e}return n===`/`||n.length===0?null:n},ln=e=>(M=e,typeof window<`u`&&m(`homeDirectory`,e,{storage:N}),_({homeDirectory:e}),e),un=async()=>{let e=e=>{let t=cn(e);return t?ln(t):null};try{let t=e(await A.getFilesystemHome());if(t)return t}catch(e){console.warn(`Failed to obtain filesystem home directory:`,e)}try{let t=e((await A.getSystemInfo())?.homeDirectory);if(t)return t}catch(e){console.warn(`Failed to get home directory from system info:`,e)}try{let t=e(await ie());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=L();return e(t)||t},R=(()=>{if(!f())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null})()||L(),z=(()=>{let e=on();return e&&!f()?I(e,R):R})();z&&A.setDirectory(z);var dn=!!(R&&R!==`/`),B=ae()(oe((e,t)=>({currentDirectory:z,directoryHistory:[z],historyIndex:0,homeDirectory:R,hasPersistedDirectory:nn,isHomeReady:dn,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=I(n,M||t().homeDirectory||p(`homeDirectory`,{storage:N}));Vt(),ue(t().currentDirectory,i)&&(A.setDirectory(i),P(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return m(`lastDirectory`,i,{storage:N}),_({lastDirectory:i}),{currentDirectory:i,directoryHistory:t,historyIndex:t.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}}))},goBack:()=>{let n=t();if(n.historyIndex>0){let t=n.historyIndex-1,r=n.directoryHistory[t];A.setDirectory(r),P(),m(`lastDirectory`,r,{storage:N}),_({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{let n=t();if(n.historyIndex<n.directoryHistory.length-1){let t=n.historyIndex+1,r=n.directoryHistory[t];A.setDirectory(r),P(),m(`lastDirectory`,r,{storage:N}),_({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{let{currentDirectory:e,setDirectory:n}=t();if(e===(M||t().homeDirectory||L())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?M||L():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=M||t().homeDirectory||await un();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;M=i;let a=r.homeDirectory!==i,o=p(`lastDirectory`,{storage:N}),s=typeof o==`string`&&o.length>0,c=!s&&(r.currentDirectory===`/`||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||e({isHomeReady:!0});return}let l=typeof i==`string`&&i!==``&&i!==`/`,u=r.currentDirectory?I(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>I(e,i)),f=d.some((e,t)=>e!==r.directoryHistory[t]),h=!!(u&&u!==r.currentDirectory),g={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(g.currentDirectory=i,g.directoryHistory=[i],g.historyIndex=0,g.isSwitchingDirectory=!1):(h||f)&&(g.currentDirectory=u,g.directoryHistory=d,g.historyIndex=Math.min(r.historyIndex,d.length-1),g.isSwitchingDirectory=!1),e(()=>g),(c||h)&&l){let e=c?i:u;A.setDirectory(e),P(),m(`lastDirectory`,e,{storage:N}),_({lastDirectory:e})}_({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(un().then(e=>{B.getState().synchronizeHomeDirectory(e)}),u(e=>{M=null;let n=++en;if(t(e)){let e=an(),t=on(),n=e||`/`,r=t||n;M=e,B.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(A.setDirectory(r),P())}un().then(e=>{n===en&&B.getState().synchronizeHomeDirectory(e)})}));var fn=`x-openchamber-target-port`,pn=()=>{let e=a();for(let[t,n]of Object.entries(e)){if(t.trim().toLowerCase()!==fn)continue;let e=n.trim();return e?{[fn]:e}:void 0}},mn=(e,t)=>{let n=s();return n?n.openWebSocket(d(e),t,pn()):l(t?new WebSocket(e,t):new WebSocket(e))},V=`/api/git`,hn=1200,gn=5e3,_n=2,vn=5e3,yn=`${V}/worktrees/queue-activation`,bn=`message_queue_activation_pending`,xn=`worktree_lifecycle_busy`,Sn=`worktree_activation_stale`,Cn=5e3,wn=3e4,Tn=[0,500,1e3,2e3,4e3,8e3,14e3],H=new Map,U=new Map,En=new Map,W=new Map,G=new Map,K=new Map,q=new Map,Dn=new Map,J=new Map,On=new Map,kn=new Set,Y=0,An=[],jn=()=>Y<_n?(Y+=1,Promise.resolve()):new Promise(e=>{An.push(e)}),Mn=()=>{let e=An.shift();if(e){e();return}Y=Math.max(0,Y-1)},Nn=async e=>{await jn();try{return await e()}finally{Mn()}},Pn=Symbol.for(`openchamber.git.discoveryGated`),Fn=e=>(Object.defineProperty(e,Pn,{value:!0,configurable:!0}),e),In=e=>typeof e==`function`&&e[Pn]===!0,X=e=>e.trim(),Ln=(e,t)=>t===`light`?`${X(e)}::light`:X(e),Rn=e=>En.get(X(e))??0,Z=e=>{let t=X(e);En.set(t,Rn(e)+1);for(let e of Array.from(H.keys()))(e===t||e.startsWith(`${t}::`))&&H.delete(e);for(let e of Array.from(U.keys()))(e===t||e.startsWith(`${t}::`))&&U.delete(e)},zn=e=>On.get(X(e))??0,Q=e=>{let t=X(e);t&&(On.set(t,zn(e)+1),Dn.delete(t),J.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),i().api(e,r)}var Bn=(e,t,n)=>{let r=X(e);if(!r)return;let i=Date.now()+vn;W.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;K.set(r,{value:{root:a},expiresAt:i})};async function Vn(e){let t=Array.from(new Set(e.map(e=>X(e)).filter(Boolean))),n=new Map;if(t.length===0)return n;let r=Date.now(),a=[];for(let e of t){let t=W.get(e),i=K.get(e);if(t&&t.expiresAt>r&&i&&i.expiresAt>r){n.set(e,{isGitRepository:t.value,primaryRoot:i.value.root});continue}a.push(e)}if(a.length===0)return n;let o=e=>{for(let t of e){let e=typeof t.directory==`string`?X(t.directory):``;if(!e)continue;let r=!!t.isGitRepository,i=typeof t.primaryRoot==`string`&&t.primaryRoot?t.primaryRoot:null;Bn(e,r,i),n.set(e,{isGitRepository:r,primaryRoot:i})}},s=async e=>{await Promise.all(e.map(async e=>{try{let[t,r]=await Promise.all([Hn(e),Wn(e).then(e=>e.root).catch(()=>e)]);Bn(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Bn(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Nn(async()=>{let e=new URLSearchParams;for(let t of a)e.append(`directories`,t);let t=i().api(`${V}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await g(r);if(s.status===501||!s.ok)throw Error(`Batch git discover unavailable: ${s.status} ${s.statusText}`);let c=await s.json().catch(()=>null),l=Array.isArray(c)?c:[];if(l.length===0&&a.length>0)throw Error(`Batch git discover returned empty payload`);o(l)})}catch{}let c=a.filter(e=>!n.has(e));return c.length>0&&await s(c),n}async function Hn(e){let t=X(e),n=Date.now(),r=W.get(t);if(r&&r.expiresAt>n)return r.value;let i=G.get(t);if(i)return i;let a=(async()=>{let n=await g($(`${V}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return W.set(t,{value:r,expiresAt:Date.now()+gn}),r})();G.set(t,a);try{return await a}finally{G.get(t)===a&&G.delete(t)}}async function Un(e,t){let n=t?.mode,r=Ln(e,n),i=Date.now(),a=H.get(r);if(a&&a.expiresAt>i)return a.value;let o=U.get(r);if(o)return o;let s=(async()=>{let t=Rn(e),i=await g($(`${V}/status`,e,n?{mode:n}:void 0));if(!i.ok)throw Error(`Failed to get git status: ${i.statusText}`);let a=await i.json();return Rn(e)===t&&H.set(r,{value:a,expiresAt:Date.now()+hn}),a})();U.set(r,s);try{return await s}finally{U.get(r)===s&&U.delete(r)}}async function Wn(e){let t=X(e),n=Date.now(),r=K.get(t);if(r&&r.expiresAt>n)return r.value;let i=q.get(t);if(i)return i;let a=Nn(async()=>{let n=await g($(`${V}/primary-root`,e));if(!n.ok)throw Error(`Failed to resolve git primary root: ${n.statusText}`);let r=await n.json().catch(()=>({})),i={root:typeof r.root==`string`&&r.root?r.root:e};return K.set(t,{value:i,expiresAt:Date.now()+vn}),i});q.set(t,a);try{return await a}finally{q.get(t)===a&&q.delete(t)}}async function Gn(e){let t=await g($(`${V}/toplevel`,e));if(!t.ok)throw Error(`Failed to resolve git toplevel: ${t.statusText}`);let n=await t.json().catch(()=>({}));return{root:typeof n.root==`string`&&n.root?n.root:e}}async function Kn(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await g($(`${V}/diff`,e,{path:n,staged:r?`true`:void 0,context:i}));if(!a.ok)throw Error(`Failed to get git diff: ${a.statusText}`);return a.json()}async function qn(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await g($(`${V}/file-diff`,e,{path:n,staged:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get git file diff: ${i.statusText}`);return i.json()}async function Jn(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await g($(`${V}/revert`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to revert git changes`)}Z(e)}async function Yn(e,t){await Xn(e,[t])}async function Xn(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to stage git changes`);let r=await g($(`${V}/stage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to stage git changes`)}Z(e)}async function Zn(e,t){await Qn(e,[t])}async function Qn(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to unstage git changes`);let r=await g($(`${V}/unstage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to unstage git changes`)}Z(e)}async function $n(e,t,n){await nr(e,t,n,`stage`)}async function er(e,t,n){await nr(e,t,n,`unstage`)}async function tr(e,t,n){await nr(e,t,n,`discard`)}async function nr(e,t,n,r){if(!t)throw Error(`path is required to apply a git hunk`);if(typeof n!=`string`||!n.trim())throw Error(`patch is required to apply a git hunk`);let i=await g($(`${V}/apply-hunk`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,patch:n,action:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to apply git hunk`)}Z(e)}async function rr(e){if(!e)return!1;let t=await g($(`${V}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function ir(e,t){let n=await g($(`${V}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function ar(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await g($(`${V}/branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete branch`)}return n.json()}async function or(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await g($(`${V}/remote-branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete remote branch`)}return n.json()}async function sr(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await g($(`${V}/remotes`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remote:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to remove remote`)}return r.json()}async function cr(e,t,n){if(!Array.isArray(t)||t.length===0)throw Error(`No files provided to generate commit message`);let r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);let i=await g($(`${V}/commit-message`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));console.error(`[git-generation][browser] http error`,{status:i.status,statusText:i.statusText,error:e});let t=typeof e?.traceId==`string`&&e.traceId?` (traceId: ${e.traceId})`:``;throw Error(`${e.error||`Failed to generate commit message`}${t}`)}let a=await i.json();if(!a?.message||typeof a.message!=`object`)throw Error(`Malformed commit generation response`);return{message:{subject:typeof a.message.subject==`string`&&a.message.subject.trim().length>0?a.message.subject.trim():``,highlights:Array.isArray(a.message.highlights)?a.message.highlights.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()):[]}}}async function lr(e,t){let{base:n,head:r,context:i,zenModel:a,providerId:o,modelId:s}=t;if(!n||!r)throw Error(`base and head are required`);let c={base:n,head:r};i?.trim()&&(c.context=i.trim()),a&&(c.zenModel=a),o&&(c.providerId=o),s&&(c.modelId=s);let l=await g($(`${V}/pr-description`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c)});if(!l.ok){let e=await l.json().catch(()=>({error:l.statusText}));throw Error(e.error||`Failed to generate PR description`)}let u=await l.json().catch(()=>null),d=typeof u?.title==`string`?u.title:``,f=typeof u?.body==`string`?u.body:``;if(!d&&!f)throw Error(`Malformed PR description response`);return{title:d,body:f}}async function ur(e){let t=X(e),n=Date.now(),r=Dn.get(t);if(r&&r.expiresAt>n)return r.value;let i=J.get(t);if(i)return i;let a=zn(e),o=Nn(async()=>{let n=await g($(`${V}/worktrees`,e));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to list worktrees`)}let r=await n.json();return a===zn(e)&&Dn.set(t,{value:r,expiresAt:Date.now()+vn}),r});J.set(t,o);try{return await o}finally{J.get(t)===o&&J.delete(t)}}Fn(ur);async function dr(e,t){let n=await g($(`${V}/worktrees/validate`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to validate worktree`)}return n.json()}async function fr(e){let t=await g($(`${V}/worktrees/bootstrap-status`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to get worktree bootstrap status`)}return t.json()}async function pr(e,t){let n=await g($(`${V}/worktrees/preview`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to preview worktree`)}return n.json()}var mr=e=>typeof e==`string`&&e.length>0,hr=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!mr(t.name)||!mr(t.path))return null;let n={head:typeof t.head==`string`?t.head:``,name:t.name,branch:typeof t.branch==`string`?t.branch:``,path:t.path};return t.directoryCreated===!0&&(n.directoryCreated=!0),t.bootstrapStatus&&typeof t.bootstrapStatus==`object`&&(n.bootstrapStatus=t.bootstrapStatus),n},gr=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==bn)return null;let i=hr(r.worktree);if(!i)return null;let a=r.repair;if(!a||typeof a!=`object`)return null;let o=a;if(o.method!==`POST`||o.path!==yn)return null;let s=o.body;if(!s||typeof s!=`object`)return null;let c=s;return c.projectDirectory!==n||c.directory!==i.path?null:i},_r=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,vr=e=>new Promise(t=>{setTimeout(t,e)}),yr=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===xn||t?.code===Sn}return e.status===503&&(await e.json().catch(()=>null))?.code===bn},br=e=>e===400||e===401||e===403||e===501,xr=(e,t)=>{let r=n(),i=o(),a=_r(r,i,e,t);if(kn.has(a))return;kn.add(a);let s=()=>n()===r&&o()===i;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<wn;){if(!s())return;let i=Tn[Math.min(r,Tn.length-1)]??0;if(i>0){let e=wn-(Date.now()-n);if(e<=0||(await vr(Math.min(i,e)),!s()))return}let a=new AbortController,o=setTimeout(()=>a.abort(),Cn);try{let n=await g($(yn,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:a.signal});if(n.ok||br(n.status))return;if(await yr(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(o)}}})().catch(()=>{}).finally(()=>{kn.delete(a)})};async function Sr(e,t){let n=await g($(`${V}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=hr(r);if(t)return Q(e),t;if(r&&typeof r==`object`)return Q(e),r;throw Error(`Failed to create worktree`)}let i=gr(n.status,r,e);if(i)return Q(e),xr(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function Cr(e,t){let n=await g($(`${V}/worktrees`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete worktree`)}let r=await n.json();return Q(e),r}async function wr(e,t,n={}){let r=await g($(`${V}/commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create commit`)}let i=await r.json();return Z(e),i}async function Tr(e,t={}){let n=await g($(`${V}/push`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to push`)}let r=await n.json();return Z(e),r}async function Er(e,t={}){let n=await g($(`${V}/pull`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to pull`)}let r=await n.json();return Z(e),r}async function Dr(e,t={}){let n=await g($(`${V}/fetch`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to fetch`)}let r=await n.json();return Z(e),r}async function Or(e){let t=await g($(`${V}/stashes`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to list stashes`)}return t.json()}async function kr(e,t){let n=await g($(`${V}/stashes/file-counts`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refs:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to count stash files`)}return n.json()}async function Ar(e,t={}){let n=await g($(`${V}/stash`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to stash changes`)}return n.json()}var jr=async(e,t,n)=>{let r=await g($(`${V}/${t}`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to ${t}`)}return r.json()},Mr=(e,t)=>jr(e,`stash/apply`,t),Nr=(e,t)=>jr(e,`stash/pop`,t),Pr=(e,t)=>jr(e,`stash/drop`,t);async function Fr(e,t){let n=await g($(`${V}/checkout`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({branch:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout branch`)}return n.json()}async function Ir(e,t,n){let r=await g($(`${V}/branches`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create branch`)}return r.json()}async function Lr(e,t,n){let r=await g($(`${V}/branches/rename`,e),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename branch`)}return r.json()}async function Rr(e,t={}){let n=await g($(`${V}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?`true`:void 0}));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(`Failed to get git log: ${e.error||n.statusText}`)}return n.json()}async function zr(e,t){let n=await g($(`${V}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Br(e,t,n,r){let i=await g($(`${V}/commit-file-diff`,e,{hash:t,path:n,binary:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function Vr(){let e=await g($(`${V}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Hr(e){let t=await g($(`${V}/identities`,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to create git identity`)}return t.json()}async function Ur(e,t){let n=await g($(`${V}/identities/${e}`,void 0),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to update git identity`)}return n.json()}async function Wr(e){let t=await g($(`${V}/identities/${e}`,void 0),{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to delete git identity`)}}async function Gr(e){if(!e)return null;let t=await g($(`${V}/current-identity`,e));if(!t.ok)throw Error(`Failed to get current git identity: ${t.statusText}`);let n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Kr(e){if(!e)return!1;let t=await g($(`${V}/has-local-identity`,e));if(!t.ok)throw Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function qr(){let e=await g($(`${V}/global-identity`,void 0));if(!e.ok)throw Error(`Failed to get global git identity: ${e.statusText}`);let t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Jr(e,t){let n=await g($(`${V}/set-identity`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profileId:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to set git identity`)}return n.json()}async function Yr(){let e=await g($(`${V}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Xr(e,t){let n=await g($(`${V}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function Zr(e,t){let n=await g($(`${V}/rebase`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to rebase`)}return n.json()}async function Qr(e){let t=await g($(`${V}/rebase/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort rebase`)}return t.json()}async function $r(e,t){let n=await g($(`${V}/merge`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to merge`)}return n.json()}async function ei(e,t){let n=await g($(`${V}/checkout-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout commit`)}return n.json()}async function ti(e,t){let n=await g($(`${V}/cherry-pick`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to cherry-pick`)}return n.json()}async function ni(e,t){let n=await g($(`${V}/revert-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to revert commit`)}return n.json()}async function ri(e,t,n,r){let i=await g($(`${V}/reset-to-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t,mode:n,force:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to reset`)}return i.json()}async function ii(e){let t=await g($(`${V}/merge/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort merge`)}return t.json()}async function ai(e){let t=await g($(`${V}/rebase/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue rebase`)}return t.json()}async function oi(e){let t=await g($(`${V}/merge/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue merge`)}return t.json()}async function si(e,t){return await Ar(e,{message:t?.message}),{success:!0}}async function ci(e){return await Nr(e,{ref:`stash@{0}`}),{success:!0}}async function li(e){let t=await g($(`${V}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function ui(e,t){let n=await g(`${V}/validate-directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function di(e){let t=await g(`${V}/canonicalize-worktree-state`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e})});if(!t.ok)throw Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}var fi=()=>typeof window>`u`?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol===`capacitor:`,pi=()=>{if(typeof window>`u`||!fi()||mi()!==`ios`)return!1;let e=navigator.userAgent||``,t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},mi=()=>{if(typeof window<`u`){let e=window.Capacitor?.getPlatform?.();if(e===`ios`||e===`android`)return e}return f()?`vscode`:h()?`desktop`:`web`};export{Zr as $,li as A,$t as At,Xr as B,Pe as Bt,Yr as C,B as Ct,lr as D,qt as Dt,cr as E,Jt as Et,Vr as F,it as Ft,Q as G,Ge as Gt,Er as H,Be as Ht,Rr as I,rt as It,Or as J,ye as Jt,In as K,Fe as Kt,Un as L,Ve as Lt,ir as M,Bt as Mt,Kn as N,A as Nt,Br as O,Vt as Ot,qn as P,C as Pt,pr as Q,fr as R,Me as Rt,or as S,mn as St,Pr as T,Xt as Tt,Tr as U,He as Ut,Dr as V,ze as Vt,Kr as W,Ue as Wt,$r as X,ur as Y,Se as Yt,Nr as Z,Hr as _,er as _t,Qr as a,ni as at,Wr as b,ui as bt,Hn as c,Jr as ct,ti as d,$n as dt,sr as et,oi as f,si as ft,wr as g,Qn as gt,Ir as h,Zn as ht,ii as i,Gn as it,Gr as j,Qt as jt,zr as k,Zt as kt,Fr as l,Yn as lt,kr as m,ci as mt,fi as n,ri as nt,Mr as o,Jn as ot,ai as p,Ar as pt,rr as q,be as qt,pi as r,Wn as rt,di as s,tr as st,mi as t,Lr as tt,ei as u,Xn as ut,Sr as v,Ur as vt,Vn as w,Yt as wt,Cr as x,Nn as xt,ar as y,dr as yt,qr as z,Ne as zt};