@openchambery/web 1.19.7-beta.9 → 1.19.7
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/dist/assets/AgentAvatar-CX0a1rKE.js +1 -0
- package/dist/assets/AssistantView-nVF0kdFh.js +2 -0
- package/dist/assets/DiagramView-B2UtQ8mw.js +1 -0
- package/dist/assets/FadeInOnReveal-CK4asqVR.js +1 -0
- package/dist/assets/Icon-BYM02QyU.js +1 -0
- package/dist/assets/MarkdownLoadingSkeleton-DWs4Jg7b.js +3 -0
- package/dist/assets/MarkdownRenderer-DT_GN1Ex.js +2 -0
- package/dist/assets/MarkdownRendererImpl-Cslh4XN_.js +7 -0
- package/dist/assets/MarkstreamRendererImpl-CsNwy1T5.css +1 -0
- package/dist/assets/MarkstreamRendererImpl-Ymm12x6J.js +1 -0
- package/dist/assets/MobileDetailNavigation-DD29ENgU.js +1 -0
- package/dist/assets/MobileShareBridge-CrTe_QND.js +4 -0
- package/dist/assets/MobileSurface-DjxchpUC.js +2 -0
- package/dist/assets/{MultiRunWindow-Ohj6UbWj.js → MultiRunWindow-jG5dCEMH.js} +1 -1
- package/dist/assets/OnboardingScreen-C3-wzeSX.js +1 -0
- package/dist/assets/OverlayScrollbar-KUpvYHdv.js +2 -0
- package/dist/assets/SettingsView-UKlEewdq.js +25 -0
- package/dist/assets/{SettingsWindow-B4lzhAbO.js → SettingsWindow-DO1aAplT.js} +1 -1
- package/dist/assets/TerminalView-BG1UPLsz.js +8 -0
- package/dist/assets/ToolOutputDialog-CWr5eVTK.js +10 -0
- package/dist/assets/appThemeRegistry-BI5drVpC.js +1 -0
- package/dist/assets/{button-z0GOBtWi.js → button-C0cth9tl.js} +1 -1
- package/dist/assets/clipboard-DJ4nQEuY.js +1 -0
- package/dist/assets/{collapsible-D9zJRpeB.js → collapsible-DFT9cE80.js} +1 -1
- package/dist/assets/context-menu-CAp74NfV.js +1 -0
- package/dist/assets/desktopHosts-CWxex1c3.js +1 -0
- package/dist/assets/desktopRelayRestore-9EbBYQ9s.js +1 -0
- package/dist/assets/{diagram-CoEqmReY.js → diagram-BryzMuta.js} +1 -1
- package/dist/assets/{dialog-x2hirWBd.js → dialog-CgbV5ljg.js} +1 -1
- package/dist/assets/dropdown-menu.styles-Bzo6L3FH.js +1 -0
- package/dist/assets/{es-C8Sqjsia.js → es-BHqnSjoZ.js} +1 -1
- package/dist/assets/fileQueries-BY-9OWzp.js +1 -0
- package/dist/assets/fileReferenceActions-BJJtX_S5.js +1 -0
- package/dist/assets/{fr-p-Zwm_j2.js → fr-BfrlJY9i.js} +1 -1
- package/dist/assets/{gitApi-CtS4kWoo.js → gitApi-D9hFlE3T.js} +3 -3
- package/dist/assets/{input-BG3VWTIF.js → input-DFLpqjGR.js} +1 -1
- package/dist/assets/insertionBoundaries-D2L7D0Oe.js +4 -0
- package/dist/assets/{ja-B6REu1qP.js → ja-DP-7qt-x.js} +1 -1
- package/dist/assets/{ko-CJBNH9IZ.js → ko-E2B5vGQP.js} +1 -1
- package/dist/assets/main-BRedOs_V.js +169 -0
- package/dist/assets/main-DlXpJ0Vw.js +2 -0
- package/dist/assets/markdown-worker-BuveaH3O.js +1 -0
- package/dist/assets/markdownTheme-CzZm3riB.js +2 -0
- package/dist/assets/miniChat-CBLbFpfy.js +2 -0
- package/dist/assets/mobile-CoZsWdWk.js +2 -0
- package/dist/assets/multirun-BF-I0r2_.js +4 -0
- package/dist/assets/outsideFileGrants-DnplRxr-.js +1 -0
- package/dist/assets/path-utils-jGozTg9d.js +1 -0
- package/dist/assets/persistence-DdUac14I.js +3 -0
- package/dist/assets/{pl-B2cBI_7K.js → pl-r8X5gRM5.js} +1 -1
- package/dist/assets/platform-B4KKLnZ5.js +2 -0
- package/dist/assets/projectMeta-2t4L5_4a.js +3 -0
- package/dist/assets/{pt-BR-CrCc9hmt.js → pt-BR-DcpdXCf5.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-fl7O3iHy.js +2 -0
- package/dist/assets/renderMobileApp-CKYDwf4U.js +28 -0
- package/dist/assets/runtimeConfig-B4eb4ZiU.js +2 -0
- package/dist/assets/runtimeEndpointReset-BHuTYyzc.js +147 -0
- package/dist/assets/sessionChangeSummary-DOq8EN_H.js +1 -0
- package/dist/assets/sessionLookup-DNc0ZeR3.js +1 -0
- package/dist/assets/sortable-tabs-strip-C8_9kHqu.js +1 -0
- package/dist/assets/src-DasvfkEg.css +2 -0
- package/dist/assets/{store-CL3WP48T.js → store-BDFdnk6l.js} +2 -2
- package/dist/assets/terminalApi-947l7Ra3.js +1 -0
- package/dist/assets/textarea-Cgo_nWUU.js +1 -0
- package/dist/assets/toolHelpers-DEvVP9U0.js +2 -0
- package/dist/assets/{tooltip-CtH61mQh.js → tooltip-BifLJ8o0.js} +1 -1
- package/dist/assets/{uk-C8YKAz0x.js → uk-Di0vl9V-.js} +1 -1
- package/dist/assets/url-Pk6tQ1EZ.js +1 -0
- package/dist/assets/{ChatContainer-CDExXwgn.js → useAppFontEffects-Dle8xs5h.js} +44 -39
- package/dist/assets/useAssistantUIStore-me6s63b2.js +1 -0
- package/dist/assets/useDesktopWindowControlsLayout-_QAwKcQn.js +1 -0
- package/dist/assets/useEffectiveDirectory-BSyuAgz6.js +1 -0
- package/dist/assets/useFontPreferences-BCOBlaAd.js +1 -0
- package/dist/assets/useMobileNavigationStore-f8xHJk7C.js +413 -0
- package/dist/assets/useSessionAutoCleanup-BHiXaW0J.js +1 -0
- package/dist/assets/useUIStore-CuaA8-Hp.js +1 -0
- package/dist/assets/useWorkerHighlightedLines-DuvXTSm_.js +7 -0
- package/dist/assets/utils-BiK3tBGM.js +1 -0
- package/dist/assets/{vendor-markstream-react-CwvbEg9R.js → vendor-markstream-react-C3K8YH0d.js} +4 -4
- package/dist/assets/{zh-CN-CCYwUnmB.js → zh-CN-coFCfeQE.js} +1 -1
- package/dist/assets/{zh-TW-D8Y6py08.js → zh-TW-oDRZ1-yb.js} +1 -1
- package/dist/index.html +9 -11
- package/dist/mini-chat.html +9 -11
- package/dist/mobile.html +15 -17
- package/package.json +2 -1
- package/server/index.js +2 -0
- package/server/lib/assistant-delivery-parts.js +3 -1
- package/server/lib/assistant-delivery-parts.test.js +11 -0
- package/server/lib/assistants/DOCUMENTATION.md +76 -3
- package/server/lib/assistants/assign.js +225 -0
- package/server/lib/assistants/assign.test.js +118 -0
- package/server/lib/assistants/bubbles.js +45 -0
- package/server/lib/assistants/bubbles.test.js +36 -0
- package/server/lib/assistants/cards.js +148 -0
- package/server/lib/assistants/cards.test.js +116 -0
- package/server/lib/assistants/contact-store.js +284 -0
- package/server/lib/assistants/contact-store.test.js +131 -0
- package/server/lib/assistants/contact-tools.js +761 -0
- package/server/lib/assistants/contact-tools.test.js +328 -0
- package/server/lib/assistants/contracts.js +20 -1
- package/server/lib/assistants/harness.js +551 -0
- package/server/lib/assistants/harness.test.js +607 -0
- package/server/lib/assistants/routes.js +44 -4
- package/server/lib/assistants/service.js +930 -17
- package/server/lib/assistants/service.test.js +1163 -45
- package/server/lib/event-stream/DOCUMENTATION.md +12 -1
- package/server/lib/event-stream/directory-ws-bridge.js +11 -2
- package/server/lib/event-stream/global-ws-bridge.js +19 -3
- package/server/lib/event-stream/protocol.js +11 -1
- package/server/lib/event-stream/reasoning-projection.js +425 -0
- package/server/lib/event-stream/reasoning-projection.test.js +300 -0
- package/server/lib/event-stream/runtime.js +10 -0
- package/server/lib/event-stream/runtime.test.js +53 -0
- package/server/lib/llm/DOCUMENTATION.md +84 -0
- package/server/lib/llm/catalog.js +100 -0
- package/server/lib/llm/catalog.test.js +78 -0
- package/server/lib/llm/completions.js +151 -0
- package/server/lib/llm/completions.test.js +127 -0
- package/server/lib/llm/generate.js +570 -0
- package/server/lib/llm/generate.test.js +459 -0
- package/server/lib/llm/routes.js +47 -0
- package/server/lib/llm/temp-directory.js +37 -0
- package/server/lib/notifications/APNS.md +19 -13
- package/server/lib/notifications/DOCUMENTATION.md +4 -3
- package/server/lib/notifications/runtime.js +148 -37
- package/server/lib/notifications/runtime.test.js +100 -0
- package/server/lib/opencode/DOCUMENTATION.md +2 -1
- package/server/lib/opencode/feature-routes-runtime.js +30 -0
- package/server/lib/opencode/feature-routes-runtime.test.js +20 -0
- package/server/lib/opencode/proxy.js +103 -9
- package/server/lib/opencode/proxy.test.js +177 -1
- package/server/lib/opencode/settings-runtime.js +2 -2
- package/server/lib/relay/reasoning-projection.e2e.test.ts +529 -0
- package/server/lib/session-goal/DOCUMENTATION.md +8 -1
- package/server/lib/session-goal/runtime.js +20 -0
- package/server/lib/session-index/DOCUMENTATION.md +3 -1
- package/server/lib/session-index/service.js +10 -4
- package/server/lib/session-index/service.test.js +37 -0
- package/server/lib/session-title/runtime.js +1 -0
- package/server/lib/session-title/runtime.test.js +11 -0
- package/server/lib/session-turn-pages/DOCUMENTATION.md +2 -1
- package/server/lib/session-turn-pages/routes.js +22 -3
- package/server/lib/session-turn-pages/routes.test.js +43 -0
- package/server/lib/transcript-cache/DOCUMENTATION.md +2 -2
- package/server/lib/transcript-cache/routes.js +9 -2
- package/server/lib/transcript-cache/routes.test.js +32 -0
- package/dist/assets/AgentAvatar-Di8F4QJh.js +0 -1
- package/dist/assets/AssistantView-DSxVAAb_.js +0 -1
- package/dist/assets/ContextPanel-DgwEIdqR.js +0 -285
- package/dist/assets/DiagramView-BKQO61y8.js +0 -1
- package/dist/assets/FadeInOnReveal-CV2s6YN8.js +0 -1
- package/dist/assets/Icon-CLpn1mIz.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CTgmghSh.js +0 -7
- package/dist/assets/MarkstreamRendererImpl-BKsc-avF.js +0 -1
- package/dist/assets/MarkstreamRendererImpl-CxeWpDCK.css +0 -1
- package/dist/assets/MobileDetailNavigation-BcA6rd8Q.js +0 -1
- package/dist/assets/MobileShareBridge-w6T2ZrsW.js +0 -4
- package/dist/assets/MobileSurface-CG1n7v0h.js +0 -2
- package/dist/assets/OnboardingScreen-D6rtE7rj.js +0 -1
- package/dist/assets/OverlayScrollbar-DlNZho3q.js +0 -2
- package/dist/assets/SettingsView-CiF3r83e.js +0 -25
- package/dist/assets/TerminalView-Ctx_Jt_b.js +0 -8
- package/dist/assets/ToolOutputDialog-Dv9_fUYl.js +0 -10
- package/dist/assets/appThemeRegistry-DnwUIQB9.js +0 -2
- package/dist/assets/clipboard-D35XSwID.js +0 -1
- package/dist/assets/desktop-CfLlmafK.js +0 -1
- package/dist/assets/desktopHosts-C1Ns3DUu.js +0 -1
- package/dist/assets/desktopRelayRestore-8pvI_dSc.js +0 -1
- package/dist/assets/fileQueries-DGHZqZHc.js +0 -1
- package/dist/assets/insertionBoundaries-hK4mQj4W.js +0 -4
- package/dist/assets/main-BmbZFoO4.js +0 -29
- package/dist/assets/main-BwNhn8ml.js +0 -2
- package/dist/assets/markdown-worker-y3ewaqAK.js +0 -4
- package/dist/assets/markdownTheme-SPe4jOwX.js +0 -2
- package/dist/assets/miniChat-BN89siC3.js +0 -2
- package/dist/assets/mobile-DE9rVo5D.js +0 -2
- package/dist/assets/multirun-BiEuyDq3.js +0 -4
- package/dist/assets/persistence-w-AiX2i4.js +0 -3
- package/dist/assets/platform-4eCmsdol.js +0 -2
- package/dist/assets/projectMeta-DSLKcH1a.js +0 -3
- package/dist/assets/radio-HD5AB2Qf.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-f_UxpFjv.js +0 -2
- package/dist/assets/renderMobileApp-BAhCai6d.js +0 -28
- package/dist/assets/runtime-switch-BkpTTbEi.js +0 -1
- package/dist/assets/runtimeConfig-qG_oNBoa.js +0 -2
- package/dist/assets/runtimeEndpointReset-BDeKD3EM.js +0 -4
- package/dist/assets/shikiHighlight-BphLZnac.js +0 -1
- package/dist/assets/sortable-tabs-strip-CNDgyX0B.js +0 -1
- package/dist/assets/src-DZt1nWf5.css +0 -2
- package/dist/assets/terminalApi-CGtOtc8I.js +0 -1
- package/dist/assets/url-KeihbE0d.js +0 -1
- package/dist/assets/useAppFontEffects--0dwVTSm.js +0 -7
- package/dist/assets/useAssistantUIStore-I0VWrB5V.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-DsbeBLvv.js +0 -1
- package/dist/assets/useEffectiveDirectory-CHvvohcG.js +0 -1
- package/dist/assets/useFontPreferences-BLZ3y6mN.js +0 -1
- package/dist/assets/useMobileNavigationStore-peTDuC00.js +0 -412
- package/dist/assets/useSessionAutoCleanup-D_ZC9E5g.js +0 -1
- package/dist/assets/useUIStore-CNLmCoPU.js +0 -1
- package/dist/assets/useWorkerHighlightedLines-B1YzuMYR.js +0 -7
- package/dist/assets/utils-CTL16t2f.js +0 -1
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{D as t,M as n,_ as r,c as i,f as a,h as o,i as s,n as c,o as l,r as u,t as d}from"./runtime-switch-BkpTTbEi.js";import{V as f,h as p}from"./desktop-CfLlmafK.js";import{a as m,i as h,r as ee}from"./vendor-zustand-B4dlGEM2.js";import{rt as te}from"./vendor-base-ui-CnHfUmDN.js";import{S as ne,b as g,f as re,i as ie,p as ae,r as oe,t as _,y as se}from"./useUIStore-CNLmCoPU.js";import{i as ce}from"./vendor-pathe-vBmvQE8f.js";import{n as le}from"./vendor-react-DLPElpoQ.js";import{t as ue}from"./vendor-tanstack-query-core-BWz0ose6.js";var v=e=>e.startsWith(`/api/`)||e===`/api`||e.startsWith(`/auth/`)||e===`/auth`||e===`/health`,de=()=>typeof window>`u`?``:window.location.origin||``,fe=e=>{if(typeof window>`u`)return!1;let t=de();if(t&&e.origin===t)return!0;try{let n=new URL(window.location.href||t);return e.protocol===n.protocol&&e.host===n.host}catch{return!1}},pe=e=>/^[a-z][a-z\d+.-]*:\/\//i.test(e),me=(e,t)=>{if(!t)return;let n=t instanceof URLSearchParams?Array.from(t.entries()):Object.entries(t);for(let[t,r]of n)r!=null&&e.searchParams.set(t,String(r))},he=e=>{try{let t=a().api(`/api`);if(!/^[a-z][a-z\d+.-]*:\/\//i.test(t))return!1;let n=new URL(t);return e.origin===n.origin&&v(e.pathname)}catch{return!1}},ge=e=>{if(v(e))return!0;if(!/^[a-z][a-z\d+.-]*:\/\//i.test(e))return!1;try{let t=new URL(e);return fe(t)&&v(t.pathname)}catch{return!1}},_e=(e,t)=>{try{let n=new URL(e);if(!fe(n))return e;let r=y(`${n.pathname}${n.search}`,t);return!pe(r)&&(n.protocol===`http:`||n.protocol===`https:`)?(me(n,t),n.toString()):n.hash?`${r}${n.hash}`:r}catch{return e}},y=(e,t)=>e===`/health`?a().health(t):e.startsWith(`/auth/`)||e===`/auth`?a().auth(e,t):v(e)?a().api(e,t):/^[a-z][a-z\d+.-]*:\/\//i.test(e)?_e(e,t):e,ve=e=>{let t=e instanceof Request?e.url:e.toString();if(!pe(t))return v(t);try{return he(new URL(t))}catch{return!1}},ye=/^\/api\/session\/(?!status$)([^/]+)(?:\/(?:message|children|todo|diff))?$/,be=/^\/api\/openchamber\/sessions\/([^/]+)\/messages\/?$/,xe=null,Se=e=>{xe=e},Ce=e=>{try{return decodeURIComponent(e)}catch{return e}},we=e=>xe?e===xe||Ce(e)===xe:!1,Te=new Set([`/health`,`/api/opencode/health`,`/api/opencode/upgrade-status`,`/api/global/config`,`/api/project`,`/api/project/current`,`/api/config`,`/api/config/providers`,`/api/config/settings`,`/api/config/themes`,`/api/experimental/session`,`/api/session/status`,`/api/session-folders`,`/api/github/pr/status`,`/api/openchamber/session-index`]),Ee=[`/api/agent`,`/api/command`,`/api/mcp`,`/api/lsp`,`/api/vcs`,`/api/question`,`/api/permission`,`/api/git/check`,`/api/git/primary-root`,`/api/git/discover`,`/api/git/status`,`/api/git/worktrees`,`/api/quota`],De=e=>Te.has(e)||Ee.some(t=>e===t||e.startsWith(`${t}/`)),Oe=e=>{if(!pe(e))return v(e);try{return he(new URL(e))}catch{return!1}},ke=e=>{try{return new URL(e,`http://openchamber.local`).pathname}catch{return null}},Ae=(e,t)=>{if(e.toUpperCase()!==`GET`||!Oe(t))return;let n=ke(t);if(!n)return;let r=n.match(ye);if(r?.[1]&&we(r[1]))return`high`;let i=n.match(be);if(i?.[1]&&we(i[1]))return`high`;if(De(n))return`low`},je=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},Me=(e,t)=>!je(t),Ne=e=>{if(!e)return;let t=e instanceof Headers?Array.from(e.entries()):Array.isArray(e)?e:Object.entries(e);if(t.length===0)return;let n=[],r=!1,i=!1;for(let[e,a]of t)Me(e,a)?(n.push([e,encodeURIComponent(a)]),r=!0,e.toLowerCase()===`x-opencode-directory`&&(i=!0)):n.push([e,a]);return i&&n.push([`x-opencode-directory-encoding`,`uri`]),r?n:void 0},b=async(e,t,n=!0)=>{let r=new Headers(Ne(e)??e);return t&&new Headers(Ne(t)??t).forEach((e,t)=>r.set(t,e)),n?o(r):r},Pe=(e,t)=>{if(!t)return e;let r=new URL(e,n);return me(r,t),`${r.pathname}${r.search}`},Fe=(e,t)=>{let n=e instanceof Request?e.url:e.toString();if(!pe(n))return v(n)?Pe(n,t):null;try{let e=new URL(n);return!fe(e)||!v(e.pathname)?null:(me(e,t),`${e.pathname}${e.search}`)}catch{return null}},Ie=async(e,n,r)=>{let i=t();if(!i)return null;let a=Fe(e,r);if(a===null)return null;let o=await b(e instanceof Request?e.headers:void 0,n.headers,!0);return e instanceof Request?i.fetch(e,{...n,headers:o}):i.fetch(a,{...n,headers:o})},Le=(e,t)=>{if(typeof e==`string`)return y(e,t);if(e instanceof URL)return y(e.toString(),t);let n=y(e.url,t);return n===e.url?e:new Request(n,e)},Re=/\/api\/(config|path|app\/agents|agent|project|command|opencode\/upgrade-status)(\b|\/|\?|$)/,ze=new Map,Be=new WeakMap,Ve=1,He=e=>{let t=Be.get(e);if(t)return t;let n=Ve;return Ve+=1,Be.set(e,n),n},Ue=(e,t,n,r,i,a)=>n||!i||e!==`GET`||t.includes(`/event`)||!Re.test(t)?null:`GET ${a?`relay:${He(a)}`:`url:${t}`} ${t} auth:${r}`,We=async(e,n={})=>{let{query:i,...a}=n,o=t(),s=o?Fe(e,i):null,c=r(),l,u,d;if(o&&s!==null){let t=await b(e instanceof Request?e.headers:void 0,a.headers,!0);l=e instanceof Request?()=>o.fetch(e,{...a,headers:t}):()=>o.fetch(s,{...a,headers:t}),u=s,d=String(a.method??(e instanceof Request?e.method:`GET`)).toUpperCase()}else{let t=Le(e,i),n=await b(t instanceof Request?t.headers:void 0,a.headers,ve(t));u=t instanceof Request?t.url:t instanceof URL?t.toString():String(t),d=String(a.method??(t instanceof Request?t.method:`GET`)).toUpperCase();let r=a.priority??Ae(d,u),o=r?{...a,priority:r}:a;l=t instanceof Request?()=>fetch(new Request(t,{...o,headers:n})):()=>fetch(t,{...o,headers:n})}let f=a.signal!=null||e instanceof Request,p=Ue(d,u,f,c,c===r(),o&&s!==null?o:null);if(!p)return l();let m=ze.get(p);if(m)return m.then(e=>e.clone());let h=l();return ze.set(p,h),h.then(()=>ze.delete(p),()=>ze.delete(p)),h.then(e=>e.clone())},Ge=!1,Ke=()=>{if(Ge||typeof window>`u`)return;Ge=!0;let e=window.fetch.bind(window);window.fetch=async(t,n)=>{let r=await Ie(t,n??{});if(r)return r;if(typeof t==`string`){if(!ge(t)){try{if(he(new URL(t))){let r=await b(void 0,n?.headers);return e(t,{...n,headers:r})}}catch{}return e(t,n)}let r=await b(void 0,n?.headers);return e(y(t),{...n,headers:r})}if(t instanceof URL){let r=t.toString();if(!ge(r)){if(he(t)){let r=await b(void 0,n?.headers);return e(t,{...n,headers:r})}return e(t,n)}let i=await b(void 0,n?.headers);return e(y(r),{...n,headers:i})}if(t instanceof Request){if(!ge(t.url)){try{if(he(new URL(t.url))){let r=await b(t.headers,n?.headers);return e(new Request(t,{...n,headers:r}))}}catch{}return e(t,n)}let r=await b(t.headers,n?.headers),i=y(t.url),a=i===t.url?t:new Request(i,t),o=await e(new Request(a,{...n,headers:r}));if(o.status>=500){let e=i;try{e=new URL(i).pathname}catch{}console.error(`[runtime-fetch] server request failed`,{method:a.method,path:e,status:o.status,statusText:o.statusText},Error(`runtime fetch received HTTP ${o.status}`))}return o}return e(t,n)}},qe=`oc.inst.`,Je=e=>{try{return btoa(unescape(encodeURIComponent(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}catch{return encodeURIComponent(e)}},Ye=e=>{let t=(e??u()).trim();return t.length>0?t:`default`},Xe=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim().replace(/\/+$/,``):``},x=(e,t=u())=>`${qe}${Je(Ye(t))}.${e}`,Ze=(e=u())=>Ye(e).startsWith(`relay:`),Qe=(e=u())=>{let t=Ye(e);if(t==="default"||t===`local`)return!0;if(Ze(t)||!t.startsWith(`url:`))return!1;let n=Xe();if(!n)return!1;try{return new URL(t.slice(4)).origin===new URL(n).origin}catch{return!1}},$e=(e=u())=>!Ze(e),et=(e,t=d())=>{let n=t.trim().replace(/\/+$/,``);return n?`${e}:${encodeURIComponent(n)}`:null},tt=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{getItem:()=>null}),r=t?.runtimeKey??u(),i=n.getItem(x(e,r));if(i!==null)return i;if($e(r)){let t=et(e),r=t?n.getItem(t):null;if(r!==null)return r}return Qe(r)?n.getItem(e):null},S=(e,t,n)=>{let r=n?.storage??(typeof localStorage<`u`?localStorage:{setItem:()=>void 0}),i=n?.runtimeKey??u();r.setItem(x(e,i),t)},nt=e=>({getItem:t=>tt(t,{storage:e}),setItem:(t,n)=>{S(t,n,{storage:e})},removeItem:t=>{C(t,{storage:e})}}),C=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{removeItem:()=>void 0}),r=t?.runtimeKey??u();n.removeItem(x(e,r))},rt=e=>{let t;try{t=ne()}catch{return}let n=t=>t===null?null:JSON.parse(t,e?.reviver),r=e=>t.getItem(e);return{getItem:e=>{let t=u(),i=x(e,t),a=r(i);if(a instanceof Promise)return a.then(i=>{if(i!==null)return n(i);if(!Qe(t))return null;let a=r(e);return a instanceof Promise?a.then(n):n(a)});if(a!==null)return n(a);if(!Qe(t))return null;let o=r(e);return o instanceof Promise?o.then(n):n(o)},setItem:(n,r)=>{let i=x(n,u());t.setItem(i,JSON.stringify(r,e?.replacer))},removeItem:e=>{let n=x(e,u());t.removeItem(n)}}},it=(e=at)=>{let t=new Map,n=0;return{countUnicodeCodePoints:r=>{let i=t.get(r);if(i!==void 0)return t.delete(r),t.set(r,i),i;let a=e(r);if(r.length>4e5)return a;for(;n+r.length>4e5&&t.size>0;){let e=t.keys().next().value;n-=e.length,t.delete(e)}return t.set(r,a),n+=r.length,a}}},at=e=>{let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){let t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(n+=1)}t+=1}return t},ot=it(),st=e=>ot.countUnicodeCodePoints(e),w=(e,t)=>{if(!e)throw Error(`${t} must be non-empty`);return e},ct=({transportIdentity:e},t)=>({transportIdentity:w(e,`transportIdentity`),owner:{kind:`session`,ownerID:w(t,`sessionID`)}}),lt=({transportIdentity:e},t)=>({transportIdentity:w(e,`transportIdentity`),owner:{kind:`draft`,ownerID:w(t,`draftID`)}}),ut=e=>{let t=typeof e.projectId==`string`?e.projectId.trim():``;if(t)return`new-session:project:${t}`;let n=typeof e.directory==`string`?e.directory.trim():``;return n?`new-session:directory:${n}`:`new-session:default`},dt=({transportIdentity:e},t)=>({transportIdentity:w(e,`transportIdentity`),owner:{kind:`surface`,ownerID:w(t,`surfaceID`)}}),ft=8192,pt=e=>{if(typeof e!=`string`||e.length===0||e.length>ft)return!1;try{let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`file:`}catch{return!1}},mt=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID]),ht=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID,e.attachmentOccurrenceRefID]),gt=e=>JSON.stringify([`root`,e]),_t=(e,t)=>JSON.stringify([`part`,e,t]),vt={mentionCount:1e3,valueLength:8192,pathLength:8192,labelLength:512},T={referenceCount:1e3,idLength:512,displayLength:514,sessionIDLength:128,skillNameLength:511,commandNameLength:511,commandReferenceLength:8192,pastePayloadLength:1e5,totalPastePayloadLength:2e5},E=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},D=(e,t)=>Object.keys(e).every(e=>t.includes(e)),O=e=>typeof e==`string`&&e.length>0,yt=e=>typeof e==`string`,k=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,A=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,bt=(e,t)=>{if(t<=0||t>=e.length)return!0;let n=e.charCodeAt(t-1),r=e.charCodeAt(t);return!(n>=55296&&n<=56319&&r>=56320&&r<=57343)},xt=(e,t)=>{if(!Array.isArray(t)||t.length>vt.mentionCount)return;let n=[],r=new Set,i=0;for(let a of t){if(!E(a)||!D(a,[`kind`,`value`,`path`,`label`,`range`])||a.kind!==`file`&&a.kind!==`directory`&&a.kind!==`agent`||!A(a.value,vt.valueLength)||!A(a.path,vt.pathLength)||!A(a.label,vt.labelLength)||!E(a.range)||!D(a.range,[`start`,`end`])||!k(a.range.start)||!k(a.range.end)||a.range.end<=a.range.start||a.range.end>e.length||a.range.start<i||!bt(e,a.range.start)||!bt(e,a.range.end)||e.slice(a.range.start,a.range.end)!==`@${a.value}`)return;let t=JSON.stringify([a.kind,a.value,a.path,a.label,a.range.start,a.range.end]);if(r.has(t))return;r.add(t),i=a.range.end,n.push({kind:a.kind,value:a.value,path:a.path,label:a.label,range:{start:a.range.start,end:a.range.end}})}return n},St=e=>A(e,T.sessionIDLength)&&/^[A-Za-z0-9_-]+$/.test(e),Ct=e=>A(e,T.skillNameLength)&&/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(e),wt=e=>A(e,T.commandNameLength)&&/^[\p{L}\p{N}._/-]+$/u.test(e),Tt=e=>A(e,T.commandReferenceLength)&&!/[\]\r\n]/u.test(e),Et=e=>{if(!(!E(e)||!A(e.id,T.idLength)||!A(e.display,T.displayLength)||!k(e.start)||!k(e.end)||e.end<=e.start)){if(e.kind===`session`&&D(e,[`id`,`kind`,`start`,`end`,`display`,`sessionId`])&&St(e.sessionId))return{id:e.id,kind:`session`,start:e.start,end:e.end,display:e.display,sessionId:e.sessionId};if(e.kind===`paste`&&D(e,[`id`,`kind`,`start`,`end`,`display`,`text`,`characterCount`,`index`])&&typeof e.text==`string`&&e.text.length<=T.pastePayloadLength&&k(e.characterCount)&&e.characterCount===st(e.text)&&k(e.index)&&e.index>=1)return{id:e.id,kind:`paste`,start:e.start,end:e.end,display:e.display,text:e.text,characterCount:e.characterCount,index:e.index};if(e.kind===`skill`&&D(e,[`id`,`kind`,`start`,`end`,`display`,`skillName`])&&Ct(e.skillName)&&(e.display===`/${e.skillName}`||e.display===`/ ${e.skillName}`))return{id:e.id,kind:`skill`,start:e.start,end:e.end,display:e.display,skillName:e.skillName};if(e.kind===`command`&&D(e,[`id`,`kind`,`start`,`end`,`display`,`commandName`,`reference`])&&wt(e.commandName)&&Tt(e.reference)&&(e.display===`/${e.commandName}`||e.display===`/ ${e.commandName}`))return{id:e.id,kind:`command`,start:e.start,end:e.end,display:e.display,commandName:e.commandName,reference:e.reference}}},Dt=(e,t)=>{if(!Array.isArray(t)||t.length>T.referenceCount)return;let n=t.map(Et);if(!n.every(Boolean))return;let r=n,i=new Set,a=0,o=0;for(let t of r)if(i.has(t.id)||t.start<a||t.end>e.length||e.slice(t.start,t.end)!==t.display||(i.add(t.id),a=t.end,t.kind===`paste`&&(o+=t.text.length,o>T.totalPastePayloadLength)))return;return{text:e,references:r}},Ot=(e,t)=>{if(e===null||[`string`,`number`,`boolean`,`undefined`].includes(typeof e))return!0;if(typeof e!=`object`||e instanceof Blob||typeof File<`u`&&e instanceof File||!Array.isArray(e)&&!E(e)||t.has(e))return!1;t.add(e);let n=Object.values(e).every(e=>Ot(e,t));return t.delete(e),n},kt=e=>{if(!(!E(e)||!D(e,[`kind`,`ownerID`])||!O(e.ownerID))&&(e.kind===`session`||e.kind===`draft`||e.kind===`surface`))return{kind:e.kind,ownerID:e.ownerID}},At=e=>{if(!E(e)||!D(e,[`transportIdentity`,`owner`])||!O(e.transportIdentity))return;let t=kt(e.owner);return t?{transportIdentity:e.transportIdentity,owner:t}:void 0},jt=e=>{if(!(!E(e)||!O(e.kind))){if(e.kind===`blob`&&D(e,[`kind`,`blobID`])&&O(e.blobID))return{kind:`blob`,blobID:e.blobID};if(!(e.kind!==`url`||!D(e,[`kind`,`url`])||!pt(e.url)))return{kind:`url`,url:e.url}}},Mt=(e,t,n)=>{try{let r=JSON.parse(e);return Array.isArray(r)?n===void 0?r.length===2&&r[0]===`root`&&r[1]===t:r.length===3&&r[0]===`part`&&r[1]===n&&r[2]===t:!1}catch{return!1}},Nt=(e,t)=>{if(!E(e)||!D(e,[`attachmentID`,`attachmentRefID`,`filename`,`mimeType`,`size`,`locator`,`source`,`serverPath`,`vscodePath`,`vscodeSource`])||!O(e.attachmentID)||!O(e.attachmentRefID)||!Mt(e.attachmentRefID,e.attachmentID,t)||!O(e.filename)||!yt(e.mimeType)||!k(e.size)||e.source!==`local`&&e.source!==`vscode`&&e.source!==`server`||e.serverPath!==void 0&&!O(e.serverPath)||e.vscodePath!==void 0&&!O(e.vscodePath)||e.vscodeSource!==void 0&&e.vscodeSource!==`file`&&e.vscodeSource!==`selection`||e.source===`server`&&!O(e.serverPath)||e.source===`vscode`&&(!O(e.vscodePath)||e.vscodeSource!==`file`&&e.vscodeSource!==`selection`))return;let n=jt(e.locator);if(n)return{attachmentID:e.attachmentID,attachmentRefID:e.attachmentRefID,filename:e.filename,mimeType:e.mimeType,size:e.size,locator:n,source:e.source,...e.serverPath===void 0?{}:{serverPath:e.serverPath},...e.vscodePath===void 0?{}:{vscodePath:e.vscodePath},...e.vscodeSource===void 0?{}:{vscodeSource:e.vscodeSource}}},Pt=e=>{if(!Ot(e,new Set)||!E(e)||!D(e,[`version`,`key`,`revision`,`text`,`attachments`,`syntheticParts`,`mentions`,`composerReferences`])||e.version!==1||!k(e.revision)||e.revision<1||typeof e.text!=`string`||!Array.isArray(e.attachments)||!Array.isArray(e.syntheticParts)||!Array.isArray(e.mentions))return;let t=e.text,n=At(e.key),r=e.attachments.map(e=>Nt(e)),i=e.syntheticParts.map(e=>{if(!E(e)||!D(e,[`partID`,`text`,`attachments`,`synthetic`])||!O(e.partID)||typeof e.text!=`string`||!Array.isArray(e.attachments)||e.synthetic!==void 0&&typeof e.synthetic!=`boolean`)return;let t=e.partID,n=e.text,r=e.attachments.map(e=>Nt(e,t));return r.every(Boolean)?{partID:t,text:n,attachments:r,...e.synthetic===void 0?{}:{synthetic:e.synthetic}}:void 0}),a=xt(t,e.mentions),o=e.composerReferences===void 0?{text:t,references:[]}:Dt(t,e.composerReferences);if(!n||!r.every(Boolean)||!i.every(Boolean)||!a||!o)return;let s=r,c=i,l=new Set;for(let e of[...s,...c.flatMap(e=>e.attachments)]){if(l.has(e.attachmentRefID))return;l.add(e.attachmentRefID)}if(new Set(c.map(e=>e.partID)).size===c.length)return{version:1,key:n,revision:e.revision,text:t,attachments:s,syntheticParts:c,mentions:a,...e.composerReferences===void 0?{}:{composerReferences:o.references}}},Ft=e=>Pt(e),j=` `,It=`0.2em`,Lt=`size-[1em]`,Rt=e=>e.startsWith(j)?e.slice(j.length):e,zt=e=>e.replaceAll(`/${j}`,`/`).replaceAll(`@${j}`,`@`).replaceAll(`[${j}`,`[`),Bt=e=>{let t=e.match(/^\s*/)?.[0].length??0,n=e.slice(t);if(!n.startsWith(`/`))return null;let r=1;n.startsWith(j,r)&&(r+=j.length);let i=n.slice(r);if(!i)return null;let a=i.search(/\s/u),o=a===-1?i:i.slice(0,a);return o?{commandName:o,argumentsText:a===-1?``:i.slice(a).trim()}:null},Vt=e=>M({trigger:`[`,icon:`file-image`,label:e,suffix:`]`}),Ht=({trigger:e,label:t,suffix:n=``})=>`${e}${t}${n}`,M=e=>`${e.trigger}${j}${e.label}${e.suffix??``}`,Ut=e=>Ht(e),Wt=(e,t)=>e===Ut(t)||e===M(t),Gt=(e,t)=>{let n=t===M(e);return{trigger:n?`${e.trigger}${j}`:e.trigger,icon:e.icon,align:e.align??`end`,label:e.label,suffix:e.suffix,slot:n?`reserved`:`compact`}},Kt=(e,t,n=``)=>{let r=e.startsWith(t)?e.slice(t.length):e,i=r.startsWith(j)?r.slice(j.length):r;return n&&i.endsWith(n)?i.slice(0,-n.length):i},qt=(e,t)=>e===t||!!e&&!!t&&e.trigger===t.trigger&&e.icon===t.icon&&e.align===t.align&&e.label===t.label&&e.suffix===t.suffix&&e.slot===t.slot,Jt=0n,Yt=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,Xt=14;function Zt(e){let t=``;for(let n=0;n<e;n++)t+=Yt[Math.floor(Math.random()*62)];return t}var Qt=/^[0-9a-f]{12}$/,$t=/^[0-9A-Za-z]{14}$/,en=(1n<<48n)-1n,tn=(e,t)=>{if(typeof t!=`string`||!t.startsWith(`${e}_`))return;let n=t.slice(e.length+1),r=n.slice(0,12);if(!(!Qt.test(r)||!$t.test(n.slice(12))))return BigInt(`0x${r}`)},nn=(e,t)=>{let n=BigInt(Date.now())*4096n&en,r=tn(e,t)??0n,i=[n,Jt,r].reduce((e,t)=>e>t?e:t);if(i>=en)throw Error(`Ascending ID space exhausted`);let a=i+1n;Jt=a;let o=new Uint8Array(6);for(let e=0;e<6;e++)o[e]=Number(a>>BigInt(40-8*e)&BigInt(255));let s=``;for(let e=0;e<o.length;e++)s+=o[e].toString(16).padStart(2,`0`);return`${e}_${s}${Zt(Xt)}`},rn=e=>nn(e),an=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/g,``).trim();if(!t)return``;let n=new TextEncoder().encode(t),r=``;for(let e of n)r+=String.fromCharCode(e);return`path_${typeof btoa==`function`?btoa(r).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``):t.replace(/[^A-Za-z0-9._-]+/g,`_`)}`},on=()=>globalThis.crypto===void 0?null:{randomUUID:typeof globalThis.crypto.randomUUID==`function`?()=>globalThis.crypto.randomUUID():void 0,getRandomValues:typeof globalThis.crypto.getRandomValues==`function`?e=>globalThis.crypto.getRandomValues(e):void 0},sn=(e=on())=>{try{let t=e?.randomUUID?.();if(t)return t}catch{}let t=new Uint8Array(16),n=!1;try{e?.getRandomValues&&(e.getRandomValues(t),n=!0)}catch{}if(!n)for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,e=>e.toString(16).padStart(2,`0`));return`${r.slice(0,4).join(``)}-${r.slice(4,6).join(``)}-${r.slice(6,8).join(``)}-${r.slice(8,10).join(``)}-${r.slice(10).join(``)}`},cn=e=>/^[\\/]+$/.test(e),ln=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;if(cn(t))return t.length===1?`/`:null;let n=ce(t);return n===`/`?`/`:(n.length>1?n.replace(/\/+$/,``):n)||null},un=e=>{if(typeof e!=`string`)return``;let t=e.trim();return t?ln(t)??t:``},N={...T,sessionIdLength:T.sessionIDLength,visibleTextLength:1e5,canonicalOutputLength:2e5},dn=e=>typeof e==`string`&&St(e),fn=e=>e.replaceAll(`\\`,`/`).split(`/`).at(-1)?.replace(/\.md$/,``)??``,pn=e=>({trigger:`@`,icon:`chat-thread`,label:e}),P=(e,t)=>({trigger:`/`,icon:t,label:e}),mn={session:{kind:`session`,validatePayload:e=>dn(e.sessionId),contributeCanonical:e=>({text:`@session:${e.sessionId}`,semantic:{type:`session`,sessionId:e.sessionId}}),contributeDirectSend:e=>({text:Ut(pn(Kt(e.display,`@`))),semantic:{type:`session`,sessionId:e.sessionId}}),decorate:e=>({style:`mentionSession`,visual:Gt(pn(Kt(e.display,`@`)),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:/@session:([A-Za-z0-9_-]+)/g,resolveDisplay:(e,t)=>{let n=e.index===0?``:t.text[e.index-1],r=t.text[e.index+e[0].length]??``;return(n===``||/[\s([{]/.test(n))&&(r===``||/[\s)\]},.!?;:]/.test(r))?M(pn(t.sessionTitles.get(e[1])||e[1])):null},materialize:(e,t,n)=>({id:`session:${e[1]}:${e.index}`,kind:`session`,sessionId:e[1],display:t,start:n,end:n+t.length})}},paste:{kind:`paste`,validatePayload:e=>typeof e.text==`string`&&e.text.length<=N.pastePayloadLength&&typeof e.characterCount==`number`&&Number.isSafeInteger(e.characterCount)&&e.characterCount===st(e.text)&&typeof e.index==`number`&&Number.isSafeInteger(e.index)&&e.index>=1,contributeCanonical:e=>({text:e.text}),contributeDirectSend:e=>({text:e.text}),decorate:()=>({style:`mentionPaste`}),payloadBudget:e=>({category:`opaque-text`,length:e.text.length})},skill:{kind:`skill`,validatePayload:e=>Ct(e.skillName)&&typeof e.display==`string`&&Wt(e.display,P(e.skillName,`book-open`)),contributeCanonical:e=>({text:`[skill:${e.skillName}]`}),contributeDirectSend:e=>({text:`[skill:${e.skillName}]`}),decorate:e=>({style:`mentionCommand`,skillName:e.skillName,visual:Gt(P(e.skillName,`book-open`),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:/\[skill:([A-Za-z0-9][A-Za-z0-9_-]*)\]/g,resolveDisplay:e=>M(P(e[1],`book-open`)),materialize:(e,t,n)=>({id:`skill:${n}`,kind:`skill`,skillName:e[1],display:t,start:n,end:n+t.length})}},command:{kind:`command`,validatePayload:e=>wt(e.commandName)&&Tt(e.reference)&&typeof e.display==`string`&&Wt(e.display,P(e.commandName,`command`)),contributeCanonical:e=>({text:`[command:${e.reference}]`}),contributeDirectSend:e=>({text:`[command:${e.reference}]`}),decorate:e=>({style:`mentionCommand`,visual:Gt(P(e.commandName,`command`),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:/\[command:([^\]\r\n]+)\]/g,resolveDisplay:e=>{let t=fn(e[1]);return Tt(e[1])&&wt(t)?M(P(t,`command`)):null},materialize:(e,t,n)=>({id:`command:${n}`,kind:`command`,commandName:fn(e[1]),reference:e[1],display:t,start:n,end:n+t.length})}}},F=e=>mn[e],hn=(e,t)=>F(e).validatePayload(t),gn=e=>F(e.kind).contributeCanonical(e),_n=e=>F(e.kind).contributeDirectSend(e),vn=e=>F(e.kind).decorate(e),yn=e=>F(e.kind).payloadBudget(e),bn=e=>F(e.kind).describeResourceIdentity?.(e),xn=Object.keys(mn),Sn=e=>typeof e==`string`&&xn.includes(e),Cn=()=>xn.flatMap(e=>{let t=F(e).canonical;return t?[t]:[]}),wn=e=>{if(e.type===`attachment`)return`attachment:${e.attachmentRefID}`},Tn=e=>{let t=new Map;for(let n of e.references){let e=bn(n);e&&t.set(wn(e),e)}return[...t.values()]},En=(e,t)=>{let n=new Map(e.map(e=>[wn(e),e])),r=new Map(t.map(e=>[wn(e),e]));return{previous:[...n.values()],next:[...r.values()],added:[...r].flatMap(([e,t])=>n.has(e)?[]:[t]),removed:[...n].flatMap(([e,t])=>r.has(e)?[]:[t])}},Dn=(e,t)=>En(Tn(e),Tn(t)),On=(e,t=`queue-canonical`)=>{if(e.references.length>N.referenceCount)return{ok:!1,reason:`reference-budget-exceeded`};let n=[...e.references].sort((e,t)=>e.start-t.start),r=0,i=0;for(let t of n){if(t.start<r||t.start<0||t.end<=t.start||t.end>e.text.length||e.text.slice(t.start,t.end)!==t.display)return{ok:!1,reason:`invalid-references`};r=t.end;let n=yn(t);i+=n?.category===`opaque-text`?n.length:0}if(i>N.totalPastePayloadLength)return{ok:!1,reason:`reference-payload-budget-exceeded`};let a=[],o=[],s=0;for(let r of n){s<r.start&&a.push({provenance:`authored`,text:e.text.slice(s,r.start),start:s,end:r.start});let n=t===`direct-send-display`?_n(r):gn(r);n.semantic?(a.push({provenance:`generated-reference`,text:n.text,start:r.start,end:r.end,referenceId:r.id,semantic:n.semantic}),o.push(n.semantic)):a.push({provenance:`reference-payload`,text:n.text,start:r.start,end:r.end,referenceId:r.id}),s=r.end}s<e.text.length&&a.push({provenance:`authored`,text:e.text.slice(s),start:s,end:e.text.length});let c=a.map(e=>e.text).join(``);return c.length>N.canonicalOutputLength?{ok:!1,reason:`canonical-output-too-large`}:{ok:!0,plan:{chunks:a,semantics:o},text:c}},I=(e,t)=>Math.max(0,Math.min(e,t)),kn=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,An=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return!kn(t.id,N.displayLength)||!kn(t.display,N.displayLength)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||typeof t.kind!=`string`?!1:Sn(t.kind)&&hn(t.kind,t)},L=(e,t)=>{let n=[],r=0,i=[],a=Math.min(t.length,N.referenceCount);for(let e=0;e<a;e+=1){let a=t[e];if(!An(a)){typeof a==`object`&&a&&typeof a.id==`string`&&n.push(a.id),r+=1;continue}i.push({reference:a,index:e})}i.sort((e,t)=>e.reference.start-t.reference.start||e.index-t.index);let o=[],s=new Set,c=0,l=0,u=!1;for(let{reference:t}of i){if(s.has(t.id)||t.start<c||t.start<0||t.end<=t.start||t.end>e.length||e.slice(t.start,t.end)!==t.display){n.push(t.id),r+=1;continue}s.add(t.id),c=t.end;let i=yn(t);if(l+=i?.category===`opaque-text`?i.length:0,l>T.totalPastePayloadLength){n.push(t.id),r+=1,s.delete(t.id),c=o.at(-1)?.end??0,u=!0,l-=i?.category===`opaque-text`?i.length:0;continue}o.push(t)}return r+=t.length-a,{document:{text:e,references:o},rejectedIds:n,rejectedCount:r,budgetExceeded:t.length>N.referenceCount,payloadBudgetExceeded:u}},R=e=>{let t=[...e.references].sort((e,t)=>e.start-t.start||e.end-t.end),n=[],r=new Set,i=0,a=0;for(let o of t){if(!kn(o.id,N.idLength)||!kn(o.display,N.displayLength)||!Sn(o.kind)||!Number.isSafeInteger(o.start)||!Number.isSafeInteger(o.end)||r.has(o.id)||o.start<i||o.start<0||o.end<=o.start||o.end>e.text.length||e.text.slice(o.start,o.end)!==o.display)continue;let t=yn(o),s=t?.category===`opaque-text`?t.length:0;a+s>T.totalPastePayloadLength||(r.add(o.id),i=o.end,a+=s,n.push(o))}return{text:e.text,references:n}},jn=(e,t)=>{if(t.length>T.pastePayloadLength)return!1;let n=L(e.text,e.references);return n.budgetExceeded||n.payloadBudgetExceeded?!1:n.document.references.reduce((e,t)=>{let n=yn(t);return e+(n?.category===`opaque-text`?n.length:0)},0)+t.length<=T.totalPastePayloadLength},Mn=(e,t,n)=>{let r=e.filter(e=>t===n?t>e.start&&t<e.end:e.start<n&&e.end>t);return r.length===0?{start:t,end:n}:{start:Math.min(t,...r.map(e=>e.start)),end:Math.max(n,...r.map(e=>e.end))}};function Nn(e,t,n,r,i={}){let a=R(e);if(!hn(r.kind,r))return{document:a,caret:I(n,a.text.length),edit:{oldStart:t,oldEnd:n,newEnd:n}};let o=I(t,a.text.length),s=Math.max(o,I(n,a.text.length)),c=Mn(a.references,o,s),l=a.text.slice(0,c.start),u=a.text.slice(c.end),d=!!i.padDocumentEdges&&i.padLeadingDocumentEdge!==!1,f=!!i.padDocumentEdges,p=i.inlineBoundaries&&(l.length>0||d)&&!/\s$/.test(l)?` `:``,m=i.inlineBoundaries&&(u.length>0||f)&&!/^\s/.test(u)?` `:``,h=`${l}${p}${r.display}${m}${u}`,ee={...r,start:c.start+p.length,end:c.start+p.length+r.display.length},te=p.length+r.display.length+m.length-(c.end-c.start);return{document:R({text:h,references:[...a.references.filter(e=>e.end<=c.start||e.start>=c.end).map(e=>e.start>=c.end?{...e,start:e.start+te,end:e.end+te}:e),ee]}),caret:ee.end,edit:{oldStart:c.start,oldEnd:c.end,newEnd:c.start+p.length+r.display.length+m.length}}}var Pn=(e,t)=>e<=t.oldStart?e:e>=t.oldEnd?e+t.newEnd-t.oldEnd:t.newEnd,Fn=(e,t,n=t.length,r=n)=>{let i=R(e),a=0,o=Math.min(i.text.length,t.length);for(;a<o&&i.text[a]===t[a];)a+=1;let s=0;for(;s<i.text.length-a&&s<t.length-a&&i.text[i.text.length-s-1]===t[t.length-s-1];)s+=1;let c={oldStart:a,oldEnd:i.text.length-s,newEnd:t.length-s},l=Mn(i.references,c.oldStart,c.oldEnd),u=l.start!==c.oldStart||l.end!==c.oldEnd,d=i.references.filter(e=>e.start<l.end&&e.end>l.start),f=t.slice(c.oldStart,c.newEnd),p=`${i.text.slice(0,l.start)}${f}${i.text.slice(l.end)}`,m={oldStart:l.start,oldEnd:l.end,newEnd:l.start+f.length},h=m.newEnd-m.oldEnd,ee=i.references.filter(e=>e.end<=l.start||e.start>=l.end).map(e=>e.start>=l.end?{...e,start:e.start+h,end:e.end+h}:e),te=(e,n)=>{let r=I(e,t.length),i=c.newEnd+l.end-c.oldEnd;return I(r<=l.start?r:r<c.oldStart||r===c.oldStart&&n===`start`?l.start:r<c.newEnd||r===c.newEnd&&n===`start`?l.start+r-c.oldStart:r<=i?m.newEnd:m.newEnd+r-i,p.length)},ne=te(n,`start`),g=Math.max(ne,te(r,`end`)),re=R({text:p,references:ee});return{document:re,edit:m,requiresTextCorrection:u,selectionStart:ne,selectionEnd:g,caret:g,mapCaret:e=>I(Pn(e,m),re.text.length),removedReferences:d}},In=(e,t,n)=>{let r=Mn(n,e,t);return r.start===e&&r.end===t?null:r},Ln=(e,t,n)=>{let r=n,i=n;if(t===`Backspace`){for(;r>0&&/\s/.test(e[r-1]);)--r;for(;r>0&&!/\s/.test(e[r-1]);)--r}else{for(;i<e.length&&/\s/.test(e[i]);)i+=1;for(;i<e.length&&!/\s/.test(e[i]);)i+=1}return{start:r,end:i}},Rn=(e,t)=>{let n=R(e),r=I(t.selectionStart,n.text.length),i=Math.max(r,I(t.selectionEnd,n.text.length)),a=r===i?t.altKey?Ln(n.text,t.key,r):t.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(n.text.length,r+1)}:{start:r,end:i},o=In(a.start,a.end,n.references);if(!o)return null;let s=n.references.filter(e=>e.start<o.end&&e.end>o.start);return{document:R({text:`${n.text.slice(0,o.start)}${n.text.slice(o.end)}`,references:n.references.filter(e=>!s.includes(e)).map(e=>e.start>=o.end?{...e,start:e.start-(o.end-o.start),end:e.end-(o.end-o.start)}:e)}),caret:o.start,edit:{oldStart:o.start,oldEnd:o.end,newEnd:o.start},removedIds:s.map(e=>e.id),removedReferences:s}},zn=(e,t)=>{let n=t,r=t;for(;n>0&&/\s/.test(e[n-1]);)--n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;let i=n>0&&r<e.length?` `:``;return{text:`${e.slice(0,n)}${i}${e.slice(r)}`,caret:n+i.length}},Bn=(e,t=`queue-canonical`)=>{let n=L(e.text,e.references);if(n.budgetExceeded)return{ok:!1,reason:`reference-budget-exceeded`};if(n.payloadBudgetExceeded)return{ok:!1,reason:`reference-payload-budget-exceeded`};if(n.rejectedCount>0)return{ok:!1,reason:`invalid-references`};let r=On(n.document,t);return r.ok?{ok:!0,text:r.text,chunks:r.plan.chunks,semantics:r.plan.semantics}:r},Vn=(e,t)=>e.match.index-t.match.index||e.adapterOrder-t.adapterOrder||e.matchOrder-t.matchOrder,Hn=e=>{if(e.length>N.canonicalOutputLength||e.length>N.visibleTextLength)return null;let t=[],n=0;for(let[r,i]of Cn().entries()){i.matcher.lastIndex=0;let a,o=0;for(;(a=i.matcher.exec(e))!==null;){if(n+=1,n>N.referenceCount)return null;let e={codec:i,match:a,adapterOrder:r,matchOrder:o};o+=1;let s=t.findIndex(t=>Vn(e,t)<0);s===-1?t.push(e):t.splice(s,0,e)}}return t},Un=(e,t)=>{let n=L(e.text,e.references).document,r=Hn(n.text);if(r===null)return n;let i={text:n.text,sessionTitles:t},a=[],o=``,s=0,c=0,l=new Set(n.references.map(e=>e.id)),u=[];for(let e of r){let{match:t,codec:r}=e,a=t.index,o=a+t[0].length;if(a<c||n.references.some(e=>e.start<o&&e.end>a))continue;let s=r.resolveDisplay(t,i);if(s===null||s.length>N.displayLength)continue;let d=r.materialize(t,s,a),f=d.id;for(;l.has(f);)f=`materialized:${f}`;l.add(f),u.push({start:a,end:o,display:s,reference:{...d,id:f}}),c=o}s=0;let d=0;for(let e of u){o+=`${n.text.slice(s,e.start)}${e.display}`;let t=e.start+d;a.push({...e.reference,start:t,end:t+e.display.length}),d+=e.display.length-(e.end-e.start),s=e.end}if(o+=n.text.slice(s),o.length>N.visibleTextLength)return n;let f=n.references.map(e=>{let t=u.filter(t=>t.end<=e.start).reduce((e,t)=>e+t.display.length-(t.end-t.start),0);return{...e,start:e.start+t,end:e.end+t}});return L(o,[...f,...a]).document},Wn=(e,t)=>Un({text:e,references:[]},t),Gn=(e,t,n=`
|
|
2
|
-
|
|
3
|
-
`)=>{let r=L(e.text,e.references).document,i=L(t.text,t.references).document;if(r.text===i.text&&JSON.stringify(r.references)===JSON.stringify(i.references))return i;let a=new Set(r.references.map(e=>e.id)),o=e=>{let t=e;for(;a.has(t);)t=`recovered:${t}`;return a.add(t),t},s=r.text.length+n.length;return L(`${r.text}${n}${i.text}`,[...r.references,...i.references.map(e=>({...e,id:o(e.id),start:e.start+s,end:e.end+s}))]).document},Kn=e=>({state:`unbound-legacy`,sessionID:e}),z=e=>e.state===`bound`?`bound:${JSON.stringify([e.transportIdentity,un(e.directory),e.sessionID,e.deliveryTarget??{kind:`primary`}])}`:`unbound-legacy:${JSON.stringify([e.sessionID])}`,qn=(e,t)=>e.queuedMessages[z(t)]??Jn,Jn=[],Yn=3e4,Xn=`queue`,Zn=e=>e===`steer`||e===`queue`,Qn=(e,t)=>e===`immediate`?`steer`:Zn(e)?e:t===!1?`steer`:`queue`,$n=[],er=(e,t)=>e.pendingAdmissions[z(t)]??$n,tr=e=>`${e}-${sn()}`,nr=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype,B=(e,t,n=[])=>{if(!nr(e)||!Object.keys(e).every(e=>e===`text`||e===`references`))return;let r=e;if(typeof r.text!=`string`)return;let i=Dt(r.text,r.references),a=i&&Bn(i,`queue-canonical`);if(!a||!a.ok||a.text!==t)return;let o=new Set(n.map(e=>e.id));return Tn(i).every(e=>o.has(e.attachmentRefID))?i:void 0},V=(e,t)=>{if(e===void 0)return[];if(!t)return;let n=xt(t.text,e);if(n)return n.some(e=>t.references.some(t=>e.range.start<t.end&&t.start<e.range.end))?void 0:n},rr=(e,t)=>{let n=nr(e)&&typeof e.content==`string`?e:t,r=B(n.composerDocument,n.content,Array.isArray(n.attachments)?n.attachments:[]),i=V(n.composerMentions,r);return{content:n.content,...r?{composerDocument:r}:{},...r&&i?.length?{composerMentions:i}:{},...Array.isArray(n.attachments)?{attachments:n.attachments}:{},...nr(n.sendConfig)?{sendConfig:n.sendConfig}:{}}},ir=e=>rr(void 0,e),ar=(e,t)=>e.queueItemID===t.queueItemID&&e.operationID===t.operationID&&(!t.messageID||e.messageID===t.messageID),H=e=>e.status===`sending`||e.status===`reconciling`,or=se(),sr=()=>or?.flush()??!0,cr=`quiescing`,lr=new Set,ur=new Set,dr=e=>{if(cr!==e){cr=e;for(let e of ur)e()}},fr=e=>{if(!(!e||lr.has(e))){lr.add(e);for(let e of ur)e()}},pr=e=>e.state===`bound`&&lr.has(e.transportIdentity),U=e=>cr===`open`&&(!e||!pr(e)),mr=(e,t=Date.now())=>({reconciliationStartedAt:e.reconciliationStartedAt??t,reconciliationDeadlineAt:e.reconciliationDeadlineAt??(e.reconciliationStartedAt??t)+Yn,reconciliationChecks:Math.max(0,Math.floor(e.reconciliationChecks??0))}),hr=(e,t,n)=>{let r=t.queueItemID??(t.id||tr(`queued`)),i=!t.owner&&(t.status===`sending`||t.status===`reconciling`),a=i?`unresolved`:t.status===`sending`?`reconciling`:t.status===`retrying`||t.status===`reconciling`||t.status===`unresolved`||t.status===`failed`?t.status:`queued`,o=typeof t.messageID==`string`&&t.messageID.startsWith(`msg_`)?t.messageID:rn(`msg`),s=B(t.composerDocument,t.content,t.attachments),c=V(t.composerMentions,s);return{...t,...s?{composerDocument:s}:{composerDocument:void 0},...s&&c?.length?{composerMentions:c}:{composerMentions:void 0},id:r,queueItemID:r,operationID:t.operationID??tr(`operation`),messageID:o,owner:n,status:a,attemptCount:Math.max(0,Math.floor(t.attemptCount??0)),...t.status===`sending`||t.status===`reconciling`?mr(t):{},...i||a===`reconciling`&&t.status===`sending`?{failure:{kind:`ambiguous-dispatch`,recovery:rr(t.failure?.recovery,t)}}:{}}},gr=e=>{let t=e??{},n={};for(let[e,r]of Object.entries(t.queuedMessages??{})){if(!Array.isArray(r))continue;let t;if(e.startsWith(`bound:`)||e.startsWith(`unbound-legacy:`)){let n=r[0],i=e.startsWith(`unbound-legacy:`)?(()=>{try{let t=JSON.parse(e.slice(15));return Array.isArray(t)&&typeof t[0]==`string`?t[0]:e}catch{return e}})():e;t=n?.owner?.state===`bound`?n.owner:Kn(n?.owner?.sessionID??i)}else t=Kn(e);for(let e of r){let r=e.owner?.state===`bound`?e.owner:t,i=z(r);(n[i]??=[]).push(hr(r.sessionID,e,r))}}return{queuedMessages:n,followUpBehavior:Qn(t.followUpBehavior,t.queueModeEnabled??null)}},W=(e,t,n,r)=>{if(pr(t))return;let i=z(t);e(e=>{let t=e.queuedMessages[i],a=t?.findIndex(e=>z(e.owner)===i&&ar(e,n))??-1;if(a<0||!t)return e;let o=r(t[a]);if(o===t[a])return e;let s=t.slice();return s[a]=o,{queuedMessages:{...e.queuedMessages,[i]:s}}})},_r=m()(ee(h((e,t)=>({queuedMessages:{},followUpBehavior:Xn,pendingAdmissions:{},addToQueue:(t,n)=>{if(!U(t))return{ok:!1,reason:`invalid-composer-document`};let r=B(n.composerDocument,n.content,n.attachments);if(n.composerDocument!==void 0&&!r)return{ok:!1,reason:`invalid-composer-document`};let i=V(n.composerMentions,r);if(n.composerMentions!==void 0&&!i)return{ok:!1,reason:`invalid-composer-mentions`};n={...n,...r?{composerDocument:r}:{},...i?.length?{composerMentions:i}:{}};let a={...n,id:tr(`queued`),queueItemID:``,operationID:tr(`operation`),messageID:rn(`msg`),createdAt:Date.now(),owner:t,status:`queued`,attemptCount:0};a.queueItemID=a.id;let o=z(t);return e(e=>({queuedMessages:{...e.queuedMessages,[o]:[...e.queuedMessages[o]??[],a]}})),{ok:!0,item:a}},removeFromQueue:(n,r,i)=>{if(!U(n)||!i)return!1;let a=z(n),o=t().queuedMessages[a];if(!o||o.length===0)return!0;let s=o.find(e=>(e.queueItemID===r||e.id===r)&&z(e.owner)===a);if(s&&s.operationID!==i)return!1;let c=o.find(e=>(e.queueItemID===r||e.id===r)&&e.operationID===i&&z(e.owner)===a);return!c||!H(c)&&(e(e=>{let t=e.queuedMessages[a];if(!t)return e;let n=t.filter(e=>e!==c);if(n.length===t.length)return e;if(n.length)return{queuedMessages:{...e.queuedMessages,[a]:n}};let{[a]:r,...i}=e.queuedMessages;return{queuedMessages:i}}),!qn(t(),n).some(e=>e===c||(e.queueItemID===r||e.id===r)&&e.operationID===i))},reorderQueue:(t,n,r,i)=>{if(!U(t)||!i)return;let a=z(t);e(e=>{let t=e.queuedMessages[a],o=t?.findIndex(e=>(e.id===n||e.queueItemID===n)&&e.operationID===i&&z(e.owner)===a)??-1,s=t?.findIndex(e=>(e.id===r||e.queueItemID===r)&&z(e.owner)===a)??-1;if(!t||o<0||s<0||o===s||H(t[o])||H(t[s]))return e;let c=t.slice(),[l]=c.splice(o,1);return c.splice(s,0,l),{queuedMessages:{...e.queuedMessages,[a]:c}}})},popToInput:(e,n,r)=>{if(!U(e)||!r)return null;let i=qn(t(),e).find(t=>(t.id===n||t.queueItemID===n)&&t.operationID===r&&z(t.owner)===z(e));return!i||H(i)||!t().removeFromQueue(e,i.queueItemID,i.operationID)?null:i},clearQueue:n=>{if(!U(n))return!1;let r=z(n),i=t().queuedMessages[r],a=(t().pendingAdmissions[r]??[]).length>0;return(!i||i.length===0)&&!a||!i?.some(H)&&(e(e=>{if(e.queuedMessages[r]?.some(H))return e;let t={...e.queuedMessages},n={...e.pendingAdmissions};return delete t[r],delete n[r],{queuedMessages:t,pendingAdmissions:n}}),(t().queuedMessages[r]??[]).length===0)},clearAllQueues:()=>{U()&&e(e=>{let t={},n=!1;for(let[r,i]of Object.entries(e.queuedMessages)){if(i[0]&&pr(i[0].owner)){t[r]=i;continue}let e=i.filter(H);e.length&&(t[r]=e),e.length!==i.length&&(n=!0)}let r=Object.keys(e.pendingAdmissions).length>0;return n||r?{queuedMessages:t,pendingAdmissions:{}}:e})},setFollowUpBehavior:t=>{U()&&(e({followUpBehavior:t}),ea({followUpBehavior:t}))},getQueueForScope:e=>qn(t(),e),getPendingAdmissionsForScope:e=>er(t(),e),stageAdmission:(t,n)=>{if(!U(t)||!n.requestID||!n.queueItemID||!n.operationID||!n.messageID||typeof n.content!=`string`)return;let r=B(n.composerDocument,n.content);if(n.composerDocument!==void 0&&!r)return;let i=V(n.composerMentions,r);if(n.composerMentions!==void 0&&!i)return;let a=z(t),o={kind:`pending-admission`,requestID:n.requestID,queueItemID:n.queueItemID,operationID:n.operationID,messageID:n.messageID,content:n.content,createdAt:n.createdAt,phase:`admitting`,attachmentCount:Math.max(0,Math.floor(n.attachmentCount??0)),...r?{composerDocument:r}:{},...r&&i?.length?{composerMentions:i}:{}};e(e=>{let t=[...(e.pendingAdmissions[a]??[]).filter(e=>e.requestID!==o.requestID&&e.queueItemID!==o.queueItemID),o];return{pendingAdmissions:{...e.pendingAdmissions,[a]:t}}})},unstageAdmission:(t,n)=>{if(!n)return;let r=z(t);e(e=>{let t=e.pendingAdmissions[r];if(!t?.length)return e;let i=t.filter(e=>e.requestID!==n);if(i.length===t.length)return e;if(i.length)return{pendingAdmissions:{...e.pendingAdmissions,[r]:i}};let{[r]:a,...o}=e.pendingAdmissions;return{pendingAdmissions:o}})},confirmAdmission:(n,r)=>{if(!U(n)||!r.requestID||!r.sendConfig?.providerID||!r.sendConfig?.modelID)return{ok:!1,reason:`invalid-composer-document`};let i=z(n),a=(t().pendingAdmissions[i]??[]).find(e=>e.requestID===r.requestID);if(!a)return{ok:!1,reason:`invalid-composer-document`};let o=B(a.composerDocument,a.content,r.attachments);if(a.composerDocument!==void 0&&!o)return{ok:!1,reason:`invalid-composer-document`};let s=V(a.composerMentions,o);if(a.composerMentions!==void 0&&!s)return{ok:!1,reason:`invalid-composer-mentions`};let c={id:a.queueItemID,queueItemID:a.queueItemID,operationID:a.operationID,messageID:a.messageID,content:a.content,createdAt:a.createdAt,owner:n,status:`queued`,attemptCount:0,sendConfig:r.sendConfig,...o?{composerDocument:o}:{},...o&&s?.length?{composerMentions:s}:{},...r.attachments?.length?{attachments:r.attachments}:{}};return e(e=>{let t=(e.pendingAdmissions[i]??[]).filter(e=>e.requestID!==r.requestID);return{pendingAdmissions:t.length?{...e.pendingAdmissions,[i]:t}:(()=>{let{[i]:t,...n}=e.pendingAdmissions;return n})(),queuedMessages:{...e.queuedMessages,[i]:[...e.queuedMessages[i]??[],c]}}}),{ok:!0,item:c}},bindLegacyQueue:(t,n)=>{if(!U(t)||!U(n)||t.state!==`unbound-legacy`||n.state!==`bound`||t.sessionID!==n.sessionID)return[];let r=z(t),i=z(n),a=[];return e(e=>{let t=e.queuedMessages[r];if(!t||(a=t.filter(e=>!H(e)),a.length===0))return e;let o=t.filter(H),s={...e.queuedMessages,[i]:[...a.map(e=>({...e,owner:n})),...e.queuedMessages[i]??[]]};return o.length?s[r]=o:delete s[r],{queuedMessages:s}}),a.map(e=>({...e,owner:n}))},markQueueItemSendAttempt:(t,n)=>{U(t)&&W(e,t,n,e=>e.status===`queued`||e.status===`retrying`&&(e.nextAttemptAt??0)<=Date.now()?{...e,status:`sending`,attemptCount:e.attemptCount+1,nextAttemptAt:void 0,failure:void 0}:e)},markQueueItemPreDispatchRetry:(t,n,r,i)=>W(e,t,n,e=>e.status===`sending`?{...e,status:`retrying`,nextAttemptAt:r,failure:{kind:`pre-dispatch`,recovery:i?.recovery??ir(e)}}:e),markQueueItemReconciling:(t,n,r)=>W(e,t,n,e=>e.status===`sending`?{...e,status:`reconciling`,nextAttemptAt:void 0,...mr(e),reconciliationNextCheckAt:void 0,failure:{kind:`ambiguous-dispatch`,recovery:r?.recovery??ir(e)}}:e),recordQueueItemReconciliationCheck:(t,n)=>W(e,t,n,e=>e.status===`reconciling`&&ar(e,n)?{...e,reconciliationChecks:(e.reconciliationChecks??0)+1,reconciliationNextCheckAt:Date.now()+2e3}:e),resolveQueueItemReconciliation:(t,n)=>W(e,t,n,e=>e.status===`reconciling`&&ar(e,n)?{...e,status:`unresolved`,nextAttemptAt:void 0}:e),markQueueItemDefinitiveFailure:(t,n,r)=>W(e,t,n,e=>e.status===`sending`?{...e,status:`failed`,nextAttemptAt:void 0,failure:{kind:`definitive`,recovery:r?.recovery??ir(e)}}:e),resetQueueItemForDispatch:(t,n)=>{U(t)&&W(e,t,n,e=>e.status!==`failed`&&e.status!==`unresolved`&&e.status!==`retrying`?e:{...e,status:`queued`,nextAttemptAt:void 0,failure:void 0,reconciliationStartedAt:void 0,reconciliationDeadlineAt:void 0,reconciliationChecks:void 0,reconciliationNextCheckAt:void 0})},beginQueueItemDispatch:(t,n,r,i,a=Date.now())=>{if(!U(t)||!r.startsWith(`msg_`))return null;let o=z(t),s=null;return e(e=>{let t=e.queuedMessages[o],c=i?t?.findIndex(e=>z(e.owner)===o&&ar(e,n))??-1:0,l=c>=0?t?.[c]:void 0,u=l?.status===`queued`||l?.status===`retrying`&&(i||(l.nextAttemptAt??0)<=a)||i&&(l?.status===`failed`||l?.status===`unresolved`);if(!l||z(l.owner)!==o||!ar(l,n)||!u||t?.some(H))return e;s={...l,messageID:r,status:`sending`,attemptCount:l.attemptCount+1,nextAttemptAt:void 0,failure:void 0,reconciliationStartedAt:void 0,reconciliationDeadlineAt:void 0,reconciliationChecks:void 0,reconciliationNextCheckAt:void 0};let d=t.slice();return d.splice(c,1),d.unshift(s),{queuedMessages:{...e.queuedMessages,[o]:d}}}),s},confirmQueueItem:(t,n)=>{if(pr(t))return;let r=z(t);e(e=>{let t=e.queuedMessages[r],i=t?.find(e=>{let t=!n.operationID||e.operationID===n.operationID,r=!n.messageID||e.messageID===n.messageID,i=!n.queueItemID||e.queueItemID===n.queueItemID;return t&&r&&i});if(!i||!n.operationID&&!n.messageID)return e;let a=t.filter(e=>e!==i);if(a.length)return{queuedMessages:{...e.queuedMessages,[r]:a}};let{[r]:o,...s}=e.queuedMessages;return{queuedMessages:s}})}}),{name:`message-queue-store`,version:4,storage:or,partialize:e=>({queuedMessages:e.queuedMessages,followUpBehavior:e.followUpBehavior}),migrate:gr,merge:(e,t)=>({...t,...gr(e),pendingAdmissions:t.pendingAdmissions})}),{name:`message-queue-store`})),vr=(e,t)=>{let n=_r.getState().queuedMessages,r=[],i=[];for(let[a,o]of Object.entries(n)){let n=o[0]?.owner;if(!n||n.state!==`unbound-legacy`)continue;let s=t(n.sessionID);if(!s){i.push(n.sessionID);continue}r.push({sourceKey:a,target:{state:`bound`,transportIdentity:e,directory:s,sessionID:n.sessionID},items:o})}return!e||i.length?{ok:!1,unresolvedSessionIDs:i}:r.length?(_r.setState(e=>{let t={...e.queuedMessages};for(let e of r){let n=z(e.target);t[n]=[...e.items.map(t=>({...t,owner:e.target})),...t[n]??[]],delete t[e.sourceKey]}return{queuedMessages:t}}),{ok:!0,moved:r.reduce((e,t)=>e+t.items.length,0)}):{ok:!0,moved:0}},yr=le(),br=e(te(),1),xr=`directoryTreeShowHidden`,Sr=`directory-show-hidden-change`,Cr=()=>{if(typeof window>`u`)return!0;try{let e=g().getItem(xr);return e===null||e===`true`}catch{return!0}},wr=()=>{typeof window>`u`||window.dispatchEvent(new Event(Sr))},Tr=(e,t={})=>{if(!(typeof window>`u`)){try{g().setItem(xr,e?`true`:`false`),wr()}catch{}t.persist!==!1&&ea({directoryShowHidden:e})}},Er=()=>{let e=(0,yr.c)(2),[t,n]=br.useState(Cr),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>{n(Cr())};return window.addEventListener(`storage`,e),window.addEventListener(Sr,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(Sr,e)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),br.useEffect(r,i),t},Dr=`filesViewShowGitignored`,Or=`files-view-show-gitignored-change`,kr=()=>{if(typeof window>`u`)return!1;try{return g().getItem(Dr)===`true`}catch{return!1}},Ar=()=>{typeof window>`u`||window.dispatchEvent(new Event(Or))},jr=(e,t={})=>{if(!(typeof window>`u`)){try{g().setItem(Dr,e?`true`:`false`),Ar()}catch{}t.persist!==!1&&ea({filesViewShowGitignored:e})}},Mr=()=>{let e=(0,yr.c)(2),[t,n]=br.useState(kr),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>{n(kr())};return window.addEventListener(`storage`,e),window.addEventListener(Or,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(Or,e)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),br.useEffect(r,i),t},Nr=e=>{if(!e||typeof e!=`object`)return null;let t={};return typeof e.showReasoningTraces==`boolean`&&(t.showReasoningTraces=e.showReasoningTraces),typeof e.collapsibleThinkingBlocks==`boolean`&&(t.collapsibleThinkingBlocks=e.collapsibleThinkingBlocks),Object.keys(t).length>0?t:null},Pr=e=>{if(!e||typeof e!=`object`)return null;let t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},Fr=e=>{let t=_.getState();typeof e.showReasoningTraces==`boolean`&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks==`boolean`&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},Ir=async()=>{if(typeof window>`u`)return null;let e=localStorage.getItem(`appearance-preferences`);if(!e)return null;try{return Nr(Pr(JSON.parse(e)))}catch(e){return console.warn(`Failed to parse stored appearance preferences:`,e),null}},Lr=[{name:`explore`,icon:`compass-3`,labelKey:`chat.draftPresets.explore.label`,command:`/explore`},{name:`catch-up`,icon:`history`,labelKey:`chat.draftPresets.catchup.label`,command:`/catch-up`},{name:`weigh`,icon:`scales-3`,labelKey:`chat.draftPresets.weigh.label`,command:`/weigh`},{name:`craft-goal`,icon:`target`,labelKey:`chat.draftPresets.craftGoal.label`,command:`/craft-goal`},{name:`debug`,icon:`bug`,labelKey:`chat.draftPresets.debug.label`,command:`/debug`},{name:`review`,icon:`search-eye`,labelKey:`chat.draftPresets.review.label`,command:`/workspace-review`}],Rr=new Map(Lr.map(e=>[e.name,e])),zr=e=>Rr.get(e),Br=[{type:`command`,name:`explore`},{type:`command`,name:`catch-up`},{type:`command`,name:`weigh`},{type:`command`,name:`debug`},{type:`command`,name:`review`}],Vr=`terminal-box`,Hr=`book-open`,Ur=e=>`${e.type}:${e.name}`,Wr=(e,t)=>e.type===t.type&&e.name===t.name,Gr=e=>{let t=e.replace(/^\//,``).replace(/[-_]+/g,` `).replace(/\s+/g,` `).trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},Kr=e=>{if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!r||typeof r!=`object`)continue;let e=r,i=e.type===`command`||e.type===`skill`?e.type:null,a=typeof e.name==`string`?e.name.trim():``;if(!i||!a)continue;let o=`${i}:${a}`;n.has(o)||(n.add(o),t.push({type:i,name:a}))}return t},qr=`oc.rt.`,Jr=e=>{try{return btoa(unescape(encodeURIComponent(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}catch{return encodeURIComponent(e)}},G=(e,t=s())=>`${qr}${Jr(t.trim().length>0?t.trim():`default`)}.${e}`,Yr=(e,t,n=s())=>e?e===G(t,n):!1,Xr=()=>{if(typeof window>`u`)return!0;let e=window.__OPENCHAMBER_API_BASE_URL__,t=window.__OPENCHAMBER_LOCAL_ORIGIN__;if(typeof e==`string`&&e.trim()&&typeof t==`string`&&t.trim())try{return new URL(e).origin===new URL(t).origin}catch{return!1}try{if(p())return!0}catch{}if(typeof e==`string`&&e.trim())try{let t=new URL(e).hostname;if(t!==`localhost`&&t!==`127.0.0.1`&&t!==`::1`)return!1}catch{return!1}return!0},Zr=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{getItem:()=>null}),r=t?.transport??s(),i=n.getItem(G(e,r));return i===null?Xr()?n.getItem(e):null:i},K=(e,t,n)=>{let r=n?.storage??(typeof localStorage<`u`?localStorage:{setItem:()=>void 0}),i=n?.transport??s();r.setItem(G(e,i),t)},Qr=e=>{let t;try{t=ne()}catch{return}let n=t=>t===null?null:JSON.parse(t,e?.reviver),r=e=>t.getItem(e);return{getItem:e=>{let t=G(e,s()),i=r(t);if(i instanceof Promise)return i.then(t=>{if(t!==null)return n(t);if(!Xr())return null;let i=r(e);return i instanceof Promise?i.then(n):n(i)});if(i!==null)return n(i);if(!Xr())return null;let a=r(e);return a instanceof Promise?a.then(n):n(a)},setItem:(n,r)=>{let i=G(n,s());t.setItem(i,JSON.stringify(r,e?.replacer))},removeItem:e=>{let n=G(e,s());t.removeItem(n)}}},$r=512,ei=4096,ti=64,ni=2e5,ri=[`concise`,`detailed`,`mentor`,`pushback`,`noFiller`,`matchEnergy`,`warmPeer`,`custom`],ii=[`defaultModel`,`defaultVariant`,`defaultAgent`,`autoCreateWorktree`,`gitmojiEnabled`,`defaultFileViewerPreview`,`zenModel`,`messageStreamTransport`,`sttProvider`,`sttServerUrl`,`sttModel`,`sttLocalModel`,`sttLanguage`,`responseStyleEnabled`,`responseStylePreset`,`responseStyleCustomInstructions`],ai=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype,oi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),si=(e,t)=>{if(typeof e!=`string`)return;let n=e.trim();return n.length<=t?n:void 0},ci=e=>{let t=si(e,ei);if(t!==void 0)try{let e=new URL(t);return(e.protocol===`http:`||e.protocol===`https:`)&&!e.username&&!e.password?t:void 0}catch{return}},li=(e,t)=>typeof e==`string`&&t.includes(e)?e:void 0,ui=e=>typeof e==`boolean`?e:void 0,di=(e,t)=>{let n=e[t];switch(t){case`autoCreateWorktree`:case`gitmojiEnabled`:case`defaultFileViewerPreview`:case`responseStyleEnabled`:return ui(n);case`messageStreamTransport`:return li(n,[`auto`,`ws`,`sse`]);case`sttProvider`:return li(n,[`local`,`openai-compatible`]);case`sttServerUrl`:return ci(n);case`sttLanguage`:return si(n,ti);case`responseStyleCustomInstructions`:return si(n,ni);case`responseStylePreset`:return li(n,ri);default:return si(n,$r)}},fi=e=>{if(!ai(e))throw Error(`Invalid settings bootstrap response`);if(!oi(e,`schemaVersion`)||e.schemaVersion!==1)throw Error(`Unsupported settings bootstrap schema version`);let t={schemaVersion:1};for(let n of ii){if(!oi(e,n))continue;let r=di(e,n);r!==void 0&&Object.assign(t,{[n]:r})}return t},pi=e=>{if(!ai(e))throw Error(`Invalid settings bootstrap patch`);for(let t of Object.keys(e))if(!ii.includes(t))throw Error(`Invalid settings bootstrap patch`);let t=fi({schemaVersion:1,...e}),n={};for(let r of ii)if(oi(e,r)){if(!oi(t,r))throw Error(`Invalid settings bootstrap patch`);Object.assign(n,{[r]:t[r]})}return n},mi=e=>{if(!ai(e))return{};let t={};for(let n of ii){if(!oi(e,n))continue;let r=di(e,n);r!==void 0&&Object.assign(t,{[n]:r})}return t},q=new ue({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:1,refetchOnWindowFocus:!1}}}),hi={runtime:()=>[s()],scoped:(...e)=>[s(),...e],quota:e=>[s(),e],commands:{list:(e,t=s())=>[t,`commands`,e]},agents:{list:(e,t=s())=>[t,`agents`,e],raw:(e,t=s())=>[t,`agents`,`raw`]},configCatalog:{providers:(e,t=s())=>[t,`configCatalog`,`providers`,e]},providers:{list:(e,t=s())=>[t,`providers`,e]},skills:{list:(e,t=s())=>[t,`skills`,e]},skillsCatalog:{sources:(e,t=s())=>[t,`skillsCatalog`,`sources`,J(e)],source:(e,t,n=s())=>[n,`skillsCatalog`,`source`,J(e),t]},messageQueue:{status:(e=s())=>[e,`messageQueue`,`status`],snapshot:(e=s())=>[e,`messageQueue`,`snapshot`],scope:(e,t,n=s())=>[n,`messageQueue`,`scope`,e,t]},mcp:{configs:(e,t=s())=>[t,`mcp`,`configs`,J(e)],status:(e,t=s())=>[t,`mcp`,`status`,J(e)]},github:{auth:(e=s())=>[e,`github`,`auth`]},git:{branches:(e,t=s())=>[t,`git`,`branches`,J(e)],remotes:(e,t=s())=>[t,`git`,`remotes`,J(e)]},sessionIndex:{snapshot:(e=s())=>[e,`sessionIndex`,`snapshot`]},sessionStatus:{snapshot:(e,t=s())=>[t,`sessionStatus`,`snapshot`,J(e)]},sessionTurnChanges:{file:(e,t,n,r,i,a=s())=>[a,`sessionTurnChanges`,`file`,J(e),t,n,r,typeof i==`number`&&Number.isFinite(i)?Math.max(0,Math.trunc(i)):null]},sessionActive:{snapshot:(e,t)=>[e,`sessionActive`,`snapshot`,t]},sessionTranscript:{infinite:(e,t,n=s(),r=c())=>[n,r,`session-transcript`,J(e)??``,t],page:(e,t,n,r,i=s(),a=c())=>[i,a,`sessionMessages`,`page`,J(e)??``,t,n,r?.trim()?r.trim():`tail`],tailTask:(e,t,n,r=s(),i=c())=>[r,i,`session-transcript-task`,`tail`,J(e)??``,t,n],reconcileTask:(e,t,n,r=s(),i=c())=>[r,i,`session-transcript-task`,`reconcile`,J(e)??``,t,n],checkpoint:(e,t,n=s(),r=c())=>[n,r,`session-transcript-checkpoint`,J(e)??``,t]},plugins:{list:(e,t=s())=>[t,`plugins`,`list`,e],registry:(e,t,n=!1,r=s())=>[r,`plugins`,`registry`,e,gi(t),n],file:(e,t,n=s())=>[n,`plugins`,`file`,e,t]},files:{directory:(e,t,n,r=s())=>[r,`files`,`directory`,Y(e),Y(t),!!n],search:(e,t,n,r,i,a=s())=>[a,`files`,`search`,Y(e),t.trim(),n??null,!!r,!!i],content:(e,t,n,r=s())=>_i(`content`,e,t,n,r),stat:(e,t,n,r=s())=>_i(`stat`,e,t,n,r)}},gi=e=>Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))).sort(),J=e=>e?.trim()||null,Y=e=>{if(typeof e!=`string`)return null;let t=e.trim().replace(/\\/g,`/`);return t?t.length>1?t.replace(/\/+$/,``):t:null},_i=(e,t,n,r,i)=>[i,`files`,e,Y(t),Y(n),!!r?.allowOutsideWorkspace,r?.outsideFileGrant??null,!!r?.optional,Y(r?.directory)],vi=async(e,t)=>{let n=await We(`/api/quota/${encodeURIComponent(e)}`,{signal:t}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error||`Failed to fetch quota`);return r},yi=e=>i(t=>{l(t)&&e.clear()}),bi=class extends Error{status;constructor(e){super(`Settings bootstrap request failed (${e})`),this.status=e,this.name=`SettingsBootstrapRequestError`}},xi=(e=s())=>[e,`settings`,`bootstrap`],Si=(e=s())=>({queryKey:xi(e),queryFn:async({signal:e})=>{let t=await We(`/api/config/settings/bootstrap`,{method:`GET`,headers:{Accept:`application/json`},signal:e});if(!t.ok)throw new bi(t.status);return fi(await t.json())},retry:(e,t)=>!(t instanceof bi&&(t.status===404||t.status===501))&&e<1,staleTime:1/0,gcTime:1/0}),Ci=(e=s())=>q.fetchQuery(Si(e)),wi=(e=s())=>q.getQueryData(xi(e)),Ti=(e,t=s())=>{let n=pi(e),r=xi(t),i=fi({schemaVersion:1,...q.getQueryData(r),...n});return q.setQueryData(r,i),i},Ei=e=>{if(!(typeof window>`u`)&&!(typeof window.__OPENCHAMBER_HOME__==`string`&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},Di=e=>{if(!(typeof window>`u`)){if(e.themeId&&K(`selectedThemeId`,e.themeId),e.themeVariant&&K(`selectedThemeVariant`,e.themeVariant),e.lightThemeId&&K(`lightThemeId`,e.lightThemeId),e.darkThemeId&&K(`darkThemeId`,e.darkThemeId),typeof e.useSystemTheme==`boolean`&&(K(`useSystemTheme`,String(e.useSystemTheme)),K(`themeMode`,e.useSystemTheme?`system`:e.themeVariant===`dark`||e.themeVariant===`light`?e.themeVariant:`system`)),e.lastDirectory&&S(`lastDirectory`,e.lastDirectory),e.homeDirectory&&(S(`homeDirectory`,e.homeDirectory),Ei(e.homeDirectory)),Array.isArray(e.projects)&&e.projects.length>0?S(`projects`,JSON.stringify(e.projects)):C(`projects`),e.activeProjectId?S(`activeProjectId`,e.activeProjectId):C(`activeProjectId`),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?S(`pinnedDirectories`,JSON.stringify(e.pinnedDirectories)):C(`pinnedDirectories`),Array.isArray(e.projects)&&e.projects.length>0){let t=e.projects.filter(e=>e.sidebarCollapsed===!0).map(e=>e.id).filter(e=>typeof e==`string`&&e.length>0);t.length>0?S(`oc.sessions.projectCollapse`,JSON.stringify(t)):C(`oc.sessions.projectCollapse`)}if(typeof e.gitmojiEnabled==`boolean`?localStorage.setItem(`gitmojiEnabled`,String(e.gitmojiEnabled)):localStorage.removeItem(`gitmojiEnabled`),typeof e.directoryShowHidden==`boolean`&&localStorage.setItem(`directoryTreeShowHidden`,e.directoryShowHidden?`true`:`false`),typeof e.filesViewShowGitignored==`boolean`&&localStorage.setItem(`filesViewShowGitignored`,e.filesViewShowGitignored?`true`:`false`),typeof e.openInAppId==`string`&&e.openInAppId.length>0&&localStorage.setItem(`openInAppId`,e.openInAppId),typeof e.pwaAppName==`string`){let t=e.pwaAppName.trim().replace(/\s+/g,` `).slice(0,64);t.length>0?localStorage.setItem(`openchamber.pwaName`,t):localStorage.removeItem(`openchamber.pwaName`)}if(typeof e.mobileKeyboardMode==`string`&&ie(e.mobileKeyboardMode),typeof e.openCodeUpdateToastDismissedVersion==`string`){let t=e.openCodeUpdateToastDismissedVersion.trim();t?localStorage.setItem(`opencode-update-toast-dismissed-version`,t):localStorage.removeItem(`opencode-update-toast-dismissed-version`)}typeof e.dictationEnabled==`boolean`&&localStorage.setItem(`dictationEnabled`,String(e.dictationEnabled)),(e.sttProvider===`local`||e.sttProvider===`openai-compatible`)&&localStorage.setItem(`sttProvider`,e.sttProvider),typeof e.sttServerUrl==`string`&&localStorage.setItem(`sttServerUrl`,e.sttServerUrl),typeof e.sttModel==`string`&&localStorage.setItem(`sttModel`,e.sttModel),typeof e.sttLocalModel==`string`&&localStorage.setItem(`sttLocalModel`,e.sttLocalModel),typeof e.sttLanguage==`string`&&localStorage.setItem(`sttLanguage`,e.sttLanguage)}},Oi=e=>{typeof window>`u`||window.dispatchEvent(new CustomEvent(`openchamber:settings-synced`,{detail:e}))},ki=e=>{if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(!r||typeof r!=`object`)continue;let e=r,i=typeof e.id==`string`?e.id.trim():``,a=typeof e.label==`string`?e.label.trim():``,o=typeof e.source==`string`?e.source.trim():``,s=typeof e.subpath==`string`?e.subpath.trim():``,c=typeof e.gitIdentityId==`string`?e.gitIdentityId.trim():``;!i||!a||!o||n.has(i)||(n.add(i),t.push({id:i,label:a,source:o,...s?{subpath:s}:{},...c?{gitIdentityId:c}:{}}))}return t},Ai=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e)){let e=typeof n==`string`?n.trim():``,i=typeof r==`string`?r.trim():``;!e||!i||(t[e]=i)}return t},ji=(e,t)=>{let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([e,n])=>t[e]===n)},Mi=(e,t)=>e.length===t.length&&e.every((e,n)=>e.providerID===t[n]?.providerID&&e.modelID===t[n]?.modelID&&e.variant===t[n]?.variant),Ni=(e,t)=>{if(t.length===0)return t;let n=new Map;for(let t of e)typeof t.variant==`string`&&t.variant.length>0&&n.set(`${t.providerID}/${t.modelID}`,t.variant);return t.map(e=>{if(typeof e.variant==`string`&&e.variant.length>0)return e;let t=n.get(`${e.providerID}/${e.modelID}`);return t?{providerID:e.providerID,modelID:e.modelID,variant:t}:e})},Pi=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Fi=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(e=>typeof e==`string`&&e.length>0)))},Ii=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e)){if(!n||!Array.isArray(r))continue;let e=Fi(r);e&&e.length>0&&(t[n]=e.slice(0,5))}return Object.keys(t).length>0?t:void 0},Li=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Array.isArray(t[n])&&Pi(e[n],t[n]))},Ri=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,zi=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&Ri.test(t)?t.toLowerCase():null},Bi=e=>{if(!Array.isArray(e))return;let t=[],n=new Set,r=new Set;for(let i of e){if(!i||typeof i!=`object`)continue;let e=i,a=typeof e.path==`string`?e.path.trim():``;if(!a)continue;let o=a===`/`?a:a.replace(/\\/g,`/`).replace(/\/+$/,``);if(!o)continue;let s=an(o);if(!s||n.has(s)||r.has(o))continue;n.add(s),r.add(o);let c={id:s,path:o};if(typeof e.label==`string`&&e.label.trim().length>0&&(c.label=e.label.trim()),typeof e.icon==`string`&&e.icon.trim().length>0&&(c.icon=e.icon.trim()),e.iconImage===null)c.iconImage=null;else if(e.iconImage&&typeof e.iconImage==`object`){let t=e.iconImage,n=typeof t.mime==`string`?t.mime.trim():``,r=typeof t.updatedAt==`number`&&Number.isFinite(t.updatedAt)?Math.max(0,Math.round(t.updatedAt)):0,i=t.source===`custom`||t.source===`auto`?t.source:null;n&&r>0&&i&&(c.iconImage={mime:n,updatedAt:r,source:i})}if(typeof e.color==`string`&&e.color.trim().length>0&&(c.color=e.color.trim()),e.iconBackground===null)c.iconBackground=null;else{let t=zi(e.iconBackground);t&&(c.iconBackground=t)}typeof e.addedAt==`number`&&Number.isFinite(e.addedAt)&&e.addedAt>=0&&(c.addedAt=e.addedAt),typeof e.lastOpenedAt==`number`&&Number.isFinite(e.lastOpenedAt)&&e.lastOpenedAt>=0&&(c.lastOpenedAt=e.lastOpenedAt),typeof e.sidebarCollapsed==`boolean`&&(c.sidebarCollapsed=e.sidebarCollapsed),t.push(c)}return t.length>0?t:void 0},Vi=(e,t,n)=>{if(!Array.isArray(e))return;let r=[],i=new Set,a=n?.preserveVariant===!0;for(let n of e){if(!n||typeof n!=`object`)continue;let e=n,o=typeof e.providerID==`string`?e.providerID.trim():``,s=typeof e.modelID==`string`?e.modelID.trim():``;if(!o||!s)continue;let c=`${o}/${s}`;if(!i.has(c)&&(i.add(c),a&&typeof e.variant==`string`&&e.variant.trim().length>0?r.push({providerID:o,modelID:s,variant:e.variant.trim()}):r.push({providerID:o,modelID:s}),r.length>=t))break}return r},Hi=()=>{let e=_.persist;if(e&&typeof e==`object`)return e},Ui=()=>f()?.settings??null,Wi=(e,t,n)=>{let r={...mi(t),...mi(e)};if(Object.keys(r).length!==0)try{Ti(r,n)}catch(e){console.warn(`Failed to patch settings bootstrap cache:`,e)}},Gi=e=>{let t=_.getState(),n=typeof window<`u`?window.__zustand_config_store__?.getState?.()??null:null,r=typeof window<`u`?window.__zustand_config_store__??null:null,i=_r.getState();if(typeof e.showReasoningTraces==`boolean`&&e.showReasoningTraces!==t.showReasoningTraces&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.sessionTitleRefreshEnabled==`boolean`&&e.sessionTitleRefreshEnabled!==t.sessionTitleRefreshEnabled&&t.setSessionTitleRefreshEnabled(e.sessionTitleRefreshEnabled),typeof e.sessionGoalEnabled==`boolean`&&e.sessionGoalEnabled!==t.sessionGoalEnabled&&t.setSessionGoalEnabled(e.sessionGoalEnabled),typeof e.sessionGoalDefaultBudgetEnabled==`boolean`&&e.sessionGoalDefaultBudgetEnabled!==t.sessionGoalDefaultBudgetEnabled&&t.setSessionGoalDefaultBudgetEnabled(e.sessionGoalDefaultBudgetEnabled),typeof e.sessionGoalDefaultBudget==`number`&&Number.isFinite(e.sessionGoalDefaultBudget)&&e.sessionGoalDefaultBudget!==t.sessionGoalDefaultBudget&&t.setSessionGoalDefaultBudget(e.sessionGoalDefaultBudget),typeof e.collapsibleThinkingBlocks==`boolean`&&e.collapsibleThinkingBlocks!==t.collapsibleThinkingBlocks&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks),typeof e.autoDeleteEnabled==`boolean`&&e.autoDeleteEnabled!==t.autoDeleteEnabled&&t.setAutoDeleteEnabled(e.autoDeleteEnabled),typeof e.autoDeleteAfterDays==`number`&&Number.isFinite(e.autoDeleteAfterDays)){let n=Math.max(1,Math.min(365,e.autoDeleteAfterDays));n!==t.autoDeleteAfterDays&&t.setAutoDeleteAfterDays(n)}(e.sessionRetentionAction===`archive`||e.sessionRetentionAction===`delete`)&&e.sessionRetentionAction!==t.sessionRetentionAction&&t.setSessionRetentionAction(e.sessionRetentionAction);let a=null;if(Zn(e.followUpBehavior)?a=e.followUpBehavior:typeof e.queueModeEnabled==`boolean`&&(a=Qn(void 0,e.queueModeEnabled)),a&&a!==i.followUpBehavior&&i.setFollowUpBehavior(a),typeof e.showDeletionDialog==`boolean`&&e.showDeletionDialog!==t.showDeletionDialog&&t.setShowDeletionDialog(e.showDeletionDialog),typeof e.nativeNotificationsEnabled==`boolean`&&e.nativeNotificationsEnabled!==t.nativeNotificationsEnabled&&t.setNativeNotificationsEnabled(e.nativeNotificationsEnabled),typeof e.notificationMode==`string`&&(e.notificationMode===`always`||e.notificationMode===`hidden-only`)&&e.notificationMode!==t.notificationMode&&t.setNotificationMode(e.notificationMode),typeof e.notifyOnSubtasks==`boolean`&&e.notifyOnSubtasks!==t.notifyOnSubtasks&&t.setNotifyOnSubtasks(e.notifyOnSubtasks),typeof e.notifyOnCompletion==`boolean`&&e.notifyOnCompletion!==t.notifyOnCompletion&&t.setNotifyOnCompletion(e.notifyOnCompletion),typeof e.notifyOnError==`boolean`&&e.notifyOnError!==t.notifyOnError&&t.setNotifyOnError(e.notifyOnError),typeof e.notifyOnQuestion==`boolean`&&e.notifyOnQuestion!==t.notifyOnQuestion&&t.setNotifyOnQuestion(e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates==`object`&&t.setNotificationTemplates(e.notificationTemplates),typeof e.summarizeLastMessage==`boolean`&&e.summarizeLastMessage!==t.summarizeLastMessage&&t.setSummarizeLastMessage(e.summarizeLastMessage),typeof e.summaryThreshold==`number`&&Number.isFinite(e.summaryThreshold)&&t.setSummaryThreshold(e.summaryThreshold),typeof e.summaryLength==`number`&&Number.isFinite(e.summaryLength)&&t.setSummaryLength(e.summaryLength),typeof e.maxLastMessageLength==`number`&&Number.isFinite(e.maxLastMessageLength)&&t.setMaxLastMessageLength(e.maxLastMessageLength),typeof e.inputSpellcheckEnabled==`boolean`&&e.inputSpellcheckEnabled!==t.inputSpellcheckEnabled&&t.setInputSpellcheckEnabled(e.inputSpellcheckEnabled),typeof e.showOpenCodeUpdateNotifications==`boolean`&&e.showOpenCodeUpdateNotifications!==t.showOpenCodeUpdateNotifications&&t.setShowOpenCodeUpdateNotifications(e.showOpenCodeUpdateNotifications),typeof e.showToolFileIcons==`boolean`&&e.showToolFileIcons!==t.showToolFileIcons&&t.setShowToolFileIcons(e.showToolFileIcons),typeof e.codeBlockLineWrap==`boolean`&&e.codeBlockLineWrap!==t.codeBlockLineWrap&&t.setCodeBlockLineWrap(e.codeBlockLineWrap),typeof e.showTurnChangedFiles==`boolean`&&e.showTurnChangedFiles!==t.showTurnChangedFiles&&t.setShowTurnChangedFiles(e.showTurnChangedFiles),typeof e.showExpandedBashTools==`boolean`&&e.showExpandedBashTools!==t.showExpandedBashTools&&t.setShowExpandedBashTools(e.showExpandedBashTools),typeof e.showSubagentTaskDetails==`boolean`&&e.showSubagentTaskDetails!==t.showSubagentTaskDetails&&t.setShowSubagentTaskDetails(e.showSubagentTaskDetails),typeof e.timeFormatPreference==`string`&&(e.timeFormatPreference===`auto`||e.timeFormatPreference===`12h`||e.timeFormatPreference===`24h`)&&e.timeFormatPreference!==t.timeFormatPreference&&t.setTimeFormatPreference(e.timeFormatPreference),typeof e.weekStartPreference==`string`&&(e.weekStartPreference===`auto`||e.weekStartPreference===`sunday`||e.weekStartPreference===`monday`)&&e.weekStartPreference!==t.weekStartPreference&&t.setWeekStartPreference(e.weekStartPreference),typeof e.desktopWindowControlsPosition==`string`&&(e.desktopWindowControlsPosition===`auto`||e.desktopWindowControlsPosition===`left`||e.desktopWindowControlsPosition===`right`)&&e.desktopWindowControlsPosition!==t.desktopWindowControlsPosition&&t.setDesktopWindowControlsPosition(e.desktopWindowControlsPosition),typeof e.chatRenderMode==`string`&&(e.chatRenderMode===`sorted`||e.chatRenderMode===`live`)&&e.chatRenderMode!==t.chatRenderMode&&t.setChatRenderMode(e.chatRenderMode),typeof e.activityRenderMode==`string`&&(e.activityRenderMode===`collapsed`||e.activityRenderMode===`summary`)&&e.activityRenderMode!==t.activityRenderMode&&t.setActivityRenderMode(e.activityRenderMode),typeof e.mermaidRenderingMode==`string`&&(e.mermaidRenderingMode===`svg`||e.mermaidRenderingMode===`ascii`)&&e.mermaidRenderingMode!==t.mermaidRenderingMode&&t.setMermaidRenderingMode(e.mermaidRenderingMode),typeof e.userMessageRenderingMode==`string`&&(e.userMessageRenderingMode===`markdown`||e.userMessageRenderingMode===`plain`)&&e.userMessageRenderingMode!==t.userMessageRenderingMode&&t.setUserMessageRenderingMode(e.userMessageRenderingMode),typeof e.collapsibleUserMessages==`boolean`&&e.collapsibleUserMessages!==t.collapsibleUserMessages&&t.setCollapsibleUserMessages(e.collapsibleUserMessages),typeof e.messageStreamTransport==`string`&&(e.messageStreamTransport===`auto`||e.messageStreamTransport===`ws`||e.messageStreamTransport===`sse`)&&n&&e.messageStreamTransport!==n.settingsMessageStreamTransport&&n.setSettingsMessageStreamTransport(e.messageStreamTransport),typeof e.stickyUserHeader==`boolean`&&e.stickyUserHeader!==t.stickyUserHeader&&t.setStickyUserHeader(e.stickyUserHeader),typeof e.promptNavigatorEnabled==`boolean`&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.expandedEditorToolbar==`boolean`&&e.expandedEditorToolbar!==t.expandedEditorToolbar&&t.setExpandedEditorToolbar(e.expandedEditorToolbar),typeof e.wideChatLayoutEnabled==`boolean`&&e.wideChatLayoutEnabled!==t.wideChatLayoutEnabled&&t.setWideChatLayoutEnabled(e.wideChatLayoutEnabled),typeof e.showSplitAssistantMessageActions==`boolean`&&e.showSplitAssistantMessageActions!==t.showSplitAssistantMessageActions&&t.setShowSplitAssistantMessageActions(e.showSplitAssistantMessageActions),typeof e.showAssistantTps==`boolean`&&e.showAssistantTps!==t.showAssistantTps&&t.setShowAssistantTps(e.showAssistantTps),typeof e.reportUsage==`boolean`&&e.reportUsage!==t.reportUsage&&t.setReportUsage(e.reportUsage),typeof e.fontSize==`number`&&Number.isFinite(e.fontSize)&&e.fontSize!==t.fontSize&&t.setFontSize(e.fontSize),Array.isArray(e.draftStarters)){let n=Kr(e.draftStarters);JSON.stringify(t.globalDraftStarters)!==JSON.stringify(n)&&t.setGlobalDraftStarters(n)}if(typeof e.terminalFontSize==`number`&&Number.isFinite(e.terminalFontSize)&&e.terminalFontSize!==t.terminalFontSize&&t.setTerminalFontSize(e.terminalFontSize),typeof e.editorFontSize==`number`&&Number.isFinite(e.editorFontSize)&&e.editorFontSize!==t.editorFontSize&&t.setEditorFontSize(e.editorFontSize),ae(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),re(e.monoFont)&&e.monoFont!==t.monoFont&&t.setMonoFont(e.monoFont),typeof e.padding==`number`&&Number.isFinite(e.padding)&&e.padding!==t.padding&&t.setPadding(e.padding),typeof e.cornerRadius==`number`&&Number.isFinite(e.cornerRadius)&&e.cornerRadius!==t.cornerRadius&&t.setCornerRadius(e.cornerRadius),typeof e.inputBarOffset==`number`&&Number.isFinite(e.inputBarOffset)&&e.inputBarOffset!==t.inputBarOffset&&t.setInputBarOffset(e.inputBarOffset),e.shortcutOverrides&&!ji(e.shortcutOverrides,t.shortcutOverrides)&&_.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode==`string`){let n=oe(e.mobileKeyboardMode,t.mobileKeyboardMode);n!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(n)}if(r&&n){let t={};typeof e.dictationEnabled==`boolean`&&e.dictationEnabled!==n.dictationEnabled&&(t.dictationEnabled=e.dictationEnabled),(e.sttProvider===`local`||e.sttProvider===`openai-compatible`)&&e.sttProvider!==n.sttProvider&&(t.sttProvider=e.sttProvider),typeof e.sttServerUrl==`string`&&e.sttServerUrl!==n.sttServerUrl&&(t.sttServerUrl=e.sttServerUrl),typeof e.sttModel==`string`&&e.sttModel!==n.sttModel&&(t.sttModel=e.sttModel),typeof e.sttLocalModel==`string`&&e.sttLocalModel!==n.sttLocalModel&&(t.sttLocalModel=e.sttLocalModel),typeof e.sttLanguage==`string`&&e.sttLanguage!==n.sttLanguage&&(t.sttLanguage=e.sttLanguage),Object.keys(t).length>0&&r.setState(t)}if(Array.isArray(e.favoriteModels)){let n=t.favoriteModels,r=Ni(n,e.favoriteModels);Mi(n,r)||_.setState({favoriteModels:r})}if(Array.isArray(e.hiddenModels)){let n=t.hiddenModels,r=e.hiddenModels;Mi(n,r)||_.setState({hiddenModels:r})}if(Array.isArray(e.collapsedModelProviders)){let n=t.collapsedModelProviders,r=e.collapsedModelProviders;Pi(n,r)||_.setState({collapsedModelProviders:r})}if(Array.isArray(e.recentModels)){let n=t.recentModels,r=Ni(n,e.recentModels);Mi(n,r)||_.setState({recentModels:r})}if(Array.isArray(e.recentAgents)){let n=t.recentAgents,r=e.recentAgents;Pi(n,r)||_.setState({recentAgents:r})}if(e.recentEfforts&&typeof e.recentEfforts==`object`){let n=t.recentEfforts,r=e.recentEfforts;Li(n,r)||_.setState({recentEfforts:r})}typeof e.diffLayoutPreference==`string`&&(e.diffLayoutPreference===`dynamic`||e.diffLayoutPreference===`inline`||e.diffLayoutPreference===`side-by-side`)&&e.diffLayoutPreference!==t.diffLayoutPreference&&t.setDiffLayoutPreference(e.diffLayoutPreference),typeof e.gitChangesViewMode==`string`&&(e.gitChangesViewMode===`flat`||e.gitChangesViewMode===`tree`)&&e.gitChangesViewMode!==t.gitChangesViewMode&&t.setGitChangesViewMode(e.gitChangesViewMode),typeof e.directoryShowHidden==`boolean`&&Tr(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored==`boolean`&&jr(e.filesViewShowGitignored,{persist:!1})},Ki=e=>{if(!e||typeof e!=`object`)return null;let t=e,n={};if(typeof t.themeId==`string`&&t.themeId.length>0&&(n.themeId=t.themeId),(t.useSystemTheme===!0||t.useSystemTheme===!1)&&(n.useSystemTheme=t.useSystemTheme),typeof t.themeVariant==`string`&&(t.themeVariant===`light`||t.themeVariant===`dark`)&&(n.themeVariant=t.themeVariant),typeof t.lightThemeId==`string`&&t.lightThemeId.length>0&&(n.lightThemeId=t.lightThemeId),typeof t.darkThemeId==`string`&&t.darkThemeId.length>0&&(n.darkThemeId=t.darkThemeId),typeof t.lastDirectory==`string`&&t.lastDirectory.length>0&&(n.lastDirectory=t.lastDirectory),typeof t.homeDirectory==`string`&&t.homeDirectory.length>0&&(n.homeDirectory=t.homeDirectory),typeof t.opencodeBinary==`string`){let e=t.opencodeBinary.trim();n.opencodeBinary=e.length>0?e:void 0}typeof t.desktopLanAccessEnabled==`boolean`&&(n.desktopLanAccessEnabled=t.desktopLanAccessEnabled),typeof t.desktopKeepAwakeEnabled==`boolean`&&(n.desktopKeepAwakeEnabled=t.desktopKeepAwakeEnabled),typeof t.desktopMinimizeToTrayEnabled==`boolean`&&(n.desktopMinimizeToTrayEnabled=t.desktopMinimizeToTrayEnabled);let r=Bi(t.projects);if(r&&(n.projects=r),typeof t.activeProjectId==`string`&&t.activeProjectId.length>0&&(n.activeProjectId=t.activeProjectId),Array.isArray(t.securityScopedBookmarks)&&(n.securityScopedBookmarks=t.securityScopedBookmarks.filter(e=>typeof e==`string`&&e.length>0)),Array.isArray(t.pinnedDirectories)&&(n.pinnedDirectories=Array.from(new Set(t.pinnedDirectories.filter(e=>typeof e==`string`&&e.length>0)))),Array.isArray(t.draftStarters)&&(n.draftStarters=Kr(t.draftStarters)),typeof t.draftStartersCraftGoalAdded==`boolean`&&(n.draftStartersCraftGoalAdded=t.draftStartersCraftGoalAdded),typeof t.showReasoningTraces==`boolean`&&(n.showReasoningTraces=t.showReasoningTraces),typeof t.sessionTitleRefreshEnabled==`boolean`&&(n.sessionTitleRefreshEnabled=t.sessionTitleRefreshEnabled),typeof t.sessionGoalEnabled==`boolean`&&(n.sessionGoalEnabled=t.sessionGoalEnabled),typeof t.sessionGoalDefaultBudgetEnabled==`boolean`&&(n.sessionGoalDefaultBudgetEnabled=t.sessionGoalDefaultBudgetEnabled),typeof t.sessionGoalDefaultBudget==`number`&&Number.isFinite(t.sessionGoalDefaultBudget)&&t.sessionGoalDefaultBudget>0&&(n.sessionGoalDefaultBudget=Math.floor(t.sessionGoalDefaultBudget)),typeof t.collapsibleThinkingBlocks==`boolean`&&(n.collapsibleThinkingBlocks=t.collapsibleThinkingBlocks),typeof t.autoDeleteEnabled==`boolean`&&(n.autoDeleteEnabled=t.autoDeleteEnabled),typeof t.autoDeleteAfterDays==`number`&&Number.isFinite(t.autoDeleteAfterDays)&&(n.autoDeleteAfterDays=t.autoDeleteAfterDays),(t.sessionRetentionAction===`archive`||t.sessionRetentionAction===`delete`)&&(n.sessionRetentionAction=t.sessionRetentionAction),typeof t.defaultModel==`string`&&t.defaultModel.length>0&&(n.defaultModel=t.defaultModel),typeof t.defaultVariant==`string`&&t.defaultVariant.length>0&&(n.defaultVariant=t.defaultVariant),typeof t.defaultAgent==`string`&&t.defaultAgent.length>0&&(n.defaultAgent=t.defaultAgent),typeof t.smallModelUseDefault==`boolean`&&(n.smallModelUseDefault=t.smallModelUseDefault),typeof t.smallModelOverride==`string`&&t.smallModelOverride.length>0&&(n.smallModelOverride=t.smallModelOverride),(t.summaryModelMode===`provider`||t.summaryModelMode===`custom`)&&(n.summaryModelMode=t.summaryModelMode),typeof t.summaryProviderID==`string`&&t.summaryProviderID.length>0&&(n.summaryProviderID=t.summaryProviderID),typeof t.summaryModelID==`string`&&t.summaryModelID.length>0&&(n.summaryModelID=t.summaryModelID),typeof t.summaryCustomBaseURL==`string`&&(n.summaryCustomBaseURL=t.summaryCustomBaseURL),typeof t.hasSummaryCustomAPIToken==`boolean`&&(n.hasSummaryCustomAPIToken=t.hasSummaryCustomAPIToken),typeof t.summaryCommitPrompt==`string`&&(n.summaryCommitPrompt=t.summaryCommitPrompt),typeof t.summarySessionTitlePrompt==`string`&&(n.summarySessionTitlePrompt=t.summarySessionTitlePrompt),typeof t.autoCreateWorktree==`boolean`&&(n.autoCreateWorktree=t.autoCreateWorktree),typeof t.gitmojiEnabled==`boolean`&&(n.gitmojiEnabled=t.gitmojiEnabled),Zn(t.followUpBehavior)?n.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled==`boolean`&&(n.followUpBehavior=Qn(void 0,t.queueModeEnabled)),typeof t.showDeletionDialog==`boolean`&&(n.showDeletionDialog=t.showDeletionDialog),typeof t.nativeNotificationsEnabled==`boolean`&&(n.nativeNotificationsEnabled=t.nativeNotificationsEnabled),typeof t.notificationMode==`string`&&(t.notificationMode===`always`||t.notificationMode===`hidden-only`)&&(n.notificationMode=t.notificationMode),typeof t.notifyOnSubtasks==`boolean`&&(n.notifyOnSubtasks=t.notifyOnSubtasks),typeof t.notifyOnCompletion==`boolean`&&(n.notifyOnCompletion=t.notifyOnCompletion),typeof t.notifyOnError==`boolean`&&(n.notifyOnError=t.notifyOnError),typeof t.notifyOnQuestion==`boolean`&&(n.notifyOnQuestion=t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates==`object`){let e=t.notificationTemplates,r=t=>{let n=e[t];if(!n||typeof n!=`object`)return;let r=n;return{title:typeof r.title==`string`?r.title:``,message:typeof r.message==`string`?r.message:``}},i=r(`completion`),a=r(`error`),o=r(`question`),s=r(`subtask`);(i||a||o||s)&&(n.notificationTemplates={completion:i??{title:`Task Complete`,message:`Your task has finished.`},error:a??{title:`Error Occurred`,message:`An error occurred while processing your task.`},question:o??{title:`Input Needed`,message:`Please provide input to continue.`},subtask:s??{title:`Subtask Complete`,message:`A subtask has finished.`}})}if(typeof t.summarizeLastMessage==`boolean`&&(n.summarizeLastMessage=t.summarizeLastMessage),typeof t.summaryThreshold==`number`&&Number.isFinite(t.summaryThreshold)&&(n.summaryThreshold=Math.max(0,Math.round(t.summaryThreshold))),typeof t.summaryLength==`number`&&Number.isFinite(t.summaryLength)&&(n.summaryLength=Math.max(10,Math.round(t.summaryLength))),typeof t.maxLastMessageLength==`number`&&Number.isFinite(t.maxLastMessageLength)&&(n.maxLastMessageLength=Math.max(10,Math.round(t.maxLastMessageLength))),typeof t.usageAutoRefresh==`boolean`&&(n.usageAutoRefresh=t.usageAutoRefresh),typeof t.usageRefreshIntervalMs==`number`&&Number.isFinite(t.usageRefreshIntervalMs)&&(n.usageRefreshIntervalMs=t.usageRefreshIntervalMs),(t.usageDisplayMode===`usage`||t.usageDisplayMode===`remaining`)&&(n.usageDisplayMode=t.usageDisplayMode),typeof t.usageShowPredValues==`boolean`&&(n.usageShowPredValues=t.usageShowPredValues),Array.isArray(t.usageDropdownProviders)&&(n.usageDropdownProviders=t.usageDropdownProviders.filter(e=>typeof e==`string`&&e.length>0)),t.usageSelectedModels&&typeof t.usageSelectedModels==`object`){let e={};for(let[n,r]of Object.entries(t.usageSelectedModels))Array.isArray(r)&&(e[n]=r.filter(e=>typeof e==`string`));Object.keys(e).length>0&&(n.usageSelectedModels=e)}if(t.usageCollapsedFamilies&&typeof t.usageCollapsedFamilies==`object`){let e={};for(let[n,r]of Object.entries(t.usageCollapsedFamilies))Array.isArray(r)&&(e[n]=r.filter(e=>typeof e==`string`));Object.keys(e).length>0&&(n.usageCollapsedFamilies=e)}if(t.usageExpandedFamilies&&typeof t.usageExpandedFamilies==`object`){let e={};for(let[n,r]of Object.entries(t.usageExpandedFamilies))Array.isArray(r)&&(e[n]=r.filter(e=>typeof e==`string`));Object.keys(e).length>0&&(n.usageExpandedFamilies=e)}if(t.usageModelGroups&&typeof t.usageModelGroups==`object`){let e={};for(let[n,r]of Object.entries(t.usageModelGroups))if(r&&typeof r==`object`){let t=r,i={};Array.isArray(t.customGroups)&&(i.customGroups=t.customGroups.filter(e=>e&&typeof e==`object`).map(e=>({id:String(e.id??``),label:String(e.label??``),models:Array.isArray(e.models)?e.models.filter(e=>typeof e==`string`):[],order:typeof e.order==`number`?e.order:0}))),t.modelAssignments&&typeof t.modelAssignments==`object`&&(i.modelAssignments=Object.fromEntries(Object.entries(t.modelAssignments).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,String(t)]))),t.renamedGroups&&typeof t.renamedGroups==`object`&&(i.renamedGroups=Object.fromEntries(Object.entries(t.renamedGroups).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,String(t)]))),Object.keys(i).length>0&&(e[n]=i)}Object.keys(e).length>0&&(n.usageModelGroups=e)}typeof t.inputSpellcheckEnabled==`boolean`&&(n.inputSpellcheckEnabled=t.inputSpellcheckEnabled),typeof t.showOpenCodeUpdateNotifications==`boolean`&&(n.showOpenCodeUpdateNotifications=t.showOpenCodeUpdateNotifications),typeof t.openCodeUpdateToastDismissedVersion==`string`&&(n.openCodeUpdateToastDismissedVersion=t.openCodeUpdateToastDismissedVersion.trim().slice(0,128)),typeof t.showToolFileIcons==`boolean`&&(n.showToolFileIcons=t.showToolFileIcons),typeof t.codeBlockLineWrap==`boolean`&&(n.codeBlockLineWrap=t.codeBlockLineWrap),typeof t.showTurnChangedFiles==`boolean`&&(n.showTurnChangedFiles=t.showTurnChangedFiles),typeof t.showExpandedBashTools==`boolean`&&(n.showExpandedBashTools=t.showExpandedBashTools),typeof t.showSubagentTaskDetails==`boolean`&&(n.showSubagentTaskDetails=t.showSubagentTaskDetails),typeof t.timeFormatPreference==`string`&&(t.timeFormatPreference===`auto`||t.timeFormatPreference===`12h`||t.timeFormatPreference===`24h`)&&(n.timeFormatPreference=t.timeFormatPreference),typeof t.weekStartPreference==`string`&&(t.weekStartPreference===`auto`||t.weekStartPreference===`sunday`||t.weekStartPreference===`monday`)&&(n.weekStartPreference=t.weekStartPreference),typeof t.desktopWindowControlsPosition==`string`&&(t.desktopWindowControlsPosition===`auto`||t.desktopWindowControlsPosition===`left`||t.desktopWindowControlsPosition===`right`)&&(n.desktopWindowControlsPosition=t.desktopWindowControlsPosition),typeof t.chatRenderMode==`string`&&(t.chatRenderMode===`sorted`||t.chatRenderMode===`live`)&&(n.chatRenderMode=t.chatRenderMode),typeof t.messageStreamTransport==`string`&&(t.messageStreamTransport===`auto`||t.messageStreamTransport===`ws`||t.messageStreamTransport===`sse`)&&(n.messageStreamTransport=t.messageStreamTransport),typeof t.activityRenderMode==`string`&&(t.activityRenderMode===`collapsed`||t.activityRenderMode===`summary`)&&(n.activityRenderMode=t.activityRenderMode),typeof t.mermaidRenderingMode==`string`&&(t.mermaidRenderingMode===`svg`||t.mermaidRenderingMode===`ascii`)&&(n.mermaidRenderingMode=t.mermaidRenderingMode),typeof t.userMessageRenderingMode==`string`&&(t.userMessageRenderingMode===`markdown`||t.userMessageRenderingMode===`plain`)&&(n.userMessageRenderingMode=t.userMessageRenderingMode),typeof t.collapsibleUserMessages==`boolean`&&(n.collapsibleUserMessages=t.collapsibleUserMessages),typeof t.stickyUserHeader==`boolean`&&(n.stickyUserHeader=t.stickyUserHeader),typeof t.promptNavigatorEnabled==`boolean`&&(n.promptNavigatorEnabled=t.promptNavigatorEnabled),typeof t.wideChatLayoutEnabled==`boolean`&&(n.wideChatLayoutEnabled=t.wideChatLayoutEnabled),typeof t.showSplitAssistantMessageActions==`boolean`&&(n.showSplitAssistantMessageActions=t.showSplitAssistantMessageActions),typeof t.showAssistantTps==`boolean`&&(n.showAssistantTps=t.showAssistantTps),typeof t.fontSize==`number`&&Number.isFinite(t.fontSize)&&(n.fontSize=t.fontSize),typeof t.terminalFontSize==`number`&&Number.isFinite(t.terminalFontSize)&&(n.terminalFontSize=t.terminalFontSize),typeof t.editorFontSize==`number`&&Number.isFinite(t.editorFontSize)&&(n.editorFontSize=t.editorFontSize),ae(t.uiFont)&&(n.uiFont=t.uiFont),re(t.monoFont)&&(n.monoFont=t.monoFont),typeof t.padding==`number`&&Number.isFinite(t.padding)&&(n.padding=t.padding),typeof t.cornerRadius==`number`&&Number.isFinite(t.cornerRadius)&&(n.cornerRadius=t.cornerRadius),typeof t.inputBarOffset==`number`&&Number.isFinite(t.inputBarOffset)&&(n.inputBarOffset=t.inputBarOffset);let i=Ai(t.shortcutOverrides);i&&(n.shortcutOverrides=i),typeof t.mobileKeyboardMode==`string`&&(t.mobileKeyboardMode===`native`||t.mobileKeyboardMode===`resize-content`)&&(n.mobileKeyboardMode=t.mobileKeyboardMode);let a=Vi(t.favoriteModels,64,{preserveVariant:!0});a&&(n.favoriteModels=a);let o=Vi(t.hiddenModels,1024);o&&(n.hiddenModels=o);let s=Fi(t.collapsedModelProviders);s&&(n.collapsedModelProviders=s);let c=Vi(t.recentModels,16,{preserveVariant:!0});c&&(n.recentModels=c);let l=Fi(t.recentAgents);l&&(n.recentAgents=l);let u=Ii(t.recentEfforts);if(u&&(n.recentEfforts=u),typeof t.diffLayoutPreference==`string`&&(t.diffLayoutPreference===`dynamic`||t.diffLayoutPreference===`inline`||t.diffLayoutPreference===`side-by-side`)&&(n.diffLayoutPreference=t.diffLayoutPreference),typeof t.gitChangesViewMode==`string`&&(t.gitChangesViewMode===`flat`||t.gitChangesViewMode===`tree`)&&(n.gitChangesViewMode=t.gitChangesViewMode),typeof t.directoryShowHidden==`boolean`&&(n.directoryShowHidden=t.directoryShowHidden),typeof t.filesViewShowGitignored==`boolean`&&(n.filesViewShowGitignored=t.filesViewShowGitignored),typeof t.openInAppId==`string`&&t.openInAppId.length>0&&(n.openInAppId=t.openInAppId),typeof t.pwaAppName==`string`){let e=t.pwaAppName.trim().replace(/\s+/g,` `).slice(0,64);n.pwaAppName=e.length>0?e:``}let d=ki(t.skillCatalogs);return d&&(n.skillCatalogs=d),typeof t.reportUsage==`boolean`&&(n.reportUsage=t.reportUsage),typeof t.globalBehaviorPrompt==`string`&&(n.globalBehaviorPrompt=t.globalBehaviorPrompt),typeof t.responseStyleEnabled==`boolean`&&(n.responseStyleEnabled=t.responseStyleEnabled),typeof t.responseStylePreset==`string`&&(t.responseStylePreset===`concise`||t.responseStylePreset===`detailed`||t.responseStylePreset===`mentor`||t.responseStylePreset===`pushback`||t.responseStylePreset===`noFiller`||t.responseStylePreset===`matchEnergy`||t.responseStylePreset===`warmPeer`||t.responseStylePreset===`custom`)&&(n.responseStylePreset=t.responseStylePreset),typeof t.responseStyleCustomInstructions==`string`&&(n.responseStyleCustomInstructions=t.responseStyleCustomInstructions),typeof t.dictationEnabled==`boolean`&&(n.dictationEnabled=t.dictationEnabled),t.sttProvider===`local`||t.sttProvider===`openai-compatible`?n.sttProvider=t.sttProvider:t.sttProvider===`server`?n.sttProvider=`openai-compatible`:(t.sttProvider===`browser`||t.sttProvider===`wasm`)&&(n.sttProvider=`local`),typeof t.sttServerUrl==`string`&&(n.sttServerUrl=t.sttServerUrl.trim()),typeof t.sttModel==`string`&&(n.sttModel=t.sttModel.trim()),typeof t.sttLocalModel==`string`&&(n.sttLocalModel=t.sttLocalModel.trim()),typeof t.sttLanguage==`string`&&(n.sttLanguage=t.sttLanguage.trim()),n},X=new Map,qi=new Map,Ji=2e3,Yi=async e=>{let t=X.get(e);if(t&&Date.now()-t.at<Ji)return t.value;let n=qi.get(e);if(n)return n;let r=(async()=>{if(s()!==e)return null;let t=Ui();if(t)try{let n=Ki((await t.load()).settings);return X.set(e,{value:n,at:Date.now()}),n}catch(e){console.warn(`Failed to load shared settings from runtime settings API:`,e)}if(s()!==e)return null;try{let t=await We(`/api/config/settings`,{method:`GET`,headers:{Accept:`application/json`}});if(!t.ok)return null;let n=Ki(await t.json().catch(()=>null));return X.set(e,{value:n,at:Date.now()}),n}catch(e){return console.warn(`Failed to load shared settings from server:`,e),null}})();qi.set(e,r);try{return await r}finally{qi.get(e)===r&&qi.delete(e)}},Xi=async()=>{if(typeof window>`u`)return;let e=s(),t=Hi(),n=()=>!t?.hasHydrated||t.hasHydrated()||!t.onFinishHydration?Promise.resolve():new Promise(e=>{let n=!1,r=()=>{n||(n=!0,e())},i=t.onFinishHydration(()=>{i?.(),r()});t.hasHydrated?.()&&r()}),r=async t=>{if(await n(),s()===e){try{Di(t)}catch(e){console.warn(`persistToLocalStorage failed:`,e)}try{Gi(t)}catch(e){console.warn(`applyDesktopUiPreferences failed:`,e)}Oi(t)}};try{let t=await Yi(e);t&&s()===e&&await r(t)}catch(e){console.warn(`Failed to synchronise settings:`,e)}},Z=null,Q=null,$=null,Zi=[],Qi=200,$i=async()=>{let e=Z,t=Q,n=Zi;if(Z=null,Q=null,$=null,Zi=[],!e||!t||Object.keys(e).length===0){n.forEach(e=>e());return}if(s()!==t){n.forEach(e=>e());return}let r=()=>s()===t,i=Ui();if(i){try{let a=await i.save(e);Wi(a,e,t),a&&r()&&(Di(a),Gi(a),Oi(a),X.set(t,{value:Ki(a),at:Date.now()})),n.forEach(e=>e());return}catch(e){console.warn(`Failed to update settings via runtime settings API:`,e)}if(!r()){n.forEach(e=>e());return}}try{let n=await We(`/api/config/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!n.ok){console.warn(`Failed to update shared settings via API:`,n.status,n.statusText);return}let i=await n.json().catch(()=>null);Wi(i,e,t),i&&r()&&(Di(i),Gi(i),Oi(i),X.set(t,{value:Ki(i),at:Date.now()}))}catch(e){console.warn(`Failed to update shared settings via API:`,e)}finally{n.forEach(e=>e())}},ea=async e=>{if(typeof window>`u`)return;let t=s();if(Q&&Q!==t){$&&=(clearTimeout($),null),Z=null,Q=null;let e=Zi;Zi=[],e.forEach(e=>e())}let n={...Z??{}},r=X.get(t)?.value;for(let[t,i]of Object.entries(e)){let e=r?.[t];Object.is(i,e)||i!==void 0&&e!==void 0&&JSON.stringify(i)===JSON.stringify(e)?delete n[t]:n[t]=i}if(Z=n,Q=t,Object.keys(n).length===0&&!$){Z=null,Q=null;return}$&&clearTimeout($);let i=new Promise(e=>{Zi.push(e)});return $=setTimeout(()=>void $i(),Qi),i},ta=async()=>{if(typeof window>`u`)return;let e=Hi();try{let t=await Ir();if(!t)return;let n=()=>Fr(t);if(e?.hasHydrated?.()){n();return}if(n(),e?.onFinishHydration){let t=e.onFinishHydration(()=>{t?.(),n()})}}catch(e){console.warn(`Failed to load appearance preferences:`,e)}};export{ln as $,sr as A,nt as At,Nn as B,Wr as C,lt as Ct,Mr as D,ct as Dt,jr as E,Pt as Et,vr as F,Ke as Ft,Fn as G,Wn as H,z as I,We as It,L as J,Rn as K,dr as L,Se as Lt,qn as M,tt as Mt,Kn as N,C as Nt,Tr as O,dt as Ot,fr as P,S as Pt,un as Q,_r as R,Gr as S,pt as St,Ur as T,xt as Tt,Gn as U,Un as V,zn as W,Tn as X,vn as Y,Dn as Z,Lr as _,ut as _t,Ti as a,Lt as at,Hr as b,gt as bt,yi as c,M as ct,hi as d,Bt as dt,sn as et,mi as f,qt as ft,K as g,Ft as gt,Zr as h,T as ht,Ci as i,It as it,er as j,$e as jt,Er as k,rt as kt,gi as l,Ut as lt,Yr as m,zt as mt,Xi as n,rn as nt,wi as o,j as ot,Qr as p,Rt as pt,Bn as q,ea as r,nn as rt,vi as s,Vt as st,ta as t,an as tt,q as u,Gt as ut,Vr as v,ht as vt,Kr as w,Dt as wt,zr as x,_t as xt,Br as y,mt as yt,jn as z};
|
|
@@ -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{D as t,N as n,c as r,f as i,i as a,j as o,n as s,r as c,s as l}from"./runtime-switch-BkpTTbEi.js";import{It as u,Mt as d,Pt as f,nt as p,ot as m,pt as h,r as g,st as _}from"./persistence-w-AiX2i4.js";import{V as ee,a as te,g as ne,y as v}from"./desktop-CfLlmafK.js";import{a as re,r as ie}from"./vendor-zustand-B4dlGEM2.js";import{t as ae}from"./vendor-opencode-sdk-C07HQypa.js";import{b as oe}from"./useUIStore-CNLmCoPU.js";import{i as se}from"./vendor-pathe-vBmvQE8f.js";import{o as ce}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";var le=(e,t)=>e!==t,ue=new Set([`image/heic`,`image/heif`]),de=!1,fe=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},pe=e=>ue.has((e.type||``).toLowerCase()),me=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)},he=(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})},ge=async e=>{if(!pe(e)||de)return null;let t=fe();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 me(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 he(t.data,r)}catch(e){return de=!0,console.warn(`Native HEIC transcode failed`,e),null}},_e=e=>e.trim().toLowerCase(),ve=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,ye=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(_e)),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=h(e.slice(t+1,a)).trim();n.has(_e(i))&&r.push({start:t,end:a+1})}i=a+1}return r},be=(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}},xe=(e,t,n,r)=>{let i=ye(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}=be(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}},Se=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),Ce={"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(),we=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Te=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>we(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},Ee=e=>Ce[e?.trim().toLowerCase()??``]??`png`,De=e=>{let t=Te(e.name),n=Ee(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}},Oe=e=>{let{base:t}=De({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(Se.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&Se.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},b=(e,t)=>`${e}.${t}`,ke=(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)},Ae=(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)},je=(e,t)=>{let n=new Set(t.map(y));return e.map(e=>{let{base:t,ext:r}=De(e),i=Oe(b(t,r))?Ae(r,n):ke(t,r,n);return n.add(y(i)),i})},Me=e=>e.map(e=>_(e)).join(` `),Ne=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[_(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},Pe=(e,t)=>{if(t.length>=e.length)return null;let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n+=1;let i=0;for(;i<e.length-n&&i<t.length-n&&e[e.length-1-i]===t[t.length-1-i];)i+=1;let a=e.length-i;return t.length-i!==n||a<=n?null:{start:n,end:a}},Fe=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=Pe(e,t);if(i){let t=Ke(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=Ne(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Ie=e=>e.replaceAll(`[${m}`,`[`),Le=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Re=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},ze=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Re(t)||!Le.test(t)&&!Le.test(r))continue;let i=`[${r}]`;n=n.split(_(t)).join(i).split(`[${t}]`).join(i)}return n},Be=(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(_(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Ve=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),He=`application/x-directory`,Ue=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,We=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Ge=(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}},Ke=(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?Ge(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=ye(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=>h(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://`,qe=e=>{let t=e.trim();if(t.toLowerCase().startsWith(S))return t;let n=se(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${S}/${n}`:`${S}${n}`},Je=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},Ye=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),Xe=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ze=async e=>{let t;try{t=await e.json()}catch{throw new x(e.status,`unavailable`)}if(!Xe(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:qe(t.path),mime:n,size:r,sha256:i}},Qe=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}`},$e=(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}},et=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),tt=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 Ye(n),i=Qe(e.filename),a;try{a=await u(`/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 Ze(a);if(o.size!==n.size)throw new x(a.status,`unavailable`);return{...o,mime:t}},nt=500,rt=()=>{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}},it=()=>rt(),C=(e,t)=>{if(!rt())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>nt&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-nt)};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 at=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}},ot=3,st=3e4,ct=32e3,lt=36e5,ut=6e5,dt=new Set([429,502,503,504]),w=new Map;function ft(){let e=Date.now();for(let[t,n]of w)n.consecutiveErrors===0&&e-n.lastErrorAt>lt&&w.delete(t)}typeof setInterval<`u`&&setInterval(ft,ut).unref?.();function pt(e){let t=w.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:st},w.set(e,t)),t}function mt(e){if(!e)return;let t=w.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function ht(e,t){if(!e)return;let n=pt(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),gt(t)&&n.consecutiveErrors>=ot&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function gt(e){return e!==void 0&&dt.has(e)}function _t(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,ct*4),!1):!0:!1}function vt(e){if(!(!e||!_t(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var yt=`/api`,bt=1e4,xt=4e3,St=3e3,Ct=1e3,wt=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 Tt=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Et=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(Tt.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}},Dt=()=>{try{return i().api(`/api`)}catch{return null}},Ot=()=>{try{return i().api(`/`)}catch{return null}},kt=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)}},At=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=>ae({...e,fetch:u}),jt=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),Mt=e=>{let t=[];for(let n of e){if(!jt(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=Je(r).trim();i&&t.push({filename:e,path:i})}return t},Nt=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=>ze(e,Mt([...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,`/`),Pt=400,Ft=()=>{let e=ee();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=yt){let t=Dt()||e;this.baseUrl=Et(t),this.client=O({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){let e=Et(Dt()||yt);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(d(`lastDirectory`)),t(d(`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=$e(t.url,t.mime);if(!n)return t;let r=await ge(n)??await(await ce(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(et(n)){let e=$e(n,t.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${t.filename??`file`}`);n=(await tt({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 Nt(e,e=>this.toNormalizedFilePartInput(e))}async sendMessage(e){let t=e.messageId??p(`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),vt(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 ht(e.providerID),t}if(i.ok)return mt(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,ht(e.providerID,i.status),s}async sendCommand(e){let t=e.messageId??p(`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:Et(Ot()||`/`)}).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 u(`/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()+bt}),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=kt(wt),r=At(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 u(`/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=c(),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 r=this.healthCacheGeneration,i=(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=kt(xt),i=await u(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 r!==this.healthCacheGeneration||e!==c()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?St:Ct)}),t)})();this.healthInFlight.set(e,i);try{return await i}finally{this.healthInFlight.get(e)===i&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=Ft();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 u(`${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 u(`${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=Ft();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()+Pt}),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 u(`${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()+Pt}),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=c();if(!e||e===`local`){let e=await te();if(e)return e}try{let e=await u(`${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 u(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}}},It=3e4,Lt=40,Rt=60,zt=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},Bt=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},Vt=re()(ie((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=Rt,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=zt(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<It)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>Lt;){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=>!Bt(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!Bt(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Ht=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`openchamber_stream_debug`)===`1`}catch{return!1}},Ut=`openchamber_stream_perf`,j=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(Ut)===`1`}catch{return!1}},Wt=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),Gt=()=>{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},Kt=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),qt=(e,t)=>{let n=Gt();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()},Jt=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(Ut,`1`),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(Ut),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Yt=()=>{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()}))},Xt=()=>{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:Kt(e.counters)}},Zt=()=>{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:Kt(e.counters)}},Qt=(e,t=1)=>{qt(e,t)},$t=(e,t)=>{qt(e,t)},en=(e,t)=>{if(!j())return t();let n=Wt();try{return t()}finally{qt(e,Wt()-n)}},M=null,tn=0,N=oe(),nn=d(`lastDirectory`,{storage:N}),rn=typeof nn==`string`&&nn.length>0,P=e=>{try{Vt.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},an=(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(an(e,t)),on=()=>{let e=d(`homeDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},sn=()=>{let e=d(`lastDirectory`,{storage:N});if(typeof e!=`string`||e.trim().length===0)return null;let t=F(e);return t.length>0?t:null},cn=()=>{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},ln=()=>{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,f(`homeDirectory`,e,{storage:N}),e;let t=on();if(t&&!v())return M=t,t}return cn()||`/`},un=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},dn=e=>(M=e,typeof window<`u`&&f(`homeDirectory`,e,{storage:N}),g({homeDirectory:e}),e),fn=async()=>{let e=e=>{let t=un(e);return t?dn(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 te());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=ln();return e(t)||t},L=(()=>{if(!v())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})()||ln(),R=(()=>{let e=sn();return e&&!v()?I(e,L):L})();R&&A.setDirectory(R);var pn=!!(L&&L!==`/`),z=re()(ie((e,t)=>({currentDirectory:R,directoryHistory:[R],historyIndex:0,homeDirectory:L,hasPersistedDirectory:rn,isHomeReady:pn,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=I(n,M||t().homeDirectory||d(`homeDirectory`,{storage:N}));Ht(),le(t().currentDirectory,i)&&(A.setDirectory(i),P(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return f(`lastDirectory`,i,{storage:N}),g({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(),f(`lastDirectory`,r,{storage:N}),g({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(),f(`lastDirectory`,r,{storage:N}),g({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||ln())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?M||ln():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=M||t().homeDirectory||await fn();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;M=i;let a=r.homeDirectory!==i,o=d(`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,p=r.directoryHistory.map(e=>I(e,i)),m=p.some((e,t)=>e!==r.directoryHistory[t]),h=!!(u&&u!==r.currentDirectory),_={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(_.currentDirectory=i,_.directoryHistory=[i],_.historyIndex=0,_.isSwitchingDirectory=!1):(h||m)&&(_.currentDirectory=u,_.directoryHistory=p,_.historyIndex=Math.min(r.historyIndex,p.length-1),_.isSwitchingDirectory=!1),e(()=>_),(c||h)&&l){let e=c?i:u;A.setDirectory(e),P(),f(`lastDirectory`,e,{storage:N}),g({lastDirectory:e})}g({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(fn().then(e=>{z.getState().synchronizeHomeDirectory(e)}),r(e=>{M=null;let t=++tn;if(l(e)){let e=on(),t=sn(),n=e||`/`,r=t||n;M=e,z.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(A.setDirectory(r),P())}fn().then(e=>{t===tn&&z.getState().synchronizeHomeDirectory(e)})}));var mn=(e,r)=>{let i=t();return i?i.openWebSocket(n(e),r):o(r?new WebSocket(e,r):new WebSocket(e))},B=`/api/git`,hn=1200,gn=5e3,_n=2,vn=5e3,yn=`${B}/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],V=new Map,H=new Map,En=new Map,U=new Map,W=new Map,G=new Map,K=new Map,Dn=new Map,q=new Map,On=new Map,kn=new Set,J=0,An=[],jn=()=>J<_n?(J+=1,Promise.resolve()):new Promise(e=>{An.push(e)}),Mn=()=>{let e=An.shift();if(e){e();return}J=Math.max(0,J-1)},Y=async e=>{await jn();try{return await e()}finally{Mn()}},Nn=Symbol.for(`openchamber.git.discoveryGated`),Pn=e=>(Object.defineProperty(e,Nn,{value:!0,configurable:!0}),e),Fn=e=>typeof e==`function`&&e[Nn]===!0,X=e=>e.trim(),In=(e,t)=>t===`light`?`${X(e)}::light`:X(e),Ln=e=>En.get(X(e))??0,Z=e=>{let t=X(e);En.set(t,Ln(e)+1);for(let e of Array.from(V.keys()))(e===t||e.startsWith(`${t}::`))&&V.delete(e);for(let e of Array.from(H.keys()))(e===t||e.startsWith(`${t}::`))&&H.delete(e)},Rn=e=>On.get(X(e))??0,Q=e=>{let t=X(e);t&&(On.set(t,Rn(e)+1),Dn.delete(t),q.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),i().api(e,r)}var zn=(e,t,n)=>{let r=X(e);if(!r)return;let i=Date.now()+vn;U.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;G.set(r,{value:{root:a},expiresAt:i})};async function Bn(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=U.get(e),i=G.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;zn(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([Vn(e),Un(e).then(e=>e.root).catch(()=>e)]);zn(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{zn(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Y(async()=>{let e=new URLSearchParams;for(let t of a)e.append(`directories`,t);let t=i().api(`${B}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await u(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 Vn(e){let t=X(e),n=Date.now(),r=U.get(t);if(r&&r.expiresAt>n)return r.value;let i=W.get(t);if(i)return i;let a=(async()=>{let n=await u($(`${B}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return U.set(t,{value:r,expiresAt:Date.now()+gn}),r})();W.set(t,a);try{return await a}finally{W.get(t)===a&&W.delete(t)}}async function Hn(e,t){let n=t?.mode,r=In(e,n),i=Date.now(),a=V.get(r);if(a&&a.expiresAt>i)return a.value;let o=H.get(r);if(o)return o;let s=(async()=>{let t=Ln(e),i=await u($(`${B}/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 Ln(e)===t&&V.set(r,{value:a,expiresAt:Date.now()+hn}),a})();H.set(r,s);try{return await s}finally{H.get(r)===s&&H.delete(r)}}async function Un(e){let t=X(e),n=Date.now(),r=G.get(t);if(r&&r.expiresAt>n)return r.value;let i=K.get(t);if(i)return i;let a=Y(async()=>{let n=await u($(`${B}/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 G.set(t,{value:i,expiresAt:Date.now()+vn}),i});K.set(t,a);try{return await a}finally{K.get(t)===a&&K.delete(t)}}async function Wn(e){let t=await u($(`${B}/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 Gn(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await u($(`${B}/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 Kn(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await u($(`${B}/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 qn(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await u($(`${B}/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 Jn(e,t){await Yn(e,[t])}async function Yn(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 u($(`${B}/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 Xn(e,t){await Zn(e,[t])}async function Zn(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 u($(`${B}/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 Qn(e,t,n){await tr(e,t,n,`stage`)}async function $n(e,t,n){await tr(e,t,n,`unstage`)}async function er(e,t,n){await tr(e,t,n,`discard`)}async function tr(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 u($(`${B}/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 nr(e){if(!e)return!1;let t=await u($(`${B}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function rr(e,t){let n=await u($(`${B}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function ir(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await u($(`${B}/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 ar(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await u($(`${B}/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 or(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await u($(`${B}/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 sr(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 u($(`${B}/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 cr(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 u($(`${B}/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 d=await l.json().catch(()=>null),f=typeof d?.title==`string`?d.title:``,p=typeof d?.body==`string`?d.body:``;if(!f&&!p)throw Error(`Malformed PR description response`);return{title:f,body:p}}async function lr(e){let t=X(e),n=Date.now(),r=Dn.get(t);if(r&&r.expiresAt>n)return r.value;let i=q.get(t);if(i)return i;let a=Rn(e),o=Y(async()=>{let n=await u($(`${B}/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===Rn(e)&&Dn.set(t,{value:r,expiresAt:Date.now()+vn}),r});q.set(t,o);try{return await o}finally{q.get(t)===o&&q.delete(t)}}Pn(lr);async function ur(e,t){let n=await u($(`${B}/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 dr(e){let t=await u($(`${B}/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 fr(e,t){let n=await u($(`${B}/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 pr=e=>typeof e==`string`&&e.length>0,mr=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!pr(t.name)||!pr(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},hr=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==bn)return null;let i=mr(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},gr=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,_r=e=>new Promise(t=>{setTimeout(t,e)}),vr=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},yr=e=>e===400||e===401||e===403||e===501,br=(e,t)=>{let n=a(),r=s(),i=gr(n,r,e,t);if(kn.has(i))return;kn.add(i);let o=()=>a()===n&&s()===r;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<wn;){if(!o())return;let i=Tn[Math.min(r,Tn.length-1)]??0;if(i>0){let e=wn-(Date.now()-n);if(e<=0||(await _r(Math.min(i,e)),!o()))return}let a=new AbortController,s=setTimeout(()=>a.abort(),Cn);try{let n=await u($(yn,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:a.signal});if(n.ok||yr(n.status))return;if(await vr(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(s)}}})().catch(()=>{}).finally(()=>{kn.delete(i)})};async function xr(e,t){let n=await u($(`${B}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=mr(r);if(t)return Q(e),t;if(r&&typeof r==`object`)return Q(e),r;throw Error(`Failed to create worktree`)}let i=hr(n.status,r,e);if(i)return Q(e),br(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function Sr(e,t){let n=await u($(`${B}/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 Cr(e,t,n={}){let r=await u($(`${B}/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 wr(e,t={}){let n=await u($(`${B}/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 Tr(e,t={}){let n=await u($(`${B}/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 Er(e,t={}){let n=await u($(`${B}/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 Dr(e){let t=await u($(`${B}/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 Or(e,t){let n=await u($(`${B}/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 kr(e,t={}){let n=await u($(`${B}/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 Ar=async(e,t,n)=>{let r=await u($(`${B}/${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()},jr=(e,t)=>Ar(e,`stash/apply`,t),Mr=(e,t)=>Ar(e,`stash/pop`,t),Nr=(e,t)=>Ar(e,`stash/drop`,t);async function Pr(e,t){let n=await u($(`${B}/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 Fr(e,t,n){let r=await u($(`${B}/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 Ir(e,t,n){let r=await u($(`${B}/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 Lr(e,t={}){let n=await u($(`${B}/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 Rr(e,t){let n=await u($(`${B}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function zr(e,t,n,r){let i=await u($(`${B}/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 Br(){let e=await u($(`${B}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Vr(e){let t=await u($(`${B}/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 Hr(e,t){let n=await u($(`${B}/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 Ur(e){let t=await u($(`${B}/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 Wr(e){if(!e)return null;let t=await u($(`${B}/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 Gr(e){if(!e)return!1;let t=await u($(`${B}/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 Kr(){let e=await u($(`${B}/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 qr(e,t){let n=await u($(`${B}/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 Jr(){let e=await u($(`${B}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Yr(e,t){let n=await u($(`${B}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function Xr(e,t){let n=await u($(`${B}/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 Zr(e){let t=await u($(`${B}/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 Qr(e,t){let n=await u($(`${B}/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 $r(e,t){let n=await u($(`${B}/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 ei(e,t){let n=await u($(`${B}/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 ti(e,t){let n=await u($(`${B}/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 ni(e,t,n,r){let i=await u($(`${B}/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 ri(e){let t=await u($(`${B}/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 ii(e){let t=await u($(`${B}/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 ai(e){let t=await u($(`${B}/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 oi(e,t){return await kr(e,{message:t?.message}),{success:!0}}async function si(e){return await Mr(e,{ref:`stash@{0}`}),{success:!0}}async function ci(e){let t=await u($(`${B}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function li(e,t){let n=await u(`${B}/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 ui(e){let t=await u(`${B}/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 di=()=>typeof window>`u`?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol===`capacitor:`,fi=()=>{if(typeof window>`u`||!di()||pi()!==`ios`)return!1;let e=navigator.userAgent||``,t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},pi=()=>{if(typeof window<`u`){let e=window.Capacitor?.getPlatform?.();if(e===`ios`||e===`android`)return e}return v()?`vscode`:ne()?`desktop`:`web`};export{Xr as $,ci as A,en as At,Yr as B,Ne as Bt,Jr as C,z as Ct,cr as D,Jt as Dt,sr as E,Yt as Et,Br as F,at as Ft,Q as G,Fe as Gt,Tr as H,Ve as Ht,Lr as I,it as It,Dr as J,ye as Jt,Fn as K,Ke as Kt,Hn as L,He as Lt,rr as M,Vt as Mt,Gn as N,A as Nt,zr as O,Ht as Ot,Kn as P,C as Pt,fr as Q,dr as R,je as Rt,ar as S,mn as St,Nr as T,Zt as Tt,wr as U,Ue as Ut,Er as V,Be as Vt,Gr as W,We as Wt,Qr as X,xe as Xt,lr as Y,ve as Yt,Mr as Z,Vr as _,$n as _t,Zr as a,ti as at,Ur as b,li as bt,Vn as c,qr as ct,ei as d,Qn as dt,or as et,ai as f,oi as ft,Cr as g,Zn as gt,Fr as h,Xn as ht,ri as i,Wn as it,Wr as j,$t as jt,Rr as k,Qt as kt,Pr as l,Jn as lt,Or as m,si as mt,di as n,ni as nt,jr as o,qn as ot,ii as p,kr as pt,nr as q,Ie as qt,fi as r,Un as rt,ui as s,er as st,pi as t,Ir as tt,$r as u,Yn as ut,xr as v,Hr as vt,Bn as w,Xt as wt,Sr as x,Y as xt,ir as y,ur as yt,Kr as z,Me as zt};
|