@openchambery/web 1.18.4-beta.6 → 1.18.4-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +25 -0
- package/bin/lib/DOCUMENTATION.md +2 -1
- package/bin/lib/cli-args.js +19 -0
- package/bin/lib/commands-serve.js +73 -4
- package/dist/assets/{AgentAvatar-BvhXxFvg.js → AgentAvatar-DAnelAnB.js} +1 -1
- package/dist/assets/{AssistantView-C71fxVQJ.js → AssistantView-gAiFMDUJ.js} +1 -1
- package/dist/assets/{ChatContainer-C25uUZEc.js → ChatContainer--pExLV0s.js} +18 -18
- package/dist/assets/{DiagramView-D-0pq_LG.js → DiagramView-DVPEFJ-e.js} +1 -1
- package/dist/assets/{FadeInOnReveal-98buIVdv.js → FadeInOnReveal-QxF1vuqX.js} +1 -1
- package/dist/assets/{Icon-BhSwbLaF.js → Icon-D-X70irR.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BPBGslhm.js → MarkdownRendererImpl-BRHbul8Z.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-CeuGZn2R.js → MobileDetailNavigation-QdKhV7QI.js} +1 -1
- package/dist/assets/MobileShareBridge-BZQU25sk.js +4 -0
- package/dist/assets/MobileSurface-D8lS-QI-.js +2 -0
- package/dist/assets/{MultiRunWindow-Cnnhxk-c.js → MultiRunWindow-CFkkK54L.js} +1 -1
- package/dist/assets/{OnboardingScreen-BN4L1hqu.js → OnboardingScreen-BIhY1_hf.js} +1 -1
- package/dist/assets/{OverlayScrollbar-CXFN6Cqq.js → OverlayScrollbar-CHXk_jvF.js} +1 -1
- package/dist/assets/{SettingsView-CxBOEPcX.js → SettingsView-BK_KyEGa.js} +10 -10
- package/dist/assets/{SettingsWindow-CSnveV5T.js → SettingsWindow-Jh9KQuAX.js} +1 -1
- package/dist/assets/{TerminalView-4X9QIzLd.js → TerminalView-CsJ_5RIn.js} +1 -1
- package/dist/assets/{ToolOutputDialog-C5Rsi0ix.js → ToolOutputDialog-DVCDFHSZ.js} +1 -1
- package/dist/assets/{appThemeRegistry-6YCqPDdh.js → appThemeRegistry-BD3shSNM.js} +2 -2
- package/dist/assets/{button-KTZJ84Mx.js → button-CwLFtUNT.js} +1 -1
- package/dist/assets/{clipboard-BvJ7NunE.js → clipboard-DKpuHEKi.js} +1 -1
- package/dist/assets/{collapsible-CqcZGw3W.js → collapsible-CP1-_pY6.js} +1 -1
- package/dist/assets/{context-menu-ItR7JeMm.js → context-menu-g6mcnBM7.js} +1 -1
- package/dist/assets/desktopHosts-Cr3LE55y.js +1 -0
- package/dist/assets/desktopRelayRestore-VfMK9fdk.js +1 -0
- package/dist/assets/{diagram-B8D9Klct.js → diagram-rYL80jaS.js} +1 -1
- package/dist/assets/{dialog-sGFkIKP2.js → dialog-BUMPZfVo.js} +1 -1
- package/dist/assets/{es-BuinIayO.js → es-BXwKr_ZN.js} +2 -2
- package/dist/assets/{fileQueries-BSE4ycQt.js → fileQueries-CXaw4b1W.js} +1 -1
- package/dist/assets/{fr-CT7us58h.js → fr-DwB802Hk.js} +3 -3
- package/dist/assets/{gitApi-C05aarFU.js → gitApi-jtNyXM2i.js} +1 -1
- package/dist/assets/{input-CgIoxUJc.js → input-D52Jicb1.js} +1 -1
- package/dist/assets/{insertionBoundaries-B1qEhnwJ.js → insertionBoundaries-PCEg03bu.js} +1 -1
- package/dist/assets/{ja-CCuAH4nO.js → ja-Bi58i710.js} +2 -2
- package/dist/assets/{ko-lXbhGt6P.js → ko-Bpdqclbh.js} +2 -2
- package/dist/assets/{main-CUjrXmZE.js → main-BYR7oXuI.js} +2 -2
- package/dist/assets/{main-CMSXnD8-.js → main-BhfSJeRs.js} +13 -13
- package/dist/assets/{markdown-worker-C5Om4TVK.js → markdown-worker-N9d_Z-7s.js} +1 -1
- package/dist/assets/{markdownTheme-BdF4C4-o.js → markdownTheme-Bl0Sy0Lf.js} +1 -1
- package/dist/assets/{miniChat-t_4iBTuw.js → miniChat-DJn_UXg4.js} +2 -2
- package/dist/assets/mobile-DLhipvmN.js +2 -0
- package/dist/assets/{multirun-Deu0GsaN.js → multirun-C2pAuOrf.js} +1 -1
- package/dist/assets/persistence-vZ7H8WKh.js +3 -0
- package/dist/assets/pl-Du2feKpf.js +15 -0
- package/dist/assets/platform-CTaznShj.js +2 -0
- package/dist/assets/{projectMeta-C_kYsova.js → projectMeta-Cn9CpPEo.js} +2 -2
- package/dist/assets/{pt-BR-DWbGs1bc.js → pt-BR-BWH_Buhv.js} +2 -2
- package/dist/assets/{radio-uNnEkXyx.js → radio-DVYb5sTr.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-C8DAzLcf.js → renderElectronMiniChatApp-xKOT0Nvl.js} +2 -2
- package/dist/assets/{renderMobileApp-AjwW2czA.js → renderMobileApp-BGDuJARi.js} +5 -5
- package/dist/assets/runtimeConfig-Cldsj4A8.js +2 -0
- package/dist/assets/{runtimeEndpointReset-DJkQXFX9.js → runtimeEndpointReset-CSgU2-12.js} +2 -2
- package/dist/assets/{sortable-tabs-strip-pSnPuBXA.js → sortable-tabs-strip-yILKXhUh.js} +1 -1
- package/dist/assets/src-Dbdlm5x1.css +2 -0
- package/dist/assets/{store-BuXogmxp.js → store-Dd7SwiXs.js} +2 -2
- package/dist/assets/{terminalApi-jfes-HIU.js → terminalApi-KDUc5mh2.js} +1 -1
- package/dist/assets/{tooltip-rN8LrxMF.js → tooltip-CaCe-GAm.js} +1 -1
- package/dist/assets/{uk-DgOxtvS7.js → uk-DLdEJOBL.js} +2 -2
- package/dist/assets/{url-B0Ak7X6b.js → url-B-FWrnxu.js} +1 -1
- package/dist/assets/useAppFontEffects-CXQZ4yy-.js +7 -0
- package/dist/assets/{useAssistantUIStore-SPh025NE.js → useAssistantUIStore-ifqNyja4.js} +1 -1
- package/dist/assets/{useDesktopWindowControlsLayout-D3dqdJeh.js → useDesktopWindowControlsLayout-C1jjLChc.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-DwBUAdt4.js → useEffectiveDirectory-Bkoa0uuw.js} +1 -1
- package/dist/assets/{useFontPreferences-Bz3crRRO.js → useFontPreferences-D_LFFhFS.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-DbgXlqQj.js → useMobileNavigationStore-B34Winlp.js} +11 -11
- package/dist/assets/useSessionAutoCleanup-C9bcDyFO.js +1 -0
- package/dist/assets/useUIStore-NfqK-HA7.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-uDlox7Hk.js → useWorkerHighlightedLines-wbAA15f3.js} +1 -1
- package/dist/assets/{utils-DfPDhqys.js → utils-C2P0wcWO.js} +1 -1
- package/dist/assets/{zh-CN-BPGatJp9.js → zh-CN-D_ZMA-QZ.js} +2 -2
- package/dist/assets/{zh-TW-qUWWsaxK.js → zh-TW-CBJ2QB4M.js} +2 -2
- package/dist/index.html +9 -9
- package/dist/mini-chat.html +9 -9
- package/dist/mobile.html +9 -9
- package/package.json +1 -1
- package/server/index.d.ts +0 -4
- package/server/index.js +11 -20
- package/server/lib/client-auth/pairing.js +1 -7
- package/server/lib/client-auth/pairing.test.js +0 -45
- package/server/lib/opencode/DOCUMENTATION.md +4 -4
- package/server/lib/opencode/bootstrap-runtime.js +0 -6
- package/server/lib/opencode/cli-entry-runtime.js +5 -1
- package/server/lib/opencode/cli-entry-runtime.test.js +17 -0
- package/server/lib/opencode/core-routes.js +0 -3
- package/server/lib/opencode/core-routes.test.js +0 -15
- package/server/lib/opencode/openchamber-routes.js +0 -11
- package/server/lib/relay/DOCUMENTATION.md +3 -45
- package/server/lib/relay/host-client.js +1 -4
- package/server/lib/relay/service.js +28 -16
- package/server/lib/relay/service.test.js +64 -4
- package/server/lib/relay/tunnel-host.js +2 -52
- package/server/lib/relay/tunnel-host.test.js +2 -250
- package/dist/assets/MobileShareBridge-x6v_4qIx.js +0 -4
- package/dist/assets/MobileSurface-Dzu9algh.js +0 -2
- package/dist/assets/desktopHosts-aA40MHzB.js +0 -1
- package/dist/assets/desktopRelayRestore-CxUYRC6v.js +0 -1
- package/dist/assets/mobile-DTpbEiyr.js +0 -2
- package/dist/assets/persistence-DwXJK4-j.js +0 -3
- package/dist/assets/pl-DCsKBRAg.js +0 -15
- package/dist/assets/platform-CXJwZIZe.js +0 -2
- package/dist/assets/runtimeConfig-C3lfsV4y.js +0 -2
- package/dist/assets/src-CV_a1GoP.css +0 -2
- package/dist/assets/useAppFontEffects-DKx61bCr.js +0 -7
- package/dist/assets/useSessionAutoCleanup-x2K_C50s.js +0 -1
- package/dist/assets/useUIStore-BJpkPwky.js +0 -1
- package/server/lib/desktop-hosts/routes.js +0 -157
- package/server/lib/desktop-hosts/routes.test.js +0 -227
|
@@ -1,2 +0,0 @@
|
|
|
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-BJpkPwky.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-DwXJK4-j.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};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-capacitor-app-PzT84wSx.js","assets/rolldown-runtime-C0FnF6B9.js","assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{F as e,G as t,H as n,I as r,K as i,N as a,O as o,P as s,U as c,W as l}from"./useUIStore-BJpkPwky.js";import{On as u,et as d,kn as f}from"./persistence-DwXJK4-j.js";import{t as ee}from"./desktopRelayRestore-CxUYRC6v.js";import{$ as te,A as ne,B as re,Ct as ie,D as ae,E as oe,F as se,H as ce,I as le,J as ue,L as de,M as fe,N as pe,P as me,Q as he,R as ge,S as _e,T as ve,U as ye,V as be,W as xe,X as Se,Y as p,Z as Ce,_ as we,_t as Te,a as Ee,at as De,b as Oe,bt as ke,c as Ae,ct as je,d as Me,dt as Ne,et as m,f as h,ft as g,g as _,gt as v,h as y,ht as b,i as Pe,j as Fe,k as Ie,l as Le,lt as Re,m as ze,mt as Be,n as x,nt as Ve,o as He,ot as Ue,p as We,pt as Ge,q as Ke,s as qe,st as Je,t as Ye,tt as Xe,u as Ze,ut as Qe,v as S,vt as $e,x as C,y as et,yt as w}from"./platform-CXJwZIZe.js";import{n as T,o as E}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{a as tt,c as nt,l as rt,n as it,r as at,s as ot,t as st}from"./terminalApi-jfes-HIU.js";import{t as D}from"./types-BuiqMmh_.js";import{n as O,t as k}from"./capgoAdapter-DCowZ2ab.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var ct=e=>{let t=e?.retry;return{maxRetries:t?.maxRetries??3,initialRetryDelay:t?.initialDelayMs??1e3,maxRetryDelay:t?.maxDelayMs??8e3,connectionTimeout:e?.connectionTimeoutMs??1e4}},lt=()=>({async createSession(e){return at(e)},connect(e,t,n){let r=it(e,t.onEvent,t.onError,ct(n));return{close:()=>r()}},async sendInput(e,t){await rt(e,t)},async resize(e){await ot(e.sessionId,e.cols,e.rows)},async close(e){await st(e)},async restartSession(e,t){return nt(e,{cwd:t.cwd??``,cols:t.cols,rows:t.rows})},async forceKill(e){await tt(e)}}),ut=()=>({checkIsGitRepository:Ae,getGitStatus:de,getGitDiff:pe,getGitFileDiff:me,revertGitFile:Ue,stageGitFile:Re,stageGitFiles:Qe,unstageGitFile:b,unstageGitFiles:v,stageGitHunk:Ne,unstageGitHunk:Te,revertGitHunk:Je,isLinkedWorktree:Ke,getGitBranches:fe,deleteGitBranch:et,deleteRemoteBranch:_e,removeRemote:m,generateCommitMessage:oe,generatePullRequestDescription:ae,listGitWorktrees:p,validateGitWorktree:w,createGitWorktree:S,deleteGitWorktree:C,validateWorktreeDirectory:ke,canonicalizeWorktreeState:qe,createGitCommit(e,t,n){return _(e,t,n)},gitPush:ye,gitPull:ce,gitFetch:be,listGitStashes:ue,countGitStashFiles:ze,stashGitChanges:Ge,applyGitStash:He,popGitStash:Ce,dropGitStash:ve,checkoutBranch:Le,createBranch:y,renameBranch:Xe,getGitLog(e,t){return le(e,t)},getCommitFiles:Ie,getCurrentGitIdentity:Fe,hasLocalIdentity:xe,setGitIdentity:je,getGitIdentities:se,createGitIdentity:we,updateGitIdentity:$e,deleteGitIdentity:Oe,getRemotes:re,rebase:te,abortRebase:Ee,continueRebase:We,merge:Se,abortMerge:Pe,continueMerge:h,checkoutCommit:Ze,cherryPick:Me,revertCommit:De,resetToCommit:Ve,stash:g,stashPop:Be,getConflictDetails:ne,worktree:{list:p,validate:w,bootstrapStatus:ge,preview:he,create:S,remove:C}}),A=e=>e.replace(/\\/g,`/`),dt=(e,t)=>({directory:A(t?.directory||t?.path||e),entries:(Array.isArray(t?.entries)?t.entries:[]).filter(e=>!!(e&&typeof e.name==`string`&&typeof e.path==`string`)).map(e=>({name:e.name,path:A(e.path),isDirectory:!!e.isDirectory}))}),j=(e,t)=>{let n=t||e?.();return n?{"x-opencode-directory":n}:void 0},ft=({getDirectory:e})=>({async listDirectory(t,n){let r=A(t),i=new URLSearchParams;r&&i.set(`path`,r),n?.respectGitignore&&i.set(`respectGitignore`,`true`);let a=await f(`/api/fs/list`,{query:i,headers:j(e)});if(!a.ok){let e=await a.json().catch(()=>({error:a.statusText}));throw Error(e.error||`Failed to list directory`)}return dt(r,await a.json())},async search(t){let n=new URLSearchParams,r=A(t.directory);r&&n.set(`directory`,r),n.set(`query`,t.query),n.set(`dirs`,`false`),n.set(`type`,`file`),typeof t.maxResults==`number`&&Number.isFinite(t.maxResults)&&n.set(`limit`,String(t.maxResults));let i=await f(`/api/find/file`,{query:n,headers:j(e)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to search files`)}let a=await i.json();return(Array.isArray(a)?a:[]).map(e=>({path:A(`${r}/${e}`),preview:[A(e)]}))},async createDirectory(t){let n=A(t),r=await f(`/api/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`,...j(e)},body:JSON.stringify({path:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create directory`)}let i=await r.json();return{success:!!i?.success,path:typeof i?.path==`string`?A(i.path):n}},async statFile(t,n){let r=A(t),i=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&i.set(`allowOutsideWorkspace`,`true`),n?.outsideFileGrant&&i.set(`outsideFileGrant`,n.outsideFileGrant);let a=await f(`/api/fs/stat`,{query:i,headers:j(e,n?.directory)});if(!a.ok){let e=await a.json().catch(()=>({error:a.statusText}));throw Error(e.error||`Failed to stat file`)}let o=await a.json().catch(()=>({}));return{path:typeof o.path==`string`?A(o.path):r,isFile:!!o.isFile,size:typeof o.size==`number`?o.size:0,mtimeMs:typeof o.mtimeMs==`number`?o.mtimeMs:void 0,isBinary:typeof o.isBinary==`boolean`?o.isBinary:void 0}},async readFile(t,n){let r=A(t),i=new URLSearchParams({path:r});n?.allowOutsideWorkspace&&i.set(`allowOutsideWorkspace`,`true`),n?.outsideFileGrant&&i.set(`outsideFileGrant`,n.outsideFileGrant),n?.optional&&i.set(`optional`,`true`);let a=await f(`/api/fs/read`,{query:i,cache:n?.optional?`no-store`:`default`,headers:j(e,n?.directory)});if(!a.ok){let e=await a.json().catch(()=>({error:a.statusText}));throw Error(e.error||`Failed to read file`)}let o=await a.text();if(n?.optional){let e=a.headers.get(`x-openchamber-file-exists`);if(e!==`true`&&e!==`false`)throw Error(`Optional file read requires an existence response header`);return{content:o,path:r,exists:e===`true`}}return{content:o,path:r,exists:!0}},async writeFile(t,n){let r=A(t),i=await f(`/api/fs/write`,{method:`POST`,headers:{"Content-Type":`application/json`,...j(e)},body:JSON.stringify({path:r,content:n})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to write file`)}let a=await i.json().catch(()=>({}));return{success:!!a.success,path:typeof a.path==`string`?A(a.path):r}},async delete(t){let n=A(t),r=await f(`/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...j(e)},body:JSON.stringify({path:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to delete file`)}return{success:!!(await r.json().catch(()=>({}))).success}},async rename(t,n){let r=await f(`/api/fs/rename`,{method:`POST`,headers:{"Content-Type":`application/json`,...j(e)},body:JSON.stringify({oldPath:t,newPath:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename file`)}let i=await r.json().catch(()=>({}));return{success:!!i.success,path:typeof i.path==`string`?A(i.path):n}},async revealPath(t){let n=await f(`/api/fs/reveal`,{method:`POST`,headers:{"Content-Type":`application/json`,...j(e)},body:JSON.stringify({path:A(t)})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to reveal path`)}return{success:!!(await n.json().catch(()=>({}))).success}},async downloadFile(t){let n=A(t),r=await f(`/api/fs/raw`,{query:{path:n,download:!0},headers:j(e)});if(!r.ok)throw Error(`Download failed (${r.status})`);let i=await r.blob(),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.split(`/`).pop()||`file`,document.body.appendChild(o),o.click(),document.body.removeChild(o),setTimeout(()=>URL.revokeObjectURL(a),100)}}),M=`/api/config/settings`,pt=`/api/config/reload`,N=e=>!e||typeof e!=`object`?{}:e,mt=()=>({async load(){let e=await f(M,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`Failed to load settings: ${e.statusText}`);return{settings:N(await e.json().catch(()=>({}))),source:`web`}},async save(e){let t=await f(M,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to save settings`)}return N(await t.json().catch(()=>({})))},async restartOpenCode(){let e=await f(pt,{method:`POST`});if(!e.ok){let t=await e.json().catch(()=>({error:e.statusText}));throw Error(t.error||`Failed to restart OpenCode`)}return{restarted:!0}}}),ht=()=>({async requestDirectoryAccess(e){return{success:!0,path:e.path}},async startAccessingDirectory(e){return{success:!0}},async stopAccessingDirectory(e){return{success:!0}}}),gt=1500,P=5e3,_t=`openchamber-notification-claim:`,F=new Map,vt=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus(),yt=e=>(typeof e?.tag==`string`?e.tag.trim():``)||[e?.sessionId,e?.kind,e?.title,e?.body].filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()).join(`|`),bt=e=>{for(let[t,n]of F)e-n>P&&F.delete(t)},xt=e=>{let t=yt(e);if(!t)return!0;let n=Date.now();if(bt(n),n-(F.get(t)??0)<P)return!1;try{if(typeof window<`u`&&window.localStorage){let e=`${_t}${t}`,r=Number(window.localStorage.getItem(e)??`0`);if(Number.isFinite(r)&&n-r<P)return F.set(t,r),!1;Number.isFinite(r)&&r>0&&window.localStorage.removeItem(e),window.localStorage.setItem(e,String(n))}}catch{}return F.set(t,n),!0},I=async()=>{if(typeof navigator>`u`||!(`serviceWorker`in navigator))return null;let e=null;try{e=await navigator.serviceWorker.getRegistration()??null}catch{e=null}if(e?.active)return e;if(!e)return null;try{return await Promise.race([navigator.serviceWorker.ready,new Promise(e=>{setTimeout(()=>e(null),gt)})])??e}catch{return e}},St=async e=>{let t=await I();if(!t||typeof t.showNotification!=`function`)return!1;try{return await t.showNotification(e?.title??`OpenChamber`,{body:e?.body,tag:e?.tag}),!0}catch(e){return console.warn(`Failed to send notification via service worker`,e),!1}},Ct=async()=>{let e=await I();if(!e||!(`pushManager`in e)||!e.pushManager)return!1;try{return!!await e.pushManager.getSubscription()}catch{return!1}},wt=async e=>{if(e?.requireHidden&&typeof document<`u`&&document.hasFocus())return!0;if(typeof Notification>`u`)return!1;if(Notification.permission==="default"&&await Notification.requestPermission()!==`granted`||Notification.permission!==`granted`)return console.warn(`Notification permission not granted`),!1;if(!vt()&&await Ct()||!xt(e))return!0;try{return await St(e)||new Notification(e?.title??`OpenChamber`,{body:e?.body,tag:e?.tag}),!0}catch(e){return console.warn(`Failed to send notification`,e),!1}},Tt=async e=>{if(typeof window>`u`)return!1;let t=window.__OPENCHAMBER_DESKTOP__;if(!t?.invoke)return!1;try{return await t.invoke(`desktop_notify`,{payload:{title:e?.title,body:e?.body,tag:e?.tag,kind:e?.kind,sessionId:e?.sessionId,directory:e?.directory,requireHidden:e?.requireHidden}}),!0}catch(e){return console.warn(`Failed to send native notification (desktop)`,e),!1}},Et=()=>({async notifyAgentCompletion(e){return await Tt(e)||await wt(e)},canNotify:()=>typeof window<`u`&&window.__OPENCHAMBER_DESKTOP__?.invoke?!0:typeof Notification<`u`&&Notification.permission===`granted`}),Dt=()=>({async getAvailableTools(){let e=await f(`/api/experimental/tool/ids`);if(!e.ok)throw Error(`Tools API returned ${e.status} ${e.statusText}`);let t=await e.json();if(!Array.isArray(t))throw Error(`Tools API returned invalid data format`);return t.filter(e=>typeof e==`string`&&e!==`invalid`).sort()}}),L=async(e,t)=>{try{let n=await f(e,{...t,credentials:`include`,headers:{Accept:`application/json`,...t?.headers??{}}});return n.ok?await n.json():null}catch{return null}},Ot=()=>({async getVapidPublicKey(){return L(`/api/push/vapid-public-key`)},async subscribe(e){return L(`/api/push/subscribe`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})},async unsubscribe(e){return L(`/api/push/subscribe`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})},async setVisibility(e){return L(`/api/push/visibility`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),keepalive:!0})},async registerApnsToken(e){return L(`/api/push/apns-token`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})},async unregisterApnsToken(e){return L(`/api/push/apns-token`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})}}),R=async e=>await e.json().catch(()=>null),kt=({urls:e})=>({async authStatus(){let e=await f(`/api/github/auth/status`,{method:`GET`,headers:{Accept:`application/json`}}),t=await R(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to load GitHub status`);return t},async authStart(){let e=await f(`/api/github/auth/start`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({})}),t=await R(e);if(!e.ok||!t||!(`deviceCode`in t))throw Error(t?.error||e.statusText||`Failed to start GitHub auth`);return t},async authComplete(e){let t=await f(`/api/github/auth/complete`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({deviceCode:e})}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to complete GitHub auth`);return n},async authDisconnect(){let e=await f(`/api/github/auth`,{method:`DELETE`,headers:{Accept:`application/json`}}),t=await R(e);if(!e.ok)throw Error(t?.error||e.statusText||`Failed to disconnect GitHub`);return{removed:!!t?.removed}},async authActivate(e){let t=await f(`/api/github/auth/activate`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({accountId:e})}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to activate GitHub account`);return n},async authSetGhCliDisabled(e){let t=await f(`/api/github/auth/gh-cli`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({disabled:e})}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to update gh CLI setting`);return{disabled:!!n.disabled}},async me(){let e=await f(`/api/github/me`,{method:`GET`,headers:{Accept:`application/json`}}),t=await R(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to fetch GitHub user`);return t},async prStatus(e,t,n,r){let i=new URLSearchParams({directory:e,branch:t,...n?{remote:n}:{},...r?.force?{force:`true`}:{}}),a=await f(`/api/github/pr/status?${i.toString()}`,{method:`GET`,headers:{Accept:`application/json`}}),o=await R(a);if(!a.ok||!o)throw Error(o?.error||a.statusText||`Failed to load PR status`);return o},async prCreate(e){let t=await f(`/api/github/pr/create`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to create PR`);return n},async prUpdate(e){let t=await f(`/api/github/pr/update`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to update PR`);return n},async prMerge(e){let t=await f(`/api/github/pr/merge`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to merge PR`);return n},async prReady(e){let t=await f(`/api/github/pr/ready`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to mark PR ready`);return n},async repoUpstream(e){let t=await f(`/api/github/repo/upstream?directory=${encodeURIComponent(e)}`,{method:`GET`,headers:{Accept:`application/json`}}),n=await R(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to detect upstream repo`);return n},async repoBranches(e,t){let n=await f(`/api/github/repo/branches?owner=${encodeURIComponent(e)}&repo=${encodeURIComponent(t)}`,{method:`GET`,headers:{Accept:`application/json`}}),r=await R(n);if(!n.ok||!r)throw Error(r?.error||n.statusText||`Failed to fetch repo branches`);return r.branches??[]},async prsList(e,t){let n=t?.page??1,r=new URLSearchParams({directory:e,page:String(n)});t?.query&&r.set(`query`,t.query);let i=await f(`/api/github/pulls/list?${r.toString()}`,{method:`GET`,headers:{Accept:`application/json`}}),a=await R(i);if(!i.ok||!a)throw Error(a?.error||i.statusText||`Failed to load pull requests`);return a},async prContext(t,n,r){let i=new URLSearchParams({directory:t,number:String(n)});r?.includeDiff&&i.set(`diff`,`1`),r?.includeCheckDetails&&i.set(`checkDetails`,`1`),r?.sourceRepo?.owner&&r.sourceRepo.repo&&(i.set(`owner`,r.sourceRepo.owner),i.set(`repo`,r.sourceRepo.repo));let a=await f(e.api(`/api/github/pulls/context`,i),{method:`GET`,headers:{Accept:`application/json`}}),o=await R(a);if(!a.ok||!o)throw Error(o?.error||a.statusText||`Failed to load pull request context`);return o},async issuesList(e,t){let n=t?.page??1,r=new URLSearchParams({directory:e,page:String(n)});t?.query&&r.set(`query`,t.query);let i=await f(`/api/github/issues/list?${r.toString()}`,{method:`GET`,headers:{Accept:`application/json`}}),a=await R(i);if(!i.ok||!a)throw Error(a?.error||i.statusText||`Failed to load issues`);return a},async issueGet(t,n,r){let i=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(i.set(`owner`,r.sourceRepo.owner),i.set(`repo`,r.sourceRepo.repo));let a=await f(e.api(`/api/github/issues/get`,i),{method:`GET`,headers:{Accept:`application/json`}}),o=await R(a);if(!a.ok||!o)throw Error(o?.error||a.statusText||`Failed to load issue`);return o},async issueComments(t,n,r){let i=new URLSearchParams({directory:t,number:String(n)});r?.sourceRepo?.owner&&r.sourceRepo.repo&&(i.set(`owner`,r.sourceRepo.owner),i.set(`repo`,r.sourceRepo.repo));let a=await f(e.api(`/api/github/issues/comments`,i),{method:`GET`,headers:{Accept:`application/json`}}),o=await R(a);if(!a.ok||!o)throw Error(o?.error||a.statusText||`Failed to load issue comments`);return o}}),z=async e=>await e.json().catch(()=>null),At=()=>({async listClients(){let e=await f(`/api/client-auth/clients`,{method:`GET`,headers:{Accept:`application/json`}}),t=await z(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to load remote clients`);return Array.isArray(t.clients)?t.clients:[]},async createClient(e={}){let t=await f(`/api/client-auth/clients`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:e.label??``})}),n=await z(t);if(!t.ok||!n?.client||typeof n.token!=`string`)throw Error(n?.error||t.statusText||`Failed to create remote client token`);return n},async createPairingSession(e={}){let t=await f(`/api/client-auth/pairing/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:e.label??``,...e.allowedClientKinds?{allowedClientKinds:e.allowedClientKinds}:{},...e.serverUrl?{serverUrl:e.serverUrl}:{},...typeof e.includeRelay==`boolean`?{includeRelay:e.includeRelay}:{},...typeof e.includeDirect==`boolean`?{includeDirect:e.includeDirect}:{},...e.relayUrl?{relayUrl:e.relayUrl}:{},...e.sshHostId?{sshHostId:e.sshHostId}:{}})}),n=await z(t);if(!t.ok||typeof n?.pairing?.secret!=`string`||!n?.server)throw Error(n?.error||t.statusText||`Failed to create pairing session`);return n},async listPendingPairings(){let e=await f(`/api/client-auth/pairing/sessions`,{method:`GET`,headers:{Accept:`application/json`}}),t=await z(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to load pending pairings`);return Array.isArray(t.pending)?t.pending:[]},async getPairingTransports(){let e=await f(`/api/client-auth/pairing/transports`,{method:`GET`,headers:{Accept:`application/json`}}),t=await z(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to load pairing transports`);return{local:t.local??null,lan:t.lan??null,relayAvailable:t.relayAvailable===!0,...typeof t.relayUrl==`string`?{relayUrl:t.relayUrl}:{},...typeof t.relayUrlLocked==`boolean`?{relayUrlLocked:t.relayUrlLocked}:{}}},async cancelPairing(e){let t=await f(`/api/client-auth/pairing/sessions/${encodeURIComponent(e)}`,{method:`DELETE`,headers:{Accept:`application/json`}}),n=await z(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to cancel pairing`);return{cancelled:n.cancelled===!0}},async revokeClient(e){let t=await f(`/api/client-auth/clients/${encodeURIComponent(e)}`,{method:`DELETE`,headers:{Accept:`application/json`}}),n=await z(t);if(!t.ok||!n)throw Error(n?.error||t.statusText||`Failed to revoke remote client`);return n},async purgeRevokedClients(){let e=await f(`/api/client-auth/clients`,{method:`DELETE`,headers:{Accept:`application/json`}}),t=await z(e);if(!e.ok||!t)throw Error(t?.error||e.statusText||`Failed to clear revoked clients`);return t}}),B=e=>typeof e==`object`&&!!e&&!Array.isArray(e),V=e=>typeof e==`number`&&Number.isFinite(e),jt=e=>{if(!B(e)||typeof e.ok!=`boolean`)return!1;if(e.ok===!0)return B(e.session)&&typeof e.session.id==`string`&&typeof e.messageID==`string`;let t=e.phase;if(typeof t!=`string`)return!1;switch(t){case`validate`:return typeof e.error==`string`&&Array.isArray(e.errors)&&e.errors.every(e=>typeof e==`string`);case`create`:return!(typeof e.error!=`string`||`status`in e&&e.status!==void 0&&!V(e.status));case`prompt`:return B(e.session)&&typeof e.session.id==`string`&&typeof e.messageID==`string`&&typeof e.ambiguous==`boolean`&&typeof e.error==`string`&&(!(`status`in e)||e.status===void 0||V(e.status));case`conflict`:return typeof e.error==`string`;case`unavailable`:return typeof e.error==`string`;case`internal`:return typeof e.error==`string`;default:return!1}},Mt=()=>({async createWithPrompt(e,t){let n;try{n=await f(`/api/openchamber/conversations`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t})}catch{throw Error(`Conversation request failed`)}let r;try{r=await n.json()}catch{throw Error(`Unexpected server response: invalid JSON`)}if(!jt(r))throw Error(`Unexpected server response: result shape mismatch`);return r}}),Nt=`https://openchamber.xiaobe.top/v1/mobile/update/check`,Pt=`https://openchamber-update.vercel.app/v1/mobile/update/check`,Ft=1e4,H=`openchamber.mobile-ota.device-id.v1`,U=e=>typeof e==`string`&&e.trim().length>0?e.trim():null,W=()=>{try{let e=T;return((typeof e.getConfig==`function`?e.getConfig():void 0)??e.config)?.OpenChamberOTA??{}}catch{return{}}},G=()=>W().channel===`stable`?`stable`:`beta`,It=()=>{let e=W().shellApiVersion;return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):1},Lt=()=>{let e=Ye();if(e===`ios`||e===`android`)return e;try{let e=T.getPlatform();if(e===`ios`||e===`android`)return e}catch{}return`android`},Rt=()=>{if(typeof window>`u`)return null;try{return U(window.localStorage.getItem(H))}catch{return null}},K=e=>{if(!(typeof window>`u`))try{window.localStorage.setItem(H,e)}catch{}},zt=async e=>{if(e)try{let t=U((await e.getDeviceId()).deviceId);if(t)return K(t),t}catch{}let t=Rt();if(t)return t;let n=d();return K(n),n},Bt=async()=>{let e=U(`1.18.4-beta.6`);if(x())try{let{App:t}=await E(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([0,1,2])),n=await t.getInfo(),r=U(n.version)??e??`0.0.0`,i=U(n.build),a=i?Number.parseInt(i,10):0;return{version:r,build:Number.isFinite(a)?a:0}}catch{}return{version:e??`0.0.0`,build:0}},q=(e,t,n)=>{let r=U(e?.version),i=U(t);if(n===`beta`&&i)return i;if(r&&r!==`builtin`)return i&&i!==r&&i.startsWith(`${r}-`)?i:r;let a=U(e?.id);return a&&a!==`builtin`?a:i??`builtin`},Vt=()=>U(`1.18.4-beta.6`),Ht=async e=>{let t=Vt(),n=G();if(!e)return q(null,t,n);try{return q((await e.current()).bundle,t,n)}catch{return q(null,t,n)}},Ut=()=>[Nt,Pt],Wt=(e,t,n)=>{let r=e-n();return r<=0||t<=0?null:Math.max(1,Math.ceil(r/t))};async function Gt(e,t,n,r){try{if(x())try{let{CapacitorHttp:r}=await E(async()=>{let{CapacitorHttp:e}=await import(`./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js`).then(e=>e.i);return{CapacitorHttp:e}},__vite__mapDeps([2,1])),i=Object.fromEntries(new Headers(t.headers).entries()),a;if(typeof t.body==`string`)try{a=JSON.parse(t.body)}catch{a=t.body}let o=await Promise.race([r.request({url:e,method:t.method||`GET`,headers:i,data:a,connectTimeout:n,readTimeout:n}),new Promise(e=>{window.setTimeout(()=>e(null),n)})]);return o?{ok:o.status>=200&&o.status<300,status:o.status,json:async()=>{if(typeof o.data==`string`)try{return JSON.parse(o.data)}catch{return o.data}return o.data}}:null}catch{}let i=await r(e,{...t,signal:AbortSignal.timeout(n)});return{ok:i.ok,status:i.status,json:()=>i.json()}}catch{return null}}var J=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return!(t.status!==`ok`||t.primaryAction!==`none`&&t.primaryAction!==`apply_ota`&&t.primaryAction!==`install_native_required`||!t.ota||typeof t.ota!=`object`||!t.native||typeof t.native!=`object`||typeof t.nextCheckInSec!=`number`||!Number.isFinite(t.nextCheckInSec))};async function Kt(e,t,n,r){let i=await Gt(e,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(t)},n,r);if(!i?.ok)return null;let a;try{a=await i.json()}catch{return null}return J(a)?a:null}async function qt(e={}){let t=e.updater===void 0?await k():e.updater;if(!t&&!x())throw new D;let n=e.fetchImpl??fetch,r=e.now??Date.now,[i,a,o]=await Promise.all([zt(t),Bt(),Ht(t)]),s={channel:G(),platform:Lt(),deviceId:i,nativeVersion:a.version,nativeBuild:a.build,shellApiVersion:It(),currentBundleId:o},c=Ut(),l=r()+Ft,u=null;for(let[e,t]of c.entries()){let i=Wt(l,c.length-e,r);if(i===null)break;try{let e=await Kt(t,s,i,n);if(e)return e;u=Error(`Mobile OTA check failed at ${t}`)}catch(e){u=e instanceof Error?e:Error(`Mobile OTA check failed`)}}throw u??Error(`Unable to check for mobile OTA updates`)}async function Jt(e){let t=await k();if(!t)return null;try{let{bundles:n}=await t.list();return n.find(t=>t.checksum===e.checksum&&t.version===e.releaseVersion&&(t.status===`success`||t.status===`pending`))?.id??null}catch{return null}}async function Yt(e){let t=await k();if(!t)throw new D;return(await t.download({url:e.url,version:e.releaseVersion,checksum:e.checksum,...e.sessionKey?{sessionKey:e.sessionKey}:{}})).id}async function Xt(){let e=await k();if(!e)throw new D;await e.reload()}async function Zt(e){let t=await k();if(!t)throw new D;await t.next({id:e})}var Y=null,X=e=>typeof e==`string`&&e.trim().length>0?e.trim():null,Z=async()=>{let e=X(`1.18.4-beta.6`);try{if(T.isNativePlatform()){let{App:t}=await E(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([0,1,2]));return X((await t.getInfo()).version)??e??`unknown`}}catch{}return e??`unknown`},Qt=()=>({async checkForOtaUpdate(){if(!O()&&!T.isNativePlatform())throw new D;return qt()},async downloadOtaUpdate(e){if(!O())throw new D;let t=await Jt(e);return t?(Y=t,{skipped:!0}):(Y=await Yt(e),{skipped:!1})},async applyOtaUpdateNow(){if(!O())throw new D;await Xt()},async queueOtaUpdateForNextLaunch(){if(!O())throw new D;let e=Y;if(!e)throw Error(`No downloaded OTA bundle to queue`);await Zt(e)},async getOtaStatus(){if(!O())return{supported:!1,currentBundleId:`builtin`,nativeVersion:await Z()};let e=await k();if(!e)return{supported:!1,currentBundleId:`builtin`,nativeVersion:await Z()};try{let[t,n]=await Promise.all([e.current(),Z()]);return{supported:!0,currentBundleId:X(t.bundle?.id)||`builtin`,nativeVersion:n}}catch{return{supported:!0,currentBundleId:`builtin`,nativeVersion:await Z()}}}}),$t=()=>({api:(...t)=>e().api(...t),authenticatedAsset:(...t)=>e().authenticatedAsset(...t),auth:(...t)=>e().auth(...t),health:(...t)=>e().health(...t),rawFile:(...t)=>e().rawFile(...t),sse:(...t)=>e().sse(...t),websocket:(...t)=>e().websocket(...t)}),en=(e={})=>{let t=e.urls??s();r(t);let n=$t();return{runtime:{platform:`web`,isDesktop:!1,isVSCode:!1,label:`web`},terminal:lt(),git:ut(),files:ft({urls:n,getDirectory:()=>ie.getState().currentDirectory}),settings:mt(),permissions:ht(),notifications:Et(),github:kt({urls:n}),push:Ot(),mobileUpdates:Qt(),clientAuth:At(),tools:Dt(),conversations:Mt()}},Q=(e,t)=>{if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},$=Promise.resolve(),tn=()=>$,nn=()=>{let e=typeof window.__OPENCHAMBER_API_BASE_URL__==`string`?window.__OPENCHAMBER_API_BASE_URL__.trim():``,r=typeof window.__OPENCHAMBER_CLIENT_TOKEN__==`string`?window.__OPENCHAMBER_CLIENT_TOKEN__.trim():``,s=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__==`string`?window.__OPENCHAMBER_LOCAL_ORIGIN__.trim():``,d=a({apiBaseUrl:e||void 0,realtimeBaseUrl:e||void 0});o({apiBaseUrl:e,runtimeKey:Q(e,s)?`local`:null}),t(r||null),i(window.__OPENCHAMBER_RUNTIME_HEADERS__||null),l(e||void 0).catch(()=>{}),s&&!Q(e,s)&&Object.keys(n()).length>0&&c(s).catch(()=>{}),u();let f=window.__OPENCHAMBER_RELAY_HOST_ID__;return $=Promise.race([ee(typeof f==`string`&&f?f:void 0).catch(()=>{}),new Promise(e=>{window.setTimeout(e,1e4)})]),en({urls:d})};export{tn as n,nn as t};
|