@openchambery/web 2.1.8-beta.7 → 2.1.8-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/assets/{AgentAvatar-qSjSZvIG.js → AgentAvatar-mchFM3n-.js} +1 -1
  2. package/dist/assets/AssistantView-BKUwYL67.js +3 -0
  3. package/dist/assets/{DiagramView-BzgI7Ugy.js → DiagramView-D_Ib5vBc.js} +1 -1
  4. package/dist/assets/{FadeInOnReveal-CD5d1k_u.js → FadeInOnReveal-BXDM9joC.js} +1 -1
  5. package/dist/assets/{Icon-QASb6r3F.js → Icon-BGp_ize2.js} +1 -1
  6. package/dist/assets/{ImageLoadingPlaceholder-BuGiEI7w.js → ImageLoadingPlaceholder-DmUxjyxq.js} +1 -1
  7. package/dist/assets/{LoadingImage-FRySi1BM.js → LoadingImage-DGjlKW_O.js} +1 -1
  8. package/dist/assets/{MarkdownRenderer-C7Rxb6Z8.js → MarkdownRenderer-Cfof1peT.js} +2 -2
  9. package/dist/assets/{MarkdownRendererImpl-DtHTDXL6.js → MarkdownRendererImpl-ChI65FCt.js} +2 -2
  10. package/dist/assets/{MarkstreamRendererImpl-H0RBa8Lc.js → MarkstreamRendererImpl-DVH-ftYX.js} +1 -1
  11. package/dist/assets/{MobileDetailNavigation-D-1rcvj_.js → MobileDetailNavigation-DSO5eFBk.js} +1 -1
  12. package/dist/assets/{MobileShareBridge-CDiwapde.js → MobileShareBridge-BeEyMgN3.js} +1 -1
  13. package/dist/assets/{MobileTabPageHeader-CJoiSp8u.js → MobileTabPageHeader-BnSDaiNY.js} +1 -1
  14. package/dist/assets/{MultiRunWindow-BzJkoXja.js → MultiRunWindow-BUMMBZVZ.js} +1 -1
  15. package/dist/assets/{OnboardingScreen-CHa767GT.js → OnboardingScreen-DmJgU0Jc.js} +1 -1
  16. package/dist/assets/{OverlayScrollbar-C7Ls30Hy.js → OverlayScrollbar-BkJCkZp3.js} +1 -1
  17. package/dist/assets/{SettingsView-CQUOFiau.js → SettingsView-O01tqMQO.js} +6 -6
  18. package/dist/assets/{SettingsWindow-pAUyRdBf.js → SettingsWindow-B23iyDA3.js} +1 -1
  19. package/dist/assets/{TerminalView-Cc54ph8a.js → TerminalView-DtakSdhD.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-CfVHQDPS.js → ToolOutputDialog-ClmLLL4n.js} +1 -1
  21. package/dist/assets/{appThemeRegistry-Dijsc1TR.js → appThemeRegistry-Bo8eOMlc.js} +1 -1
  22. package/dist/assets/{button-DOrwfkre.js → button-BKjGCkH3.js} +1 -1
  23. package/dist/assets/{collapsible-BJwPZMpo.js → collapsible-03FGLsF4.js} +1 -1
  24. package/dist/assets/{desktopHosts-DSBZ-9-L.js → desktopHosts-BZ7iYE-l.js} +1 -1
  25. package/dist/assets/{desktopRelayRestore-DK8TzHRx.js → desktopRelayRestore-S9wEiY2U.js} +1 -1
  26. package/dist/assets/{diagram-BFevUcKu.js → diagram-D4QHcaSQ.js} +1 -1
  27. package/dist/assets/{dialog-FSXwOR2i.js → dialog-nm_cQEUZ.js} +1 -1
  28. package/dist/assets/{dropdown-menu.styles-CfTQwJHe.js → dropdown-menu.styles-WkR8IcF2.js} +1 -1
  29. package/dist/assets/{es-VbQQdCdi.js → es-C9PRwAQm.js} +2 -2
  30. package/dist/assets/{fileMentionTouchSelection-DNtAG7n8.js → fileMentionTouchSelection-9tUq311z.js} +1 -1
  31. package/dist/assets/{fileQueries-BGE5l3Jd.js → fileQueries-DZR-mK8h.js} +1 -1
  32. package/dist/assets/{fr-BotRbS9t.js → fr-2tfGTcme.js} +2 -2
  33. package/dist/assets/{gitApi-CizY9AdM.js → gitApi-C2zxDfMk.js} +1 -1
  34. package/dist/assets/{image-loading-qNtUCy69.js → image-loading-CsxDGgek.js} +1 -1
  35. package/dist/assets/{input-Ctgb06ot.js → input-Buww8enN.js} +1 -1
  36. package/dist/assets/insertionBoundaries-DB9s3jca.js +1 -0
  37. package/dist/assets/{ja-l_gq6Coh.js → ja-D7NHmhJr.js} +2 -2
  38. package/dist/assets/{ko-yhU5rfe5.js → ko-DeGmXmv6.js} +2 -2
  39. package/dist/assets/main-0PxRleO0.js +169 -0
  40. package/dist/assets/{main-CRTSUx9O.js → main-BjL5V6ie.js} +2 -2
  41. package/dist/assets/{markdownHeightCache-B6drDnVO.js → markdownHeightCache-B6wZ-UwD.js} +1 -1
  42. package/dist/assets/{mcpQueries-CWF6gsQp.js → mcpQueries-CWB2bCOV.js} +1 -1
  43. package/dist/assets/{miniChat-Co2aZmGn.js → miniChat-CHCwBkzu.js} +2 -2
  44. package/dist/assets/{mobile-C-jsM-at.js → mobile-CG3SgbAO.js} +2 -2
  45. package/dist/assets/{multirun-BrG61uYF.js → multirun-47QshrE2.js} +1 -1
  46. package/dist/assets/{persistence-B7ORJ371.js → persistence-B4Ni3Gmv.js} +1 -1
  47. package/dist/assets/{pl-BkynZgOJ.js → pl-CyWLY1AT.js} +2 -2
  48. package/dist/assets/{platform-CiBU2bCp.js → platform-BQPsr8Zl.js} +1 -1
  49. package/dist/assets/{projectMeta-DeZn_2IB.js → projectMeta-_nxyshbo.js} +1 -1
  50. package/dist/assets/{pt-BR-Dw_Dokez.js → pt-BR-D9VVxvts.js} +2 -2
  51. package/dist/assets/{renderElectronMiniChatApp-94_7gkv4.js → renderElectronMiniChatApp-DHs8HXNl.js} +2 -2
  52. package/dist/assets/renderMobileApp-DYne1Jhg.js +28 -0
  53. package/dist/assets/{runtimeConfig-GWscdI1w.js → runtimeConfig-CRWwlAOU.js} +1 -1
  54. package/dist/assets/{runtimeEndpointReset-CQOgpDQQ.js → runtimeEndpointReset-B082-H3n.js} +15 -15
  55. package/dist/assets/{scheduledTaskNavigation-DEMPeoot.js → scheduledTaskNavigation-C-HGgCQA.js} +1 -1
  56. package/dist/assets/{sessionChangeSummary-CLeHgwn-.js → sessionChangeSummary-D_C2s2Fi.js} +1 -1
  57. package/dist/assets/{sessionLookup-BNyl-F_j.js → sessionLookup-CLMT7sx_.js} +1 -1
  58. package/dist/assets/{sortable-tabs-strip-BVnwfMAa.js → sortable-tabs-strip-cHZM0f0Z.js} +1 -1
  59. package/dist/assets/speechSettingsQueries-BPjR3N-x.js +4 -0
  60. package/dist/assets/{src-C9BNQK0O.css → src-OjoeiMbd.css} +1 -1
  61. package/dist/assets/{store-COtDAfPx.js → store-Ds-7Em7C.js} +2 -2
  62. package/dist/assets/{terminalApi-bN5IYQau.js → terminalApi-kRMttlcP.js} +1 -1
  63. package/dist/assets/{textarea-DJ52TDJj.js → textarea-BZHD_GND.js} +1 -1
  64. package/dist/assets/{tooltip-JgW0lJaV.js → tooltip-DCeWvAqN.js} +1 -1
  65. package/dist/assets/{uk-DSl09YqU.js → uk-Df44svOl.js} +2 -2
  66. package/dist/assets/{url-nbXEti6c.js → url-Bd61gNgl.js} +1 -1
  67. package/dist/assets/{useAppFontEffects-DrhKfpyE.js → useAppFontEffects-AQXif_Vl.js} +26 -26
  68. package/dist/assets/{useDesktopWindowControlsLayout-CqByoGOq.js → useDesktopWindowControlsLayout-CDYvCUVb.js} +1 -1
  69. package/dist/assets/{useEffectiveDirectory-C562rMTt.js → useEffectiveDirectory-CJCTgfPc.js} +1 -1
  70. package/dist/assets/{useFontPreferences-6LD7d7hP.js → useFontPreferences-lAw0Cbza.js} +1 -1
  71. package/dist/assets/useMobileNavigationStore-Buez5E56.js +417 -0
  72. package/dist/assets/{useWorkerHighlightedLines-B1wPAG8-.js → useWorkerHighlightedLines-DFkH7EUL.js} +1 -1
  73. package/dist/assets/{zh-CN-NtO1bA00.js → zh-CN-wowfzo60.js} +2 -2
  74. package/dist/assets/{zh-TW-CF0z_L0k.js → zh-TW-DwojcgA_.js} +2 -2
  75. package/dist/index.html +8 -8
  76. package/dist/mini-chat.html +8 -8
  77. package/dist/mobile.html +8 -8
  78. package/package.json +1 -1
  79. package/server/lib/opencode/feature-routes-runtime.js +1 -0
  80. package/server/lib/session-folders/DOCUMENTATION.md +20 -0
  81. package/server/lib/session-folders/order-routes.js +69 -0
  82. package/server/lib/session-folders/routes.js +3 -0
  83. package/server/lib/session-folders/routes.test.js +49 -0
  84. package/dist/assets/AssistantView-BYVyU99L.js +0 -3
  85. package/dist/assets/insertionBoundaries-DiezF3t9.js +0 -1
  86. package/dist/assets/main-Bq9n4CsP.js +0 -169
  87. package/dist/assets/renderMobileApp-C7Ab_Jn1.js +0 -28
  88. package/dist/assets/speechSettingsQueries-BNqvjxZr.js +0 -4
  89. package/dist/assets/useMobileNavigationStore-CYheYCC_.js +0 -417
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{w as t}from"./runtime-auth-C8w0nlKy.js";import{c as n,i as r,n as i,o as a,r as o,t as s}from"./runtime-switch-3ad3yzM7.js";import{n as c}from"./runtime-fetch-QCWYlAx0.js";import{a as l,i as u,r as d}from"./vendor-zustand-o69pgTEK.js";import{it as f}from"./vendor-base-ui-CdzJ6My_.js";import{C as p,a as m,b as ee,i as te,m as h,n as g,p as ne,x as _}from"./useUIStore-CDMI_Yzu.js";import{n as re}from"./vendor-react-BP2cRVqX.js";import{i as ie}from"./vendor-pathe-vBmvQE8f.js";import{t as ae}from"./vendor-tanstack-query-core-BWz0ose6.js";var oe=[`local`,`remote`,null],se=[`ok`,`not-configured`,`unreachable`,`incompatible`,`wrong-service`,`missing`];function ce(e){if(!e||typeof e!=`object`)return{valid:!1};let t=e,n=t.target,r=t.status;if(n!==null&&(typeof n!=`string`||!oe.includes(n))||typeof r!=`string`||!se.includes(r))return{valid:!1};if(n===`remote`||n===`local`){if(r===`ok`&&n===`local`)return{valid:!0,outcome:{target:`local`,status:`ok`}};if(r===`ok`&&n===`remote`)return typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`ok`,hostId:t.hostId,url:t.url}};if(r===`unreachable`)return n===`local`?{valid:!0,outcome:{target:`local`,status:`unreachable`}}:typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`unreachable`,hostId:t.hostId,url:t.url}};if(r===`incompatible`||r===`wrong-service`)return n!==`remote`||typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:r,hostId:t.hostId,url:t.url}};if(r===`missing`)return n!==`remote`||typeof t.hostId!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`missing`,hostId:t.hostId}}}if(n===null){if(r===`not-configured`)return{valid:!0,outcome:{target:null,status:`not-configured`}};if(r===`missing`)return{valid:!1}}return{valid:!1}}function le(e){if(!e.isDesktopShell)return null;let t=e.bootOutcome;if(!t)return null;if(t.status===`ok`){if(t.target===`local`)return{screen:`main`};if(t.target===`remote`)return{screen:`main`,hostId:t.hostId,url:t.url}}if(t.target===null&&t.status===`not-configured`)return{screen:`chooser`};if(t.target===`local`&&t.status===`unreachable`)return{screen:`recovery`,variant:`local-unavailable`};if(t.target===`remote`){if(t.status===`unreachable`)return{screen:`recovery`,variant:`remote-unreachable`,hostId:t.hostId,url:t.url};if(t.status===`incompatible`)return{screen:`recovery`,variant:`remote-incompatible`,hostId:t.hostId,url:t.url};if(t.status===`wrong-service`)return{screen:`recovery`,variant:`remote-wrong-service`,hostId:t.hostId,url:t.url};if(t.status===`missing`)return{screen:`recovery`,variant:`remote-missing`,hostId:t.hostId}}return null}function ue(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1||e.isInitialized:!1:e.isInitialized}function de(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function fe(){if(me()!==`valid`)return null;let e=ce(pe());return e.valid?e.outcome:null}var pe=()=>{if(typeof window>`u`)return;let e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;if(e!=null)return e;let t=window.__OPENCHAMBER_DESKTOP_BOOT__;if(t&&typeof t.getOutcome==`function`)try{return t.getOutcome()}catch{return}return e};function me(){if(typeof window>`u`)return`not-injected`;let e=pe();return e==null?`not-injected`:ce(e).valid?`valid`:`malformed`}var he=null,ge=e=>{he=e},_e=()=>he||(typeof window>`u`?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),ve=()=>typeof window>`u`?null:window.__OPENCHAMBER_ELECTRON__??null,v=()=>typeof window>`u`?null:window.__OPENCHAMBER_DESKTOP__??null,y=()=>ve()?.runtime===`electron`,ye=()=>y()&&ve()?.packaged===!0,be=e=>{if(!y())return null;let t=v()?.getPathForFile?.(e);return typeof t==`string`&&t.trim()?t:null},xe=()=>{if(typeof window>`u`)return null;let e=window.__OPENCHAMBER_PLATFORM__;return typeof e==`string`?e:null},Se=()=>{if(!y())return!1;let e=xe();return e===`win32`||e===`linux`},Ce=(e=xe())=>e===`linux`?`left`:`right`,we=(e,t=xe())=>e===`left`||e===`right`?e:Ce(t),b=()=>typeof v()?.invoke==`function`,x=()=>y()&&b(),S=async(e,t)=>{let n=v();return typeof n?.invoke==`function`?n.invoke(e,t??{}):null},Te=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_launch_at_login`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get launch at login status`,e),null}},Ee=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_launch_at_login`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set launch at login status`,e),null}},De=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_minimize_to_tray`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get minimize to tray status`,e),null}},Oe=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_minimize_to_tray`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set minimize to tray status`,e),null}},ke=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_keep_awake`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`||typeof e.active!=`boolean`?null:e}catch(e){return console.warn(`Failed to get keep awake status`,e),null}},Ae=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_keep_awake`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`||typeof t.active!=`boolean`?null:t}catch(e){return console.warn(`Failed to set keep awake status`,e),null}},je=e=>{let t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`).origin}catch{return null}}},Me=e=>{let t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`)}catch{return null}}},Ne=e=>e.replace(/^\[|\]$/g,``).toLowerCase(),Pe=e=>{let t=Ne(e);return t===`localhost`||t===`127.0.0.1`||t===`::1`},C=()=>{if(typeof window>`u`||!Fe()||t())return!1;let e=o();if(e.startsWith(`host:`))return!1;if(e===`local`)return!0;let n=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__==`string`?window.__OPENCHAMBER_LOCAL_ORIGIN__:``,r=Me(n),i=Me(s());if(!i&&r&&fe()?.target===`local`)return!0;if(r&&i){if(r.origin===i.origin)return!0;let e=r.port||(r.protocol===`https:`?`443`:`80`),t=i.port||(i.protocol===`https:`?`443`:`80`);return r.protocol===i.protocol&&e===t&&Pe(r.hostname)&&Pe(i.hostname)}let a=Me(window.location.origin);if(r&&a){if(r.origin===a.origin)return!0;let e=r.port||(r.protocol===`https:`?`443`:`80`),t=a.port||(a.protocol===`https:`?`443`:`80`);return r.protocol===a.protocol&&e===t&&Pe(r.hostname)&&Pe(a.hostname)}let c=je(n),l=je(window.location.origin)||window.location.origin;return c&&l&&c===l?!0:!!(a&&Pe(a.hostname))},Fe=()=>typeof window>`u`?!1:y(),Ie=async()=>{if(!Fe())return!1;try{return await S(`desktop_start_window_drag`),!0}catch{return!1}},Le=()=>_e()?.runtime?.isVSCode===!0,Re=()=>{let e=_e()?.runtime?.platform;return e===`web`?!0:e===`desktop`||e===`vscode`?!1:!Le()},ze=async()=>{if(typeof window<`u`){let e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},Be=async e=>{if(b()&&C())try{let e=await v()?.openDialog?.({directory:!0,multiple:!1,title:`Select Working Directory`});return!e||typeof e!=`string`?{success:!1,error:`Directory selection cancelled`}:{success:!0,path:e}}catch(e){return console.warn(`Failed to request directory access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:e}},Ve=e=>typeof e==`object`&&!!e&&!Array.isArray(e),He=async e=>{if(b()&&C())try{let t=await v()?.openDialog?.({directory:!1,multiple:!1,title:`Select File`,returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:`File selection cancelled`};if(typeof t==`string`)return{success:!0,path:t};if(!Ve(t))return{success:!1,error:`File selection cancelled`};let n=typeof t.path==`string`?t.path:``;return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant==`string`?t.outsideFileGrant:void 0}:{success:!1,error:`File selection cancelled`}}catch(e){return console.warn(`Failed to request file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:`Native file picker not available`}},Ue=async e=>{let t=typeof e==`string`?e.trim():``;if(!t)return{success:!1,error:`Path is required`};if(!b()||!C())return{success:!1,error:`Native file access not available`};try{let e=await v()?.grantFileAccess?.(t);if(!Ve(e))return{success:!1,error:`File access was not granted`};let n=typeof e.path==`string`?e.path:``,r=typeof e.outsideFileGrant==`string`?e.outsideFileGrant:``;return!n||!r?{success:!1,error:`File access was not granted`}:{success:!0,path:n,outsideFileGrant:r}}catch(e){return console.warn(`Failed to request existing file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}},We=async e=>({success:!0}),Ge=async e=>({success:!0}),Ke=async e=>{if(!b())throw Error(`Desktop update checker is unavailable`);let t=await S(`desktop_check_for_updates`,{channelOverride:e});if(!t)throw Error(`Desktop update checker returned no result`);return t},qe=async e=>{b()&&await S(`desktop_ota_ready`,{version:e})},Je=()=>S(`desktop_get_app_version`),Ye=async e=>{let t=v();return typeof t?.listen==`function`?t.listen(`openchamber:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({event:typeof r.event==`string`?r.event:void 0,data:r.data&&typeof r.data==`object`?r.data:void 0})}):null},Xe=async e=>{let t=v();return typeof t?.listen==`function`?t.listen(`openchamber:update-ready`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({version:typeof r.version==`string`?r.version:null,downloaded:r.downloaded===!0})}):null},Ze=async e=>{if(!b())return!1;let t=v(),n=null,r=0,i;try{return typeof e==`function`&&t?.listen&&(n=await t.listen(`openchamber:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let a=n,o=typeof a.event==`string`?a.event:null,s=a.data&&typeof a.data==`object`?a.data:null;if(o===`Started`){r=0,i=typeof s?.contentLength==`number`?s.contentLength:void 0,e({downloaded:r,total:i});return}if(o===`Progress`){let t=s?.downloaded,n=s?.total;typeof t==`number`&&(r=t),typeof n==`number`&&(i=n),e({downloaded:r,total:i});return}o===`Finished`&&e({downloaded:r,total:i})})),await S(`desktop_download_and_install_update`),!0}catch(e){throw e instanceof Error?e:Error(String(e))}finally{if(n)try{let e=n();e instanceof Promise&&await e}catch{}}},Qe=async()=>b()?$e({applyUpdate:!0}):!1,$e=async({applyUpdate:e=!1}={})=>{if(!b())return!1;try{return await S(`desktop_restart`,e?{applyUpdate:!0}:void 0),!0}catch(e){return console.warn(`Failed to restart desktop app`,e),!1}},et=async()=>{if(!b()||!C())return null;try{let e=await S(`desktop_get_lan_address`);return typeof e==`string`&&e.trim().length>0?e.trim():null}catch(e){return console.warn(`Failed to get desktop LAN address`,e),null}},tt=async(e,t)=>{if(!b()||!C())return!1;let n=e?.trim();if(!n)return!1;try{return await S(`desktop_open_path`,{path:n,app:typeof t==`string`&&t.trim().length>0?t.trim():void 0}),!0}catch(e){return console.warn(`Failed to open path`,e),!1}},nt=async e=>{if(!b()||!C())return null;let t=e?.trim();if(!t)return null;try{let e=await S(`desktop_is_binary_path`,{path:t});return typeof e==`boolean`?e:null}catch{return null}},rt=async e=>{if(!b()||!C())return!1;let t=e?.trim();if(!t)return!1;try{return await S(`desktop_reveal_path`,{path:t}),!0}catch{return tt(t)}},it=async(e,t)=>{if(!b()||!C())return null;let n=e?.trim();if(!n)return null;try{let e=await S(`desktop_save_markdown_file`,{defaultFileName:n,content:t});return typeof e==`string`&&e.trim().length>0?e:null}catch(e){return console.warn(`Failed to save markdown file`,e),null}},at=async(e,t,n)=>{if(!b()||!C())return!1;let r=e?.trim(),i=t?.trim(),a=n?.trim();if(!r||!i||!a)return!1;try{return await S(`desktop_open_in_app`,{projectPath:r,appId:i,appName:a}),!0}catch(e){return console.warn(`Failed to open project in app`,e),!1}},ot=async(e,t,n)=>{if(!b()||!C())return!1;let r=e?.trim(),i=t?.trim(),a=n?.trim();if(!r||!i||!a)return!1;try{return await S(`desktop_open_file_in_app`,{filePath:r,appId:i,appName:a}),!0}catch(e){return console.warn(`Failed to open file in app`,e),!1}},st=async(e,t)=>{if(!b()||!C())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};if(xe()===`linux`)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};let n=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{let e=await S(`desktop_get_installed_apps`,{apps:n,force:t===!0||void 0});if(!e||typeof e!=`object`)return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};let r=e;return r.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(r.apps)?{apps:r.apps.filter(e=>e&&typeof e==`object`).map(e=>{let t=e;return{name:typeof t.name==`string`?t.name:``,iconDataUrl:typeof t.iconDataUrl==`string`?t.iconDataUrl:null}}).filter(e=>e.name.length>0),success:!0,hasCache:r.hasCache===!0,isCacheStale:r.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(e){return console.warn(`Failed to fetch installed apps`,e),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},ct=`oc.inst.`,lt=e=>{try{return btoa(unescape(encodeURIComponent(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}catch{return encodeURIComponent(e)}},ut=e=>{let t=(e??o()).trim();return t.length>0?t:`default`},dt=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim().replace(/\/+$/,``):``},w=(e,t=o())=>`${ct}${lt(ut(t))}.${e}`,ft=(e=o())=>ut(e).startsWith(`relay:`),pt=(e=o())=>{let t=ut(e);if(t==="default"||t===`local`)return!0;if(ft(t)||!t.startsWith(`url:`))return!1;let n=dt();if(!n)return!1;try{return new URL(t.slice(4)).origin===new URL(n).origin}catch{return!1}},mt=(e=o())=>!ft(e),ht=(e,t=s())=>{let n=t.trim().replace(/\/+$/,``);return n?`${e}:${encodeURIComponent(n)}`:null},gt=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{getItem:()=>null}),r=t?.runtimeKey??o(),i=n.getItem(w(e,r));if(i!==null)return i;if(mt(r)){let t=ht(e),r=t?n.getItem(t):null;if(r!==null)return r}return pt(r)?n.getItem(e):null},T=(e,t,n)=>{let r=n?.storage??(typeof localStorage<`u`?localStorage:{setItem:()=>void 0}),i=n?.runtimeKey??o();r.setItem(w(e,i),t)},_t=e=>({getItem:t=>gt(t,{storage:e}),setItem:(t,n)=>{T(t,n,{storage:e})},removeItem:t=>{E(t,{storage:e})}}),E=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{removeItem:()=>void 0}),r=t?.runtimeKey??o();n.removeItem(w(e,r))},vt=e=>{let t;try{t=p()}catch{return}let n=t=>t===null?null:JSON.parse(t,e?.reviver),r=e=>t.getItem(e);return{getItem:e=>{let t=o(),i=w(e,t),a=r(i);if(a instanceof Promise)return a.then(i=>{if(i!==null)return n(i);if(!pt(t))return null;let a=r(e);return a instanceof Promise?a.then(n):n(a)});if(a!==null)return n(a);if(!pt(t))return null;let s=r(e);return s instanceof Promise?s.then(n):n(s)},setItem:(n,r)=>{let i=w(n,o());t.setItem(i,JSON.stringify(r,e?.replacer))},removeItem:e=>{let n=w(e,o());t.removeItem(n)}}},yt=(e=bt)=>{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}}},bt=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},xt=yt(),St=e=>xt.countUnicodeCodePoints(e),D=(e,t)=>{if(!e)throw Error(`${t} must be non-empty`);return e},Ct=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`session`,ownerID:D(t,`sessionID`)}}),wt=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`draft`,ownerID:D(t,`draftID`)}}),Tt=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`},Et=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`surface`,ownerID:D(t,`surfaceID`)}}),Dt=8192,Ot=e=>{if(typeof e!=`string`||e.length===0||e.length>Dt)return!1;try{let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`file:`}catch{return!1}},kt=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID]),At=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID,e.attachmentOccurrenceRefID]),jt=e=>JSON.stringify([`root`,e]),Mt=(e,t)=>JSON.stringify([`part`,e,t]),Nt={mentionCount:1e3,valueLength:8192,pathLength:8192,labelLength:512},O={referenceCount:1e3,idLength:512,displayLength:514,sessionIDLength:128,skillNameLength:511,commandNameLength:511,commandReferenceLength:8192,pastePayloadLength:1e5,totalPastePayloadLength:2e5},k=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},A=(e,t)=>Object.keys(e).every(e=>t.includes(e)),j=e=>typeof e==`string`&&e.length>0,Pt=e=>typeof e==`string`,M=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,N=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ft=(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)},It=(e,t)=>{if(!Array.isArray(t)||t.length>Nt.mentionCount)return;let n=[],r=new Set,i=0;for(let a of t){if(!k(a)||!A(a,[`kind`,`value`,`path`,`label`,`range`])||a.kind!==`file`&&a.kind!==`directory`&&a.kind!==`agent`||!N(a.value,Nt.valueLength)||!N(a.path,Nt.pathLength)||!N(a.label,Nt.labelLength)||!k(a.range)||!A(a.range,[`start`,`end`])||!M(a.range.start)||!M(a.range.end)||a.range.end<=a.range.start||a.range.end>e.length||a.range.start<i||!Ft(e,a.range.start)||!Ft(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},Lt=e=>N(e,O.sessionIDLength)&&/^[A-Za-z0-9_-]+$/.test(e),Rt=/^[^\s/\\[\]\r\n]+$/u,zt=()=>/\[skill:([^\s/\\\]\r\n]+)\]/gu,Bt=e=>N(e,O.skillNameLength)&&Rt.test(e),Vt=e=>N(e,O.commandNameLength)&&/^[\p{L}\p{N}._/-]+$/u.test(e),Ht=e=>N(e,O.commandReferenceLength)&&!/[\]\r\n]/u.test(e),Ut=e=>{if(!(!k(e)||!N(e.id,O.idLength)||!N(e.display,O.displayLength)||!M(e.start)||!M(e.end)||e.end<=e.start)){if(e.kind===`session`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`sessionId`])&&Lt(e.sessionId))return{id:e.id,kind:`session`,start:e.start,end:e.end,display:e.display,sessionId:e.sessionId};if(e.kind===`paste`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`text`,`characterCount`,`index`])&&typeof e.text==`string`&&e.text.length<=O.pastePayloadLength&&M(e.characterCount)&&e.characterCount===St(e.text)&&M(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`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`skillName`])&&Bt(e.skillName)&&(e.display===`/${e.skillName}`||e.display===`/ ${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`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`commandName`,`reference`])&&Vt(e.commandName)&&Ht(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}}},Wt=(e,t)=>{if(!Array.isArray(t)||t.length>O.referenceCount)return;let n=t.map(Ut);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>O.totalPastePayloadLength)))return;return{text:e,references:r}},Gt=(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)&&!k(e)||t.has(e))return!1;t.add(e);let n=Object.values(e).every(e=>Gt(e,t));return t.delete(e),n},Kt=e=>{if(!(!k(e)||!A(e,[`kind`,`ownerID`])||!j(e.ownerID))&&(e.kind===`session`||e.kind===`draft`||e.kind===`surface`))return{kind:e.kind,ownerID:e.ownerID}},qt=e=>{if(!k(e)||!A(e,[`transportIdentity`,`owner`])||!j(e.transportIdentity))return;let t=Kt(e.owner);return t?{transportIdentity:e.transportIdentity,owner:t}:void 0},Jt=e=>{if(!(!k(e)||!j(e.kind))){if(e.kind===`blob`&&A(e,[`kind`,`blobID`])&&j(e.blobID))return{kind:`blob`,blobID:e.blobID};if(!(e.kind!==`url`||!A(e,[`kind`,`url`])||!Ot(e.url)))return{kind:`url`,url:e.url}}},Yt=(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}},Xt=(e,t)=>{if(!k(e)||!A(e,[`attachmentID`,`attachmentRefID`,`filename`,`mimeType`,`size`,`locator`,`source`,`serverPath`,`vscodePath`,`vscodeSource`])||!j(e.attachmentID)||!j(e.attachmentRefID)||!Yt(e.attachmentRefID,e.attachmentID,t)||!j(e.filename)||!Pt(e.mimeType)||!M(e.size)||e.source!==`local`&&e.source!==`vscode`&&e.source!==`server`||e.serverPath!==void 0&&!j(e.serverPath)||e.vscodePath!==void 0&&!j(e.vscodePath)||e.vscodeSource!==void 0&&e.vscodeSource!==`file`&&e.vscodeSource!==`selection`||e.source===`server`&&!j(e.serverPath)||e.source===`vscode`&&(!j(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}}},Zt=e=>{if(!Gt(e,new Set)||!k(e)||!A(e,[`version`,`key`,`revision`,`text`,`attachments`,`syntheticParts`,`mentions`,`composerReferences`])||e.version!==1||!M(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=qt(e.key),r=e.attachments.map(e=>Xt(e)),i=e.syntheticParts.map(e=>{if(!k(e)||!A(e,[`partID`,`text`,`attachments`,`synthetic`])||!j(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=>Xt(e,t));return r.every(Boolean)?{partID:t,text:n,attachments:r,...e.synthetic===void 0?{}:{synthetic:e.synthetic}}:void 0}),a=It(t,e.mentions),o=e.composerReferences===void 0?{text:t,references:[]}:Wt(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}}},Qt=e=>Zt(e),P=` `,$t=`0.2em`,en=`size-[1em]`,tn=e=>e.startsWith(P)?e.slice(P.length):e,nn=e=>e.replaceAll(`/${P}`,`/`).replaceAll(`@${P}`,`@`).replaceAll(`[${P}`,`[`),rn=e=>{let t=e.match(/^\s*/)?.[0].length??0,n=e.slice(t);if(!n.startsWith(`/`))return null;let r=1;n.startsWith(P,r)&&(r+=P.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},an=e=>F({trigger:`[`,icon:`file-image`,label:e,suffix:`]`}),on=({trigger:e,label:t,suffix:n=``})=>`${e}${t}${n}`,F=e=>`${e.trigger}${P}${e.label}${e.suffix??``}`,sn=e=>on(e),cn=(e,t)=>e===sn(t)||e===F(t),ln=(e,t)=>{let n=t===F(e);return{trigger:n?`${e.trigger}${P}`:e.trigger,icon:e.icon,align:e.align??`end`,label:e.label,suffix:e.suffix,slot:n?`reserved`:`compact`}},un=(e,t,n=``)=>{let r=e.startsWith(t)?e.slice(t.length):e,i=r.startsWith(P)?r.slice(P.length):r;return n&&i.endsWith(n)?i.slice(0,-n.length):i},dn=(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,fn=0n,pn=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,mn=14;function hn(e){let t=``;for(let n=0;n<e;n++)t+=pn[Math.floor(Math.random()*62)];return t}var gn=/^[0-9a-f]{12}$/,_n=/^[0-9A-Za-z]{14}$/,vn=(1n<<48n)-1n,yn=(e,t)=>{if(typeof t!=`string`||!t.startsWith(`${e}_`))return;let n=t.slice(e.length+1),r=n.slice(0,12);if(!(!gn.test(r)||!_n.test(n.slice(12))))return BigInt(`0x${r}`)},bn=(e,t)=>{let n=BigInt(Date.now())*4096n&vn,r=yn(e,t)??0n,i=[n,fn,r].reduce((e,t)=>e>t?e:t);if(i>=vn)throw Error(`Ascending ID space exhausted`);let a=i+1n;fn=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}${hn(mn)}`},xn=e=>bn(e),Sn=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,`_`)}`},Cn=()=>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},wn=(e=Cn())=>{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(``)}`},Tn=e=>/^[\\/]+$/.test(e),En=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;if(Tn(t))return t.length===1?`/`:null;let n=ie(t);return n===`/`?`/`:(n.length>1?n.replace(/\/+$/,``):n)||null},Dn=e=>{if(typeof e!=`string`)return``;let t=e.trim();return t?En(t)??t:``},I={...O,sessionIdLength:O.sessionIDLength,visibleTextLength:1e5,canonicalOutputLength:2e5},On=e=>typeof e==`string`&&Lt(e),kn=e=>e.replaceAll(`\\`,`/`).split(`/`).at(-1)?.replace(/\.md$/,``)??``,An=e=>({trigger:`@`,icon:`chat-thread`,label:e}),jn=(e,t)=>({trigger:`/`,icon:t,label:e}),Mn=(e,t)=>({trigger:t,icon:`book-open`,label:e}),Nn=(e,t)=>[`/`,`@`].some(n=>cn(e,Mn(t,n))),Pn=(e,t)=>cn(e,Mn(t,`@`))?Mn(t,`@`):Mn(t,`/`),Fn={session:{kind:`session`,validatePayload:e=>On(e.sessionId),contributeCanonical:e=>({text:`@session:${e.sessionId}`,semantic:{type:`session`,sessionId:e.sessionId}}),contributeDirectSend:e=>({text:sn(An(un(e.display,`@`))),semantic:{type:`session`,sessionId:e.sessionId}}),decorate:e=>({style:`mentionSession`,visual:ln(An(un(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))?F(An(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<=I.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=>Bt(e.skillName)&&typeof e.display==`string`&&Nn(e.display,e.skillName),contributeCanonical:e=>({text:`[skill:${e.skillName}]`}),contributeDirectSend:e=>({text:`[skill:${e.skillName}]`}),decorate:e=>({style:`mentionCommand`,skillName:e.skillName,visual:ln(Pn(e.display,e.skillName),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:zt(),resolveDisplay:e=>F(Mn(e[1],`@`)),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=>Vt(e.commandName)&&Ht(e.reference)&&typeof e.display==`string`&&cn(e.display,jn(e.commandName,`command`)),contributeCanonical:e=>({text:`[command:${e.reference}]`}),contributeDirectSend:e=>({text:`[command:${e.reference}]`}),decorate:e=>({style:`mentionCommand`,visual:ln(jn(e.commandName,`command`),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:/\[command:([^\]\r\n]+)\]/g,resolveDisplay:e=>{let t=kn(e[1]);return Ht(e[1])&&Vt(t)?F(jn(t,`command`)):null},materialize:(e,t,n)=>({id:`command:${n}`,kind:`command`,commandName:kn(e[1]),reference:e[1],display:t,start:n,end:n+t.length})}}},L=e=>Fn[e],In=(e,t)=>L(e).validatePayload(t),Ln=e=>L(e.kind).contributeCanonical(e),Rn=e=>L(e.kind).contributeDirectSend(e),zn=e=>L(e.kind).decorate(e),Bn=e=>L(e.kind).payloadBudget(e),Vn=e=>L(e.kind).describeResourceIdentity?.(e),Hn=Object.keys(Fn),Un=e=>typeof e==`string`&&Hn.includes(e),Wn=()=>Hn.flatMap(e=>{let t=L(e).canonical;return t?[t]:[]}),Gn=e=>{if(e.type===`attachment`)return`attachment:${e.attachmentRefID}`},Kn=e=>{let t=new Map;for(let n of e.references){let e=Vn(n);e&&t.set(Gn(e),e)}return[...t.values()]},qn=(e,t)=>{let n=new Map(e.map(e=>[Gn(e),e])),r=new Map(t.map(e=>[Gn(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])}},Jn=(e,t)=>qn(Kn(e),Kn(t)),Yn=(e,t=`queue-canonical`)=>{if(e.references.length>I.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=Bn(t);i+=n?.category===`opaque-text`?n.length:0}if(i>I.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`?Rn(r):Ln(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>I.canonicalOutputLength?{ok:!1,reason:`canonical-output-too-large`}:{ok:!0,plan:{chunks:a,semantics:o},text:c}},R=(e,t)=>Math.max(0,Math.min(e,t)),Xn=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Zn=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return!Xn(t.id,I.displayLength)||!Xn(t.display,I.displayLength)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||typeof t.kind!=`string`?!1:Un(t.kind)&&In(t.kind,t)},z=(e,t)=>{let n=[],r=0,i=[],a=Math.min(t.length,I.referenceCount);for(let e=0;e<a;e+=1){let a=t[e];if(!Zn(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=Bn(t);if(l+=i?.category===`opaque-text`?i.length:0,l>O.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>I.referenceCount,payloadBudgetExceeded:u}},B=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(!Xn(o.id,I.idLength)||!Xn(o.display,I.displayLength)||!Un(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=Bn(o),s=t?.category===`opaque-text`?t.length:0;a+s>O.totalPastePayloadLength||(r.add(o.id),i=o.end,a+=s,n.push(o))}return{text:e.text,references:n}},Qn=(e,t)=>{if(t.length>O.pastePayloadLength)return!1;let n=z(e.text,e.references);return n.budgetExceeded||n.payloadBudgetExceeded?!1:n.document.references.reduce((e,t)=>{let n=Bn(t);return e+(n?.category===`opaque-text`?n.length:0)},0)+t.length<=O.totalPastePayloadLength},$n=(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 er(e,t,n,r,i={}){let a=B(e);if(!In(r.kind,r))return{document:a,caret:R(n,a.text.length),edit:{oldStart:t,oldEnd:n,newEnd:n}};let o=R(t,a.text.length),s=Math.max(o,R(n,a.text.length)),c=$n(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)?` `:``,ee=`${l}${p}${r.display}${m}${u}`,te={...r,start:c.start+p.length,end:c.start+p.length+r.display.length},h=p.length+r.display.length+m.length-(c.end-c.start);return{document:B({text:ee,references:[...a.references.filter(e=>e.end<=c.start||e.start>=c.end).map(e=>e.start>=c.end?{...e,start:e.start+h,end:e.end+h}:e),te]}),caret:te.end,edit:{oldStart:c.start,oldEnd:c.end,newEnd:c.start+p.length+r.display.length+m.length}}}var tr=(e,t)=>e<=t.oldStart?e:e>=t.oldEnd?e+t.newEnd-t.oldEnd:t.newEnd,nr=(e,t,n=t.length,r=n)=>{let i=B(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=$n(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},ee=m.newEnd-m.oldEnd,te=i.references.filter(e=>e.end<=l.start||e.start>=l.end).map(e=>e.start>=l.end?{...e,start:e.start+ee,end:e.end+ee}:e),h=(e,n)=>{let r=R(e,t.length),i=c.newEnd+l.end-c.oldEnd;return R(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)},g=h(n,`start`),ne=Math.max(g,h(r,`end`)),_=B({text:p,references:te});return{document:_,edit:m,requiresTextCorrection:u,selectionStart:g,selectionEnd:ne,caret:ne,mapCaret:e=>R(tr(e,m),_.text.length),removedReferences:d}},rr=(e,t,n)=>{let r=$n(n,e,t);return r.start===e&&r.end===t?null:r},ir=(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}},ar=(e,t)=>{let n=B(e),r=R(t.selectionStart,n.text.length),i=Math.max(r,R(t.selectionEnd,n.text.length)),a=r===i?t.altKey?ir(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=rr(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:B({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}},or=(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}},sr=(e,t=`queue-canonical`)=>{let n=z(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=Yn(n.document,t);return r.ok?{ok:!0,text:r.text,chunks:r.plan.chunks,semantics:r.plan.semantics}:r},cr=(e,t)=>e.match.index-t.match.index||e.adapterOrder-t.adapterOrder||e.matchOrder-t.matchOrder,lr=e=>{if(e.length>I.canonicalOutputLength||e.length>I.visibleTextLength)return null;let t=[],n=0;for(let[r,i]of Wn().entries()){i.matcher.lastIndex=0;let a,o=0;for(;(a=i.matcher.exec(e))!==null;){if(n+=1,n>I.referenceCount)return null;let e={codec:i,match:a,adapterOrder:r,matchOrder:o};o+=1;let s=t.findIndex(t=>cr(e,t)<0);s===-1?t.push(e):t.splice(s,0,e)}}return t},ur=(e,t)=>{let n=z(e.text,e.references).document,r=lr(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>I.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>I.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 z(o,[...f,...a]).document},dr=(e,t)=>ur({text:e,references:[]},t),fr=(e,t)=>dr(e,t),pr=(e,t,n=`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{w as t}from"./runtime-auth-C8w0nlKy.js";import{c as n,i as r,n as i,o as a,r as o,t as s}from"./runtime-switch-3ad3yzM7.js";import{n as c}from"./runtime-fetch-QCWYlAx0.js";import{a as l,i as u,r as d}from"./vendor-zustand-o69pgTEK.js";import{it as f}from"./vendor-base-ui-CdzJ6My_.js";import{C as p,a as m,b as ee,i as te,m as h,n as g,p as ne,x as _}from"./useUIStore-CDMI_Yzu.js";import{n as re}from"./vendor-react-BP2cRVqX.js";import{i as ie}from"./vendor-pathe-vBmvQE8f.js";import{t as ae}from"./vendor-tanstack-query-core-BWz0ose6.js";var oe=[`local`,`remote`,null],se=[`ok`,`not-configured`,`unreachable`,`incompatible`,`wrong-service`,`missing`];function ce(e){if(!e||typeof e!=`object`)return{valid:!1};let t=e,n=t.target,r=t.status;if(n!==null&&(typeof n!=`string`||!oe.includes(n))||typeof r!=`string`||!se.includes(r))return{valid:!1};if(n===`remote`||n===`local`){if(r===`ok`&&n===`local`)return{valid:!0,outcome:{target:`local`,status:`ok`}};if(r===`ok`&&n===`remote`)return typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`ok`,hostId:t.hostId,url:t.url}};if(r===`unreachable`)return n===`local`?{valid:!0,outcome:{target:`local`,status:`unreachable`}}:typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`unreachable`,hostId:t.hostId,url:t.url}};if(r===`incompatible`||r===`wrong-service`)return n!==`remote`||typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:r,hostId:t.hostId,url:t.url}};if(r===`missing`)return n!==`remote`||typeof t.hostId!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`missing`,hostId:t.hostId}}}if(n===null){if(r===`not-configured`)return{valid:!0,outcome:{target:null,status:`not-configured`}};if(r===`missing`)return{valid:!1}}return{valid:!1}}function le(e){if(!e.isDesktopShell)return null;let t=e.bootOutcome;if(!t)return null;if(t.status===`ok`){if(t.target===`local`)return{screen:`main`};if(t.target===`remote`)return{screen:`main`,hostId:t.hostId,url:t.url}}if(t.target===null&&t.status===`not-configured`)return{screen:`chooser`};if(t.target===`local`&&t.status===`unreachable`)return{screen:`recovery`,variant:`local-unavailable`};if(t.target===`remote`){if(t.status===`unreachable`)return{screen:`recovery`,variant:`remote-unreachable`,hostId:t.hostId,url:t.url};if(t.status===`incompatible`)return{screen:`recovery`,variant:`remote-incompatible`,hostId:t.hostId,url:t.url};if(t.status===`wrong-service`)return{screen:`recovery`,variant:`remote-wrong-service`,hostId:t.hostId,url:t.url};if(t.status===`missing`)return{screen:`recovery`,variant:`remote-missing`,hostId:t.hostId}}return null}function ue(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1||e.isInitialized:!1:e.isInitialized}function de(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function fe(){if(me()!==`valid`)return null;let e=ce(pe());return e.valid?e.outcome:null}var pe=()=>{if(typeof window>`u`)return;let e=window.__OPENCHAMBER_DESKTOP_BOOT_OUTCOME__;if(e!=null)return e;let t=window.__OPENCHAMBER_DESKTOP_BOOT__;if(t&&typeof t.getOutcome==`function`)try{return t.getOutcome()}catch{return}return e};function me(){if(typeof window>`u`)return`not-injected`;let e=pe();return e==null?`not-injected`:ce(e).valid?`valid`:`malformed`}var he=null,ge=e=>{he=e},_e=()=>he||(typeof window>`u`?null:window.__OPENCHAMBER_RUNTIME_APIS__??null),ve=()=>typeof window>`u`?null:window.__OPENCHAMBER_ELECTRON__??null,v=()=>typeof window>`u`?null:window.__OPENCHAMBER_DESKTOP__??null,y=()=>ve()?.runtime===`electron`,ye=()=>y()&&ve()?.packaged===!0,be=e=>{if(!y())return null;let t=v()?.getPathForFile?.(e);return typeof t==`string`&&t.trim()?t:null},xe=()=>{if(typeof window>`u`)return null;let e=window.__OPENCHAMBER_PLATFORM__;return typeof e==`string`?e:null},Se=()=>{if(!y())return!1;let e=xe();return e===`win32`||e===`linux`},Ce=(e=xe())=>e===`linux`?`left`:`right`,we=(e,t=xe())=>e===`left`||e===`right`?e:Ce(t),b=()=>typeof v()?.invoke==`function`,x=()=>y()&&b(),S=async(e,t)=>{let n=v();return typeof n?.invoke==`function`?n.invoke(e,t??{}):null},Te=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_launch_at_login`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get launch at login status`,e),null}},Ee=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_launch_at_login`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set launch at login status`,e),null}},De=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_minimize_to_tray`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get minimize to tray status`,e),null}},Oe=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_minimize_to_tray`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set minimize to tray status`,e),null}},ke=async()=>{if(!x()||!C())return null;try{let e=await S(`desktop_get_keep_awake`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`||typeof e.active!=`boolean`?null:e}catch(e){return console.warn(`Failed to get keep awake status`,e),null}},Ae=async e=>{if(!x()||!C())return null;try{let t=await S(`desktop_set_keep_awake`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`||typeof t.active!=`boolean`?null:t}catch(e){return console.warn(`Failed to set keep awake status`,e),null}},je=e=>{let t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`).origin}catch{return null}}},Me=e=>{let t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`)}catch{return null}}},Ne=e=>e.replace(/^\[|\]$/g,``).toLowerCase(),Pe=e=>{let t=Ne(e);return t===`localhost`||t===`127.0.0.1`||t===`::1`},C=()=>{if(typeof window>`u`||!Fe()||t())return!1;let e=o();if(e.startsWith(`host:`))return!1;if(e===`local`)return!0;let n=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__==`string`?window.__OPENCHAMBER_LOCAL_ORIGIN__:``,r=Me(n),i=Me(s());if(!i&&r&&fe()?.target===`local`)return!0;if(r&&i){if(r.origin===i.origin)return!0;let e=r.port||(r.protocol===`https:`?`443`:`80`),t=i.port||(i.protocol===`https:`?`443`:`80`);return r.protocol===i.protocol&&e===t&&Pe(r.hostname)&&Pe(i.hostname)}let a=Me(window.location.origin);if(r&&a){if(r.origin===a.origin)return!0;let e=r.port||(r.protocol===`https:`?`443`:`80`),t=a.port||(a.protocol===`https:`?`443`:`80`);return r.protocol===a.protocol&&e===t&&Pe(r.hostname)&&Pe(a.hostname)}let c=je(n),l=je(window.location.origin)||window.location.origin;return c&&l&&c===l?!0:!!(a&&Pe(a.hostname))},Fe=()=>typeof window>`u`?!1:y(),Ie=async()=>{if(!Fe())return!1;try{return await S(`desktop_start_window_drag`),!0}catch{return!1}},Le=()=>_e()?.runtime?.isVSCode===!0,Re=()=>{let e=_e()?.runtime?.platform;return e===`web`?!0:e===`desktop`||e===`vscode`?!1:!Le()},ze=async()=>{if(typeof window<`u`){let e=window.__OPENCHAMBER_HOME__;if(e&&e.length>0)return e}return null},Be=async e=>{if(b()&&C())try{let e=await v()?.openDialog?.({directory:!0,multiple:!1,title:`Select Working Directory`});return!e||typeof e!=`string`?{success:!1,error:`Directory selection cancelled`}:{success:!0,path:e}}catch(e){return console.warn(`Failed to request directory access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:e}},Ve=e=>typeof e==`object`&&!!e&&!Array.isArray(e),He=async e=>{if(b()&&C())try{let t=await v()?.openDialog?.({directory:!1,multiple:!1,title:`Select File`,returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:`File selection cancelled`};if(typeof t==`string`)return{success:!0,path:t};if(!Ve(t))return{success:!1,error:`File selection cancelled`};let n=typeof t.path==`string`?t.path:``;return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant==`string`?t.outsideFileGrant:void 0}:{success:!1,error:`File selection cancelled`}}catch(e){return console.warn(`Failed to request file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:`Native file picker not available`}},Ue=async e=>{let t=typeof e==`string`?e.trim():``;if(!t)return{success:!1,error:`Path is required`};if(!b()||!C())return{success:!1,error:`Native file access not available`};try{let e=await v()?.grantFileAccess?.(t);if(!Ve(e))return{success:!1,error:`File access was not granted`};let n=typeof e.path==`string`?e.path:``,r=typeof e.outsideFileGrant==`string`?e.outsideFileGrant:``;return!n||!r?{success:!1,error:`File access was not granted`}:{success:!0,path:n,outsideFileGrant:r}}catch(e){return console.warn(`Failed to request existing file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}},We=async e=>({success:!0}),Ge=async e=>({success:!0}),Ke=async e=>{if(!b())throw Error(`Desktop update checker is unavailable`);let t=await S(`desktop_check_for_updates`,{channelOverride:e});if(!t)throw Error(`Desktop update checker returned no result`);return t},qe=async e=>{b()&&await S(`desktop_ota_ready`,{version:e})},Je=()=>S(`desktop_get_app_version`),Ye=async e=>{let t=v();return typeof t?.listen==`function`?t.listen(`openchamber:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({event:typeof r.event==`string`?r.event:void 0,data:r.data&&typeof r.data==`object`?r.data:void 0})}):null},Xe=async e=>{let t=v();return typeof t?.listen==`function`?t.listen(`openchamber:update-ready`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({version:typeof r.version==`string`?r.version:null,downloaded:r.downloaded===!0})}):null},Ze=async e=>{if(!b())return!1;let t=v(),n=null,r=0,i;try{return typeof e==`function`&&t?.listen&&(n=await t.listen(`openchamber:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let a=n,o=typeof a.event==`string`?a.event:null,s=a.data&&typeof a.data==`object`?a.data:null;if(o===`Started`){r=0,i=typeof s?.contentLength==`number`?s.contentLength:void 0,e({downloaded:r,total:i});return}if(o===`Progress`){let t=s?.downloaded,n=s?.total;typeof t==`number`&&(r=t),typeof n==`number`&&(i=n),e({downloaded:r,total:i});return}o===`Finished`&&e({downloaded:r,total:i})})),await S(`desktop_download_and_install_update`),!0}catch(e){throw e instanceof Error?e:Error(String(e))}finally{if(n)try{let e=n();e instanceof Promise&&await e}catch{}}},Qe=async()=>b()?$e({applyUpdate:!0}):!1,$e=async({applyUpdate:e=!1}={})=>{if(!b())return!1;try{return await S(`desktop_restart`,e?{applyUpdate:!0}:void 0),!0}catch(e){return console.warn(`Failed to restart desktop app`,e),!1}},et=async()=>{if(!b()||!C())return null;try{let e=await S(`desktop_get_lan_address`);return typeof e==`string`&&e.trim().length>0?e.trim():null}catch(e){return console.warn(`Failed to get desktop LAN address`,e),null}},tt=async(e,t)=>{if(!b()||!C())return!1;let n=e?.trim();if(!n)return!1;try{return await S(`desktop_open_path`,{path:n,app:typeof t==`string`&&t.trim().length>0?t.trim():void 0}),!0}catch(e){return console.warn(`Failed to open path`,e),!1}},nt=async e=>{if(!b()||!C())return null;let t=e?.trim();if(!t)return null;try{let e=await S(`desktop_is_binary_path`,{path:t});return typeof e==`boolean`?e:null}catch{return null}},rt=async e=>{if(!b()||!C())return!1;let t=e?.trim();if(!t)return!1;try{return await S(`desktop_reveal_path`,{path:t}),!0}catch{return tt(t)}},it=async(e,t)=>{if(!b()||!C())return null;let n=e?.trim();if(!n)return null;try{let e=await S(`desktop_save_markdown_file`,{defaultFileName:n,content:t});return typeof e==`string`&&e.trim().length>0?e:null}catch(e){return console.warn(`Failed to save markdown file`,e),null}},at=async(e,t,n,r)=>{if(!b()||!r&&!C())return!1;if(r)return o()===`host:${r}`&&(await S(`desktop_open_ssh_in_app`,{projectPath:e,appId:t,hostId:r}),!0);let i=e?.trim(),a=t?.trim(),s=n?.trim();if(!i||!a||!s)return!1;try{return await S(`desktop_open_in_app`,{projectPath:i,appId:a,appName:s}),!0}catch(e){return console.warn(`Failed to open project in app`,e),!1}},ot=async(e,t,n)=>{if(!b()||!C())return!1;let r=e?.trim(),i=t?.trim(),a=n?.trim();if(!r||!i||!a)return!1;try{return await S(`desktop_open_file_in_app`,{filePath:r,appId:i,appName:a}),!0}catch(e){return console.warn(`Failed to open file in app`,e),!1}},st=async(e,t)=>{if(!b())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};if(xe()===`linux`)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};let n=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{let e=await S(`desktop_get_installed_apps`,{apps:n,force:t===!0||void 0});if(!e||typeof e!=`object`)return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};let r=e;return r.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(r.apps)?{apps:r.apps.filter(e=>e&&typeof e==`object`).map(e=>{let t=e;return{name:typeof t.name==`string`?t.name:``,iconDataUrl:typeof t.iconDataUrl==`string`?t.iconDataUrl:null}}).filter(e=>e.name.length>0),success:!0,hasCache:r.hasCache===!0,isCacheStale:r.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(e){return console.warn(`Failed to fetch installed apps`,e),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},ct=`oc.inst.`,lt=e=>{try{return btoa(unescape(encodeURIComponent(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}catch{return encodeURIComponent(e)}},ut=e=>{let t=(e??o()).trim();return t.length>0?t:`default`},dt=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim().replace(/\/+$/,``):``},w=(e,t=o())=>`${ct}${lt(ut(t))}.${e}`,ft=(e=o())=>ut(e).startsWith(`relay:`),pt=(e=o())=>{let t=ut(e);if(t==="default"||t===`local`)return!0;if(ft(t)||!t.startsWith(`url:`))return!1;let n=dt();if(!n)return!1;try{return new URL(t.slice(4)).origin===new URL(n).origin}catch{return!1}},mt=(e=o())=>!ft(e),ht=(e,t=s())=>{let n=t.trim().replace(/\/+$/,``);return n?`${e}:${encodeURIComponent(n)}`:null},gt=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{getItem:()=>null}),r=t?.runtimeKey??o(),i=n.getItem(w(e,r));if(i!==null)return i;if(mt(r)){let t=ht(e),r=t?n.getItem(t):null;if(r!==null)return r}return pt(r)?n.getItem(e):null},T=(e,t,n)=>{let r=n?.storage??(typeof localStorage<`u`?localStorage:{setItem:()=>void 0}),i=n?.runtimeKey??o();r.setItem(w(e,i),t)},_t=e=>({getItem:t=>gt(t,{storage:e}),setItem:(t,n)=>{T(t,n,{storage:e})},removeItem:t=>{E(t,{storage:e})}}),E=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{removeItem:()=>void 0}),r=t?.runtimeKey??o();n.removeItem(w(e,r))},vt=e=>{let t;try{t=p()}catch{return}let n=t=>t===null?null:JSON.parse(t,e?.reviver),r=e=>t.getItem(e);return{getItem:e=>{let t=o(),i=w(e,t),a=r(i);if(a instanceof Promise)return a.then(i=>{if(i!==null)return n(i);if(!pt(t))return null;let a=r(e);return a instanceof Promise?a.then(n):n(a)});if(a!==null)return n(a);if(!pt(t))return null;let s=r(e);return s instanceof Promise?s.then(n):n(s)},setItem:(n,r)=>{let i=w(n,o());t.setItem(i,JSON.stringify(r,e?.replacer))},removeItem:e=>{let n=w(e,o());t.removeItem(n)}}},yt=(e=bt)=>{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}}},bt=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},xt=yt(),St=e=>xt.countUnicodeCodePoints(e),D=(e,t)=>{if(!e)throw Error(`${t} must be non-empty`);return e},Ct=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`session`,ownerID:D(t,`sessionID`)}}),wt=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`draft`,ownerID:D(t,`draftID`)}}),Tt=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`},Et=({transportIdentity:e},t)=>({transportIdentity:D(e,`transportIdentity`),owner:{kind:`surface`,ownerID:D(t,`surfaceID`)}}),Dt=8192,Ot=e=>{if(typeof e!=`string`||e.length===0||e.length>Dt)return!1;try{let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`file:`}catch{return!1}},kt=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID]),At=e=>JSON.stringify([e.transportIdentity,e.owner.kind,e.owner.ownerID,e.attachmentOccurrenceRefID]),jt=e=>JSON.stringify([`root`,e]),Mt=(e,t)=>JSON.stringify([`part`,e,t]),Nt={mentionCount:1e3,valueLength:8192,pathLength:8192,labelLength:512},O={referenceCount:1e3,idLength:512,displayLength:514,sessionIDLength:128,skillNameLength:511,commandNameLength:511,commandReferenceLength:8192,pastePayloadLength:1e5,totalPastePayloadLength:2e5},k=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},A=(e,t)=>Object.keys(e).every(e=>t.includes(e)),j=e=>typeof e==`string`&&e.length>0,Pt=e=>typeof e==`string`,M=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,N=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ft=(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)},It=(e,t)=>{if(!Array.isArray(t)||t.length>Nt.mentionCount)return;let n=[],r=new Set,i=0;for(let a of t){if(!k(a)||!A(a,[`kind`,`value`,`path`,`label`,`range`])||a.kind!==`file`&&a.kind!==`directory`&&a.kind!==`agent`||!N(a.value,Nt.valueLength)||!N(a.path,Nt.pathLength)||!N(a.label,Nt.labelLength)||!k(a.range)||!A(a.range,[`start`,`end`])||!M(a.range.start)||!M(a.range.end)||a.range.end<=a.range.start||a.range.end>e.length||a.range.start<i||!Ft(e,a.range.start)||!Ft(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},Lt=e=>N(e,O.sessionIDLength)&&/^[A-Za-z0-9_-]+$/.test(e),Rt=/^[^\s/\\[\]\r\n]+$/u,zt=()=>/\[skill:([^\s/\\\]\r\n]+)\]/gu,Bt=e=>N(e,O.skillNameLength)&&Rt.test(e),Vt=e=>N(e,O.commandNameLength)&&/^[\p{L}\p{N}._/-]+$/u.test(e),Ht=e=>N(e,O.commandReferenceLength)&&!/[\]\r\n]/u.test(e),Ut=e=>{if(!(!k(e)||!N(e.id,O.idLength)||!N(e.display,O.displayLength)||!M(e.start)||!M(e.end)||e.end<=e.start)){if(e.kind===`session`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`sessionId`])&&Lt(e.sessionId))return{id:e.id,kind:`session`,start:e.start,end:e.end,display:e.display,sessionId:e.sessionId};if(e.kind===`paste`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`text`,`characterCount`,`index`])&&typeof e.text==`string`&&e.text.length<=O.pastePayloadLength&&M(e.characterCount)&&e.characterCount===St(e.text)&&M(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`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`skillName`])&&Bt(e.skillName)&&(e.display===`/${e.skillName}`||e.display===`/ ${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`&&A(e,[`id`,`kind`,`start`,`end`,`display`,`commandName`,`reference`])&&Vt(e.commandName)&&Ht(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}}},Wt=(e,t)=>{if(!Array.isArray(t)||t.length>O.referenceCount)return;let n=t.map(Ut);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>O.totalPastePayloadLength)))return;return{text:e,references:r}},Gt=(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)&&!k(e)||t.has(e))return!1;t.add(e);let n=Object.values(e).every(e=>Gt(e,t));return t.delete(e),n},Kt=e=>{if(!(!k(e)||!A(e,[`kind`,`ownerID`])||!j(e.ownerID))&&(e.kind===`session`||e.kind===`draft`||e.kind===`surface`))return{kind:e.kind,ownerID:e.ownerID}},qt=e=>{if(!k(e)||!A(e,[`transportIdentity`,`owner`])||!j(e.transportIdentity))return;let t=Kt(e.owner);return t?{transportIdentity:e.transportIdentity,owner:t}:void 0},Jt=e=>{if(!(!k(e)||!j(e.kind))){if(e.kind===`blob`&&A(e,[`kind`,`blobID`])&&j(e.blobID))return{kind:`blob`,blobID:e.blobID};if(!(e.kind!==`url`||!A(e,[`kind`,`url`])||!Ot(e.url)))return{kind:`url`,url:e.url}}},Yt=(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}},Xt=(e,t)=>{if(!k(e)||!A(e,[`attachmentID`,`attachmentRefID`,`filename`,`mimeType`,`size`,`locator`,`source`,`serverPath`,`vscodePath`,`vscodeSource`])||!j(e.attachmentID)||!j(e.attachmentRefID)||!Yt(e.attachmentRefID,e.attachmentID,t)||!j(e.filename)||!Pt(e.mimeType)||!M(e.size)||e.source!==`local`&&e.source!==`vscode`&&e.source!==`server`||e.serverPath!==void 0&&!j(e.serverPath)||e.vscodePath!==void 0&&!j(e.vscodePath)||e.vscodeSource!==void 0&&e.vscodeSource!==`file`&&e.vscodeSource!==`selection`||e.source===`server`&&!j(e.serverPath)||e.source===`vscode`&&(!j(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}}},Zt=e=>{if(!Gt(e,new Set)||!k(e)||!A(e,[`version`,`key`,`revision`,`text`,`attachments`,`syntheticParts`,`mentions`,`composerReferences`])||e.version!==1||!M(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=qt(e.key),r=e.attachments.map(e=>Xt(e)),i=e.syntheticParts.map(e=>{if(!k(e)||!A(e,[`partID`,`text`,`attachments`,`synthetic`])||!j(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=>Xt(e,t));return r.every(Boolean)?{partID:t,text:n,attachments:r,...e.synthetic===void 0?{}:{synthetic:e.synthetic}}:void 0}),a=It(t,e.mentions),o=e.composerReferences===void 0?{text:t,references:[]}:Wt(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}}},Qt=e=>Zt(e),P=` `,$t=`0.2em`,en=`size-[1em]`,tn=e=>e.startsWith(P)?e.slice(P.length):e,nn=e=>e.replaceAll(`/${P}`,`/`).replaceAll(`@${P}`,`@`).replaceAll(`[${P}`,`[`),rn=e=>{let t=e.match(/^\s*/)?.[0].length??0,n=e.slice(t);if(!n.startsWith(`/`))return null;let r=1;n.startsWith(P,r)&&(r+=P.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},an=e=>F({trigger:`[`,icon:`file-image`,label:e,suffix:`]`}),on=({trigger:e,label:t,suffix:n=``})=>`${e}${t}${n}`,F=e=>`${e.trigger}${P}${e.label}${e.suffix??``}`,sn=e=>on(e),cn=(e,t)=>e===sn(t)||e===F(t),ln=(e,t)=>{let n=t===F(e);return{trigger:n?`${e.trigger}${P}`:e.trigger,icon:e.icon,align:e.align??`end`,label:e.label,suffix:e.suffix,slot:n?`reserved`:`compact`}},un=(e,t,n=``)=>{let r=e.startsWith(t)?e.slice(t.length):e,i=r.startsWith(P)?r.slice(P.length):r;return n&&i.endsWith(n)?i.slice(0,-n.length):i},dn=(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,fn=0n,pn=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,mn=14;function hn(e){let t=``;for(let n=0;n<e;n++)t+=pn[Math.floor(Math.random()*62)];return t}var gn=/^[0-9a-f]{12}$/,_n=/^[0-9A-Za-z]{14}$/,vn=(1n<<48n)-1n,yn=(e,t)=>{if(typeof t!=`string`||!t.startsWith(`${e}_`))return;let n=t.slice(e.length+1),r=n.slice(0,12);if(!(!gn.test(r)||!_n.test(n.slice(12))))return BigInt(`0x${r}`)},bn=(e,t)=>{let n=BigInt(Date.now())*4096n&vn,r=yn(e,t)??0n,i=[n,fn,r].reduce((e,t)=>e>t?e:t);if(i>=vn)throw Error(`Ascending ID space exhausted`);let a=i+1n;fn=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}${hn(mn)}`},xn=e=>bn(e),Sn=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,`_`)}`},Cn=()=>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},wn=(e=Cn())=>{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(``)}`},Tn=e=>/^[\\/]+$/.test(e),En=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;if(Tn(t))return t.length===1?`/`:null;let n=ie(t);return n===`/`?`/`:(n.length>1?n.replace(/\/+$/,``):n)||null},Dn=e=>{if(typeof e!=`string`)return``;let t=e.trim();return t?En(t)??t:``},I={...O,sessionIdLength:O.sessionIDLength,visibleTextLength:1e5,canonicalOutputLength:2e5},On=e=>typeof e==`string`&&Lt(e),kn=e=>e.replaceAll(`\\`,`/`).split(`/`).at(-1)?.replace(/\.md$/,``)??``,An=e=>({trigger:`@`,icon:`chat-thread`,label:e}),jn=(e,t)=>({trigger:`/`,icon:t,label:e}),Mn=(e,t)=>({trigger:t,icon:`book-open`,label:e}),Nn=(e,t)=>[`/`,`@`].some(n=>cn(e,Mn(t,n))),Pn=(e,t)=>cn(e,Mn(t,`@`))?Mn(t,`@`):Mn(t,`/`),Fn={session:{kind:`session`,validatePayload:e=>On(e.sessionId),contributeCanonical:e=>({text:`@session:${e.sessionId}`,semantic:{type:`session`,sessionId:e.sessionId}}),contributeDirectSend:e=>({text:sn(An(un(e.display,`@`))),semantic:{type:`session`,sessionId:e.sessionId}}),decorate:e=>({style:`mentionSession`,visual:ln(An(un(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))?F(An(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<=I.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=>Bt(e.skillName)&&typeof e.display==`string`&&Nn(e.display,e.skillName),contributeCanonical:e=>({text:`[skill:${e.skillName}]`}),contributeDirectSend:e=>({text:`[skill:${e.skillName}]`}),decorate:e=>({style:`mentionCommand`,skillName:e.skillName,visual:ln(Pn(e.display,e.skillName),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:zt(),resolveDisplay:e=>F(Mn(e[1],`@`)),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=>Vt(e.commandName)&&Ht(e.reference)&&typeof e.display==`string`&&cn(e.display,jn(e.commandName,`command`)),contributeCanonical:e=>({text:`[command:${e.reference}]`}),contributeDirectSend:e=>({text:`[command:${e.reference}]`}),decorate:e=>({style:`mentionCommand`,visual:ln(jn(e.commandName,`command`),e.display)}),payloadBudget:()=>void 0,canonical:{matcher:/\[command:([^\]\r\n]+)\]/g,resolveDisplay:e=>{let t=kn(e[1]);return Ht(e[1])&&Vt(t)?F(jn(t,`command`)):null},materialize:(e,t,n)=>({id:`command:${n}`,kind:`command`,commandName:kn(e[1]),reference:e[1],display:t,start:n,end:n+t.length})}}},L=e=>Fn[e],In=(e,t)=>L(e).validatePayload(t),Ln=e=>L(e.kind).contributeCanonical(e),Rn=e=>L(e.kind).contributeDirectSend(e),zn=e=>L(e.kind).decorate(e),Bn=e=>L(e.kind).payloadBudget(e),Vn=e=>L(e.kind).describeResourceIdentity?.(e),Hn=Object.keys(Fn),Un=e=>typeof e==`string`&&Hn.includes(e),Wn=()=>Hn.flatMap(e=>{let t=L(e).canonical;return t?[t]:[]}),Gn=e=>{if(e.type===`attachment`)return`attachment:${e.attachmentRefID}`},Kn=e=>{let t=new Map;for(let n of e.references){let e=Vn(n);e&&t.set(Gn(e),e)}return[...t.values()]},qn=(e,t)=>{let n=new Map(e.map(e=>[Gn(e),e])),r=new Map(t.map(e=>[Gn(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])}},Jn=(e,t)=>qn(Kn(e),Kn(t)),Yn=(e,t=`queue-canonical`)=>{if(e.references.length>I.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=Bn(t);i+=n?.category===`opaque-text`?n.length:0}if(i>I.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`?Rn(r):Ln(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>I.canonicalOutputLength?{ok:!1,reason:`canonical-output-too-large`}:{ok:!0,plan:{chunks:a,semantics:o},text:c}},R=(e,t)=>Math.max(0,Math.min(e,t)),Xn=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Zn=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return!Xn(t.id,I.displayLength)||!Xn(t.display,I.displayLength)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||typeof t.kind!=`string`?!1:Un(t.kind)&&In(t.kind,t)},z=(e,t)=>{let n=[],r=0,i=[],a=Math.min(t.length,I.referenceCount);for(let e=0;e<a;e+=1){let a=t[e];if(!Zn(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=Bn(t);if(l+=i?.category===`opaque-text`?i.length:0,l>O.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>I.referenceCount,payloadBudgetExceeded:u}},B=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(!Xn(o.id,I.idLength)||!Xn(o.display,I.displayLength)||!Un(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=Bn(o),s=t?.category===`opaque-text`?t.length:0;a+s>O.totalPastePayloadLength||(r.add(o.id),i=o.end,a+=s,n.push(o))}return{text:e.text,references:n}},Qn=(e,t)=>{if(t.length>O.pastePayloadLength)return!1;let n=z(e.text,e.references);return n.budgetExceeded||n.payloadBudgetExceeded?!1:n.document.references.reduce((e,t)=>{let n=Bn(t);return e+(n?.category===`opaque-text`?n.length:0)},0)+t.length<=O.totalPastePayloadLength},$n=(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 er(e,t,n,r,i={}){let a=B(e);if(!In(r.kind,r))return{document:a,caret:R(n,a.text.length),edit:{oldStart:t,oldEnd:n,newEnd:n}};let o=R(t,a.text.length),s=Math.max(o,R(n,a.text.length)),c=$n(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)?` `:``,ee=`${l}${p}${r.display}${m}${u}`,te={...r,start:c.start+p.length,end:c.start+p.length+r.display.length},h=p.length+r.display.length+m.length-(c.end-c.start);return{document:B({text:ee,references:[...a.references.filter(e=>e.end<=c.start||e.start>=c.end).map(e=>e.start>=c.end?{...e,start:e.start+h,end:e.end+h}:e),te]}),caret:te.end,edit:{oldStart:c.start,oldEnd:c.end,newEnd:c.start+p.length+r.display.length+m.length}}}var tr=(e,t)=>e<=t.oldStart?e:e>=t.oldEnd?e+t.newEnd-t.oldEnd:t.newEnd,nr=(e,t,n=t.length,r=n)=>{let i=B(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=$n(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},ee=m.newEnd-m.oldEnd,te=i.references.filter(e=>e.end<=l.start||e.start>=l.end).map(e=>e.start>=l.end?{...e,start:e.start+ee,end:e.end+ee}:e),h=(e,n)=>{let r=R(e,t.length),i=c.newEnd+l.end-c.oldEnd;return R(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)},g=h(n,`start`),ne=Math.max(g,h(r,`end`)),_=B({text:p,references:te});return{document:_,edit:m,requiresTextCorrection:u,selectionStart:g,selectionEnd:ne,caret:ne,mapCaret:e=>R(tr(e,m),_.text.length),removedReferences:d}},rr=(e,t,n)=>{let r=$n(n,e,t);return r.start===e&&r.end===t?null:r},ir=(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}},ar=(e,t)=>{let n=B(e),r=R(t.selectionStart,n.text.length),i=Math.max(r,R(t.selectionEnd,n.text.length)),a=r===i?t.altKey?ir(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=rr(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:B({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}},or=(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}},sr=(e,t=`queue-canonical`)=>{let n=z(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=Yn(n.document,t);return r.ok?{ok:!0,text:r.text,chunks:r.plan.chunks,semantics:r.plan.semantics}:r},cr=(e,t)=>e.match.index-t.match.index||e.adapterOrder-t.adapterOrder||e.matchOrder-t.matchOrder,lr=e=>{if(e.length>I.canonicalOutputLength||e.length>I.visibleTextLength)return null;let t=[],n=0;for(let[r,i]of Wn().entries()){i.matcher.lastIndex=0;let a,o=0;for(;(a=i.matcher.exec(e))!==null;){if(n+=1,n>I.referenceCount)return null;let e={codec:i,match:a,adapterOrder:r,matchOrder:o};o+=1;let s=t.findIndex(t=>cr(e,t)<0);s===-1?t.push(e):t.splice(s,0,e)}}return t},ur=(e,t)=>{let n=z(e.text,e.references).document,r=lr(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>I.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>I.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 z(o,[...f,...a]).document},dr=(e,t)=>ur({text:e,references:[]},t),fr=(e,t)=>dr(e,t),pr=(e,t,n=`
2
2
 
3
3
  `)=>{let r=z(e.text,e.references).document,i=z(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 z(`${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},mr=e=>({state:`unbound-legacy`,sessionID:e}),V=e=>e.state===`bound`?`bound:${JSON.stringify([e.transportIdentity,Dn(e.directory),e.sessionID,e.deliveryTarget??{kind:`primary`}])}`:`unbound-legacy:${JSON.stringify([e.sessionID])}`,hr=(e,t)=>e.queuedMessages[V(t)]??gr,gr=[],_r=3e4,vr=`queue`,yr=e=>e===`steer`||e===`queue`,br=(e,t)=>e===`immediate`?`steer`:yr(e)?e:t===!1?`steer`:`queue`,xr=[],Sr=(e,t)=>e.pendingAdmissions[V(t)]??xr,Cr=e=>`${e}-${wn()}`,wr=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype,Tr=(e,t,n=[])=>{if(!wr(e)||!Object.keys(e).every(e=>e===`text`||e===`references`))return;let r=e;if(typeof r.text!=`string`)return;let i=Wt(r.text,r.references),a=i&&sr(i,`queue-canonical`);if(!a||!a.ok||a.text!==t)return;let o=new Set(n.map(e=>e.id));return Kn(i).every(e=>o.has(e.attachmentRefID))?i:void 0},Er=(e,t)=>{if(e===void 0)return[];if(!t)return;let n=It(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},Dr=(e,t)=>{let n=wr(e)&&typeof e.content==`string`?e:t,r=Tr(n.composerDocument,n.content,Array.isArray(n.attachments)?n.attachments:[]),i=Er(n.composerMentions,r);return{content:n.content,...r?{composerDocument:r}:{},...r&&i?.length?{composerMentions:i}:{},...Array.isArray(n.attachments)?{attachments:n.attachments}:{},...wr(n.sendConfig)?{sendConfig:n.sendConfig}:{}}},Or=e=>Dr(void 0,e),kr=(e,t)=>e.queueItemID===t.queueItemID&&e.operationID===t.operationID&&(!t.messageID||e.messageID===t.messageID),H=e=>e.status===`sending`||e.status===`reconciling`,Ar=ee(),jr=()=>Ar?.flush()??!0,Mr=`quiescing`,Nr=new Set,Pr=new Set,Fr=e=>{if(Mr!==e){Mr=e;for(let e of Pr)e()}},Ir=e=>{if(!(!e||Nr.has(e))){Nr.add(e);for(let e of Pr)e()}},Lr=e=>e.state===`bound`&&Nr.has(e.transportIdentity),U=e=>Mr===`open`&&(!e||!Lr(e)),Rr=(e,t=Date.now())=>({reconciliationStartedAt:e.reconciliationStartedAt??t,reconciliationDeadlineAt:e.reconciliationDeadlineAt??(e.reconciliationStartedAt??t)+_r,reconciliationChecks:Math.max(0,Math.floor(e.reconciliationChecks??0))}),zr=(e,t,n)=>{let r=t.queueItemID??(t.id||Cr(`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:xn(`msg`),s=Tr(t.composerDocument,t.content,t.attachments),c=Er(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??Cr(`operation`),messageID:o,owner:n,status:a,attemptCount:Math.max(0,Math.floor(t.attemptCount??0)),...t.status===`sending`||t.status===`reconciling`?Rr(t):{},...i||a===`reconciling`&&t.status===`sending`?{failure:{kind:`ambiguous-dispatch`,recovery:Dr(t.failure?.recovery,t)}}:{}}},Br=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:mr(n?.owner?.sessionID??i)}else t=mr(e);for(let e of r){let r=e.owner?.state===`bound`?e.owner:t,i=V(r);(n[i]??=[]).push(zr(r.sessionID,e,r))}}return{queuedMessages:n,followUpBehavior:br(t.followUpBehavior,t.queueModeEnabled??null)}},W=(e,t,n,r)=>{if(Lr(t))return;let i=V(t);e(e=>{let t=e.queuedMessages[i],a=t?.findIndex(e=>V(e.owner)===i&&kr(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}}})},Vr=l()(d(u((e,t)=>({queuedMessages:{},followUpBehavior:vr,pendingAdmissions:{},addToQueue:(t,n)=>{if(!U(t))return{ok:!1,reason:`invalid-composer-document`};let r=Tr(n.composerDocument,n.content,n.attachments);if(n.composerDocument!==void 0&&!r)return{ok:!1,reason:`invalid-composer-document`};let i=Er(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:Cr(`queued`),queueItemID:``,operationID:Cr(`operation`),messageID:xn(`msg`),createdAt:Date.now(),owner:t,status:`queued`,attemptCount:0};a.queueItemID=a.id;let o=V(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=V(n),o=t().queuedMessages[a];if(!o||o.length===0)return!0;let s=o.find(e=>(e.queueItemID===r||e.id===r)&&V(e.owner)===a);if(s&&s.operationID!==i)return!1;let c=o.find(e=>(e.queueItemID===r||e.id===r)&&e.operationID===i&&V(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}}),!hr(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=V(t);e(e=>{let t=e.queuedMessages[a],o=t?.findIndex(e=>(e.id===n||e.queueItemID===n)&&e.operationID===i&&V(e.owner)===a)??-1,s=t?.findIndex(e=>(e.id===r||e.queueItemID===r)&&V(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=hr(t(),e).find(t=>(t.id===n||t.queueItemID===n)&&t.operationID===r&&V(t.owner)===V(e));return!i||H(i)||!t().removeFromQueue(e,i.queueItemID,i.operationID)?null:i},clearQueue:n=>{if(!U(n))return!1;let r=V(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]&&Lr(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}),ka({followUpBehavior:t}))},getQueueForScope:e=>hr(t(),e),getPendingAdmissionsForScope:e=>Sr(t(),e),stageAdmission:(t,n)=>{if(!U(t)||!n.requestID||!n.queueItemID||!n.operationID||!n.messageID||typeof n.content!=`string`)return;let r=Tr(n.composerDocument,n.content);if(n.composerDocument!==void 0&&!r)return;let i=Er(n.composerMentions,r);if(n.composerMentions!==void 0&&!i)return;let a=V(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=V(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=V(n),a=(t().pendingAdmissions[i]??[]).find(e=>e.requestID===r.requestID);if(!a)return{ok:!1,reason:`invalid-composer-document`};let o=Tr(a.composerDocument,a.content,r.attachments);if(a.composerDocument!==void 0&&!o)return{ok:!1,reason:`invalid-composer-document`};let s=Er(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=V(t),i=V(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??Or(e)}}:e),markQueueItemReconciling:(t,n,r)=>W(e,t,n,e=>e.status===`sending`?{...e,status:`reconciling`,nextAttemptAt:void 0,...Rr(e),reconciliationNextCheckAt:void 0,failure:{kind:`ambiguous-dispatch`,recovery:r?.recovery??Or(e)}}:e),recordQueueItemReconciliationCheck:(t,n)=>W(e,t,n,e=>e.status===`reconciling`&&kr(e,n)?{...e,reconciliationChecks:(e.reconciliationChecks??0)+1,reconciliationNextCheckAt:Date.now()+2e3}:e),resolveQueueItemReconciliation:(t,n)=>W(e,t,n,e=>e.status===`reconciling`&&kr(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??Or(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=V(t),s=null;return e(e=>{let t=e.queuedMessages[o],c=i?t?.findIndex(e=>V(e.owner)===o&&kr(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||V(l.owner)!==o||!kr(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(Lr(t))return;let r=V(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:Ar,partialize:e=>({queuedMessages:e.queuedMessages,followUpBehavior:e.followUpBehavior}),migrate:Br,merge:(e,t)=>({...t,...Br(e),pendingAdmissions:t.pendingAdmissions})}),{name:`message-queue-store`})),Hr=(e,t)=>{let n=Vr.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?(Vr.setState(e=>{let t={...e.queuedMessages};for(let e of r){let n=V(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}},Ur=re(),Wr=e(f(),1),Gr=`directoryTreeShowHidden`,Kr=`directory-show-hidden-change`,qr=()=>{if(typeof window>`u`)return!0;try{let e=_().getItem(Gr);return e===null||e===`true`}catch{return!0}},Jr=()=>{typeof window>`u`||window.dispatchEvent(new Event(Kr))},Yr=(e,t={})=>{if(!(typeof window>`u`)){try{_().setItem(Gr,e?`true`:`false`),Jr()}catch{}t.persist!==!1&&ka({directoryShowHidden:e})}},Xr=()=>{let e=(0,Ur.c)(2),[t,n]=Wr.useState(qr),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>{n(qr())};return window.addEventListener(`storage`,e),window.addEventListener(Kr,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(Kr,e)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),Wr.useEffect(r,i),t},Zr=`filesViewShowGitignored`,Qr=`files-view-show-gitignored-change`,$r=()=>{if(typeof window>`u`)return!1;try{return _().getItem(Zr)===`true`}catch{return!1}},ei=()=>{typeof window>`u`||window.dispatchEvent(new Event(Qr))},ti=(e,t={})=>{if(!(typeof window>`u`)){try{_().setItem(Zr,e?`true`:`false`),ei()}catch{}t.persist!==!1&&ka({filesViewShowGitignored:e})}},ni=()=>{let e=(0,Ur.c)(2),[t,n]=Wr.useState($r),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>{n($r())};return window.addEventListener(`storage`,e),window.addEventListener(Qr,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(Qr,e)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),Wr.useEffect(r,i),t},ri=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},ii=e=>{if(!e||typeof e!=`object`)return null;let t=e;return{showReasoningTraces:t.showReasoningTraces,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks}},ai=e=>{let t=g.getState();typeof e.showReasoningTraces==`boolean`&&t.setShowReasoningTraces(e.showReasoningTraces),typeof e.collapsibleThinkingBlocks==`boolean`&&t.setCollapsibleThinkingBlocks(e.collapsibleThinkingBlocks)},oi=async()=>{if(typeof window>`u`)return null;let e=localStorage.getItem(`appearance-preferences`);if(!e)return null;try{return ri(ii(JSON.parse(e)))}catch(e){return console.warn(`Failed to parse stored appearance preferences:`,e),null}},si=[{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`}],ci=new Map(si.map(e=>[e.name,e])),li=e=>ci.get(e),ui=[{type:`command`,name:`explore`},{type:`command`,name:`catch-up`},{type:`command`,name:`weigh`},{type:`command`,name:`debug`},{type:`command`,name:`review`}],di=`terminal-box`,fi=`book-open`,pi=e=>`${e.type}:${e.name}`,mi=(e,t)=>e.type===t.type&&e.name===t.name,hi=e=>{let t=e.replace(/^\//,``).replace(/[-_]+/g,` `).replace(/\s+/g,` `).trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e},gi=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},_i=`oc.rt.`,vi=e=>{try{return btoa(unescape(encodeURIComponent(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}catch{return encodeURIComponent(e)}},G=(e,t=r())=>`${_i}${vi(t.trim().length>0?t.trim():`default`)}.${e}`,yi=(e,t,n=r())=>e?e===G(t,n):!1,bi=()=>{if(typeof window>`u`)return!0;if(Fe())return C();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(C())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},xi=(e,t)=>{let n=t?.storage??(typeof localStorage<`u`?localStorage:{getItem:()=>null}),i=t?.transport??r(),a=n.getItem(G(e,i));return a===null?bi()?n.getItem(e):null:a},K=(e,t,n)=>{let i=n?.storage??(typeof localStorage<`u`?localStorage:{setItem:()=>void 0}),a=n?.transport??r();i.setItem(G(e,a),t)},Si=e=>{let t;try{t=p()}catch{return}let n=t=>t===null?null:JSON.parse(t,e?.reviver),i=e=>t.getItem(e);return{getItem:e=>{let t=G(e,r()),a=i(t);if(a instanceof Promise)return a.then(t=>{if(t!==null)return n(t);if(!bi())return null;let r=i(e);return r instanceof Promise?r.then(n):n(r)});if(a!==null)return n(a);if(!bi())return null;let o=i(e);return o instanceof Promise?o.then(n):n(o)},setItem:(n,i)=>{let a=G(n,r());t.setItem(a,JSON.stringify(i,e?.replacer))},removeItem:e=>{let n=G(e,r());t.removeItem(n)}}},Ci=512,wi=4096,Ti=64,Ei=2e5,Di=[`concise`,`detailed`,`mentor`,`pushback`,`noFiller`,`matchEnergy`,`warmPeer`,`custom`],Oi=[`defaultModel`,`defaultVariant`,`defaultAgent`,`autoCreateWorktree`,`gitmojiEnabled`,`defaultFileViewerPreview`,`zenModel`,`messageStreamTransport`,`sttProvider`,`sttServerUrl`,`sttModel`,`sttLocalModel`,`sttLanguage`,`responseStyleEnabled`,`responseStylePreset`,`responseStyleCustomInstructions`],ki=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype,Ai=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ji=(e,t)=>{if(typeof e!=`string`)return;let n=e.trim();return n.length<=t?n:void 0},Mi=e=>{let t=ji(e,wi);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}},Ni=(e,t)=>typeof e==`string`&&t.includes(e)?e:void 0,Pi=e=>typeof e==`boolean`?e:void 0,Fi=(e,t)=>{let n=e[t];switch(t){case`autoCreateWorktree`:case`gitmojiEnabled`:case`defaultFileViewerPreview`:case`responseStyleEnabled`:return Pi(n);case`messageStreamTransport`:return Ni(n,[`auto`,`ws`,`sse`]);case`sttProvider`:return Ni(n,[`local`,`openai-compatible`,`volcengine`]);case`sttServerUrl`:return Mi(n);case`sttLanguage`:return ji(n,Ti);case`responseStyleCustomInstructions`:return ji(n,Ei);case`responseStylePreset`:return Ni(n,Di);default:return ji(n,Ci)}},Ii=e=>{if(!ki(e))throw Error(`Invalid settings bootstrap response`);if(!Ai(e,`schemaVersion`)||e.schemaVersion!==1)throw Error(`Unsupported settings bootstrap schema version`);let t={schemaVersion:1};for(let n of Oi){if(!Ai(e,n))continue;let r=Fi(e,n);r!==void 0&&Object.assign(t,{[n]:r})}return t},Li=e=>{if(!ki(e))throw Error(`Invalid settings bootstrap patch`);for(let t of Object.keys(e))if(!Oi.includes(t))throw Error(`Invalid settings bootstrap patch`);let t=Ii({schemaVersion:1,...e}),n={};for(let r of Oi)if(Ai(e,r)){if(!Ai(t,r))throw Error(`Invalid settings bootstrap patch`);Object.assign(n,{[r]:t[r]})}return n},Ri=e=>{if(!ki(e))return{};let t={};for(let n of Oi){if(!Ai(e,n))continue;let r=Fi(e,n);r!==void 0&&Object.assign(t,{[n]:r})}return t},zi=new ae({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:1,refetchOnWindowFocus:!1}}}),Bi={runtime:()=>[r()],scoped:(...e)=>[r(),...e],quota:e=>[r(),e],commands:{list:(e,t=r())=>[t,`commands`,e]},agents:{list:(e,t=r())=>[t,`agents`,e],raw:(e,t=r())=>[t,`agents`,`raw`,e]},configCatalog:{providers:(e,t=r())=>[t,`configCatalog`,`providers`,e]},providers:{list:(e,t=r())=>[t,`providers`,e]},skills:{list:(e,t=r())=>[t,`skills`,e]},skillsCatalog:{sources:(e,t=r())=>[t,`skillsCatalog`,`sources`,q(e)],source:(e,t,n=r())=>[n,`skillsCatalog`,`source`,q(e),t]},messageQueue:{status:(e=r())=>[e,`messageQueue`,`status`],snapshot:(e=r())=>[e,`messageQueue`,`snapshot`],scope:(e,t,n=r())=>[n,`messageQueue`,`scope`,e,t]},mcp:{configs:(e,t=r())=>[t,`mcp`,`configs`,q(e)],status:(e,t=r())=>[t,`mcp`,`status`,q(e)]},github:{auth:(e=r())=>[e,`github`,`auth`]},browserProviders:{catalog:(e=r())=>[e,`browserProviders`,`catalog`]},git:{branches:(e,t=r())=>[t,`git`,`branches`,q(e)],remotes:(e,t=r())=>[t,`git`,`remotes`,q(e)]},sessionIndex:{snapshot:(e=r())=>[e,`sessionIndex`,`snapshot`]},sessionTitleSearch:{query:(e,t=r())=>[t,`sessionTitleSearch`,e]},sessionContentSearch:{query:(e,t,n,i=r())=>[i,`sessionContentSearch`,e,t,n]},workStatusChildren:{list:(e,t,n=r())=>[n,`workStatusChildren`,q(e),t]},sessionStatus:{snapshot:(e,t=r())=>[t,`sessionStatus`,`snapshot`,q(e)]},sessionTurnChanges:{file:(e,t,n,i,a,o=r())=>[o,`sessionTurnChanges`,`file`,q(e),t,n,i,typeof a==`number`&&Number.isFinite(a)?Math.max(0,Math.trunc(a)):null]},sessionActive:{snapshot:(e,t)=>[e,`sessionActive`,`snapshot`,t]},sessionTranscript:{infinite:(e,t,n=r(),a=i())=>[n,a,`session-transcript`,q(e)??``,t],page:(e,t,n,a,o=r(),s=i())=>[o,s,`sessionMessages`,`page`,q(e)??``,t,n,a?.trim()?a.trim():`tail`],tailTask:(e,t,n,a=r(),o=i())=>[a,o,`session-transcript-task`,`tail`,q(e)??``,t,n],reconcileTask:(e,t,n,a=r(),o=i())=>[a,o,`session-transcript-task`,`reconcile`,q(e)??``,t,n],checkpoint:(e,t,n=r(),a=i())=>[n,a,`session-transcript-checkpoint`,q(e)??``,t]},plugins:{list:(e,t=r())=>[t,`plugins`,`list`,e],registry:(e,t,n=!1,i=r())=>[i,`plugins`,`registry`,e,Vi(t),n],file:(e,t,n=r())=>[n,`plugins`,`file`,e,t],runtime:(e,t=r())=>[t,`plugins`,`runtime`,e]},files:{directory:(e,t,n,i=r())=>[i,`files`,`directory`,J(e),J(t),!!n],search:(e,t,n,i,a,o=r())=>[o,`files`,`search`,J(e),t.trim(),n??null,!!i,!!a],content:(e,t,n,i=r())=>Hi(`content`,e,t,n,i),stat:(e,t,n,i=r())=>Hi(`stat`,e,t,n,i)}},Vi=e=>Array.from(new Set(e.map(e=>e.trim()).filter(Boolean))).sort(),q=e=>e?.trim()||null,J=e=>{if(typeof e!=`string`)return null;let t=e.trim().replace(/\\/g,`/`);return t?t.length>1?t.replace(/\/+$/,``):t:null},Hi=(e,t,n,r,i)=>[i,`files`,e,J(t),J(n),!!r?.allowOutsideWorkspace,r?.outsideFileGrant??null,!!r?.optional,J(r?.directory)],Ui=e=>!!e&&typeof e==`object`&&typeof e.providerId==`string`&&e.providerId.length>0,Wi=async(e,t)=>{let n=await c(`/api/quota/${encodeURIComponent(e)}`,{signal:t}),r=await n.json().catch(()=>null);if(!n.ok){let e=r&&typeof r==`object`&&typeof r.error==`string`?r.error:`Failed to fetch quota`;throw Error(e)}if(!Ui(r))throw Error(`Invalid quota response`);return r},Gi=e=>n(t=>{a(t)&&e.clear()}),Ki=async(e,t)=>{let n=new AbortController,r,i=new Promise((e,t)=>{r=t}),a=e=>{r(e),n.abort(e)},o=()=>a(e.reason??new DOMException(`Request aborted`,`AbortError`)),s=setTimeout(()=>a(new DOMException(`Configuration request timed out`,`TimeoutError`)),3e4);e.addEventListener(`abort`,o,{once:!0});try{return e.aborted?(o(),await i):await Promise.race([t(n.signal),i])}finally{clearTimeout(s),e.removeEventListener(`abort`,o)}},qi=class extends Error{status;constructor(e){super(`Settings bootstrap request failed (${e})`),this.status=e,this.name=`SettingsBootstrapRequestError`}},Ji=(e=r())=>[e,`settings`,`bootstrap`],Yi=(e=r())=>({queryKey:Ji(e),queryFn:({signal:e})=>Ki(e,async e=>{let t=await c(`/api/config/settings/bootstrap`,{method:`GET`,headers:{Accept:`application/json`},signal:e});if(!t.ok)throw new qi(t.status);return Ii(await t.json())}),retry:(e,t)=>!(t instanceof qi&&(t.status===404||t.status===501))&&e<1,staleTime:1/0,gcTime:1/0}),Xi=(e=r())=>zi.fetchQuery(Yi(e)),Zi=(e=r())=>zi.getQueryData(Ji(e)),Qi=(e,t=r())=>{let n=Li(e),i=Ji(t),a=Ii({schemaVersion:1,...zi.getQueryData(i),...n});return zi.setQueryData(i,a),a},$i=e=>{if(!(typeof window>`u`)&&!(typeof window.__OPENCHAMBER_HOME__==`string`&&window.__OPENCHAMBER_HOME__.length>0))try{window.__OPENCHAMBER_HOME__=e}catch{}},ea=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&&T(`lastDirectory`,e.lastDirectory),e.homeDirectory&&(T(`homeDirectory`,e.homeDirectory),$i(e.homeDirectory)),Array.isArray(e.projects)&&e.projects.length>0?T(`projects`,JSON.stringify(e.projects)):E(`projects`),e.activeProjectId?T(`activeProjectId`,e.activeProjectId):E(`activeProjectId`),Array.isArray(e.pinnedDirectories)&&e.pinnedDirectories.length>0?T(`pinnedDirectories`,JSON.stringify(e.pinnedDirectories)):E(`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?T(`oc.sessions.projectCollapse`,JSON.stringify(t)):E(`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`&&m(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`)}}},ta=e=>{typeof window>`u`||window.dispatchEvent(new CustomEvent(`openchamber:settings-synced`,{detail:e}))},na=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},ra=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},ia=(e,t)=>{let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([e,n])=>t[e]===n)},aa=(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),oa=(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})},sa=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),ca=e=>{if(Array.isArray(e))return Array.from(new Set(e.filter(e=>typeof e==`string`&&e.length>0)))},la=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=ca(r);e&&e.length>0&&(t[n]=e.slice(0,5))}return Object.keys(t).length>0?t:void 0},ua=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Array.isArray(t[n])&&sa(e[n],t[n]))},da=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,fa=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&da.test(t)?t.toLowerCase():null},pa=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=Sn(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=fa(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},ma=(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},ha=()=>{let e=g.persist;if(e&&typeof e==`object`)return e},ga=()=>_e()?.settings??null,_a=(e,t,n)=>{let r={...Ri(t),...Ri(e)};if(Object.keys(r).length!==0)try{Qi(r,n)}catch(e){console.warn(`Failed to patch settings bootstrap cache:`,e)}},va=e=>{let t=g.getState(),n=typeof window<`u`?window.__zustand_config_store__?.getState?.()??null:null,r=Vr.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 i=null;if(yr(e.followUpBehavior)?i=e.followUpBehavior:typeof e.queueModeEnabled==`boolean`&&(i=br(void 0,e.queueModeEnabled)),i&&i!==r.followUpBehavior&&r.setFollowUpBehavior(i),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),typeof e.notifyOnPermission==`boolean`&&e.notifyOnPermission!==t.notifyOnPermission&&t.setNotifyOnPermission(e.notifyOnPermission),typeof e.notifyOnScheduledTasks==`boolean`&&e.notifyOnScheduledTasks!==t.notifyOnScheduledTasks&&t.setNotifyOnScheduledTasks(e.notifyOnScheduledTasks),typeof e.notifyOnAssistants==`boolean`&&e.notifyOnAssistants!==t.notifyOnAssistants&&t.setNotifyOnAssistants(e.notifyOnAssistants),typeof e.notifyOnGoals==`boolean`&&e.notifyOnGoals!==t.notifyOnGoals&&t.setNotifyOnGoals(e.notifyOnGoals),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.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.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.promptNavigatorEnabled==`boolean`&&e.promptNavigatorEnabled!==t.promptNavigatorEnabled&&t.setPromptNavigatorEnabled(e.promptNavigatorEnabled),typeof e.expandedEditorToolbar==`boolean`&&e.expandedEditorToolbar!==t.expandedEditorToolbar&&t.setExpandedEditorToolbar(e.expandedEditorToolbar),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=gi(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),h(e.uiFont)&&e.uiFont!==t.uiFont&&t.setUiFont(e.uiFont),ne(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&&!ia(e.shortcutOverrides,t.shortcutOverrides)&&g.setState({shortcutOverrides:e.shortcutOverrides}),typeof e.mobileKeyboardMode==`string`){let n=te(e.mobileKeyboardMode,t.mobileKeyboardMode);n!==t.mobileKeyboardMode&&t.setMobileKeyboardMode(n)}if(Array.isArray(e.favoriteModels)){let n=t.favoriteModels,r=oa(n,e.favoriteModels);aa(n,r)||g.setState({favoriteModels:r})}if(Array.isArray(e.hiddenModels)){let n=t.hiddenModels,r=e.hiddenModels;aa(n,r)||g.setState({hiddenModels:r})}if(Array.isArray(e.collapsedModelProviders)){let n=t.collapsedModelProviders,r=e.collapsedModelProviders;sa(n,r)||g.setState({collapsedModelProviders:r})}if(Array.isArray(e.recentModels)){let n=t.recentModels,r=oa(n,e.recentModels);aa(n,r)||g.setState({recentModels:r})}if(Array.isArray(e.recentAgents)){let n=t.recentAgents,r=e.recentAgents;sa(n,r)||g.setState({recentAgents:r})}if(e.recentEfforts&&typeof e.recentEfforts==`object`){let n=t.recentEfforts,r=e.recentEfforts;ua(n,r)||g.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`&&Yr(e.directoryShowHidden,{persist:!1}),typeof e.filesViewShowGitignored==`boolean`&&ti(e.filesViewShowGitignored,{persist:!1})},ya=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=pa(t.projects);if([`manual`,`a-z`,`z-a`,`date-added`,`recent`].includes(t.projectSortOrder)&&(n.projectSortOrder=t.projectSortOrder),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=gi(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.summaryCustomModelID==`string`&&t.summaryCustomModelID.length>0&&(n.summaryCustomModelID=t.summaryCustomModelID),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),yr(t.followUpBehavior)?n.followUpBehavior=t.followUpBehavior:typeof t.queueModeEnabled==`boolean`&&(n.followUpBehavior=br(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),typeof t.notifyOnPermission==`boolean`&&(n.notifyOnPermission=t.notifyOnPermission),typeof t.notifyOnScheduledTasks==`boolean`&&(n.notifyOnScheduledTasks=t.notifyOnScheduledTasks),typeof t.notifyOnAssistants==`boolean`&&(n.notifyOnAssistants=t.notifyOnAssistants),typeof t.notifyOnGoals==`boolean`&&(n.notifyOnGoals=t.notifyOnGoals),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)),typeof t.magpieUsageUrl==`string`&&(n.magpieUsageUrl=t.magpieUsageUrl),Array.isArray(t.magpieHiddenProviders)&&(n.magpieHiddenProviders=t.magpieHiddenProviders.filter(e=>typeof e==`string`&&e.startsWith(`magpie:`))),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.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.collapsibleUserMessages==`boolean`&&(n.collapsibleUserMessages=t.collapsibleUserMessages),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),h(t.uiFont)&&(n.uiFont=t.uiFont),ne(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=ra(t.shortcutOverrides);i&&(n.shortcutOverrides=i),typeof t.mobileKeyboardMode==`string`&&(t.mobileKeyboardMode===`native`||t.mobileKeyboardMode===`resize-content`)&&(n.mobileKeyboardMode=t.mobileKeyboardMode);let a=ma(t.favoriteModels,64,{preserveVariant:!0});a&&(n.favoriteModels=a);let o=ma(t.hiddenModels,1024);o&&(n.hiddenModels=o);let s=ca(t.collapsedModelProviders);s&&(n.collapsedModelProviders=s);let c=ma(t.recentModels,16,{preserveVariant:!0});c&&(n.recentModels=c);let l=ca(t.recentAgents);l&&(n.recentAgents=l);let u=la(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=na(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`||t.sttProvider===`volcengine`?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},Y=new Map,ba=new Map,xa=2e3,Sa=async e=>{let t=Y.get(e);if(t&&Date.now()-t.at<xa)return t.value;let n=ba.get(e);if(n)return n;let i=(async()=>{if(r()!==e)return null;let t=ga();if(t)try{let n=ya((await t.load()).settings);return Y.set(e,{value:n,at:Date.now()}),n}catch(e){console.warn(`Failed to load shared settings from runtime settings API:`,e)}if(r()!==e)return null;try{let t=await c(`/api/config/settings`,{method:`GET`,headers:{Accept:`application/json`}});if(!t.ok)return null;let n=ya(await t.json().catch(()=>null));return Y.set(e,{value:n,at:Date.now()}),n}catch(e){return console.warn(`Failed to load shared settings from server:`,e),null}})();ba.set(e,i);try{return await i}finally{ba.get(e)===i&&ba.delete(e)}},Ca=(e=r())=>{Y.delete(e)},wa=async()=>{if(typeof window>`u`)return;let e=r(),t=ha(),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()}),i=async t=>{if(await n(),r()===e){try{ea(t)}catch(e){console.warn(`persistToLocalStorage failed:`,e)}try{va(t)}catch(e){console.warn(`applyDesktopUiPreferences failed:`,e)}ta(t)}};try{let t=await Sa(e);t&&r()===e&&await i(t)}catch(e){console.warn(`Failed to synchronise settings:`,e)}},X=null,Z=null,Q=null,Ta=[],Ea=200,$=new Map,Da=async e=>{for(;$.get(e)?.size;)await Promise.all([...$.get(e)])},Oa=async()=>{let e=X,t=Z,n=Ta;if(X=null,Z=null,Q=null,Ta=[],!e||!t||Object.keys(e).length===0){n.forEach(e=>e());return}if(r()!==t){n.forEach(e=>e());return}let i=()=>r()===t,a=ga();if(a){try{let r=await a.save(e);_a(r,e,t),r&&i()&&(ea(r),va(r),ta(r),Y.set(t,{value:ya(r),at:Date.now()})),n.forEach(e=>e());return}catch(e){console.warn(`Failed to update settings via runtime settings API:`,e)}if(!i()){n.forEach(e=>e());return}}try{let n=await c(`/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 r=await n.json().catch(()=>null);_a(r,e,t),r&&i()&&(ea(r),va(r),ta(r),Y.set(t,{value:ya(r),at:Date.now()}))}catch(e){console.warn(`Failed to update shared settings via API:`,e)}finally{n.forEach(e=>e())}},ka=async e=>{if(typeof window>`u`)return;let t=r();if(Z&&Z!==t){Q&&=(clearTimeout(Q),null),X=null,Z=null;let e=Ta;Ta=[],e.forEach(e=>e())}let n={...X??{}},i=Y.get(t)?.value;for(let[t,r]of Object.entries(e)){let e=i?.[t];Object.is(r,e)||r!==void 0&&e!==void 0&&JSON.stringify(r)===JSON.stringify(e)?delete n[t]:n[t]=r}if(X=n,Z=t,Object.keys(n).length===0&&!Q){X=null,Z=null;return}Q&&clearTimeout(Q);let a=new Promise(e=>{Ta.push(e)}),o=$.get(t)??new Set;$.set(t,o),o.add(a),Q=setTimeout(()=>void Oa(),Ea);try{await a}finally{o.delete(a),o.size===0&&$.get(t)===o&&$.delete(t)}},Aa=async()=>{if(typeof window>`u`)return;let e=ha();try{let t=await oi();if(!t)return;let n=()=>ai(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{ar as $,De as $t,gi as A,Ge as An,Ot as At,Hr as B,mt as Bt,si as C,rt as Cn,Qt as Ct,li as D,Oe as Dn,kt as Dt,fi as E,Ee as En,zt as Et,jr as F,me as Fn,Zt as Ft,rr as G,Ke as Gt,Fr as H,E as Ht,Sr as I,fe as In,Ct as It,dr as J,Je as Jt,er as K,Ze as Kt,hr as L,le as Ln,Et as Lt,ti as M,_e as Mn,wt as Mt,ni as N,ge as Nn,Wt as Nt,hi as O,We as On,jt as Ot,Xr as P,ue as Pn,It as Pt,nr as Q,Te as Qt,mr as R,de as Rn,vt as Rt,K as S,Qe as Sn,O as St,ui as T,Ae as Tn,At as Tt,Vr as U,T as Ut,V,gt as Vt,Qn as W,x as Wt,pr as X,ke as Xt,fr as Y,ze as Yt,or as Z,et as Zt,Si as _,Be as _n,ln as _t,Da as a,C as an,Dn as at,xi as b,we as bn,tn as bt,Zi as c,ye as cn,Sn as ct,Gi as d,Ye as dn,$t as dt,be as en,sr as et,Ui as f,Xe as fn,en as ft,Ri as g,at as gn,sn as gt,Bi as h,tt as hn,F as ht,ka as i,nt as in,Jn as it,pi as j,Se as jn,Bt as jt,mi as k,Ie as kn,Mt as kt,Ki as l,Le as ln,xn as lt,zi as m,ot as mn,an as mt,Ca as n,b as nn,zn as nt,Xi as o,Fe as on,En as ot,Vi as p,qe as pn,P as pt,ur as q,st as qt,wa as r,S as rn,Kn as rt,Qi as s,y as sn,wn as st,Aa as t,xe as tn,z as tt,Wi as u,Re as un,bn as ut,yi as v,Ue as vn,rn as vt,di as w,it as wn,Tt as wt,G as x,$e as xn,nn as xt,bi as y,He as yn,dn as yt,Ir as z,_t as zt};