@yuriai/web 0.2.29-beta.5 → 0.2.29-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/assets/{AgentAvatar-GVufO03R.js → AgentAvatar-BNk56-Uq.js} +1 -1
  2. package/dist/assets/AssistantContactStatus-D0cP0UOu.js +3 -0
  3. package/dist/assets/{AssistantUnreadBadge-Xz7kMLSv.js → AssistantUnreadBadge-doY0Hft6.js} +1 -1
  4. package/dist/assets/{AssistantView-YVdgtBeh.js → AssistantView-B4mEblYi.js} +1 -1
  5. package/dist/assets/{DiagramView-DCrAY37j.js → DiagramView-Diyf4LSt.js} +1 -1
  6. package/dist/assets/{FadeInOnReveal-8NiBU75a.js → FadeInOnReveal-l6XCssmS.js} +1 -1
  7. package/dist/assets/{GuiPluginSurface-u815jFNI.js → GuiPluginSurface-rMZtD1SR.js} +1 -1
  8. package/dist/assets/{GuiPluginWindow-CW0-Tapi.js → GuiPluginWindow-DXfru2tW.js} +1 -1
  9. package/dist/assets/Icon-p_czvEI7.js +1 -0
  10. package/dist/assets/{ImageLoadingPlaceholder-DTWzB26a.js → ImageLoadingPlaceholder-Dg_CU5VT.js} +1 -1
  11. package/dist/assets/{LoadingImage-B89ghYMH.js → LoadingImage-CcML4X1d.js} +1 -1
  12. package/dist/assets/{MarkdownRenderer-DZXM92vp.js → MarkdownRenderer-DVKRLcN5.js} +2 -2
  13. package/dist/assets/{MarkdownRendererImpl-BLzRLmeZ.js → MarkdownRendererImpl-CzpxCCAo.js} +1 -1
  14. package/dist/assets/{MarkstreamRendererImpl-MqrsrtVx.js → MarkstreamRendererImpl-BRsSpYVn.js} +1 -1
  15. package/dist/assets/{MobileDetailNavigation-CozkWJ5y.js → MobileDetailNavigation-D_fj0utf.js} +1 -1
  16. package/dist/assets/{MobileResizableSheet-CAj4YGtu.js → MobileResizableSheet-B2GU_fkU.js} +1 -1
  17. package/dist/assets/{MobileShareBridge-yWj21Mpo.js → MobileShareBridge-Cr4nh-gT.js} +2 -2
  18. package/dist/assets/MobileTabPageHeader-l9R9cIsn.js +2 -0
  19. package/dist/assets/{MultiRunWindow-BDh7FxgY.js → MultiRunWindow-D22yagDA.js} +1 -1
  20. package/dist/assets/{OnboardingScreen-BdU6Tyax.js → OnboardingScreen-BYD95kJF.js} +1 -1
  21. package/dist/assets/{OverlayScrollbar-CzQC0JQI.js → OverlayScrollbar-CvwSam3X.js} +1 -1
  22. package/dist/assets/{SettingsView-C1dLufb0.js → SettingsView-wm-g9vvT.js} +11 -11
  23. package/dist/assets/{SettingsWindow-DZFZJ8PI.js → SettingsWindow-B_pQHcHp.js} +1 -1
  24. package/dist/assets/{TerminalView-2DhtuWTv.js → TerminalView-C8T2MbNS.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-COWWhGPD.js → ToolOutputDialog-CwOZ2rK4.js} +1 -1
  26. package/dist/assets/{YuriLogo-BZC0ckt0.js → YuriLogo-Bw8_KAED.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-CPa7wDcf.js → appThemeRegistry-CAryUA-D.js} +1 -1
  28. package/dist/assets/{assistant-attachment-cache-DMw2Smc8.js → assistant-attachment-cache-oatc8F4t.js} +1 -1
  29. package/dist/assets/{button-BF2cNEuq.js → button-DC4BhJtL.js} +1 -1
  30. package/dist/assets/{capgoAdapter-CQz-vZo-.js → capgoAdapter-n0GPI3Ea.js} +1 -1
  31. package/dist/assets/{collapsible-CS5qCQRU.js → collapsible-D87ZOJIG.js} +1 -1
  32. package/dist/assets/{context-menu-C6l4ycZG.js → context-menu-CD5IEDb5.js} +1 -1
  33. package/dist/assets/{diagram-D9-jif9d.js → diagram-BzzPtmNA.js} +1 -1
  34. package/dist/assets/{dialog-r7RRePv5.js → dialog-BCMKa538.js} +1 -1
  35. package/dist/assets/{dropdown-menu.styles-CX8oXdks.js → dropdown-menu.styles-DEOmf_B_.js} +1 -1
  36. package/dist/assets/{es-C8kGYKZo.js → es-C1m4Kl9P.js} +1 -1
  37. package/dist/assets/{fileMentionTouchSelection-dpFpcetU.js → fileMentionTouchSelection-PLpnmqHg.js} +1 -1
  38. package/dist/assets/{fileQueries-DWj9yB2g.js → fileQueries-C2Rs6TPz.js} +1 -1
  39. package/dist/assets/{fileReferenceActions-BBLYnGEx.js → fileReferenceActions-CvDFcgBH.js} +1 -1
  40. package/dist/assets/{fr-BV_9HcN9.js → fr-CnTFShIJ.js} +1 -1
  41. package/dist/assets/{gitApi-CXkfrI_H.js → gitApi-CP5napwr.js} +3 -3
  42. package/dist/assets/{gitApiHttp-DGAlAuET.js → gitApiHttp-Ddik7PM_.js} +1 -1
  43. package/dist/assets/{host-DB6QzbOw.js → host-D776RHTx.js} +1 -1
  44. package/dist/assets/{image-loading-BUouaouB.js → image-loading-DKQOYtti.js} +1 -1
  45. package/dist/assets/{input-DvF_mp0Y.js → input-BuAMQD1i.js} +1 -1
  46. package/dist/assets/insertionBoundaries-DxuIUK0X.js +1 -0
  47. package/dist/assets/{ja-CIMpz4Z2.js → ja-C975DGmU.js} +1 -1
  48. package/dist/assets/{ko-DPUsuWV1.js → ko-Donv-MLw.js} +1 -1
  49. package/dist/assets/{main-DuN735GT.js → main-CKdt6zYu.js} +2 -2
  50. package/dist/assets/{main-CJAnB1m1.js → main-CSNJQF6u.js} +12 -12
  51. package/dist/assets/{markdownHeightCache-D02GlOiy.js → markdownHeightCache-gGCb2TW0.js} +1 -1
  52. package/dist/assets/{mcpQueries-Ls770ehB.js → mcpQueries-BbNEHTru.js} +1 -1
  53. package/dist/assets/{miniChat-BibI1YhA.js → miniChat-Qg-TMzPz.js} +2 -2
  54. package/dist/assets/mobile-LXYsDpBs.js +2 -0
  55. package/dist/assets/{mobileBackNavigation-CXfKEN3p.js → mobileBackNavigation-BFnxHmcJ.js} +1 -1
  56. package/dist/assets/{multirun-CicU-KQt.js → multirun-B1BNFN80.js} +1 -1
  57. package/dist/assets/native-DsqzO52u.js +1 -0
  58. package/dist/assets/{native-config-BHa0LfdJ.js → native-config-CxrxYHct.js} +1 -1
  59. package/dist/assets/{persistence-Dta0OwIa.js → persistence-D-rnhgr4.js} +2 -2
  60. package/dist/assets/{pl-ChxP5OZm.js → pl-D22JxKm-.js} +1 -1
  61. package/dist/assets/{projectMeta-D3GYq5jV.js → projectMeta-D4-hBAf0.js} +1 -1
  62. package/dist/assets/{pt-BR-9N8nJVqC.js → pt-BR-D6NkqDFy.js} +1 -1
  63. package/dist/assets/{queryRuntime-CTcigFdj.js → queryRuntime-2dx7jbt9.js} +1 -1
  64. package/dist/assets/{queue-abort-optimistic-DRJa-BrH.js → queue-abort-optimistic-Bix-IUrI.js} +1 -1
  65. package/dist/assets/{readiness-lO-fOlzd.js → readiness-Bo2P-IXf.js} +1 -1
  66. package/dist/assets/{renderElectronMiniChatApp-DnzgZv3d.js → renderElectronMiniChatApp-C1vzQUQn.js} +2 -2
  67. package/dist/assets/{renderMobileApp-DLFGqfxp.js → renderMobileApp-Bxlepbqn.js} +7 -7
  68. package/dist/assets/{runtime-file-download-o29morT6.js → runtime-file-download-D6bwc3Kj.js} +1 -1
  69. package/dist/assets/{runtime-file-resource-qB_oVdE6.js → runtime-file-resource-BP4P52ry.js} +1 -1
  70. package/dist/assets/{runtimeConfig-Be6cMHuS.js → runtimeConfig-DmZoakxE.js} +1 -1
  71. package/dist/assets/{runtimeEndpointReset-DeWcqIyJ.js → runtimeEndpointReset-CGWAfy_Y.js} +15 -15
  72. package/dist/assets/{scheduledTaskNavigation-BqkeRfVc.js → scheduledTaskNavigation-Bp5rGr3m.js} +1 -1
  73. package/dist/assets/sessionLookup-CgL50yRb.js +1 -0
  74. package/dist/assets/{sortable-tabs-strip-Dc4Jr4ml.js → sortable-tabs-strip-2alRozPo.js} +1 -1
  75. package/dist/assets/{speechSettingsQueries-CsCKPsRU.js → speechSettingsQueries-BHjkhNvX.js} +3 -3
  76. package/dist/assets/{src-DME3XM8W.css → src-EZMbcCtg.css} +1 -1
  77. package/dist/assets/{store-BPYoxYhv.js → store-XWRveCM0.js} +2 -2
  78. package/dist/assets/{terminalApi-CPVNQ5DH.js → terminalApi-ChZhb60_.js} +1 -1
  79. package/dist/assets/{textarea-CIhiRPB2.js → textarea-Cj7oz4TZ.js} +1 -1
  80. package/dist/assets/{tooltip-BoAbDVNP.js → tooltip-BUDeDvMc.js} +1 -1
  81. package/dist/assets/{types-CTkS0uZU.js → types-D7m_3iXu.js} +1 -1
  82. package/dist/assets/{uk-C-aeGNQI.js → uk-DEV7vjeo.js} +1 -1
  83. package/dist/assets/{useAppFontEffects-Cs_0mUpl.js → useAppFontEffects-DupRRD7K.js} +28 -28
  84. package/dist/assets/{useAssistantUIStore-CYyXdd5c.js → useAssistantUIStore-BI_dAUjx.js} +1 -1
  85. package/dist/assets/{useDesktopWindowControlsLayout-avf-_JWZ.js → useDesktopWindowControlsLayout-DBGiDEmg.js} +1 -1
  86. package/dist/assets/{useEffectiveDirectory-esZ8PL08.js → useEffectiveDirectory-DB5tS-o5.js} +1 -1
  87. package/dist/assets/{useFontPreferences-UzjDmx4b.js → useFontPreferences-EsJ4FlIp.js} +1 -1
  88. package/dist/assets/{useMobileNavigationStore-9lAGHZos.js → useMobileNavigationStore-BsWXpW7G.js} +14 -14
  89. package/dist/assets/useUIStore-CoWJ3ROq.js +1 -0
  90. package/dist/assets/{useWorkerHighlightedLines-BxqdOw1S.js → useWorkerHighlightedLines-B76dqB8T.js} +1 -1
  91. package/dist/assets/vendor-tanstack-query-core-Y_YoRHtC.js +1 -0
  92. package/dist/assets/vendor-tanstack-react-query-B-Wpqq5J.js +1 -0
  93. package/dist/assets/{zh-CN-DOchDQti.js → zh-CN-6GRNLBLK.js} +1 -1
  94. package/dist/assets/{zh-TW-Dtigv2CE.js → zh-TW-7oorZFq9.js} +1 -1
  95. package/dist/index.html +16 -16
  96. package/dist/mini-chat.html +16 -16
  97. package/dist/mobile.html +16 -16
  98. package/package.json +1 -1
  99. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  100. package/server/lib/opencode/settings-helpers.js +0 -3
  101. package/server/lib/opencode/settings-helpers.test.js +8 -0
  102. package/server/lib/opencode/static-routes-runtime.js +5 -3
  103. package/server/lib/opencode/static-routes-runtime.test.js +23 -10
  104. package/dist/assets/AssistantContactStatus-B67HXRUY.js +0 -3
  105. package/dist/assets/Icon-CLLDJn-P.js +0 -1
  106. package/dist/assets/MobileTabPageHeader-BSbOGw3M.js +0 -2
  107. package/dist/assets/insertionBoundaries-CmxtGojv.js +0 -1
  108. package/dist/assets/mobile-DNvOl_GU.js +0 -2
  109. package/dist/assets/native-CILcYDJz.js +0 -1
  110. package/dist/assets/sessionLookup-qvz-n65R.js +0 -1
  111. package/dist/assets/useUIStore-BDZCXouA.js +0 -1
  112. package/dist/assets/vendor-tanstack-query-core-BWz0ose6.js +0 -1
  113. package/dist/assets/vendor-tanstack-react-query-B2psfNaU.js +0 -1
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,n}from"./runtime-switch-DEZ1K7qW.js";import{n as r}from"./runtime-fetch-D0YWp3FJ.js";import{t as i}from"./runtimeAPIRegistry-C2VogTny.js";import{$ as a,A as o,At as s,D as c,F as l,G as u,H as d,I as f,J as p,K as m,M as ee,P as te,S as ne,T as re,U as ie,X as ae,Y as oe,_ as se,a as ce,b as le,c as ue,d as de,et as fe,f as pe,ft as me,gt as he,h as ge,ht as _e,k as ve,m as ye,nt as be,ot as xe,pt as Se,q as Ce,r as we,s as Te,st as Ee,tt as De,ut as Oe,v as ke,vt as Ae,x as je,y as Me}from"./gitApiHttp-DGAlAuET.js";import{p as h,u as Ne,wi as g}from"./useMobileNavigationStore-9lAGHZos.js";var _=`/api/magic-prompts`,Pe=new Map([{id:`git.commit.generate.visible`,title:`Commit Generation Visible Prompt`,group:`Git`,description:`Visible user message for commit message generation.`,template:`You are generating a Conventional Commits subject line from the diffs of the selected files.`},{id:`git.commit.generate.instructions`,title:`Commit Generation Instructions`,group:`Git`,description:`Hidden instructions for commit message generation.`,placeholders:[{key:`selected_files`,description:`Bullet list of currently selected file paths.`}],template:`Return exactly one JSON object and nothing else. Do not include prose, markdown, explanations, or code fences.
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,n}from"./runtime-switch-DEZ1K7qW.js";import{n as r}from"./runtime-fetch-D0YWp3FJ.js";import{t as i}from"./runtimeAPIRegistry-C2VogTny.js";import{$ as a,A as o,At as s,D as c,F as l,G as u,H as d,I as f,J as p,K as m,M as ee,P as te,S as ne,T as re,U as ie,X as ae,Y as oe,_ as se,a as ce,b as le,c as ue,d as de,et as fe,f as pe,ft as me,gt as he,h as ge,ht as _e,k as ve,m as ye,nt as be,ot as xe,pt as Se,q as Ce,r as we,s as Te,st as Ee,tt as De,ut as Oe,v as ke,vt as Ae,x as je,y as Me}from"./gitApiHttp-Ddik7PM_.js";import{Di as h,p as g,u as Ne}from"./useMobileNavigationStore-BsWXpW7G.js";var _=`/api/magic-prompts`,Pe=new Map([{id:`git.commit.generate.visible`,title:`Commit Generation Visible Prompt`,group:`Git`,description:`Visible user message for commit message generation.`,template:`You are generating a Conventional Commits subject line from the diffs of the selected files.`},{id:`git.commit.generate.instructions`,title:`Commit Generation Instructions`,group:`Git`,description:`Hidden instructions for commit message generation.`,placeholders:[{key:`selected_files`,description:`Bullet list of currently selected file paths.`}],template:`Return exactly one JSON object and nothing else. Do not include prose, markdown, explanations, or code fences.
2
2
 
3
3
  The JSON object must have exactly this shape:
4
4
  {"subject": string, "highlights": string[]}
@@ -362,9 +362,9 @@ Use the results below as source material. Do not mention that the inputs were hi
362
362
  `)||`--- ${t} (no textual diff available)`}catch{return`--- ${t} (diff unavailable)`}})),a=``,s=0,c=!1;for(let e of i){let t=a?`
363
363
 
364
364
  `:``;if(a.length+t.length+e.length>12e4){a+=`
365
- [remaining diffs truncated by char budget — not a full selected-set dump]`,c=!0;break}a+=t+e,s+=1}let l=Math.max(0,n-r.length),u=l+(c?Math.max(0,r.length-s):0);l>0&&(a+=`\n[${l} more selected files omitted by file budget — not included]`);let d={selectedFileCount:n,includedFileCount:s,omittedFileCount:u,truncatedByCharLimit:c,fileLimit:30,charLimit:L};return{...d,text:a,budgetNote:Ye(d)}}var B=e=>{let t=typeof e?.subject==`string`?e.subject.trim():``,n=Array.isArray(e?.highlights)?e.highlights.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean).slice(0,3):[];if(!t)throw Error(`Structured output missing subject`);return{subject:t,highlights:n}},Xe=(e,t)=>{if(t?.aborted)return!0;if(!e||typeof e!=`object`)return!1;let n=`name`in e?String(e.name??``):``;return n===`AbortError`||n===`TimeoutError`},Ze=e=>{let t=new AbortController,n=()=>{try{t.abort(e?.reason)}catch{t.abort()}};e&&(e.aborted?n():e.addEventListener(`abort`,n,{once:!0}));let r=setTimeout(()=>{let e=new DOMException(`session.generate timed out after ${R}ms`,`TimeoutError`);try{t.abort(e)}catch{t.abort()}},R);return{signal:t.signal,cleanup:()=>{clearTimeout(r),e&&e.removeEventListener(`abort`,n)}}};async function Qe(){let e=h.getState().currentSessionId;if(typeof e==`string`&&e.trim())return e.trim();if(!h.getState().newSessionDraft?.open)throw Error(We);let t=g.getState();if(!t.currentProviderId||!t.currentModelId)throw Error(Ge);let n=await Ne({providerID:t.currentProviderId,modelID:t.currentModelId,agent:t.currentAgentName||void 0,variant:t.currentVariant||void 0});if(n?.sessionId)return n.sessionId;let r=h.getState().currentSessionId;if(typeof r==`string`&&r.trim())return r.trim();throw Error(`Failed to create session for generation`)}async function $e(e){let r={sessionId:await Qe(),directory:e.directory,kind:e.kind,runtimeGeneration:n(),runtimeTransport:t()},i=typeof e.prompt==`string`?e.prompt.trim():``;if(!i)throw Error(`Generation prompts are empty`);let{signal:a,cleanup:o}=Ze(e.signal),c=Date.now();r.kind,r.directory,r.sessionId,i.length;try{a.throwIfAborted();let e=await s.generateSessionAside({sessionId:r.sessionId,directory:r.directory,prompt:i,signal:a});if(n()!==r.runtimeGeneration||t()!==r.runtimeTransport)throw Error(Ke);let o=typeof e?.text==`string`?e.text.trim():``;if(!o)throw Error(qe);let l=E(o);if(!l)throw console.error(`[git-generation][browser] invalid JSON from session.generate`,{kind:r.kind,sessionId:r.sessionId,elapsedMs:Date.now()-c,textPreview:o.slice(0,400)}),Error(Je);return r.kind,r.sessionId,Date.now()-c,o.length,l}catch(e){if(Xe(e,a)){let e=a.reason instanceof Error?a.reason.message:typeof a.reason==`string`&&a.reason.trim()?a.reason:`session.generate cancelled`;throw new DOMException(e,a.reason instanceof DOMException?a.reason.name:`AbortError`)}throw e}finally{o()}}var et=(e,t)=>[Ue,typeof e==`string`?e.trim():``,typeof t==`string`?t.trim():``].filter(Boolean).join(`
365
+ [remaining diffs truncated by char budget — not a full selected-set dump]`,c=!0;break}a+=t+e,s+=1}let l=Math.max(0,n-r.length),u=l+(c?Math.max(0,r.length-s):0);l>0&&(a+=`\n[${l} more selected files omitted by file budget — not included]`);let d={selectedFileCount:n,includedFileCount:s,omittedFileCount:u,truncatedByCharLimit:c,fileLimit:30,charLimit:L};return{...d,text:a,budgetNote:Ye(d)}}var B=e=>{let t=typeof e?.subject==`string`?e.subject.trim():``,n=Array.isArray(e?.highlights)?e.highlights.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean).slice(0,3):[];if(!t)throw Error(`Structured output missing subject`);return{subject:t,highlights:n}},Xe=(e,t)=>{if(t?.aborted)return!0;if(!e||typeof e!=`object`)return!1;let n=`name`in e?String(e.name??``):``;return n===`AbortError`||n===`TimeoutError`},Ze=e=>{let t=new AbortController,n=()=>{try{t.abort(e?.reason)}catch{t.abort()}};e&&(e.aborted?n():e.addEventListener(`abort`,n,{once:!0}));let r=setTimeout(()=>{let e=new DOMException(`session.generate timed out after ${R}ms`,`TimeoutError`);try{t.abort(e)}catch{t.abort()}},R);return{signal:t.signal,cleanup:()=>{clearTimeout(r),e&&e.removeEventListener(`abort`,n)}}};async function Qe(){let e=g.getState().currentSessionId;if(typeof e==`string`&&e.trim())return e.trim();if(!g.getState().newSessionDraft?.open)throw Error(We);let t=h.getState();if(!t.currentProviderId||!t.currentModelId)throw Error(Ge);let n=await Ne({providerID:t.currentProviderId,modelID:t.currentModelId,agent:t.currentAgentName||void 0,variant:t.currentVariant||void 0});if(n?.sessionId)return n.sessionId;let r=g.getState().currentSessionId;if(typeof r==`string`&&r.trim())return r.trim();throw Error(`Failed to create session for generation`)}async function $e(e){let r={sessionId:await Qe(),directory:e.directory,kind:e.kind,runtimeGeneration:n(),runtimeTransport:t()},i=typeof e.prompt==`string`?e.prompt.trim():``;if(!i)throw Error(`Generation prompts are empty`);let{signal:a,cleanup:o}=Ze(e.signal),c=Date.now();r.kind,r.directory,r.sessionId,i.length;try{a.throwIfAborted();let e=await s.generateSessionAside({sessionId:r.sessionId,directory:r.directory,prompt:i,signal:a});if(n()!==r.runtimeGeneration||t()!==r.runtimeTransport)throw Error(Ke);let o=typeof e?.text==`string`?e.text.trim():``;if(!o)throw Error(qe);let l=E(o);if(!l)throw console.error(`[git-generation][browser] invalid JSON from session.generate`,{kind:r.kind,sessionId:r.sessionId,elapsedMs:Date.now()-c,textPreview:o.slice(0,400)}),Error(Je);return r.kind,r.sessionId,Date.now()-c,o.length,l}catch(e){if(Xe(e,a)){let e=a.reason instanceof Error?a.reason.message:typeof a.reason==`string`&&a.reason.trim()?a.reason:`session.generate cancelled`;throw new DOMException(e,a.reason instanceof DOMException?a.reason.name:`AbortError`)}throw e}finally{o()}}var et=(e,t)=>[Ue,typeof e==`string`?e.trim():``,typeof t==`string`?t.trim():``].filter(Boolean).join(`
366
366
 
367
367
  `);async function V(e,t,n){let i=Date.now(),a=n?.signal;n?.zenModel,n?.providerId,n?.modelId,t.length;let o=await w(`git.commit.generate.visible`),s=await w(`git.commit.generate.instructions`,{selected_files:t.map(e=>`- ${e}`).join(`
368
368
  `)});try{a?.throwIfAborted();let n=await z(e,t),c=[s,n.budgetNote,`Diffs of the selected files (budget-aligned; see note above):`,n.text].join(`
369
369
 
370
- `),{currentProviderId:l,currentModelId:u}=g.getState(),d=await r(`/api/small-model/generate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({purpose:`commit`,system:o,prompt:c,directory:e,...l?{preferredProviderID:l}:{},...u?{preferredModelID:u}:{}}),...a?{signal:a}:{}});if(d.status===404){t.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,c.length;let r={message:B(await $e({directory:e,prompt:et(o,c),kind:`commit`,signal:a}))};return Date.now()-i,r.message.subject.length,r.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,r}let f=await d.json().catch(()=>null);if(!d.ok||typeof f?.text!=`string`){let e=typeof f?.error==`string`?f.error:`HTTP ${d.status}`;throw Error(e)}let p={message:B(E(f.text))};return Date.now()-i,p.message.subject.length,p.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,p}catch(e){throw console.error(`[git-generation][browser] failed`,{transport:`small-model|session.generate`,kind:`commit`,elapsedMs:Date.now()-i,message:e instanceof Error?e.message:String(e),error:e}),e}}async function H(e){let t=T();if(!t)return m(e);let n=t.worktree?.list??t.listGitWorktrees;if(ie(n))return m(e);let r=t.worktree?.list?t.worktree.list.bind(t.worktree):t.listGitWorktrees.bind(t);return Ae(()=>r(e))}async function U(e,t){let n=T();return n?.worktree?.validate?n.worktree.validate(e,t):n?.validateGitWorktree?n.validateGitWorktree(e,t):he(e,t)}async function W(e){let t=T();return t?.worktree?.bootstrapStatus?t.worktree.bootstrapStatus(e):t?.getGitWorktreeBootstrapStatus?t.getGitWorktreeBootstrapStatus(e):l(e)}async function G(e,t){let n=T();return n?.worktree?.preview?n.worktree.preview(e,t):n?.previewGitWorktree?n.previewGitWorktree(e,t):oe(e,t)}async function K(e,t){let n=T(),r;return r=n?.worktree?.create?await n.worktree.create(e,t):n?.createGitWorktree?await n.createGitWorktree(e,t):await ge(e,t),d(e),r}async function q(e,t){let n=T(),r;return r=n?.worktree?.remove?await n.worktree.remove(e,t):n?.deleteGitWorktree?await n.deleteGitWorktree(e,t):await ke(e,t),d(e),r}var J={worktree:{list:H,validate:U,create:K,remove:q}};async function Y(e){let t=T();return t?t.listGitStashes(e):u(e)}async function X(e,t){let n=T();return n?n.countGitStashFiles(e,t):de(e,t)}async function Z(e,t={}){let n=T();return n?n.stashGitChanges(e,t):Oe(e,t)}async function tt(e,t){let n=T();return n?n.applyGitStash(e,t):we(e,t)}async function nt(e,t){let n=T();return n?n.popGitStash(e,t):p(e,t)}async function Q(e,t){let n=T();return n?n.dropGitStash(e,t):ne(e,t)}async function rt(e,t,n){let r=T();return r?r.createBranch(e,t,n):pe(e,t,n)}async function it(e,t,n,r){let i=T();return i?.getCommitFileDiff?i.getCommitFileDiff(e,t,n,r):re(e,t,n,r)}async function at(){let e=T();return e?e.getGitIdentities():ee()}async function ot(e){let t=T();return t?t.createGitIdentity(e):ye(e)}async function st(e,t){let n=T();return n?n.updateGitIdentity(e,t):_e(e,t)}async function ct(e){let t=T();return t?t.deleteGitIdentity(e):se(e)}async function lt(){let e=T();return e?.discoverGitCredentials?e.discoverGitCredentials():le()}async function ut(){let e=T();return e?.getGlobalGitIdentity?e.getGlobalGitIdentity():f()}async function dt(e,t){let n=T();return n?n.rebase(e,t):ae(e,t)}async function ft(e,t){let n=T();return n?n.merge(e,t):Ce(e,t)}async function pt(e,t){let n=T();return n?n.checkoutCommit(e,t):Te(e,t)}async function mt(e,t){let n=T();return n?n.cherryPick(e,t):ue(e,t)}async function ht(e,t){let n=T();return n?n.revertCommit(e,t):be(e,t)}async function gt(e,t,n,r){let i=T();return i?i.resetToCommit(e,t,n,r):a(e,t,n,r)}async function $(e){let t=T();return t?.getConflictDetails?t.getConflictDetails(e):c(e)}export{j as A,S as B,Y as C,dt as D,G as E,N as F,Be as H,P as I,st as L,M,He as N,gt as O,Z as P,x as R,Ve as S,nt as T,ze as U,w as V,Re as W,at as _,X as a,ut as b,ct as c,O as d,Q as f,F as g,$ as h,mt as i,ht as j,A as k,I as l,it as m,D as n,rt as o,V as p,pt as r,ot as s,tt as t,lt as u,k as v,ft as w,J as x,W as y,C as z};
370
+ `),{currentProviderId:l,currentModelId:u}=h.getState(),d=await r(`/api/small-model/generate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({purpose:`commit`,system:o,prompt:c,directory:e,...l?{preferredProviderID:l}:{},...u?{preferredModelID:u}:{}}),...a?{signal:a}:{}});if(d.status===404){t.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,c.length;let r={message:B(await $e({directory:e,prompt:et(o,c),kind:`commit`,signal:a}))};return Date.now()-i,r.message.subject.length,r.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,r}let f=await d.json().catch(()=>null);if(!d.ok||typeof f?.text!=`string`){let e=typeof f?.error==`string`?f.error:`HTTP ${d.status}`;throw Error(e)}let p={message:B(E(f.text))};return Date.now()-i,p.message.subject.length,p.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,p}catch(e){throw console.error(`[git-generation][browser] failed`,{transport:`small-model|session.generate`,kind:`commit`,elapsedMs:Date.now()-i,message:e instanceof Error?e.message:String(e),error:e}),e}}async function H(e){let t=T();if(!t)return m(e);let n=t.worktree?.list??t.listGitWorktrees;if(ie(n))return m(e);let r=t.worktree?.list?t.worktree.list.bind(t.worktree):t.listGitWorktrees.bind(t);return Ae(()=>r(e))}async function U(e,t){let n=T();return n?.worktree?.validate?n.worktree.validate(e,t):n?.validateGitWorktree?n.validateGitWorktree(e,t):he(e,t)}async function W(e){let t=T();return t?.worktree?.bootstrapStatus?t.worktree.bootstrapStatus(e):t?.getGitWorktreeBootstrapStatus?t.getGitWorktreeBootstrapStatus(e):l(e)}async function G(e,t){let n=T();return n?.worktree?.preview?n.worktree.preview(e,t):n?.previewGitWorktree?n.previewGitWorktree(e,t):oe(e,t)}async function K(e,t){let n=T(),r;return r=n?.worktree?.create?await n.worktree.create(e,t):n?.createGitWorktree?await n.createGitWorktree(e,t):await ge(e,t),d(e),r}async function q(e,t){let n=T(),r;return r=n?.worktree?.remove?await n.worktree.remove(e,t):n?.deleteGitWorktree?await n.deleteGitWorktree(e,t):await ke(e,t),d(e),r}var J={worktree:{list:H,validate:U,create:K,remove:q}};async function Y(e){let t=T();return t?t.listGitStashes(e):u(e)}async function X(e,t){let n=T();return n?n.countGitStashFiles(e,t):de(e,t)}async function Z(e,t={}){let n=T();return n?n.stashGitChanges(e,t):Oe(e,t)}async function tt(e,t){let n=T();return n?n.applyGitStash(e,t):we(e,t)}async function nt(e,t){let n=T();return n?n.popGitStash(e,t):p(e,t)}async function Q(e,t){let n=T();return n?n.dropGitStash(e,t):ne(e,t)}async function rt(e,t,n){let r=T();return r?r.createBranch(e,t,n):pe(e,t,n)}async function it(e,t,n,r){let i=T();return i?.getCommitFileDiff?i.getCommitFileDiff(e,t,n,r):re(e,t,n,r)}async function at(){let e=T();return e?e.getGitIdentities():ee()}async function ot(e){let t=T();return t?t.createGitIdentity(e):ye(e)}async function st(e,t){let n=T();return n?n.updateGitIdentity(e,t):_e(e,t)}async function ct(e){let t=T();return t?t.deleteGitIdentity(e):se(e)}async function lt(){let e=T();return e?.discoverGitCredentials?e.discoverGitCredentials():le()}async function ut(){let e=T();return e?.getGlobalGitIdentity?e.getGlobalGitIdentity():f()}async function dt(e,t){let n=T();return n?n.rebase(e,t):ae(e,t)}async function ft(e,t){let n=T();return n?n.merge(e,t):Ce(e,t)}async function pt(e,t){let n=T();return n?n.checkoutCommit(e,t):Te(e,t)}async function mt(e,t){let n=T();return n?n.cherryPick(e,t):ue(e,t)}async function ht(e,t){let n=T();return n?n.revertCommit(e,t):be(e,t)}async function gt(e,t,n,r){let i=T();return i?i.resetToCommit(e,t,n,r):a(e,t,n,r)}async function $(e){let t=T();return t?.getConflictDetails?t.getConflictDetails(e):c(e)}export{j as A,S as B,Y as C,dt as D,G as E,N as F,Be as H,P as I,st as L,M,He as N,gt as O,Z as P,x as R,Ve as S,nt as T,ze as U,w as V,Re as W,at as _,X as a,ut as b,ct as c,O as d,Q as f,F as g,$ as h,mt as i,ht as j,A as k,I as l,it as m,D as n,rt as o,V as p,pt as r,ot as s,tt as t,lt as u,k as v,ft as w,J as x,W as y,C as z};
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-DgJnLT1Y.js","assets/rolldown-runtime-hePW80VL.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{C as t,D as n,k as r}from"./runtime-auth-DBn9yahL.js";import{c as i,f as a,i as o,n as s,r as c,s as l}from"./runtime-switch-DEZ1K7qW.js";import{n as u}from"./runtime-fetch-D0YWp3FJ.js";import{l as d,w as f}from"./desktop-JwYqThiw.js";import{t as p}from"./runtimeAPIRegistry-C2VogTny.js";import{a as m,r as h}from"./vendor-zustand-vDaAPGfl.js";import{st as g}from"./vendor-base-ui-CzHs0bHY.js";import{B as ee,R as te,V as ne}from"./vendor-opencode-client-cQ47ywrT.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{S as re}from"./useUIStore-BDZCXouA.js";import{It as ie,Pt as ae,at as oe,ft as se,i as ce,ot as le,tt as ue,vt as de}from"./persistence-Dta0OwIa.js";import{n as fe}from"./vendor-react-DlzBev0S.js";import{i as pe}from"./vendor-pathe-vBmvQE8f.js";import{n as me}from"./runtime-file-resource-qB_oVdE6.js";import{o as he}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";var ge=(e,t)=>e!==t,_=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0};function _e(e){let t=_(e.id),n=_(e.name),r=_(e.displayName),i=t??n;if(!i)return{...e,id:``,name:``,displayName:r??``};if(n===i&&r)return{...e,id:i,name:i,displayName:r};let a=r??n??i;return{...e,id:i,name:i,displayName:a}}function ve(e){return e?_(e.displayName)??_(e.name)??_(e.id)??``:``}function ye(e,t){let n=_(t);if(!n||!e?.length)return;let r=e.find(e=>_(e.name)===n);if(r)return r;let i=e.find(e=>_(e.id)===n);if(i)return i;let a=e.find(e=>_(e.displayName)===n);if(a)return a}function be(e,t){let n=_(t);if(!n)return;let r=ye(e,n);return r?_(r.name)??_(r.id)??n:n}function xe(e){return Array.from(new Set(Array.from(e.matchAll(de()),e=>e[1])),e=>({id:e,name:e}))}function v(e){return{...e,directory:e.location?.directory}}function Se(e){let t={};for(let n of e){let e=n;!e||e.type!==`document`||!e.info||typeof e.info!=`object`||Object.assign(t,e.info)}return t}var y=e(g(),1),Ce=fe();function b(e,t){return e.findIndex(e=>e.id===t)}function we(e,t){if(!t)return e.slice();let n=b(e,t);return n<0?e.slice():e.slice(0,n)}function Te(e,t,n){let r=b(e,n);return r<0?!1:b(e,t)>=r}function Ee(e,t){if(!t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}return}let n=b(e,t);if(!(n<0))for(let t=n-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}}function De(e,t){let n=b(e,t);if(!(n<0))for(let t=n+1;t<e.length;t+=1){let n=e[t];if(n?.role===`user`)return n}}var Oe=`yuri:sync:debug`,ke;function Ae(){if(ke!==void 0)return ke;try{ke=typeof localStorage<`u`&&localStorage.getItem(Oe)===`1`}catch{ke=!1}return ke}function x(e,...t){Ae()&&(`${e}`,[...t])}var je={pipeline:{coalesced:(e,t)=>x(`pipeline`,`coalesced`,e,t),flush:e=>x(`pipeline`,`flush`,`${e} events`)},reducer:{messageUpdatedUnchanged:(e,t,n,r,i)=>x(`reducer`,`message.updated UNCHANGED (skipped)`,{sessionID:e,messageID:t,role:n,finish:r,completed:i}),partUpdatedNoExistingParts:(e,t,n)=>x(`reducer`,`message.part.updated NO EXISTING PARTS`,{messageID:e,partID:t,partType:n}),partDeltaNoParts:(e,t)=>x(`reducer`,`message.part.delta DROPPED (no parts array)`,{messageID:e,partID:t}),partDeltaNotFound:(e,t)=>x(`reducer`,`message.part.delta DROPPED (partID not found)`,{messageID:e,partID:t}),partSkipped:(e,t,n)=>x(`reducer`,`message.part.updated SKIPPED (type filtered)`,{messageID:e,partID:t,partType:n})},dispatch:{eventNoChange:(e,t,n)=>x(`dispatch`,`event → no change`,{eventType:e,sessionID:t,messageID:n}),eventApplied:(e,t,n)=>x(`dispatch`,`event → applied`,{eventType:e,sessionID:t,messageID:n})},recovery:{materializing:e=>x(`recovery`,`materializing session`,e)}};function Me(e,t){let n=new Set(t),r=new Map,i=[],a;for(let t of e){if(!n.has(t)){i.push(t);continue}i.length>0&&r.set(t,i),i=[],a=t}let o=[],s=new Set,c=e=>{s.has(e)||(s.add(e),o.push(e))};for(let e of t){for(let t of r.get(e)??[])c(t);if(c(e),e===a)for(let e of i)c(e)}if(!a)for(let e of i)c(e);return o}var Ne=`desc`;function Pe(e){return!S(e)||e.type!==`compaction`?!1:e.status===`running`||e.status===`completed`||e.status===`failed`}function Fe(e){if(e)return e.find(Pe)}var Ie=e=>e?e.toLowerCase().includes(`application/json`):!1,Le=e=>e?e.toLowerCase().includes(`text/html`):!1;function S(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function C(e){return typeof e==`string`&&e.length>0?e:void 0}function Re(e){if(!S(e))return null;let t=C(e.id);return t?{...e,id:t}:null}function ze(e,t,n){return`${e}:${t}:${n}`}function Be(e,t,n,r,i=`text`,a){return i===`reasoning`?{id:ze(t,i,n),sessionID:e,messageID:t,type:`reasoning`,text:r}:{id:ze(t,i,n),sessionID:e,messageID:t,type:`text`,text:r,...a?.synthetic===!0?{synthetic:!0}:{}}}function Ve(e){return e?e.nativeType===`synthetic`||e.type===`synthetic`:!1}function He(e,t){return!e?.id||Ve(e)||(e.clientRole??e.role)!==`user`?!1:!Array.isArray(t)||t.length===0||!(t.some(e=>e.type===`subtask`||e.type===`compaction`)||t.every(e=>!!e.synthetic))}function Ue(e){if(typeof e==`string`&&e.length!==0)return e.replace(/^evt_/,`msg_`)}function We(e){let t=e.content;return Array.isArray(t)?t.flatMap(e=>S(e)&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{C as t,D as n,k as r}from"./runtime-auth-DBn9yahL.js";import{c as i,f as a,i as o,n as s,r as c,s as l}from"./runtime-switch-DEZ1K7qW.js";import{n as u}from"./runtime-fetch-D0YWp3FJ.js";import{l as d,w as f}from"./desktop-JwYqThiw.js";import{t as p}from"./runtimeAPIRegistry-C2VogTny.js";import{a as m,r as h}from"./vendor-zustand-vDaAPGfl.js";import{st as g}from"./vendor-base-ui-CzHs0bHY.js";import{B as ee,R as te,V as ne}from"./vendor-opencode-client-cQ47ywrT.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{S as re}from"./useUIStore-CoWJ3ROq.js";import{It as ie,Pt as ae,at as oe,ft as se,i as ce,ot as le,tt as ue,vt as de}from"./persistence-D-rnhgr4.js";import{n as fe}from"./vendor-react-DlzBev0S.js";import{i as pe}from"./vendor-pathe-vBmvQE8f.js";import{n as me}from"./runtime-file-resource-BP4P52ry.js";import{o as he}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";var ge=(e,t)=>e!==t,_=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0};function _e(e){let t=_(e.id),n=_(e.name),r=_(e.displayName),i=t??n;if(!i)return{...e,id:``,name:``,displayName:r??``};if(n===i&&r)return{...e,id:i,name:i,displayName:r};let a=r??n??i;return{...e,id:i,name:i,displayName:a}}function ve(e){return e?_(e.displayName)??_(e.name)??_(e.id)??``:``}function ye(e,t){let n=_(t);if(!n||!e?.length)return;let r=e.find(e=>_(e.name)===n);if(r)return r;let i=e.find(e=>_(e.id)===n);if(i)return i;let a=e.find(e=>_(e.displayName)===n);if(a)return a}function be(e,t){let n=_(t);if(!n)return;let r=ye(e,n);return r?_(r.name)??_(r.id)??n:n}function xe(e){return Array.from(new Set(Array.from(e.matchAll(de()),e=>e[1])),e=>({id:e,name:e}))}function v(e){return{...e,directory:e.location?.directory}}function Se(e){let t={};for(let n of e){let e=n;!e||e.type!==`document`||!e.info||typeof e.info!=`object`||Object.assign(t,e.info)}return t}var y=e(g(),1),Ce=fe();function b(e,t){return e.findIndex(e=>e.id===t)}function we(e,t){if(!t)return e.slice();let n=b(e,t);return n<0?e.slice():e.slice(0,n)}function Te(e,t,n){let r=b(e,n);return r<0?!1:b(e,t)>=r}function Ee(e,t){if(!t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}return}let n=b(e,t);if(!(n<0))for(let t=n-1;t>=0;--t){let n=e[t];if(n?.role===`user`)return n}}function De(e,t){let n=b(e,t);if(!(n<0))for(let t=n+1;t<e.length;t+=1){let n=e[t];if(n?.role===`user`)return n}}var Oe=`yuri:sync:debug`,ke;function Ae(){if(ke!==void 0)return ke;try{ke=typeof localStorage<`u`&&localStorage.getItem(Oe)===`1`}catch{ke=!1}return ke}function x(e,...t){Ae()&&(`${e}`,[...t])}var je={pipeline:{coalesced:(e,t)=>x(`pipeline`,`coalesced`,e,t),flush:e=>x(`pipeline`,`flush`,`${e} events`)},reducer:{messageUpdatedUnchanged:(e,t,n,r,i)=>x(`reducer`,`message.updated UNCHANGED (skipped)`,{sessionID:e,messageID:t,role:n,finish:r,completed:i}),partUpdatedNoExistingParts:(e,t,n)=>x(`reducer`,`message.part.updated NO EXISTING PARTS`,{messageID:e,partID:t,partType:n}),partDeltaNoParts:(e,t)=>x(`reducer`,`message.part.delta DROPPED (no parts array)`,{messageID:e,partID:t}),partDeltaNotFound:(e,t)=>x(`reducer`,`message.part.delta DROPPED (partID not found)`,{messageID:e,partID:t}),partSkipped:(e,t,n)=>x(`reducer`,`message.part.updated SKIPPED (type filtered)`,{messageID:e,partID:t,partType:n})},dispatch:{eventNoChange:(e,t,n)=>x(`dispatch`,`event → no change`,{eventType:e,sessionID:t,messageID:n}),eventApplied:(e,t,n)=>x(`dispatch`,`event → applied`,{eventType:e,sessionID:t,messageID:n})},recovery:{materializing:e=>x(`recovery`,`materializing session`,e)}};function Me(e,t){let n=new Set(t),r=new Map,i=[],a;for(let t of e){if(!n.has(t)){i.push(t);continue}i.length>0&&r.set(t,i),i=[],a=t}let o=[],s=new Set,c=e=>{s.has(e)||(s.add(e),o.push(e))};for(let e of t){for(let t of r.get(e)??[])c(t);if(c(e),e===a)for(let e of i)c(e)}if(!a)for(let e of i)c(e);return o}var Ne=`desc`;function Pe(e){return!S(e)||e.type!==`compaction`?!1:e.status===`running`||e.status===`completed`||e.status===`failed`}function Fe(e){if(e)return e.find(Pe)}var Ie=e=>e?e.toLowerCase().includes(`application/json`):!1,Le=e=>e?e.toLowerCase().includes(`text/html`):!1;function S(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function C(e){return typeof e==`string`&&e.length>0?e:void 0}function Re(e){if(!S(e))return null;let t=C(e.id);return t?{...e,id:t}:null}function ze(e,t,n){return`${e}:${t}:${n}`}function Be(e,t,n,r,i=`text`,a){return i===`reasoning`?{id:ze(t,i,n),sessionID:e,messageID:t,type:`reasoning`,text:r}:{id:ze(t,i,n),sessionID:e,messageID:t,type:`text`,text:r,...a?.synthetic===!0?{synthetic:!0}:{}}}function Ve(e){return e?e.nativeType===`synthetic`||e.type===`synthetic`:!1}function He(e,t){return!e?.id||Ve(e)||(e.clientRole??e.role)!==`user`?!1:!Array.isArray(t)||t.length===0||!(t.some(e=>e.type===`subtask`||e.type===`compaction`)||t.every(e=>!!e.synthetic))}function Ue(e){if(typeof e==`string`&&e.length!==0)return e.replace(/^evt_/,`msg_`)}function We(e){let t=e.content;return Array.isArray(t)?t.flatMap(e=>S(e)&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
3
3
  `):typeof e.output==`string`?e.output:void 0}function Ge(e){return e===`patch`?`apply_patch`:e}function Ke(e,t,n){let r=C(n.id)??`${t}:tool`,i=Ge(C(n.name))??`tool`,a=S(n.state)?n.state:{},o=C(a.status)??`completed`,s=o===`streaming`?`pending`:o,c=S(n.time)?n.time:{};return{id:r,sessionID:e,messageID:t,type:`tool`,tool:i,callID:r,state:{status:s,input:a.input??{},output:We(a),error:S(a.error)?C(a.error.message):C(a.error),metadata:S(a.metadata)?a.metadata:{},time:{...typeof c.ran==`number`&&Number.isFinite(c.ran)?{start:c.ran}:{},...typeof c.completed==`number`&&Number.isFinite(c.completed)?{end:c.completed}:{}}}}}function qe(e){return S(e)?{created:typeof e.created==`number`?e.created:0,...typeof e.streamed==`number`?{streamed:e.streamed}:{},...typeof e.completed==`number`?{completed:e.completed}:{},...typeof e.start==`number`?{start:e.start}:{},...typeof e.end==`number`?{end:e.end}:{}}:{created:0}}function Je(e){if(!S(e))return;let t=S(e.cache)?{...typeof e.cache.read==`number`?{read:e.cache.read}:{},...typeof e.cache.write==`number`?{write:e.cache.write}:{}}:void 0,n={...typeof e.input==`number`?{input:e.input}:{},...typeof e.output==`number`?{output:e.output}:{},...typeof e.reasoning==`number`?{reasoning:e.reasoning}:{},...t&&(t.read!==void 0||t.write!==void 0)?{cache:t}:{}};return Object.keys(n).length>0?n:void 0}function Ye(e,t){let n=S(t.metadata)?t.metadata:void 0,r=n&&S(n.model)?n.model:void 0,i=S(t.model)?t.model:r,a=i?C(i.id)??C(i.modelID)??C(t.modelID):C(t.modelID),o=i?C(i.providerID)??C(t.providerID):C(t.providerID),s=(i?C(i.variant):void 0)??C(t.variant)??(n?C(n.variant):void 0);a&&(e.modelID=a),o&&(e.providerID=o),s&&(e.variant=s),(a||o||s)&&(e.model={...o?{providerID:o}:{},...a?{modelID:a}:{},...s?{variant:s}:{}});let c=C(t.agent)??C(t.mode)??(n?C(n.agent):void 0);c&&(e.agent=c)}function Xe(e,t,n){return{id:t.id,sessionID:e,role:n,time:qe(t.time)}}function Ze(e,t){let n=Re(t);if(!n)return null;let r=n.id,i=C(n.type)??`unknown`,a=C(n.role)??C(n.clientRole);if(i===`idle`||i===`model-switched`||i===`agent-selected`||i===`agent-switched`||i===`location-switched`||a===`idle`)return null;if(i===`user`){let t=Xe(e,n,`user`);Ye(t,n);let i=[],a=C(n.text);a&&i.push(Be(e,r,0,a));let o=n.files;return Array.isArray(o)&&o.forEach((t,n)=>{if(!S(t))return;let a=C(t.mime)??`application/octet-stream`,o=S(t.source)?t.source:{},s=o.type===`uri`?C(o.uri):void 0,c=C(t.data),l=s||(c?`data:${a};base64,${c}`:``),u={id:`${r}:file:${n}`,sessionID:e,messageID:r,type:`file`,mime:a,filename:C(t.name),url:l};i.push(u)}),{info:t,parts:i}}if(i===`assistant`){let t=Xe(e,n,`assistant`);if(S(n.model)){t.modelID=C(n.model.id)??C(n.model.modelID)??C(n.modelID),t.providerID=C(n.model.providerID)??C(n.providerID);let e=C(n.model.variant)??C(n.variant);(t.modelID||t.providerID||e)&&(t.model={...t.providerID?{providerID:t.providerID}:{},...t.modelID?{modelID:t.modelID}:{},...e?{variant:e}:{}})}else{let e=C(n.modelID),r=C(n.providerID),i=C(n.variant);e&&(t.modelID=e),r&&(t.providerID=r),(e||r||i)&&(t.model={...r?{providerID:r}:{},...e?{modelID:e}:{},...i?{variant:i}:{}})}let i=C(n.agent);i&&(t.agent=i);let a=C(n.finish)??C(n.rawFinish);a&&(t.finish=a),S(n.error)&&(t.error={type:C(n.error.type)??`error`,message:C(n.error.message)??``,...typeof n.error.status==`number`?{status:n.error.status}:{}}),typeof n.cost==`number`&&Number.isFinite(n.cost)&&(t.cost=n.cost);let o=Je(n.tokens);o&&(t.tokens=o);let s=[],c=Array.isArray(n.content)?n.content:[],l=0,u=0;for(let t of c){if(!S(t))continue;let n=C(t.type);if(n===`text`&&typeof t.text==`string`){s.push(Be(e,r,l++,t.text));continue}if(n===`reasoning`&&typeof t.text==`string`){s.push(Be(e,r,u++,t.text,`reasoning`));continue}n===`tool`&&s.push(Ke(e,r,t))}return{info:t,parts:s}}if(i===`shell`){let t=Xe(e,n,`user`),i=C(n.command)??``,a=S(n.output)&&typeof n.output.output==`string`?n.output.output:``,o=n.status===`running`?`running`:n.status===`exited`&&n.exit===0?`completed`:`error`;return{info:t,parts:[{id:ze(r,`text`,0),sessionID:e,messageID:r,type:`text`,text:i,shellAction:{command:i,output:a,status:o,shellID:C(n.shellID)}}]}}if(i===`synthetic`){let t={...Xe(e,n,`user`),nativeType:`synthetic`},i=C(n.description);i&&(t.description=i),S(n.metadata)&&(t.metadata=n.metadata);let a=C(n.shellID);a&&(t.shellID=a);let o=C(n.sessionID)&&n.sessionID!==e?C(n.sessionID):C(n.childSessionID)??C(n.taskSessionID);o&&(t.childSessionID=o);let s=C(n.text)??i??``;return{info:t,parts:s?[Be(e,r,0,s,`text`,{synthetic:!0})]:[{id:ze(r,`text`,0),sessionID:e,messageID:r,type:`text`,text:``,synthetic:!0}]}}if(i===`system`)return null;if(i===`compaction`){let t=n.status===`failed`?`failed`:n.status===`completed`?`completed`:`running`,i={...Xe(e,n,`assistant`),clientRole:`compaction`},a=S(n.error)?{type:C(n.error.type)??`error`,message:C(n.error.message)??``,...typeof n.error.status==`number`?{status:n.error.status}:{}}:void 0;return{info:i,parts:[{id:`${r}:compaction`,sessionID:e,messageID:r,type:`compaction`,status:t,reason:n.reason===`auto`?`auto`:`manual`,...typeof n.summary==`string`?{summary:n.summary}:{},...typeof n.recent==`string`?{recent:n.recent}:{},...a?{error:a}:{}}]}}return{info:Xe(e,n,`assistant`),parts:[Be(e,r,0,C(n.text)??`[${i}]`)]}}function Qe(e,t,n=Ne,r=20){if(!S(e))throw Error(`session projection: expected JSON object`);if(!Array.isArray(e.data))throw Error(`session projection: data must be an array`);let i=[];for(let n of e.data){let e=Ze(t,n);e&&i.push(e)}n===`desc`&&i.reverse();let a=S(e.cursor)?e.cursor:void 0,o=C(a?n===`asc`?a.previous:a.next:e.cursor),s=!o||e.data.length<r,c=i.filter(e=>He(e.info,e.parts)).length;return{records:i,cursor:s?void 0:o,complete:s,turnCount:c}}async function $e(e){let t=e.limit??20,n=e.order??`desc`,r=`/api/session/${encodeURIComponent(e.sessionID)}/message`,i={directory:e.directory,limit:String(t)};e.cursor?i.cursor=/^msg_[A-Za-z0-9_]+$/.test(e.cursor)?btoa(JSON.stringify({id:e.cursor,order:n,direction:n===`desc`?`next`:`previous`})).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``):e.cursor:i.order=n;let a=await u(r,{method:`GET`,query:i,signal:e.signal});if(!a.ok)throw Error(`session projection failed (${a.status})`);let o=a.headers.get(`content-type`);if(Le(o))throw Error(`session projection: unexpected HTML response`);Ie(o);let s;try{s=await a.json()}catch{throw Error(`session projection: malformed JSON`)}return Qe(s,e.sessionID,n,t)}function et(e){let t=e.fetched.filter(e=>!!e.info?.id),n=e.previous.filter(e=>!!e.info?.id),r=e.touched??new Set,i=new Map(t.map(e=>[e.info.id,e])),a=new Map(n.map(e=>[e.info.id,e])),o=new Set(e.coverageMessageIDs??t.map(e=>e.info.id)),s=n.findIndex(e=>o.has(e.info.id));if(!e.completeTail)for(let[e,t]of n.entries())i.has(t.info.id)||(s===-1||e<s)&&i.set(t.info.id,t);for(let e of r){let t=a.get(e);t?i.set(e,t):i.delete(e)}let c=n.map(e=>e.info.id).filter(e=>i.has(e)),l=t.map(e=>e.info.id).filter(e=>i.has(e)),u=l.some(e=>a.has(e));return(!e.completeTail&&!u?[...new Set([...c,...l])]:Me(c,l)).map(e=>i.get(e))}var tt=e=>e?e.toLowerCase().includes(`application/json`):!1,nt=e=>e?e.toLowerCase().includes(`text/html`):!1;function rt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function it(e){return typeof e==`string`&&e.length>0?e:void 0}function at(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ot(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function st(e){try{return(await e.text()).trim()}catch{return``}}async function ct(e,t){let n=e.headers.get(`content-type`);if(nt(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!tt(n)&&r==null)throw Error(`${t}: empty response`);return r}var lt=new Map,ut=e=>lt.get(e)??0,dt=m((e,t)=>({runningBySession:{},setRunning(t,n){lt.set(t,ut(t)+1),e(e=>{let r={...e.runningBySession};return n?r[t]=!0:delete r[t],{runningBySession:r}})},isRunning(e){return t().runningBySession[e]===!0},reset(){lt.clear(),e({runningBySession:{}})}}));function w(e,t){dt.getState().setRunning(e,t)}function ft(e){return dt.getState().isRunning(e)}function pt(e){return!ft(e.sessionID)}function mt(e){let t=rt(e)?e:null,n=t&&rt(t.data)?t.data:t;if(!n)throw Error(`session compact: expected inbox item`);let r=it(n.id),i=it(n.sessionID);if(!r||!i)throw Error(`session compact: inbox item missing id`);if(n.type&&n.type!==`compaction`)throw Error(`session compact: expected compaction inbox item`);return{id:r,sessionID:i,type:`compaction`,delivery:n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:void 0,timeCreated:at(n.timeCreated)}}function ht(e){let t=rt(e)?e:null,n=t&&Array.isArray(t.data)?t.data:Array.isArray(e)?e:null;if(!n)throw Error(`session inbox: expected list`);let r=[];for(let e of n)!rt(e)||e.type!==`compaction`||r.push(mt(e));return r}function gt(e,t){t.some(e=>e.type===`compaction`)&&w(e,!0)}function _t(e,t){for(let n=t.length-1;n>=0;--n){let r=(t[n]?.parts??[]).find(Pe);if(r){w(e,r.status===`running`);return}}}async function vt(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/compact`,n={};e.messageID&&(n.id=e.messageID),e.delivery&&(n.delivery=e.delivery);let r=await u(t,{method:`POST`,headers:{"Content-Type":`application/json`},query:{directory:e.directory},body:JSON.stringify(n),signal:e.signal});r.ok||ot(`session compact`,r.status,await st(r));let i=mt(await ct(r,`session compact`));return w(i.sessionID,!0),i}var yt=`compaction:`;function bt(e,t){return t&&t.length>0?t:`${yt}${e}`}function xt(e,t){let n=e.message[t]??[];for(let t=n.length-1;t>=0;--t){let r=n[t];if((e.part[r.id]??[]).some(e=>Pe(e)&&e.status===`running`))return r.id}}function St(e,t,n,r,i=Date.now()){let a=e.message[t]?[...e.message[t]]:[];a.some(e=>e.id===n)||(a.push({id:n,sessionID:t,role:`assistant`,clientRole:`compaction`,time:{created:i}}),e.message[t]=a);let o=e.part[n]?[...e.part[n]]:[],s=o.findIndex(Pe),c=r(s>=0?o[s]:{id:`${n}:compaction`,sessionID:t,messageID:n,type:`compaction`,status:`running`,reason:`manual`});s>=0?o[s]=c:o.push(c),e.part[n]=o}function Ct(e,t){let n=String(t.type??``);if(!n.startsWith(`session.compaction.`))return!1;let r=rt(t.properties)?t.properties:null;if(!r)return!1;let i=it(r.sessionID);if(!i)return!1;let a=it(r.inputID),o=xt(e,i),s=n===`session.compaction.started`?a??Ue(t.id)??bt(i):a??o??Ue(t.id)??bt(i);if(n===`session.compaction.started`)return!e.part[s]?.some(Pe)&&(St(e,i,s,e=>({...e,status:`running`,reason:r.reason===`auto`?`auto`:`manual`,...typeof r.recent==`string`?{recent:r.recent}:{}}),at(r.eventCreated)),w(i,!0),!0);if(n===`session.compaction.delta`){if(!o)return!1;let t=typeof r.text==`string`?r.text:``;return t?(St(e,i,s,e=>({...e,status:`running`,summary:(e.summary??``)+t})),w(i,!0),!0):!1}if(n===`session.compaction.ended`)return w(i,!1),o?(St(e,i,s,e=>({...e,status:`completed`,reason:r.reason===`auto`?`auto`:`manual`,summary:typeof r.text==`string`?r.text:e.summary,...typeof r.recent==`string`?{recent:r.recent}:{}}),at(r.eventCreated)),!0):!1;if(n===`session.compaction.failed`){if(w(i,!1),!o&&!a)return!1;let t=rt(r.error)?r.error:{};return St(e,i,s,e=>({...e,status:`failed`,reason:r.reason===`auto`?`auto`:`manual`,error:{type:it(t.type)??`error`,message:it(t.message)??``,...typeof t.status==`number`?{status:t.status}:{}}}),at(r.eventCreated)),!0}return!1}var wt=new Set([`patch`,`step-start`,`step-finish`]),Tt=[`text`,`output`],Et=new Set([`completed`,`error`,`aborted`,`failed`,`timeout`,`cancelled`]);function Dt(e,t){if(!e||t.length===0)return(e??``)+t;if(e.endsWith(t))return e;let n=Math.min(e.length,t.length);for(let r=n;r>0;r--)if(e.endsWith(t.slice(0,r)))return e+t.slice(r);return e+t}function Ot(e,t){let n=[];for(let r of Tt){let i=e[r],a=t[r];typeof i==`string`&&typeof a==`string`&&i.length!==0&&a.length!==0&&(a===i||a.startsWith(i)||i.startsWith(a))&&n.push(r)}return n}function kt(e){let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0}function At(e){if(e.type!==`tool`)return;let t=e.state?.status;return typeof t==`string`?t:void 0}function jt(e,t){if(e.type!==`tool`||t.type!==`tool`)return!1;let n=At(e),r=At(t);if(n&&Et.has(n)&&(!r||!Et.has(r)))return!0;let i=kt(e),a=kt(t);return typeof i==`number`&&typeof a!=`number`}function Mt(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return e===t;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}var Nt=[`agent`,`mode`,`providerID`,`modelID`,`variant`],Pt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ft=[`input`,`output`,`reasoning`];function It(e){if(!e||typeof e!=`object`)return!1;let t=e;return Ft.some(e=>typeof t[e]==`number`&&Number.isFinite(t[e])&&t[e]>0)}function Lt(e){if(!e||typeof e!=`object`)return!1;let t=e;return Ft.every(e=>typeof t[e]!=`number`||!Number.isFinite(t[e])||t[e]<=0)}function Rt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function zt(e,t){let n={...e,...t},r=e,i=t,a=n;for(let e of Nt){let t=Rt(i[e]),n=Rt(r[e]);t?a[e]=t:n?a[e]=n:delete a[e]}let o=i.model,s=r.model;return Pt(o)?a.model=o:Pt(s)?a.model=s:delete a.model,(e.time||t.time)&&(n.time={...e.time,...t.time}),It(r.tokens)&&Lt(i.tokens)&&(a.tokens=r.tokens),n}function Bt(e,t){if(e.time.streamed!==t.time.streamed||e.role!==t.role||e.finish!==t.finish||e.time?.completed!==t.time?.completed)return!1;for(let n of[`summary`,`error`,`cost`,`tokens`,`structured`,`model`,`tools`,`format`,`variant`,`agent`,`mode`,`providerID`,`modelID`,`system`])if(!Mt(e[n],t[n]))return!1;return!0}function Vt(e,t,n){if(!t)return!1;let r=e.message[t];return r?b(r,n)>=0:!1}function Ht(e,t){switch(t.type){case`message.updated`:{let n=t.properties.info,r=n,i=typeof r.type==`string`?r.type:void 0,a=typeof r.role==`string`?r.role:void 0;if(i===`idle`||i===`model-switched`||i===`agent-selected`||i===`agent-switched`||i===`location-switched`||a===`idle`)return!1;let o=e.message[n.sessionID],s=!!o&&o.every(t=>t.role!==`assistant`||e.part[t.id]!==void 0);if(n.role===`assistant`&&s&&e.part[n.id]===void 0&&(e.part[n.id]=[]),!o)return e.message[n.sessionID]=[n],!0;let c=b(o,n.id);if(c>=0){let t=o[c],r=zt(t,n);if(Bt(t,r))return je.reducer.messageUpdatedUnchanged(n.sessionID,n.id,n.role,n.finish,n.time?.completed),!1;let i=[...o];i[c]=r,e.message[n.sessionID]=i}else e.message[n.sessionID]=[...o,n];return!0}case`message.removed`:{let n=t.properties,r=e.message[n.sessionID];if(r){let t=b(r,n.messageID);if(t>=0){let i=[...r];i.splice(t,1),e.message[n.sessionID]=i}}return delete e.part[n.messageID],!0}case`message.part.updated`:{let n=t.properties,r=n.part;if(wt.has(r.type))return je.reducer.partSkipped(r.messageID,r.id,r.type),!1;let i=r.messageID,a=n.sessionID??r.sessionID;if(!i)return!1;let o=!Vt(e,a,i),s=e.part[i];if(!s)return je.reducer.partUpdatedNoExistingParts(i,r.id,r.type),e.part[i]=[r],!o||{changed:!0,materialization:{type:`incomplete-session-snapshot`,reason:`missing-owning-message`,sessionID:a,messageID:i,partID:r.id}};let c=[...s],l=c.findIndex(e=>e.id===r.id);if(l>=0){let e=c[l];if(jt(e,r))return!1;let t=Ot(e,r);c[l]=t.length>0?{...r,__dedupeNextDeltaFields:t}:r}else{let e=r.type===`text`||r.type===`file`?c.findIndex(e=>e.type===r.type&&e.__yuriOptimistic===!0):-1;e>=0?c[e]=r:c.push(r)}return e.part[i]=c,!o||{changed:!0,materialization:{type:`incomplete-session-snapshot`,reason:`missing-owning-message`,sessionID:a,messageID:i,partID:r.id}}}case`message.part.removed`:{let n=t.properties,r=e.part[n.messageID];if(!r)return!1;let i=r.findIndex(e=>e.id===n.partID);if(i>=0){let t=[...r];return t.splice(i,1),t.length===0?delete e.part[n.messageID]:e.part[n.messageID]=t,!0}return!1}case`message.part.delta`:{let n=t.properties,r=e.part[n.messageID];if(!r)return je.reducer.partDeltaNoParts(n.messageID,n.partID),{changed:!1,materialization:{type:`incomplete-session-snapshot`,reason:`orphan-delta`,sessionID:n.sessionID,messageID:n.messageID,partID:n.partID}};let i=r.findIndex(e=>e.id===n.partID);if(i<0)return je.reducer.partDeltaNotFound(n.messageID,n.partID),{changed:!1,materialization:{type:`incomplete-session-snapshot`,reason:`missing-delta-part`,sessionID:n.sessionID,messageID:n.messageID,partID:n.partID}};let a=r[i],o=a[n.field],s=a.__dedupeNextDeltaFields??[],c=s.includes(n.field),l=[...r];return l[i]={...a,[n.field]:c?Dt(o,n.delta):(o??``)+n.delta,__dedupeNextDeltaFields:s.filter(e=>e!==n.field)},e.part[n.messageID]=l,!0}default:return nn(e,t)}}function T(e){return!e||typeof e!=`object`||Array.isArray(e)?null:e}function E(e){return typeof e==`string`&&e.length>0?e:void 0}function Ut(e,t,n){return`${e}:${t}:${n}`}function Wt(e){return typeof e?.created==`number`&&Number.isFinite(e.created)&&e.created>0?e.created:Date.now()}function D(e){let t=e.eventCreated;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:void 0}function Gt(e,t,n,r){let i=e.message[t],a=i?b(i,n):-1;if(a>=0&&i){let n=i[a],o=n.time?.created,s=!1,c={...n,time:{...n.time}};if((o===void 0||o<=0)&&typeof r?.created==`number`&&r.created>0&&(c.time={...c.time,created:r.created},s=!0),!Rt(n.agent)&&r?.agent&&(c.agent=r.agent,s=!0),!Rt(n.modelID)&&r?.modelID&&(c.modelID=r.modelID,s=!0),!Rt(n.providerID)&&r?.providerID&&(c.providerID=r.providerID,s=!0),!Rt(n.variant)&&r?.variant&&(c.variant=r.variant,s=!0),!n.model&&r?.model&&(c.model=r.model,s=!0),!s)return!1;let l=[...i];return l[a]=c,e.message[t]=l,!0}let o={id:n,sessionID:t,role:`assistant`,time:{created:Wt(r)},...r?.agent?{agent:r.agent}:{},...r?.modelID?{modelID:r.modelID}:{},...r?.providerID?{providerID:r.providerID}:{},...r?.variant?{variant:r.variant}:{},...r?.model?{model:r.model}:{}};return e.message[t]=i?[...i,o]:[o],!0}function Kt(e){let t=E(e.agent),n=T(e.model),r=n?E(n.id)??E(n.modelID):void 0,i=n?E(n.providerID):void 0,a=n?E(n.variant):void 0;return{...t?{agent:t}:{},...r?{modelID:r}:{},...i?{providerID:i}:{},...a?{variant:a}:{},...r||i||a?{model:{...i?{providerID:i}:{},...r?{modelID:r}:{},...a?{variant:a}:{}}}:{}}}function qt(e){let t=T(e);if(!t)return;let n=T(t.cache),r={...typeof t.input==`number`?{input:t.input}:{},...typeof t.output==`number`?{output:t.output}:{},...typeof t.reasoning==`number`?{reasoning:t.reasoning}:{},...n?{cache:{...typeof n.read==`number`?{read:n.read}:{},...typeof n.write==`number`?{write:n.write}:{}}}:{}};return Object.keys(r).length>0?r:void 0}function Jt(e,t,n,r){let i=e.message[t];if(!i)return e.message[t]=[r],!0;let a=b(i,n);if(a<0)return e.message[t]=[...i,r],!0;let o=i[a],s=zt(o,r);if(Bt(o,s)&&o.time?.created===s.time?.created)return!1;let c=[...i];return c[a]=s,e.message[t]=c,!0}function Yt(e,t,n){let r=e.message[t];if(!r)return;let i=b(r,n);if(i<0)return;let a=r[i]?.time?.created;return typeof a==`number`&&Number.isFinite(a)&&a>0?a:void 0}function Xt(e,t,n,r,i){let a=D(i);if(t===`session.step.started`)return Gt(e,n,r,{created:a,...Kt(i)});if(t===`session.step.streamed`)return a?(Gt(e,n,r,{created:a}),Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??a,streamed:a}})):!1;if(t===`session.step.ended`){Gt(e,n,r,{created:a});let t=E(i.finish),o=qt(i.tokens),s=typeof i.cost==`number`&&Number.isFinite(i.cost)?i.cost:void 0;return Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??Wt({created:a}),...a?{completed:a}:{}},...t?{finish:t}:{},...o?{tokens:o}:{},...s===void 0?{}:{cost:s}})}if(t===`session.step.failed`){Gt(e,n,r,{created:a});let t=T(i.error),o=qt(i.tokens),s=typeof i.cost==`number`&&Number.isFinite(i.cost)?i.cost:void 0;return Jt(e,n,r,{id:r,sessionID:n,role:`assistant`,time:{created:Yt(e,n,r)??Wt({created:a}),...a?{completed:a}:{}},finish:`error`,...t?{error:{type:E(t.type)??`error`,message:E(t.message)??``,...typeof t.status==`number`?{status:t.status}:{}}}:E(i.error)?{error:{type:`error`,message:E(i.error)}}:{},...o?{tokens:o}:{},...s===void 0?{}:{cost:s}})}return!1}function Zt(e){if(Array.isArray(e))return e.flatMap(e=>{let t=T(e);return t&&t.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
4
4
  `)}function Qt(e,t,n,r){let i=Ut(n,t,r),a=e.findIndex(e=>e.id===i);return a>=0?a:e.map((e,t)=>({part:e,index:t})).filter(e=>e.part.type===t)[r]?.index??-1}function $t(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=Qt(s,r,n,i);if(c<0){let e={id:Ut(n,r,i),sessionID:t,messageID:n,type:r,text:``};s.push(e),c=s.length-1}let l=s[c],u=typeof a==`function`?a(l.text??``):a;return s[c]={...l,text:u},e.part[n]=s,!0}function en(e,t){return e.findIndex(e=>e.id===t||e.callID===t||e.type===`tool`&&e.id===t)}function O(e,t,n,r,i,a,o){Gt(e,t,n,o);let s=e.part[n]?[...e.part[n]]:[],c=en(s,r);return c<0&&(s.push({id:r,sessionID:t,messageID:n,type:`tool`,tool:Ge(i)??`tool`,callID:r,state:{status:`pending`,input:``,output:void 0,metadata:{}}}),c=s.length-1),s[c]=a(s[c]),e.part[n]=s,!0}function tn(e,t,n){return e.message[t]?.find(t=>e.part[t.id]?.some(e=>e.type===`text`&&e.shellAction?.shellID===n))?.id}function nn(e,t){let n=String(t.type);if(n.startsWith(`session.compaction.`))return Ct(e,t);let r=T(t.properties);if(!r)return!1;let i=E(r.sessionID);if(i&&(n===`session.shell.started`||n===`session.shell.ended`)){let a=T(r.shell),o=E(a?.id);if(!a||!o)return!1;let s=e.message[i]??[],c=tn(e,i,o),l=c?s.find(e=>e.id===c):void 0,u=l?.id??(n===`session.shell.started`?Ue(t.id):void 0);if(!u||n===`session.shell.started`&&l)return!1;let d=Ze(i,{id:u,type:`shell`,shellID:o,command:a.command,status:a.status,exit:a.exit,output:r.output,time:{created:l?.time.created??D(r),...n===`session.shell.ended`?{completed:D(r)}:{}}});return!d||l&&Mt(l,d.info)&&Mt(e.part[u],d.parts)?!1:(e.message[i]=l?s.map(e=>e.id===u?d.info:e):[...s,d.info],e.part[u]=d.parts,!0)}if(i&&n===`session.synthetic`){let n=Ue(t.id);if(!n)return!1;let a=Ze(i,{id:n,type:`synthetic`,text:r.text,description:r.description,metadata:r.metadata,time:{created:D(r)}});if(!a)return!1;let o=e.message[i]??[],s=o.find(e=>e.id===n);return s&&Mt(s,a.info)&&Mt(e.part[n],a.parts)?!1:(e.message[i]=s?o.map(e=>e.id===n?a.info:e):[...o,a.info],e.part[n]=a.parts,!0)}if(n===`session.revert.committed`)return!1;let a=E(r.assistantMessageID);if(!i||!a)return!1;let o=typeof r.ordinal==`number`?r.ordinal:0,s={created:D(r)};if(n===`session.step.started`||n===`session.step.streamed`||n===`session.step.ended`||n===`session.step.failed`)return Xt(e,n,i,a,r);if(n===`session.text.started`)return $t(e,i,a,`text`,o,``,s);if(n===`session.text.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`text`,o,e=>e+t,s):!1}if(n===`session.text.ended`)return $t(e,i,a,`text`,o,typeof r.text==`string`?r.text:``,s);if(n===`session.reasoning.started`)return $t(e,i,a,`reasoning`,o,``,s);if(n===`session.reasoning.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?$t(e,i,a,`reasoning`,o,e=>e+t,s):!1}if(n===`session.reasoning.ended`)return $t(e,i,a,`reasoning`,o,typeof r.text==`string`?r.text:``,s);let c=E(r.id);if(!c)return!1;let l=E(r.name);if(n===`session.tool.input.started`)return O(e,i,a,c,l,e=>e,s);if(n===`session.tool.input.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?O(e,i,a,c,l,e=>{let n=T(e.state)??{};if(E(n.status)&&n.status!==`pending`&&n.status!==`streaming`)return e;let r=typeof n.input==`string`?n.input+t:t;return{...e,state:{...n,status:`pending`,input:r}}},s):!1}if(n===`session.tool.input.ended`){let t=typeof r.text==`string`?r.text:``;return O(e,i,a,c,l,e=>{let n=T(e.state)??{};return{...e,state:{...n,input:t}}},s)}return n===`session.tool.called`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`pending`,input:r.input??t.input??{},metadata:T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),start:n}}}}},s):n===`session.tool.progress`?O(e,i,a,c,l,e=>{let t=T(e.state)??{};return{...e,state:{...t,metadata:T(r.metadata)??T(t.metadata)??{}}}},s):n===`session.tool.success`?O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r);return{...e,state:{...t,status:`completed`,input:t.input??r.input??{},output:Zt(r.content),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s):n===`session.tool.failed`&&O(e,i,a,c,l,e=>{let t=T(e.state)??{},n=D(r),i=T(r.error);return{...e,state:{...t,status:`error`,input:t.input??{},output:Zt(r.content),error:i?E(i.message)??E(r.error):E(r.error),metadata:T(r.metadata)??T(t.metadata)??{},...n===void 0?{}:{time:{...T(t.time),end:n}}}}},s)}function rn(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function an(e){let t=e.id;return typeof t==`string`&&t.length>0?t:void 0}function k(e){return e.slim===!0}function on(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e){let e=an(t);e&&!k(t)&&n.set(e,t)}if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e))return e;let t=an(e);if(!t)return e;let i=n.get(t);return i?(r=!0,i):e});return r?i:t}function sn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])?t:e}function cn(e){let t=e.clientRole??e.role;return typeof t==`string`?t:``}function ln(e){return cn(e)!==`assistant`||!rn(e)}function un(e,t,n){if(!e||e.length===0)return t;let r=on(e,t);if(ln(n))return sn(r,e);let i=new Set;for(let e of r){let t=an(e);t&&i.add(t)}let a=new Map,o=[],s,c=0;for(let t of e){let e=an(t);if(e&&i.has(e)){s=e;continue}if(!e)continue;if(c+=1,!s){o.push(t);continue}let n=a.get(s);if(n){n.push(t);continue}a.set(s,[t])}if(c===0)return sn(r,e);let l=[...o];for(let e of r){l.push(e);let t=an(e);if(!t)continue;let n=a.get(t);n&&l.push(...n)}return sn(l,e)}var A=e=>Object.freeze(e),dn=Object.freeze({initial:A({id:`initial`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),prepend:A({id:`history`,onStale:`drop`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),recovery:A({id:`recovery`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),"reconcile-page":A({id:`reconcile-page`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`keep-unless-full`}),materialize:A({id:`materialize`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`})}),fn=A({id:`recovery-backfill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),pn=A({id:`send-gap-fill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),mn=dn.initial;function hn(e){let t=dn[e.purpose]??mn;return!e.stale||t.onStale===`drop`?t:fn}function gn(e,t){return e.preserveStreaming===`none`?!1:e.preserveStreaming===`all`||t===`assistant`}var _n=e=>structuredClone(e),vn=e=>({transport:e.transport,generation:e.generation,directory:e.directory,sessionID:e.sessionID});function yn(e){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID])}function bn(e,t){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID,t])}function xn(e){return JSON.stringify([e.transport,e.generation])}function Sn(e,t){return e.created===t.created?e.messageID<t.messageID?-1:+(e.messageID>t.messageID):e.created-t.created}function Cn(e){let t=e.time?.created;return{created:typeof t==`number`&&Number.isFinite(t)?t:0,messageID:e.id}}function wn(e){return ln(e)}function Tn(e){return k(e)?`slim`:`full`}function En(e){return e.some(e=>k(e))?`slim`:`full`}var Dn=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Dn);let t=e,n={};for(let e of Object.keys(t).sort()){let r=t[e];r!==void 0&&(n[e]=Dn(r))}return n},On=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n};async function kn(e,t){let n=JSON.stringify(Dn({info:e,parts:t})),r=new TextEncoder().encode(n);return{hash:On(await crypto.subtle.digest(`SHA-256`,r)),byteSize:r.byteLength}}var An=e=>({scope:vn(e.scope),messageID:e.messageID,info:_n(e.info),parts:_n(e.parts),partCompleteness:e.partCompleteness.slice(),completeness:e.completeness,contentHash:e.contentHash,byteSize:e.byteSize,lastAccessedAt:e.lastAccessedAt,sortKey:{created:e.sortKey.created,messageID:e.sortKey.messageID}}),jn=e=>{let t=0;return()=>{let n=e();return t=n>t?n:t+1,t}},Mn=(e,t)=>{let n=t.slice().sort((e,t)=>Sn(e.sortKey,t.sortKey)).map(An);return{scope:vn(e),records:n,byteSize:n.reduce((e,t)=>e+t.byteSize,0)}},Nn=e=>_n(e),Pn=e=>vn(e),Fn=(e=Date.now)=>jn(e),In=e=>An(e),Ln=(e,t)=>Mn(e,t.slice());function Rn(e){return wn(e.info)?e.existing?.completeness===`full`&&e.incomingCompleteness===`slim`?{status:`skipped`,reason:`slim-downgrade`}:e.incomingHash!==void 0&&e.existing?.contentHash===e.incomingHash?{status:`skipped`,reason:`unchanged`}:{status:`written`}:{status:`skipped`,reason:`not-settled`}}var zn=[`text`,`output`],Bn={pending:1,started:2,running:3,completed:4,error:4};function Vn(e,t){return e.filter(e=>!!e?.id&&!t.has(e.type))}function Hn(e,t){if(!e||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||JSON.stringify(r)!==JSON.stringify(i))return!1}return!0}function Un(e){let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0}function Wn(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Gn(e){return Un(e)===void 0&&zn.some(t=>{let n=Wn(e,t);return typeof n==`string`&&n.length>0})}function Kn(e){let t=e.state;if(!(!t||typeof t!=`object`))return t}function qn(e){let t=Kn(e)?.status;return typeof t==`string`?t:void 0}function Jn(e){return e?Bn[e]??0:0}function Yn(e,t){if(Gn(e))return!0;if(Un(e)===void 0){if(e.type===`tool`){let n=qn(e);return n===`completed`||n===`error`?t:!0}return!0}return t}function Xn(e){let t=e.state?.time;if(!t||typeof t!=`object`)return;let n=typeof t.start==`number`?t.start:void 0,r=typeof t.end==`number`?t.end:void 0;if(n!==void 0||r!==void 0)return{start:n,end:r}}function Zn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0}function Qn(e,t,n){if(e.type!==`tool`||t.type!==`tool`)return n;let r=Kn(e);if(!r)return n;let i=Kn(n)??{},a=Kn(t)??{},o={...i},s=!1,c=qn(e),l=qn(t);Jn(c)>Jn(l)&&c&&(o={...o,status:c},s=!0);let u=r.input,d=a.input;Zn(u)&&!Zn(d)&&(o={...o,input:u},s=!0);let f=r.output,p=a.output;typeof f==`string`&&f.length>0?(typeof p!=`string`||p.length<f.length)&&(typeof p!=`string`||p.length===0||f.startsWith(p))&&(o={...o,output:f},s=!0):f!==void 0&&p===void 0&&(o={...o,output:f},s=!0);let m=r.metadata;return Zn(m)&&!Zn(a.metadata)&&(o={...o,metadata:m},s=!0),s?n===t?{...t,state:o}:{...n,state:o}:n}function $n(e,t){if(!e||Un(t)!==void 0)return t;let n=t;for(let r of zn){let i=Wn(e,r);if(!i)continue;let a=Wn(t,r);if(typeof a==`string`&&a.length>=i.length||typeof a==`string`&&a.length>0&&!i.startsWith(a))continue;n===t&&(n={...t});let o=n;o[r]=i}let r=Xn(e);if(r){let e=Xn(t),i=e?.start??r.start,a=e?.end??r.end;if(i!==e?.start||a!==e?.end){n===t&&(n={...t});let e=n;e.state={...n.state??{},time:{start:i,end:a}}}}return n=Qn(e,t,n),n}function er(e,t){if(!e||e.length===0||!t.some(e=>k(e)))return t;let n=new Map;for(let t of e)t.id&&!k(t)&&n.set(t.id,t);if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!k(e)||!e.id)return e;let t=n.get(e.id);return t?(r=!0,t):e});return r?i:t}function tr(e){return e.__yuriOptimistic===!0}function nr(e){return!!(e&&e.length>0&&e.some(tr))}function rr(e){return e.length===0||e.some(e=>k(e))}function ir(e,t,n,r,i,a){if(a===`keep-unless-full`&&e&&nr(e)&&rr(t))return e;let o=er(e,t);if(!e||e.length===0||!r)return o;let s=new Map(e.map(e=>[e.id,e])),c=o,l=!1;for(let e=0;e<o.length;e+=1){let t=o[e],n=$n(s.get(t.id),t);n!==t&&(l||(c=[...o]),c[e]=n,l=!0)}let u=new Set(o.map(e=>e.id)),d=o.some(e=>k(e)),f=e.filter(e=>!!e?.id&&!u.has(e.id)&&!n.has(e.type)&&(Yn(e,i)||d&&!k(e)));if(f.length===0)return c;let p=new Set(f.map(e=>e.id)),m=new Map,h=[];for(let t of e)p.has(t.id)?h.push(t):u.has(t.id)&&h.length>0&&(m.set(t.id,h),h=[]);let g=[];for(let e of c){for(let t of m.get(e.id)??[])g.push(t);g.push(e)}for(let e of h)g.push(e);return g}var ar=e=>e,or=e=>{let t=ar(e).finish;return typeof t==`string`&&t.length>0},sr=e=>typeof ar(e).time?.completed==`number`,cr=e=>!!ar(e).error;function lr(e,t){let n=ar(t),r=n.finish,i=n.time?.completed,a=n.time?.streamed,o=n.error,s=e.tokens,c=t.tokens,l=!or(e)&&typeof r==`string`&&r.length>0,u=!sr(e)&&typeof i==`number`,d=e.time.streamed===void 0&&typeof a==`number`&&Number.isFinite(a),f=!cr(e)&&!!o,p=!It(s)&&It(c);if(!l&&!u&&!d&&!f&&!p)return e;let m={...e};return l&&(m.finish=r),(u||d)&&(m.time={...ar(e).time,...u?{completed:i}:{},...d?{streamed:a}:{}}),f&&(m.error=o),p&&(m.tokens=c),m}function ur(e,t,n,r){if(t.length===0)return e;let i=new Map(t.map(e=>[e.id,e])),a=!1,o=[];for(let t of e){let e=n(t,i.get(t.id));e!==t&&(a=!0),o.push(e)}let s=new Set(e.map(e=>e.id));if(!t.some(e=>s.has(e.id)))return r===`prepend`?[...t,...o]:r===`by-created`?dr(o,t):[...o,...t];let c=new Map(t.map(e=>[e.id,e]));for(let e of o)c.set(e.id,e);let l=Me(e.map(e=>e.id),t.map(e=>e.id)).map(e=>c.get(e));return!a&&l.length===e.length&&l.every((t,n)=>t===e[n])?e:l}function dr(e,t){let n=e.slice();for(let e of t){let t=Cn(e),r=n.length;for(let e=0;e<n.length;e+=1)if(Sn(t,Cn(n[e]))<0){r=e;break}n.splice(r,0,e)}return n}function fr(e,t,n){return ur(e,t,(e,t)=>t?lr(e,t):e,n)}function pr(e,t,n){return ur(e,t,(e,t)=>!t||JSON.stringify(e)===JSON.stringify(t)?e:zt(e,t),n)}function mr(e,t,n,r={}){let i=r.skipPartTypes??new Set,a=r.merge??mn,o=r.placeUnanchoredNewMessages??`append`,s=n.filter(e=>!!e?.info?.id),c=s.map(e=>e.info),l=e.message[t],u=l??[],d=a.messages===`upsert`?pr(u,c,o):fr(u,c,o),f=d!==u||l===void 0&&s.length===0,p=!1,m={...e.part},h=a.parts===`skip-existing`;for(let e of s){let t=e.info.id;if(h&&m[t])continue;let n=e.info.role===`assistant`,r=m[t],o=ir(r,Vn(e.parts??[],i),i,gn(a,e.info.role),rn(e.info),a.protectOptimistic);(r?Hn(r,o):o.length===0&&!n)||o.length===0&&!n||(m[t]=o,p=!0)}return{message:f?{...e.message,[t]:d}:e.message,part:p?m:e.part,messages:d,messagesChanged:f,partsChanged:p}}function hr(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function gr(e){let t=e.messages;if(!t)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let n=t.length>0?t[t.length-1]?.id:void 0,r=[];for(let i of t)i.role===`assistant`&&(e.parts[i.id]||i.id===n&&hr(i)||r.push(i.id));return{hasMessages:!0,renderable:r.length===0,missingPartMessageIDs:r}}var _r=(e,t)=>e<t?-1:+(e>t);function vr(e){return e.filter(e=>!!e?.id)}function yr(e,t){if(t.length===0)return{...e,confirmed:[]};let n=[...e.session],r=new Map(e.part.map(e=>[e.id,vr(e.part)])),i=[];for(let e of t){if(n.findIndex(t=>t.id===e.message.id)<0){n.push(e.message),r.set(e.message.id,vr(e.parts));continue}let t=r.get(e.message.id);if(t&&t.length>0){i.push(e.message.id);continue}r.set(e.message.id,vr(e.parts))}return{cursor:e.cursor,complete:e.complete,session:n,part:[...r.entries()].sort((e,t)=>_r(e[0],t[0])).map(([e,t])=>({id:e,part:t})),confirmed:i}}var br={kind:`unknown`,loadedTurns:0},xr=3e4,Sr=12e5,Cr={project:``,projectMeta:void 0,icon:void 0,provider:{all:[],connected:[],default:{}},config:{},path:{state:``,config:``,worktree:``,directory:``,home:``},status:`loading`,agent:[],command:[],session:[],sessionTotal:0,session_status:{},session_status_observed_at:{},session_status_event_at:{},session_status_event_sequence:{},session_interrupt_acknowledged_at:{},session_execution_version:{},session_status_snapshot_at:void 0,session_error_at:{},session_execution_recovery:{},session_diff:{},todo:{},permission:{},question:{},lsp:[],vcs:void 0,limit:20},wr={ready:!1,path:{state:``,config:``,worktree:``,directory:``,home:``},projects:[],providers:{all:[],connected:[],default:{}},providerAuth:{},config:{},reload:void 0,sessionTodo:{}};function Tr(e,t){return e===void 0||t===void 0?!1:t>e}var Er=class extends Error{};function Dr(e,t,n){if(n===`reconcile-page`)return e??br;let r=0;typeof t.turnCount==`number`&&Number.isFinite(t.turnCount)?r=Math.max(0,Math.floor(t.turnCount)):typeof t.requestedTurnLimit==`number`&&Number.isFinite(t.requestedTurnLimit)?r=Math.max(0,Math.floor(t.requestedTurnLimit)):t.records.length>0&&(r=1);let i=e?.loadedTurns??0,a=n===`prepend`?i+r:r;if(t.complete)return{kind:`exhausted`,loadedTurns:a};let o=typeof t.cursor==`string`&&t.cursor.length>0?t.cursor:void 0;if(!o)throw new Er(`session message page: complete=false requires non-empty cursor`);if(n===`prepend`&&e?.kind===`has-more`&&e.cursor===o)throw new Er(`session message page: prepend returned the same cursor without progress`);if(t.records.length===0&&(n!==`prepend`||e?.kind!==`has-more`||e.cursor===o)&&n!==`initial`)throw new Er(`session message page: complete=false with zero records makes no progress`);return{kind:`has-more`,cursor:o,loadedTurns:a}}function Or(e,t){return!e||!t?e===t:e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function kr(e,t,n,r){let i=Tr(r.capturedRevision,r.liveRevision),a=hn({purpose:r.purpose,stale:i}),o=e.session_history_boundary?.[t];if(!n.ok)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.error};if(i&&a.onStale===`drop`){let n=e.message[t]??[];if(n.length>0)return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:n,boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[]}}let s=r.optimistic??[],c=yr({session:n.records.map(e=>e.info),part:n.records.map(e=>({id:e.info.id,part:e.parts??[]})),cursor:n.cursor,complete:n.complete},s),l=mr(e,t,c.session.map(e=>({info:e,parts:c.part.find(t=>t.id===e.id)?.part??[]})),{skipPartTypes:r.skipPartTypes,merge:a,placeUnanchoredNewMessages:r.purpose===`prepend`?`prepend`:r.purpose===`reconcile-page`?`by-created`:`append`}),u;try{u=Dr(o,{ok:!0,records:n.records,cursor:c.cursor,complete:c.complete,turnCount:n.turnCount,requestedTurnLimit:n.requestedTurnLimit},r.purpose)}catch(n){if(!(n instanceof Er))throw n;return{applied:!1,merge:a,changed:!1,messagesChanged:!1,partsChanged:!1,boundaryChanged:!1,message:e.message,part:e.part,messages:e.message[t]??[],boundary:void 0,meta:void 0,confirmedOptimisticIDs:[],commands:[],error:n.message}}let d=!Or(o,u),f=l.messagesChanged,p=l.partsChanged,m=f||p||d,h=[];c.confirmed.length>0&&h.push({type:`clear-optimistic`,messageIDs:c.confirmed});let g=d||!o?u:o;return{applied:!0,merge:a,changed:m,messagesChanged:f,partsChanged:p,boundaryChanged:d,message:l.message,part:l.part,messages:l.messages,boundary:g,meta:{limit:g.loadedTurns,cursor:g.kind===`has-more`?g.cursor:void 0,complete:g.kind===`exhausted`},confirmedOptimisticIDs:c.confirmed,commands:h}}var Ar=new Set([`tool`,`reasoning`,`file`,`text`]),jr=new Set([`tool`,`reasoning`,`file`]);function Mr(e){return e.some(e=>k(e)&&Ar.has(e.type))}function Nr(e,t){let n=!1,r=!1;for(let t of e)jr.has(t.type)&&(n=!0,k(t)&&(r=!0));return n?r?!0:t?rn(t):!1:!1}var Pr=e=>{if(!e)return``;let t=e.clientRole??e.role;return typeof t==`string`?t:``};function Fr(e,t){return He(e,t)}function Ir(e){let t=0;for(let n of e.messageOrder)Fr(e.messagesByID[n],e.partsByMessageID[n])&&(t+=1);return t}var Lr=(e,t)=>{let n=e.messageOrder.lastIndexOf(t);if(n<0)return[];let r=[];for(let i=n+1;i<e.messageOrder.length;i+=1){let n=e.messageOrder[i],a=e.messagesByID[n];if(!a)continue;if(Fr(a,e.partsByMessageID[n]))break;if(Pr(a)!==`assistant`)continue;let o=a.parentID;typeof o==`string`&&o.length>0&&o!==t||r.push(a)}return r},Rr=(e,t)=>rn(e)?!0:Array.isArray(t)&&t.length>0;function zr(e){let t;for(let n=e.messageOrder.length-1;n>=0;--n){let r=e.messageOrder[n];if(Fr(e.messagesByID[r],e.partsByMessageID[r])){t=r;break}}return t?Lr(e,t).some(t=>Rr(t,e.partsByMessageID[t.id])):!1}function Br(e){return e.materializeActive?`p2`:e.prependActive||e.earlierHistoryLoaded?`p1`:e.p0Satisfied?`p0`:`idle`}var Vr=new Set([`stop`,`length`]);function Hr(e){let t=e.messageOrder[e.messageOrder.length-1];if(!t)return!1;let n=e.messagesByID[t];if(!n||Pr(n)!==`assistant`||n.error)return!1;let r=n.finish;return typeof r!=`string`||!Vr.has(r)?!1:typeof n.time?.completed!=`number`||r===`stop`&&!It(n.tokens)}function Ur(e,t){return t.kind===`has-more`?{sessionID:e,boundary:t,hasPreviousPage:!0,isComplete:!1,cursor:t.cursor,loadedTurns:t.loadedTurns}:t.kind===`exhausted`?{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!0,cursor:null,loadedTurns:t.loadedTurns}:{sessionID:e,boundary:t,hasPreviousPage:!1,isComplete:!1,cursor:null,loadedTurns:t.loadedTurns}}function Wr(e){let t={},n={},r=[];for(let i of e.messages){if(!i?.id)continue;r.push(i.id),t[i.id]=i;let a=e.parts[i.id];a&&(n[i.id]=a)}return{sessionID:e.sessionID,messageOrder:r,messagesByID:t,partsByMessageID:n,boundary:e.boundary,liveRevision:e.liveRevision??0}}var Gr=`message.updated,message.removed,message.part.updated,message.part.removed,message.part.delta,session.step.started,session.step.streamed,session.shell.started,session.shell.ended,session.step.ended,session.step.failed,session.text.started,session.text.delta,session.text.ended,session.reasoning.started,session.reasoning.delta,session.reasoning.ended,session.tool.input.started,session.tool.input.delta,session.tool.input.ended,session.tool.called,session.tool.progress,session.tool.success,session.tool.failed,session.compaction.started,session.compaction.delta,session.compaction.ended,session.compaction.failed,session.synthetic,session.revert.committed`.split(`,`);function Kr(e){return Gr.includes(e)}function j(e){return e.trim()}function qr(e){return`${j(e.directory)}\n${e.sessionID}`}function Jr(e,t){return e.session_history_boundary?.[t]??br}function Yr(e){return e.filter(e=>!!e?.id)}function Xr(e,t){return e.kind!==t.kind||e.loadedTurns!==t.loadedTurns?!1:e.kind===`has-more`&&t.kind===`has-more`?e.cursor===t.cursor:!0}function Zr(e,t,n){n.applied&&e.setState(e=>{let r={};if(n.messagesChanged&&(r.message=n.message),n.partsChanged&&(r.part=n.part),n.boundary&&(n.boundaryChanged||!e.session_history_boundary?.[t]))r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary};else if(n.boundary&&n.boundaryChanged===!1){let i=e.session_history_boundary?.[t];(!i||!Xr(i,n.boundary))&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary})}return!r.message&&!r.part&&!r.session_history_boundary&&n.boundary&&(r.session_history_boundary={...e.session_history_boundary??{},[t]:n.boundary}),!r.message&&!r.part&&!r.session_history_boundary?{}:r})}function Qr(e,t,n){let r=e.getState(),i=n.page,a=kr(r,t,{ok:!0,records:i.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),cursor:i.cursor,complete:i.complete,turnCount:i.turnCount,requestedTurnLimit:i.requestedTurnLimit},{purpose:n.purpose,skipPartTypes:n.skipPartTypes,optimistic:n.optimistic?n.optimistic.map(e=>({message:e.message,parts:[...e.parts]})):void 0,capturedRevision:n.capturedLiveRevision,liveRevision:n.liveRevision});return a.applied?(Zr(e,t,a),{applied:!0,changed:a.changed,boundary:a.boundary,meta:a.meta,confirmedOptimisticIDs:a.confirmedOptimisticIDs}):{applied:!1,changed:!1,error:a.error}}function $r(e,t){if(t.length===0)return{applied:!1,changed:!1};let n=e.getState(),r={message:{...n.message??{}},part:{...n.part??{}}},i=!1,a=!1,o;for(let e of t){if(!Kr(e.type))continue;i=!0;let t=Ht(r,e),n=typeof t==`boolean`?t:t.changed,s=typeof t==`boolean`?void 0:t.materialization;s&&!o&&(o=s),n&&(a=!0)}return i?a?(e.setState({message:r.message,part:r.part}),{applied:!0,changed:!0,...o?{materialization:o}:{}}):{applied:!0,changed:!1,...o?{materialization:o}:{}}:{applied:!1,changed:!1}}function ei(e,t){return $r(e,[t.event])}function ti(e,t){return $r(e,t.events)}function ni(e,t,n){if(n.records.length===0)return{applied:!1,changed:!1};let r=e.getState(),i=mr({message:r.message??{},part:r.part??{}},t,n.records.map(e=>({info:e.info,parts:e.parts?[...e.parts]:[]})),{skipPartTypes:n.skipPartTypes,merge:n.merge});return!i.messagesChanged&&!i.partsChanged?{applied:!0,changed:!1}:(e.setState({...i.messagesChanged?{message:i.message}:{},...i.partsChanged?{part:i.part}:{}}),{applied:!0,changed:!0})}function ri(e,t,n){let r=e.getState(),i=r.message?.[t],a=r.part?.[n]!==void 0;if(!i&&!a)return{applied:!0,changed:!1};let o={...r.message??{}},s=!1;if(i){let e=[...i],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,s=!0)}let c={...r.part??{}},l=!1;return c[n]!==void 0&&(delete c[n],l=!0),!s&&!l?{applied:!0,changed:!1}:(e.setState({...s?{message:o}:{},...l?{part:c}:{}}),{applied:!0,changed:!0})}function ii(e,t,n,r,i){r.setOptimisticShadow?.({directory:i,sessionID:t,message:n.message,parts:n.parts});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=o[t]?[...o[t]]:[];return c.some(e=>e.id===n.message.id)||c.push(n.message),o[t]=c,s[n.message.id]=Yr(n.parts),e.setState({message:o,part:s}),{applied:!0,changed:!0}}function ai(e,t,n,r,i){r.clearOptimisticShadow?.({directory:i,sessionID:t,messageID:n});let a=e.getState(),o={...a.message??{}},s={...a.part??{}},c=!1,l=o[t];if(l){let e=[...l],r=e.findIndex(e=>e.id===n);r>=0&&(e.splice(r,1),o[t]=e,c=!0)}return s[n]!==void 0&&(delete s[n],c=!0),c&&e.setState({message:o,part:s}),{applied:!0,changed:c}}function oi(e,t,n,r){return n.clearOptimisticShadow?.({directory:r,sessionID:e,messageID:t}),{applied:!0,changed:!1}}function si(e,t){let n=e.getState(),r=n.message?.[t],i=n.session_history_boundary?.[t],a=!!(r&&r.length>0),o=i!==void 0,s=new Set;if(r)for(let e of r)e?.id&&s.add(e.id);let c=!1,l={...n.part??{}};for(let e of s)l[e]!==void 0&&(delete l[e],c=!0);for(let[e,n]of Object.entries(l))s.has(e)||n?.some(e=>e.sessionID===t)&&(delete l[e],c=!0);if(!a&&!o&&!c)return!1;let u={...n.message??{}};delete u[t];let d={...n.session_history_boundary??{}};return delete d[t],e.setState({message:u,part:l,session_history_boundary:d}),!0}function ci(e,t,n){let r=si(e,t);if(!n.page)return{applied:!0,changed:r};let i=Qr(e,t,{type:`http-page`,purpose:`initial`,page:n.page,capturedLiveRevision:n.capturedLiveRevision,liveRevision:n.liveRevision,skipPartTypes:n.skipPartTypes});return{...i,changed:r||i.changed,applied:i.applied||r}}function li(e){let t=new Map,n=new Map,r=r=>{let i=qr(r);if(n.has(i))return;let a=j(r.directory),o=e.getStore(a),s=r.sessionID,c=o.getState().message?.[s],l=Jr(o.getState(),s),u=new Map;for(let e of c??[])u.set(e.id,o.getState().part?.[e.id]);let d=o.subscribe(e=>{let n=e.message?.[s],a=Jr(e,s),o=!1,d=new Map;for(let t of n??[]){let n=e.part?.[t.id];d.set(t.id,n),u.get(t.id)!==n&&(o=!0)}u.size!==d.size&&(o=!0);let f=n!==c,p=Xr(a,l);if(c=n,l=a,u=d,!f&&!o&&p)return;let m=t.get(i);if(!(!m||m.size===0))for(let e of m)e(r)});n.set(i,d)},i=e=>{let r=t.get(e);if(r&&r.size>0)return;let i=n.get(e);i&&(i(),n.delete(e)),t.delete(e)},a={getTranscript(t){let n=j(t.directory),r=e.getStore(n).getState(),i=t.sessionID,a=r.message?.[i]??[],o=e.getLiveRevision?.(n,i)??0;return Wr({sessionID:i,messages:a,parts:r.part??{},boundary:Jr(r,i),liveRevision:o})},getPagination(t){let n=j(t.directory),r=e.getStore(n).getState();return Ur(t.sessionID,Jr(r,t.sessionID))},getRequestState(t){let n=j(t.directory);return e.getRequestState?.(n,t.sessionID)??{sessionID:t.sessionID,status:`idle`}},getHydrationState(e){let t=a.getTranscript(e),n=zr(t);return{sessionID:e.sessionID,p0Satisfied:n,phase:Br({p0Satisfied:n,earlierHistoryLoaded:Ir(t)>1})}},getMessage(e,t){return a.getTranscript(e).messagesByID[t]},getParts(t,n){let r=j(t.directory);return e.getStore(r).getState().part?.[n]??[]},hasSession(t){let n=j(t.directory),r=e.getStore(n).getState().message;return r?Object.prototype.hasOwnProperty.call(r,t.sessionID):!1},apply(t,n){let r=j(t.directory),i=e.getStore(r),a=t.sessionID;switch(n.type){case`http-page`:return Qr(i,a,n);case`sse-event`:return ei(i,n);case`sse-event-batch`:return ti(i,n);case`optimistic-add`:return ii(i,a,n,e,r);case`optimistic-confirm`:return oi(a,n.messageID,e,r);case`optimistic-remove`:return ai(i,a,n.messageID,e,r);case`reset`:return ci(i,a,n);case`materialize-snapshots`:return ni(i,a,n);case`remove-message`:return ri(i,a,n.messageID);case`revert-committed`:{let e=i.getState(),t=e.message?.[a];if(!Array.isArray(t)||t.length===0)return{applied:!0,changed:!1};let r=t.findIndex(e=>e.id===n.to);if(r<0)return{applied:!0,changed:!1};let o=t.slice(r),s=t.slice(0,r),c={...e.message??{}};c[a]=s;let l={...e.part??{}};for(let e of o)delete l[e.id];return i.setState({message:c,part:l}),{applied:!0,changed:o.length>0}}default:return{applied:!1,changed:!1}}},subscribe(e,n){let a=qr(e),o=t.get(a);return o||(o=new Set,t.set(a,o)),o.add(n),r(e),()=>{let e=t.get(a);e&&(e.delete(n),i(a))}}};return a}var ui=new Set,di=new Set;function fi(e,t){return`${e}\n${t}`}function pi(){for(let e of di)e()}function mi(e,t){!e||!t||(ui.add(fi(e,t)),pi())}function hi(e,t){!e||!t||ui.delete(fi(e,t))&&pi()}function gi(e,t){if(!e)return!1;if(t)return ui.has(fi(t,e));let n=`\n${e}`;for(let e of ui)if(e.endsWith(n))return!0;return!1}function _i(e){return di.add(e),()=>{di.delete(e)}}var vi=[],yi=new Map,bi=new Map,xi=0,Si=()=>{let e=vi.findIndex(e=>e.priority===`user`);if(e>=0){let[t]=vi.splice(e,1);return t}return vi.shift()},Ci=()=>{for(;xi<4;){let e=Si();if(!e)return;yi.delete(e.key),xi+=1,Promise.resolve().then(()=>e.run()).then(t=>{e.resolve(t)},t=>{e.reject(t)}).finally(()=>{--xi,bi.delete(e.key),Ci()})}};function wi(e,t,n){let r=n?.priority??`background`,i=bi.get(e);if(i){let t=yi.get(e);return t&&r===`user`&&t.priority!==`user`&&(t.priority=`user`),i}let a,o,s=new Promise((e,t)=>{a=e,o=t}),c={key:e,priority:r,run:()=>t(),resolve:e=>{a(e)},reject:o};return vi.push(c),yi.set(e,c),bi.set(e,s),Ci(),s}var Ti=null,Ei=0,Di=new Set;function Oi(){Ei+=1;for(let e of Di)e()}function ki(e){return e}function Ai(e){return Di.add(e),()=>{Di.delete(e)}}function ji(){return Ei}function Mi(e){return Ti?.repository===e?e:(Ti={kind:`query`,repository:e},Oi(),e)}function Ni(){Ti&&(Ti=null,Oi())}function M(){return Ti?.repository??null}function Pi(){let e=M();if(!e)throw Error(`TranscriptRepository is not bound — SyncProvider must mount first`);return e}function Fi(e,t){let n=M();if(n)return n;let r=ki(t);return li({getStore:e=>r})}function N(e,t,n){return{directory:e.trim(),sessionID:t,...n?.transport===void 0?{}:{transport:n.transport},...n?.generation===void 0?{}:{generation:n.generation}}}function Ii(e){try{let t=M(),n=o(),r=s();return t?.getCacheBudget?.().listCanonicalScopesForSession(e,{transport:n,generation:r})?.map(e=>N(e.directory,e.sessionID,{transport:e.transport,generation:e.generation}))??[]}catch{return[]}}function Li(e,t){let n=M();return n?n.apply(e,t):null}async function Ri(e,t,n){let r=Pi();if(typeof r.fetchPreviousPage!=`function`)throw Error(`TranscriptRepository does not support fetchPreviousPage`);await r.fetchPreviousPage(N(e,t),n)}async function zi(e,t){let n=Pi();if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support ensureInitial`);await n.ensureInitial(N(e,t))}async function Bi(e,t){let n=Pi(),r=N(e,t);if(typeof n.destructiveReset==`function`){await n.destructiveReset(r);return}if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support retryInitial`);await n.ensureInitial(r)}async function Vi(e,t,n){let r=Pi();if(typeof r.refreshFromAuthority!=`function`)throw Error(`TranscriptRepository does not support refreshFromAuthority`);if(n?.background){await r.refreshFromAuthority(N(e,t));return}mi(e,t);try{await r.refreshFromAuthority(N(e,t))}finally{hi(e,t)}}async function Hi(e,t,n,r){let i=Pi();if(typeof i.materializeMessage!=`function`)throw Error(`TranscriptRepository does not support materializeMessage`);let a=N(e,t);await wi(`${e}\n${t}\n${n}`,()=>i.materializeMessage(a,n),{priority:r?.priority??`background`})}function Ui(e,t,n){let r=M();return!r||typeof r.getMessageMaterializationState!=`function`?{sessionID:t,messageID:n,status:`idle`}:r.getMessageMaterializationState(N(e,t),n)}function Wi(e,t){M()?.purgeSession?.(N(e,t))}var P=null;function Gi(e){P&&P!==e&&P.cancelAll(`reregister`),P=e}function Ki(e){P?.captureCheckpoints(e)}function qi(e){P?.onCompensation(e)}async function Ji(e){return P?P.ensureOnObserve(e):null}function Yi(e){P?.cancelAll(e)}var Xi=e=>typeof e==`number`&&Number.isFinite(e)?e:0,Zi=e=>Xi(e.input)+Xi(e.output)+Xi(e.reasoning)+Xi(e.cache?.read)+Xi(e.cache?.write),Qi=e=>e?.type===`compaction`,$i=e=>!!e&&e.some(Qi),ea=(e,t)=>e.clientRole===`compaction`||e.type===`compaction`||$i(t),ta=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n],i=r.id?t(r.id):void 0;if(ea(r,i)){let e=i?.find(Qi)?.status??r.status;if(e===`running`||e===`failed`)continue;return{compacted:!0}}if(r.role!==`assistant`)continue;let a=r.tokens;if(!a)continue;let o=Zi(a);if(o>0)return{messageId:r.id??``,totalTokens:o,tokens:a}}return null},na=(e,t,n)=>{if(!e)return null;let r=`compacted`in e,i=r?0:e.totalTokens;return{...r?{pending:!0}:{},totalTokens:i,percentage:t>0?Math.round(i/t*100):0,contextLimit:t||0,outputLimit:n||void 0,normalizedOutput:!r&&n>0?Math.round(Xi(e.tokens.output)/n*100):void 0,thresholdLimit:t>0?t:2e5,lastMessageId:r?void 0:e.messageId}},ra=[],ia=[],aa={sessionID:``,messageOrder:[],messagesByID:{},partsByMessageID:{},boundary:br,liveRevision:0};Ur(``,br);var oa={sessionID:``,phase:`idle`,p0Satisfied:!1};function F(e,t){return Fi(e,t)}var sa=new Set;function ca(e,t){return`${e}\n${t}`}function la(e,t){if(!t)return;let n=ca(e,t);sa.has(n)||(sa.add(n),Ji(N(e,t)).catch(()=>{}).finally(()=>{sa.delete(n)}))}function ua(e,t){if(e&&t){sa.delete(ca(e,t));return}sa.clear()}function da(e,t,n,r,i=Object.is,a){let o=(0,y.useRef)(r);o.current=r;let s=(0,y.useRef)(i);s.current=i;let c=(0,y.useRef)(void 0),l=(0,y.useRef)(null),u=a?.enabled!==!1,d=(0,y.useMemo)(()=>()=>{let r=ji(),i=e&&u?F(t,n):null,a=i?.getTranscript(N(t,e))??aa,d=i?.hasSession?.(N(t,e)),f=o.current,p=s.current,m=l.current;if(m?.data===a&&m.select===f&&m.isEqual===p&&m.repository===i&&m.bindingRevision===r&&m.directory===t&&m.sessionID===e&&m.enabled===u&&m.resolved===d)return c.current;let h=f(a);return(c.current===void 0||!p(c.current,h))&&(c.current=h),l.current={data:a,select:f,isEqual:p,repository:i,bindingRevision:r,directory:t,sessionID:e,enabled:u,resolved:d},c.current},[t,u,e,n]),f=(0,y.useMemo)(()=>r=>{if(!e||!u)return()=>void 0;la(t,e);let i=F(t,n).subscribe(N(t,e),()=>{r()}),a=Ai(()=>{i(),c.current=void 0,l.current=null,ua(t,e),la(t,e),i=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{a(),i()}},[t,u,e,n]);return y.useSyncExternalStore(f,d,d)}function fa(e,t,n,r,i,a){return da(e,t,n,r,i===void 0?Object.is:i,a)}function pa(e,t){if(e.messageOrder.length===0)return ra;if(t&&t.length>0){let n=!0,r=0;for(let i of e.messageOrder){let a=e.messagesByID[i];if(a){if(r>=t.length||t[r]!==a){n=!1;break}r+=1}}if(n&&r===t.length)return t}let n=[];for(let t of e.messageOrder){let r=e.messagesByID[t];r&&n.push(r)}return n}function ma(e,t){return e.messageOrder.length===0?t?.resolved===!0?gr({messages:ra,parts:e.partsByMessageID}):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}:gr({messages:pa(e),parts:e.partsByMessageID})}var ha=(e,t)=>e.hasMessages===t.hasMessages&&e.renderable===t.renderable&&e.missingPartMessageIDs.length===t.missingPartMessageIDs.length&&e.missingPartMessageIDs.every((e,n)=>e===t.missingPartMessageIDs[n]);function ga(e,t,n,r){let i=(0,Ce.c)(4),a;return i[0]!==t||i[1]!==e||i[2]!==n?(a=r=>{if(!e)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};let i=F(t,n).hasSession?.(N(t,e));return ma(r,{resolved:i===!0||void 0})},i[0]=t,i[1]=e,i[2]=n,i[3]=a):a=i[3],da(e,t,n,a,ha,r)}function _a(e,t,n,r,i){let a=(0,Ce.c)(3),o;return a[0]!==r||a[1]!==i?(o=e=>na(ta(pa(e),t=>e.partsByMessageID[t]),r,i),a[0]=r,a[1]=i,a[2]=o):o=a[2],da(e,t,n,o,va)}function va(e,t){return e===t||!!(e&&t&&e.pending===t.pending&&e.totalTokens===t.totalTokens&&e.percentage===t.percentage&&e.contextLimit===t.contextLimit&&e.outputLimit===t.outputLimit&&e.normalizedOutput===t.normalizedOutput&&e.lastMessageId===t.lastMessageId)}var ya=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0};function ba(e,t,n,r){return da(e,t,n,pa,ya,r)}function xa(e,t){if(e===t)return!0;if(e.sessionID!==t.sessionID||e.liveRevision!==t.liveRevision||e.boundary.kind!==t.boundary.kind||e.boundary.loadedTurns!==t.boundary.loadedTurns||e.boundary.kind===`has-more`&&t.boundary.kind===`has-more`&&e.boundary.cursor!==t.boundary.cursor||e.messageOrder.length!==t.messageOrder.length)return!1;for(let n=0;n<e.messageOrder.length;n+=1){let r=e.messageOrder[n];if(r!==t.messageOrder[n]||e.messagesByID[r]!==t.messagesByID[r]||e.partsByMessageID[r]!==t.partsByMessageID[r])return!1}return!0}function Sa(e,t,n,r){return da(e,t,n,Ca,xa,r)}function Ca(e){return e}function wa(e,t,n,r){if(e.length===0)return()=>void 0;let i=[],a=()=>{for(let e of i)e();i=[]},o=()=>{let r=new Set;for(let a of e){let e=`${a.directory}\n${a.sessionID}`;if(r.has(e))continue;r.add(e);let o=M();if(o){i.push(o.subscribe(N(a.directory,a.sessionID),t));continue}let s=n?.(a.directory);if(!s)continue;let c=Fi(a.directory,s);i.push(c.subscribe(N(a.directory,a.sessionID),t))}},s=()=>{a(),o(),t()};o();let c=Ai(s),l=r?.subscribeRebuild?.(s);return()=>{l?.(),c(),a()}}function Ta(e,t){return e.length===0?``:e.map(e=>{let n=La(e.directory,e.sessionID,t?.(e.directory)),r=n[n.length-1];return`${e.sessionID}:${r?.id??``}:${r?.role??``}:${r?.time?.completed??``}`}).join(`\0`)}function Ea(e,t,n){return da(e,t,n,Da)}function Da(e){return e.messageOrder.length}function Oa(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(!1),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current=!1,!1;let r=F(t,n),a=r.hasSession?.(N(t,e))??r.getTranscript(N(t,e)).messageOrder.length>0;return i.current=a,i.current},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>e?F(t,n).subscribe(N(t,e),()=>{r()}):ka,r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function ka(){}function Aa(e,t,n,r){let i=(0,Ce.c)(10),a=(0,y.useRef)(void 0),o;i[0]!==t||i[1]!==e||i[2]!==r||i[3]!==n?(o=()=>{if(!e)return a.current=ia,ia;let i=F(t,n),o=r||e,s=i.getParts(N(t,o),e),c=s.length===0?ia:s;if(a.current===void 0||a.current!==c){if(a.current&&a.current.length===c.length&&a.current.every((e,t)=>e===c[t]))return a.current;a.current=c}return a.current},i[0]=t,i[1]=e,i[2]=r,i[3]=n,i[4]=o):o=i[4];let s=o,c;i[5]!==t||i[6]!==e||i[7]!==r||i[8]!==n?(c=i=>{if(!e)return Ma;let a=F(t,n);return r?a.subscribe(N(t,r),()=>{i()}):ja},i[5]=t,i[6]=e,i[7]=r,i[8]=n,i[9]=c):c=i[9];let l=c;return y.useSyncExternalStore(l,s,s)}function ja(){}function Ma(){}function Na(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(oa),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current!==oa&&(i.current=oa),i.current;let r=F(t,n).getHydrationState?.(N(t,e))??{sessionID:e,phase:`idle`,p0Satisfied:!1},a=i.current;return a.sessionID===r.sessionID&&a.phase===r.phase&&a.p0Satisfied===r.p0Satisfied?a:(i.current=r,r)},r[0]=t,r[1]=e,r[2]=n,r[3]=a):a=r[3];let o=a,s;r[4]!==t||r[5]!==e||r[6]!==n?(s=r=>{if(!e)return Pa;la(t,e);let a=F(t,n).subscribe(N(t,e),()=>{r()}),o=Ai(()=>{a(),i.current=oa,ua(t,e),la(t,e),a=F(t,n).subscribe(N(t,e),()=>{r()}),r()});return()=>{o(),a()}},r[4]=t,r[5]=e,r[6]=n,r[7]=s):s=r[7];let c=s;return y.useSyncExternalStore(c,o,o)}function Pa(){}function Fa(e,t,n){let r=(0,Ce.c)(2),i;return r[0]===e?i=r[1]:(i=t=>Ur(e,t.boundary),r[0]=e,r[1]=i),da(e,t,n,i,Ia)}function Ia(e,t){return e.sessionID===t.sessionID&&e.hasPreviousPage===t.hasPreviousPage&&e.isComplete===t.isComplete&&e.cursor===t.cursor&&e.loadedTurns===t.loadedTurns&&e.boundary.kind===t.boundary.kind&&e.boundary.loadedTurns===t.boundary.loadedTurns&&(e.boundary.kind!==`has-more`||t.boundary.kind!==`has-more`||e.boundary.cursor===t.boundary.cursor)}function La(e,t,n){if(!t)return[];let r=M();if(r){let n=r.getTranscript(N(e,t));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}if(!n)return[];let i=Fi(e,n).getTranscript(N(e,t));return i.messageOrder.map(e=>i.messagesByID[e]).filter(e=>!!e)}var I=null,Ra=``,za=null,Ba=new Set,Va=null,Ha=new Map,Ua=new Map;function Wa(e,t,n,r){I=t,Va!==t&&(Va=null,Ha=new Map,Ua=new Map),Ra=n,r&&(za=r)}function Ga(e,t){za?.(e,t)}function Ka(){if(!I)throw Error(`ChildStoreManager not initialized — is SyncProvider mounted?`);return I}function qa(e){let t=I;if(!t)return;let n=e||Ra;if(n)return t.getState(n)}function Ja(e){let t=qa(e)?.config;return t&&Object.keys(t).length>0?t:void 0}function Ya(e){return Ba.add(e),()=>{Ba.delete(e)}}function Xa(e,t){if(e)for(let n of Ba)n(e,t)}function Za(e){return qa(e)?.session??[]}function Qa(){return Array.from($a().values())}function $a(){let e=I;if(!e)return Ua;let t=Va!==e||Ha.size!==e.children.size;for(let[n,r]of e.children)if(Ha.get(n)!==r.getState().session){t=!0;break}if(!t)return Ua;let n=new Map,r=new Map;for(let[t,i]of e.children){let e=i.getState().session;n.set(t,e);for(let t of e)t?.id&&r.set(t.id,t)}return Va=e,Ha=n,Ua=r,Ua}function eo(e,t,n){if(n){let r=[];for(let[i,a]of n)if(a.session.some(t=>t.id===e)&&a.hasTranscript===!0){if(i===t)return i;r.push(i)}return r.length===1?r[0]:void 0}let r=[];try{let n=M();if(I){for(let[i,a]of I.children)if(a.getState().session.some(t=>t.id===e)&&(n??Fi(i,a)).hasSession?.(N(i,e))){if(i===t)return i;r.push(i)}}if(r.length===0&&n){let i=n.getCacheBudget?.().listCanonical();if(i){for(let n of i)if(n.scope.sessionID===e){if(n.scope.directory===t)return n.scope.directory;r.push(n.scope.directory)}}}}catch{}let i=[...new Set(r)];return i.length===1?i[0]:void 0}function to(e,t){if(!e)return[];try{let n=M(),r=t??Ra;if(n){let t=n.getTranscript(N(r,e));return t.messageOrder.map(e=>t.messagesByID[e]).filter(e=>!!e)}if(I){let t=I.getChild(r);if(t){let n=Fi(r,t).getTranscript(N(r,e));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}}}catch{}return[]}function no(e,t){if(!e)return[];try{let n=M(),r=t??Ra;if(n)return[...n.getParts(N(r,e),e)];if(I){let t=I.getChild(r);if(t)return[...Fi(r,t).getParts(N(r,e),e)]}}catch{}return[]}var L=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},ro=`default`;function io(e){let t=L(e);if(t&&t!==ro)return t}function ao(e){let t=e?.model;return L(t?.id)??L(t?.modelID)}function oo(e){let t=e?.model;return L(t?.providerID)}function so(e){let t=e?.model;return io(t?.variant)}function co(e){let t=io(e.variant);return{id:e.modelID.trim(),providerID:e.providerID.trim(),...t?{variant:t}:{}}}function lo(e,t,n){let r=L(n.providerID),i=L(n.modelID);if(!r||!i)return{agent:L(n.agent)};let a=(qa(t)?.session??Qa()).find(t=>t.id===e),o=co({providerID:r,modelID:i,variant:n.variant}),s=ao(a),c=oo(a),l=so(a),u=io(o.variant),d=!a||!s||!c||c!==o.providerID||s!==o.id||l!==u,f=L(n.agent),p=L(a?.agent);return{model:d?o:void 0,agent:f&&p!==f?f:void 0}}function uo(e,t,n){if(e&&!(!n.model&&!n.agent))try{let r=Ka(),i=typeof t==`string`&&t.length>0?t:void 0;if(!i)return;let a=r.getChild?.(i)??r.ensureChild?.(i,{bootstrap:!1});if(!a?.getState||!a?.setState)return;a.setState(t=>{let r=t.session;if(!Array.isArray(r))return t;let i=r.findIndex(t=>t.id===e);if(i<0)return t;let a=r[i];if(!a)return t;let o=n.model?{id:n.model.id??n.model.modelID??``,providerID:n.model.providerID,...n.model.variant?{variant:n.model.variant}:{}}:a.model,s={...a,...n.model&&o?.id&&o.providerID?{model:o}:{},...n.agent?{agent:n.agent}:{}};if(s===a)return t;let c=r.slice();return c[i]=s,{...t,session:c}})}catch{}}var fo=new Set([`image/heic`,`image/heif`]),po=!1,mo=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},ho=e=>fo.has((e.type||``).toLowerCase()),go=async e=>{let t=new Uint8Array(await e.arrayBuffer()),n=``,r=32768;for(let e=0;e<t.byteLength;e+=r){let i=t.subarray(e,Math.min(e+r,t.byteLength));n+=String.fromCharCode(...i)}return btoa(n)},_o=(e,t)=>{let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new Blob([r],{type:t})},vo=async e=>{if(!ho(e)||po)return null;let t=mo();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.YuriMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await go(e),mime:e.type.toLowerCase(),quality:.9});if(typeof t?.data!=`string`||!t.data)return null;let r=typeof t.mime==`string`&&t.mime?t.mime:`image/jpeg`;return _o(t.data,r)}catch(e){return po=!0,console.warn(`Native HEIC transcode failed`,e),null}},yo=e=>e.trim().toLowerCase(),bo=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,xo=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(yo)),r=[],i=0;for(;i<e.length;){let t=e.indexOf(`[`,i);if(t===-1)break;let a=e.indexOf(`]`,t+1);if(a===-1)break;if(e[a+1]!==`(`){let i=se(e.slice(t+1,a)).trim();n.has(yo(i))&&r.push({start:t,end:a+1})}i=a+1}return r},So=(e,t)=>{let n=t.start,r=t.end;return r<e.length&&/\s/.test(e[r])?r+=1:n>0&&/\s/.test(e[n-1])&&--n,{start:n,end:r}},Co=(e,t,n,r)=>{let i=xo(e,t);if(i.length===0)return{text:e,mentions:[...n],composerReferences:r===void 0?void 0:[...r],changed:!1};let a=e,o=[...n],s=r===void 0?[]:[...r];for(let e=i.length-1;e>=0;--e){let{start:t,end:n}=So(a,i[e]),r=n-t;a=`${a.slice(0,t)}${a.slice(n)}`,o=o.flatMap(e=>e.range.end<=t?[e]:e.range.start>=n?[{...e,range:{start:e.range.start-r,end:e.range.end-r}}]:[]),s=s.flatMap(e=>e.end<=t?[e]:e.start>=n?[{...e,start:e.start-r,end:e.end-r}]:[])}return{text:a,mentions:o,composerReferences:r===void 0?void 0:s,changed:!0}},wo=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),To={"image/avif":`avif`,"image/bmp":`bmp`,"image/gif":`gif`,"image/heic":`heic`,"image/heif":`heif`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/png":`png`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/webp":`webp`},Eo=e=>e.trim().toLowerCase(),Do=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Oo=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>Do(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},ko=e=>To[e?.trim().toLowerCase()??``]??`png`,Ao=e=>{let t=Oo(e.name),n=ko(e.type),r=t.lastIndexOf(`.`);if(r>0&&r<t.length-1){let e=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(e))return{base:t.slice(0,r).trim()||`image`,ext:e}}return{base:t.trim()||`image`,ext:n}},jo=e=>{let{base:t}=Ao({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(wo.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&wo.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Mo=(e,t)=>`${e}.${t}`,No=(e,t,n)=>{let r=Mo(e,t);if(!n.has(Eo(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=Mo(`${e}-${r}`,t);if(!n.has(Eo(i)))return i}return Mo(`${e}-${Date.now()}`,t)},Po=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=Mo(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(Eo(r)))return r}return Mo(`image-${Date.now()}`,e)},Fo=(e,t)=>{let n=new Set(t.map(Eo));return e.map(e=>{let{base:t,ext:r}=Ao(e),i=jo(Mo(t,r))?Po(r,n):No(t,r,n);return n.add(Eo(i)),i})},Io=e=>e.map(e=>le(e)).join(` `),Lo=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[le(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},Ro=(e,t)=>{if(t.length>=e.length)return null;let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n+=1;let i=0;for(;i<e.length-n&&i<t.length-n&&e[e.length-1-i]===t[t.length-1-i];)i+=1;let a=e.length-i;return t.length-i!==n||a<=n?null:{start:n,end:a}},zo=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=Ro(e,t);if(i){let t=Xo(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=Lo(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Bo=e=>e.replaceAll(`[${oe}`,`[`),Vo=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Ho=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Uo=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Ho(t)||!Vo.test(t)&&!Vo.test(r))continue;let i=`[${r}]`;n=n.split(le(t)).join(i).split(`[${t}]`).join(i)}return n},Wo=(e,t)=>{let n=e;for(let e of t??[]){if(e.source!==`vscode`||e.vscodeSource!==`selection`||!e.vscodePath)continue;let t=e.filename.match(/:(\d+(?:-\d+)?)$/)?.[1];if(!t)continue;let r=`[${e.vscodePath}:${t}]`;n=n.split(le(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Go=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Ko=`application/x-directory`,qo=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Jo=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Yo=(e,t,n)=>{if(t===`Backspace`){let t=n;for(;t>0&&/\s/.test(e[t-1]);)--t;for(;t>0&&!/\s/.test(e[t-1]);)--t;return{start:t,end:n}}let r=n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;for(;r<e.length&&!/\s/.test(e[r]);)r+=1;return{start:n,end:r}},Xo=(e,t,n)=>{let r=Math.max(0,Math.min(n.selectionStart,e.length)),i=Math.max(r,Math.min(n.selectionEnd,e.length)),a;if(a=r===i?n.altKey?Yo(e,n.key,r):n.key===`Backspace`?{start:Math.max(0,r-1),end:r}:{start:r,end:Math.min(e.length,r+1)}:{start:r,end:i},a.start===a.end)return null;let o=xo(e,t).filter(e=>e.start<a.end&&e.end>a.start);if(o.length===0)return null;let s=Math.min(a.start,...o.map(e=>e.start)),c=Math.max(a.end,...o.map(e=>e.end));return c<e.length&&/\s/.test(e[c])&&(s===0||/\s/.test(e[s-1]))?c+=1:c===e.length&&s>0&&/\s/.test(e[s-1])&&--s,{text:`${e.slice(0,s)}${e.slice(c)}`,caret:s,removedFilenames:o.map(t=>se(e.slice(t.start+1,t.end-1)).trim())}},Zo=`<system-reminder>`,Qo=`</system-reminder>`,$o=/[ \t]*<system-reminder>[\s\S]*?<\/system-reminder>[ \t]*/g,es=/[ \t]*<system-reminder>[\s\S]*$/,ts=e=>{let t=e.trim();return t?t.startsWith(Zo)&&t.endsWith(Qo)?t:`${Zo}\n${t}\n${Qo}`:``},ns=e=>e.includes(Zo)?e.replace($o,``).replace(es,``).trim():e,rs=class extends Error{status;code;constructor(e,t,n=`Failed to upload prompt attachment`){super(n),this.name=`PromptAttachmentUploadError`,this.status=e,this.code=t}},is=`file://`,as=e=>{let t=e.trim();if(t.toLowerCase().startsWith(is))return t;let n=pe(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${is}/${n}`:`${is}${n}`},os=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(is))return t;let n=t.slice(7);n.toLowerCase().startsWith(`localhost/`)&&(n=n.slice(9));let r=n.split(`/`).map(e=>{if(/^[A-Za-z]:$/.test(e))return e;try{return decodeURIComponent(e)}catch{return e}}).join(`/`);return/^\/[A-Za-z]:/.test(r)?r.slice(1):r},ss=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),cs=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ls=async e=>{let t;try{t=await e.json()}catch{throw new rs(e.status,`unavailable`)}if(!cs(t)||typeof t.path!=`string`||!t.path)throw new rs(e.status,`unavailable`);let n=typeof t.mime==`string`&&t.mime?t.mime:`application/octet-stream`,r=typeof t.size==`number`&&Number.isSafeInteger(t.size)?t.size:0,i=typeof t.sha256==`string`?t.sha256:``;return{path:t.path,url:as(t.path),mime:n,size:r,sha256:i}},us=e=>{let t=typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,n=e?.replace(/[^a-z0-9._-]+/gi,`-`).replace(/^-+|-+$/g,``).slice(0,32);return n?`att-${t}-${n}`:`att-${t}`},ds=(e,t)=>{if(!e.startsWith(`data:`))return null;let n=e.indexOf(`,`);if(n===-1)return null;let r=e.slice(5,n),i=e.slice(n+1),a=r.split(`;`,1)[0]?.trim()||t||`application/octet-stream`;try{if(r.toLowerCase().includes(`;base64`)){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([t],{type:a})}return new Blob([decodeURIComponent(i)],{type:a})}catch{return null}},fs=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),ps=async e=>{let t=me(),n=e.mime||e.body.type||`application/octet-stream`,r=e.body.type===n?e.body:new Blob([e.body],{type:n});if(!Number.isSafeInteger(r.size)||r.size<0)throw new rs(413,`too-large`);let i=await ss(r),a=us(e.filename),o;try{o=await u(`/api/fs/prompt-attachments/${encodeURIComponent(a)}?storage=temporary`,{method:`PUT`,headers:{"Content-Type":n,"Content-Length":String(r.size),"X-Yuri-Content-Length":String(r.size),"X-Yuri-Sha256":i,"X-Yuri-Mime":n,...e.filename?{"X-Yuri-Filename":encodeURIComponent(e.filename)}:{}},body:r,signal:e.signal})}catch{throw new rs(0,`unavailable`)}if(o.status===413)throw new rs(413,`too-large`);if(!o.ok)throw new rs(o.status,o.status>=500||o.status===0?`unavailable`:`rejected`);let s=await ls(o);if(s.size!==r.size)throw new rs(o.status,`unavailable`);return await t(r,s.sha256),{...s,mime:n}},ms=500,hs=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`YURI_STARTUP_TRACE`)===`1`}catch{return!1}},gs=()=>hs(),R=(e,t)=>{if(!hs())return;let n=typeof performance<`u`?performance.now():Date.now();window.__YURI_STARTUP_TRACE_START__??=n,window.__YURI_STARTUP_TRACE__??=[],window.__YURI_STARTUP_TRACE__.push({t:Math.round(n-window.__YURI_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__YURI_STARTUP_TRACE__.length>ms&&window.__YURI_STARTUP_TRACE__.splice(0,window.__YURI_STARTUP_TRACE__.length-ms)};typeof window<`u`&&(window.__YURI_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__YURI_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var _s=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();R(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return R(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw R(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},vs=e=>({kind:`session-inbox`,requestID:e.requestID,queueItemID:e.id,operationID:e.id,messageID:e.id,content:e.payload.text,createdAt:e.timeCreated,delivery:e.delivery,attachmentCount:Array.isArray(e.payload.files)?e.payload.files.length:0}),ys=[],bs=[],z=new Map,xs=512,Ss=0;function Cs(){return Ss}function B(){return{transportIdentity:o(),generation:s()}}function ws(e){return o()===e.transportIdentity&&s()===e.generation}function Ts(e,t,n){return`${n?.transportIdentity??o()}\0${n?.generation??s()}\0${e}\0${t}`}function Es(e=B()){if(z.size===0)return;let t=`${e.transportIdentity}\0${e.generation}\0`;for(let e of z.keys())e.startsWith(t)||z.delete(e);for(;z.size>xs;){let e=z.keys().next().value;if(e===void 0)break;z.delete(e)}}function Ds(e,t,n,r){let i=r??B();Es(i),Ss+=1,z.set(Ts(e,t,i),{kind:n,mark:Ss})}function Os(e,t,n){let r=n?.scope;Es(r??B());let i=z.get(Ts(e,t,r));if(!i)return!0;let a=n?.startedMark;return a!==void 0&&i.mark>a?!1:(z.delete(Ts(e,t,r)),!0)}function ks(e,t,n){return Es(n??B()),z.get(Ts(e,t,n))?.kind??null}var As=(e,t,n)=>{let r={...e};return n.length===0?delete r[t]:r[t]=n,r},V=m((e,t)=>({bySession:{},remember(t){return!ks(t.sessionID,t.id)&&(e(e=>{let n=e.bySession[t.sessionID]??[],r=n.findIndex(e=>e.id===t.id),i={...t,requestID:t.id};if(r>=0){let a=n.slice();return a[r]=i,{bySession:{...e.bySession,[t.sessionID]:a}}}return{bySession:{...e.bySession,[t.sessionID]:[...n,i]}}}),!0)},forget(t,n,r){r&&Ds(t,n,r),e(e=>{let r=e.bySession[t];if(!r?.length)return e;let i=r.filter(e=>e.id!==n);return i.length===r.length?e:{bySession:As(e.bySession,t,i)}})},forgetSession(t){e(e=>{if(!e.bySession[t])return e;let n={...e.bySession};return delete n[t],{bySession:n}})},forgetPromoted(t,n){let r=new Set(n);e(e=>{let n=e.bySession[t];if(!n?.length)return e;let i=new Set(n.filter(e=>r.has(e.id)).map(e=>e.id));if(i.size===0)return e;for(let e of i)Ds(t,e,`consumed`);return{bySession:As(e.bySession,t,n.filter(e=>!i.has(e.id)))}})},replaceFromAuthority(t,n,r){let i=r?.startedMark,a=[];for(let e of n)Os(t,e.id,{startedMark:i})&&a.push(e);e(e=>{let n=new Map((e.bySession[t]??[]).map(e=>[e.id,e])),i=r?.observedItems&&new Map(r.observedItems.map(e=>[e.id,e])),o=a.map(e=>({...e,requestID:e.id}));if(i){let e=new Map(o.map((e,t)=>[e.id,t]));for(let t of n.values()){if(i.get(t.id)===t)continue;let n=e.get(t.id);n===void 0?o.push(t):o[n]=t}}return{bySession:As(e.bySession,t,o)}})},updateDelivery(t,n,r){e(e=>{if(ks(t,n))return e;let i=e.bySession[t];if(!i?.length)return e;let a=i.findIndex(e=>e.id===n);if(a<0||i[a].delivery===r)return e;let o=i.slice();return o[a]={...i[a],delivery:r},{bySession:{...e.bySession,[t]:o}}})},list(e){return t().bySession[e]??ys}}));function js(e){return V.getState().remember(e)}function Ms(e,t){return Os(e.sessionID,e.id,t)?V.getState().remember(e):!1}function Ns(e,t,n){V.getState().forget(e,t,n)}function Ps(e,t){V.getState().forgetPromoted(e,t)}function Fs(e,t,n){V.getState().replaceFromAuthority(e,t,n)}function Is(e,t,n){V.getState().updateDelivery(e,t,n)}function Ls(e){return!!e&&typeof e==`object`&&e.kind===`session-inbox`}var Rs=e=>e?e.toLowerCase().includes(`application/json`):!1,zs=e=>e?e.toLowerCase().includes(`text/html`):!1;function H(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function U(e){return typeof e==`string`&&e.length>0?e:void 0}function Bs(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Vs(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Hs(e){try{let t=(await e.text()).trim();if(!t)return``;try{let e=JSON.parse(t);if(typeof e.error==`string`&&e.error.trim())return e.error.trim();if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}return t}catch{return``}}function Us(e){return e?{directory:e}:{}}function Ws(e,t){let n=`/api/session/${encodeURIComponent(e)}/inbox`;return t?`${n}/${encodeURIComponent(t)}`:n}async function Gs(e,t){let n=e.headers.get(`content-type`);if(zs(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!Rs(n)&&r==null)throw Error(`${t}: empty response`);return r}function Ks(e){let t=H(e)?e:null,n=t&&H(t.data)?t.data:t;if(!n)throw Error(`session prompt: expected inbox item`);let r=U(n.type);if(r&&r!==`user`)throw Error(`session prompt: expected user inbox item, got ${r}`);let i=U(n.id),a=U(n.sessionID);if(!i||!a)throw Error(`session prompt: inbox item missing id`);let o=H(n.payload)?n.payload:{},s=n.delivery===`queue`?`queue`:`steer`,c=H(n.time)?n.time:null;return{id:i,sessionID:a,timeCreated:Bs(n.timeCreated)??Bs(c?.created)??Date.now(),type:`user`,delivery:s,payload:{text:U(o.text)??U(n.text)??``,...o.files===void 0?{}:{files:o.files},...o.agents===void 0?{}:{agents:o.agents},...o.skills===void 0?{}:{skills:o.skills},...H(o.metadata)?{metadata:o.metadata}:{}}}}function qs(e){let t=H(e)?e:null,n=t&&Array.isArray(t.data)?t.data:Array.isArray(e)?e:null;if(!n)throw Error(`session inbox: expected list`);let r=[];for(let e of n)H(e)&&(e.type&&e.type!==`user`||r.push(Ks(e)));return r}function Js(e){return{runtimeKey:c(),generation:s(),directory:e,overlay:B()}}function W(e){return c()===e.runtimeKey&&s()===e.generation&&ws(e.overlay)}function Ys(e){let t=Error(`${e}: runtime switched`);throw t.name=`RuntimeGenerationMismatchError`,t}async function Xs(e){let t=e.commit??Js(e.directory);W(t)||Ys(`session prompt`);let n=`/api/session/${encodeURIComponent(e.sessionID)}/prompt`,r={id:e.messageID,text:e.text,delivery:e.delivery===`queue`?`queue`:`steer`};e.files?.length&&(r.files=e.files),e.agents?.length&&(r.agents=e.agents),e.skills?.length&&(r.skills=e.skills),e.metadata&&(r.metadata=e.metadata);let i=await u(n,{method:`POST`,headers:{"Content-Type":`application/json`},query:{directory:t.directory},body:JSON.stringify(r),signal:e.signal});if(W(t)||Ys(`session prompt`),!i.ok){let e=await Hs(i);Vs(`Failed to send message`,i.status,e)}let a=Ks(await Gs(i,`session prompt`));return W(t)||Ys(`session prompt`),js(a),a}function Zs(e){let t=e?.status;return typeof t!=`number`||!Number.isFinite(t)||t===408||t===429?!1:t>=400&&t<500}async function Qs(e){let t=e.inputID.trim();if(!t)return{status:`unknown`};let n=e.commit??Js(e.directory??``);if(!W(n))return{status:`unknown`};try{let r=await ec({sessionID:e.sessionID,directory:n.directory||e.directory,signal:e.signal});if(!W(n)||!r.current)return{status:`unknown`};let i=r.items.find(e=>e.id===t);if(i)return Ms(i,{startedMark:r.startedMark})?{status:`pending`,item:i}:{status:`unknown`}}catch{}if(!W(n))return{status:`unknown`};try{let r=await $e({sessionID:e.sessionID,directory:n.directory||e.directory||``,limit:40,...e.signal?{signal:e.signal}:{}});if(!W(n))return{status:`unknown`};if(r.records.some(e=>e?.info?.id===t))return Ns(e.sessionID,t,`consumed`),{status:`promoted`,id:t}}catch{}return{status:`unknown`}}function $s(e){let t=typeof e.type==`string`?e.type:``,n=e.properties&&typeof e.properties==`object`?e.properties:null;if(!n)return!1;let r=U(n.sessionID),i=U(n.inboxID)??U(n.id);if(!r||!i)return!1;if(t===`session.inbox.enqueued`){let e=n.item,t=H(e)?U(e.type):void 0;if(t&&t!==`user`)return!1;try{return Ms(Ks(H(e)?{...e,id:i,sessionID:r,type:t??`user`}:{id:i,sessionID:r,type:`user`,delivery:`steer`,payload:{text:``}})),!0}catch{return!1}}if(t===`session.inbox.cancelled`)return Ns(r,i,`cancelled`),!0;if(t===`session.inbox.delivered`)return Ns(r,i,`consumed`),!0;if(t===`session.inbox.delivery.changed`){let e=n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:null;return e?(Is(r,i,e),!0):!1}return!1}async function ec(e){let t=B(),n=Cs(),r=ut(e.sessionID),i={method:`GET`,query:Us(e.directory),signal:e.signal},a=await u(`/api/sessions/${encodeURIComponent(e.sessionID)}/delivery`,i);(a.status===404||a.status===501||zs(a.headers.get(`content-type`)))&&(a=await u(Ws(e.sessionID),i)),a.ok||Vs(`session inbox`,a.status,await Hs(a));let o=await Gs(a,`session inbox`),s=qs(o),c=ws(t);return c&&ut(e.sessionID)===r&&(H(o)&&typeof o.compactionRunning==`boolean`?w(e.sessionID,o.compactionRunning):gt(e.sessionID,ht(o))),{items:s,startedMark:n,scope:t,current:c}}async function tc(e){let t=B(),n=await u(Ws(e.sessionID,e.inboxID),{method:`PATCH`,headers:{"Content-Type":`application/json`},query:Us(e.directory),body:JSON.stringify({delivery:e.delivery}),signal:e.signal});n.ok||Vs(e.delivery===`steer`?`session inbox steer`:`session inbox queue`,n.status,await Hs(n)),ws(t)&&(ks(e.sessionID,e.inboxID)||Is(e.sessionID,e.inboxID,e.delivery))}async function nc(e){await tc({...e,delivery:`steer`})}async function rc(e){await tc({...e,delivery:`queue`})}async function ic(e){let t=await u(Ws(e.sessionID,e.inboxID),{method:`DELETE`,query:Us(e.directory),signal:e.signal});t.ok||Vs(`session inbox cancel`,t.status,await Hs(t))}function ac(e,t,n){Fs(e,t,n)}async function oc(e){let t=B();if(await ic(e),!ws(t))return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};Ns(e.sessionID,e.inboxID,`cancelled`);try{let n=await ec({sessionID:e.sessionID,directory:e.directory,signal:e.signal});if(!ws(t)||!n.current)return{overlay:V.getState().list(e.sessionID),transcriptRows:[]};ac(e.sessionID,n.items,{startedMark:n.startedMark})}catch{}return{overlay:V.getState().list(e.sessionID),transcriptRows:[]}}async function sc(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/interrupt`,n={};e.directory&&(n.directory=e.directory),e.resume!==void 0&&(n.resume=String(e.resume));let r=await u(t,{method:`POST`,query:n,signal:e.signal});if(!r.ok)throw Error(`Session interrupt failed (${r.status})`)}async function cc(e){return e.promotedIDs.includes(e.optimisticID)?`confirmed`:(e.removeOptimistic(e.optimisticID),await e.refreshFromAuthority(),`refreshed`)}var lc=`session-revert-busy`,uc=e=>e?e.toLowerCase().includes(`text/html`):!1;function dc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fc(e){return typeof e==`string`&&e.length>0?e:void 0}function pc(e,t,n){if(t===409)throw mc();let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);if(i.status=t,t===404&&n)try{let e=JSON.parse(n);dc(e)&&e._tag===`MessageNotFoundError`&&(i.name=`MessageNotFoundError`)}catch{}throw i}function mc(){let e=Error(lc);return e.name=`SessionRevertBusyError`,e}function hc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`SessionRevertBusyError`||t.message===`session-revert-busy`}async function gc(e){try{return(await e.text()).trim()}catch{return``}}async function _c(e,t){if(uc(e.headers.get(`content-type`)))throw Error(`${t}: unexpected HTML response`);if(e.status===204)return null;let n=await e.text();if(!n.trim()){if(e.ok)return null;throw Error(`${t}: empty response`)}try{return JSON.parse(n)}catch{throw Error(`${t}: malformed JSON`)}}function vc(e){return e?{directory:e}:{}}function yc(e,t){return`/api/session/${encodeURIComponent(e)}/revert/${t}`}function bc(e){let t=dc(e)?e:null,n=t&&dc(t.data)?t.data:t;if(!n)throw Error(`session revert: expected revert payload`);let r=fc(n.messageID);if(!r)throw Error(`session revert: missing messageID`);let i=Array.isArray(n.files)?n.files.flatMap(e=>{if(!dc(e))throw Error(`session revert: invalid file diff`);let t=fc(e.file)??fc(e.path);if(!t||e.status!==`added`&&e.status!==`deleted`&&e.status!==`modified`||typeof e.additions!=`number`||typeof e.deletions!=`number`||typeof e.patch!=`string`)throw Error(`session revert: invalid file diff`);return[{file:t,status:e.status,additions:e.additions,deletions:e.deletions,patch:e.patch}]}):void 0;return{messageID:r,...fc(n.partID)?{partID:fc(n.partID)}:{},...fc(n.snapshot)?{snapshot:fc(n.snapshot)}:{},...i?{files:i}:{}}}function xc(e){return e?.files?e.files.flatMap(e=>{let t=typeof e.file==`string`&&e.file.length>0?e.file:typeof e.path==`string`&&e.path.length>0?e.path:``;return t?[t]:[]}):[]}async function Sc(e){let t=await u(yc(e.sessionID,`stage`),{method:`POST`,headers:{"Content-Type":`application/json`},query:vc(e.directory),body:JSON.stringify({messageID:e.messageID,files:e.files!==!1}),signal:e.signal});return t.ok||pc(`session revert stage`,t.status,await gc(t)),bc(await _c(t,`session revert stage`))}async function Cc(e){let t=await u(`/api/session/${encodeURIComponent(e.sessionID)}/revert`,{method:`DELETE`,query:vc(e.directory),signal:e.signal});t.ok||pc(`session revert clear`,t.status,await gc(t))}async function wc(e){let t=await u(yc(e.sessionID,`commit`),{method:`POST`,query:vc(e.directory),signal:e.signal});t.ok||pc(`session revert commit`,t.status,await gc(t))}var Tc=e=>e?e.toLowerCase().includes(`text/html`):!1;function Ec(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Dc(e){try{return(await e.text()).trim()}catch{return``}}function Oc(e){return e?{directory:e}:{}}function kc(e,t){return`/api/session/${encodeURIComponent(e)}/permission/${encodeURIComponent(t)}/reply`}async function Ac(e){let t=await u(kc(e.sessionID,e.requestID),{method:`POST`,headers:{"Content-Type":`application/json`},query:Oc(e.directory),body:JSON.stringify({decision:e.reply,...e.message?{message:e.message}:{}}),signal:e.signal});if(t.ok||Ec(`session permission reply`,t.status,await Dc(t)),t.status!==204&&Tc(t.headers.get(`content-type`)))throw Error(`session permission reply: unexpected HTML response`)}function jc(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function Mc(e){let t=typeof e.directory==`string`?e.directory:``;return{state:``,config:``,worktree:typeof e.project?.directory==`string`?e.project.directory:t,directory:t,home:``}}function Nc(e){return e.worktree||e.canonical||``}function Pc(e,t){let n={};if(t.size===0)return n;for(let[r,i]of Object.entries(e))t.has(r)&&i?.type===`running`&&(n[r]={type:`busy`});return n}function Fc(e){return{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?.messageID?{tool:{messageID:e.source.messageID,callID:e.source.id??``}}:{}}}function Ic(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.kind===`question`}function Lc(e){let t=e.metadata&&typeof e.metadata.tool==`object`&&e.metadata.tool&&!Array.isArray(e.metadata.tool)?e.metadata.tool:void 0,n=typeof e.tool?.messageID==`string`&&e.tool.messageID.length>0?e.tool.messageID:typeof t?.messageID==`string`&&t.messageID.length>0?t.messageID:void 0;if(n)return{messageID:n,callID:typeof e.tool?.id==`string`?e.tool.id:typeof t?.id==`string`?t.id:``}}function Rc(e){let t=e.fields;if(!t||t.length===0){let t=typeof e.title==`string`&&e.title.length>0?e.title:`Form`;return[{question:t,header:t,options:[]}]}return t.map(t=>{let n=typeof t.title==`string`&&t.title.length>0?t.title:t.key;return{question:typeof t.description==`string`&&t.description.length>0?t.description:typeof e.title==`string`&&e.title.length>0?e.title:n,header:n,options:(t.options??[]).map(e=>({label:e.label||e.value||``,description:typeof e.description==`string`?e.description:``})).filter(e=>e.label.length>0),...t.type===`multiselect`?{multiple:!0}:{}}})}function zc(e){let t=e.questions&&e.questions.length>0?e.questions.map(e=>({question:e.question,header:e.header,options:e.options??[],...e.multiple?{multiple:!0}:{}})):Rc(e),n=Lc(e);return{id:e.id,sessionID:e.sessionID,questions:t,...n?{tool:n}:{}}}function Bc(e,t){let n={};for(let r=0;r<t.length;r+=1){let i=t[r],a=(e[r]??[]).map(e=>i.options?.find(t=>(t.label||t.value)===e)?.value??e),o=a[0]??``;if(i.type===`multiselect`)n[i.key]=a;else if(i.type===`number`||i.type===`integer`){let e=Number(o);if(!o.trim()||!Number.isFinite(e)||i.type===`integer`&&!Number.isInteger(e))throw Error(`Invalid numeric answer for ${i.key}`);n[i.key]=e}else if(i.type===`boolean`){if(o!==`true`&&o!==`false`)throw Error(`Invalid boolean answer for ${i.key}`);n[i.key]=o===`true`}else n[i.key]=o}return n}var Vc=3,Hc=3e4,Uc=32e3,Wc=36e5,Gc=6e5,Kc=new Set([429,502,503,504]),qc=new Map;function Jc(){let e=Date.now();for(let[t,n]of qc)n.consecutiveErrors===0&&e-n.lastErrorAt>Wc&&qc.delete(t)}typeof setInterval<`u`&&setInterval(Jc,Gc).unref?.();function Yc(e){let t=qc.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Hc},qc.set(e,t)),t}function Xc(e){if(!e)return;let t=qc.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function Zc(e,t){if(!e)return;let n=Yc(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Qc(t)&&n.consecutiveErrors>=Vc&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Qc(e){return e!==void 0&&Kc.has(e)}function $c(e){let t=qc.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Uc*4),!1):!0:!1}function el(e){if(!(!e||!$c(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var tl=`/api`,nl=1e4,rl=4e3,il=3e3,al=1e3,ol=1500,sl=12e3;function cl(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function G(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function ll(e){if(e instanceof ne&&e.reason===`UnexpectedStatus`){let t=e.cause;if(t&&typeof t==`object`&&`status`in t){let e=t.status;if(typeof e==`number`)return e}}if(e&&typeof e==`object`&&`status`in e){let t=e.status;if(typeof t==`number`)return t}}function ul(e){return e===404||e===405||e===501}function K(e){if(typeof e!=`string`)return;let t=e.trim();if(t)return{location:{directory:t}}}function dl(e){let t=e.replace(/\/+$/,``);if(t.endsWith(`/api`)){let e=t.slice(0,-4);if(e.length>0)return e}return ml(gl()||`/`)}function fl(e){return!e||typeof e.id!=`string`||e.id.length===0||typeof e.sessionID!=`string`||e.sessionID.length===0?null:{id:e.id,sessionID:e.sessionID,permission:e.action,patterns:Array.isArray(e.resources)?e.resources:[],metadata:e.metadata??{},always:Array.isArray(e.save)?e.save:[],...e.source?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}}var pl=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ml=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(pl.test(t)||typeof window>`u`)return t;let n=window.location?.href||window.location?.origin;if(!n)return t;try{return new URL(t,n).toString()}catch(e){return console.warn(`Failed to normalize OpenCode base URL:`,e),t}},hl=()=>{try{return a().api(`/api`)}catch{return null}},gl=()=>{try{return a().api(`/`)}catch{return null}},_l=e=>{let t=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof t?.timeout==`function`)return{signal:t.timeout(e),cleanup:()=>void 0};let n=new AbortController,r=setTimeout(()=>n.abort(),e);return{signal:n.signal,cleanup:()=>clearTimeout(r)}},vl=e=>{let t=e.filter(e=>e!=null);if(t.length===0)return{signal:new AbortController().signal,cleanup:()=>void 0};if(t.length===1)return{signal:t[0],cleanup:()=>void 0};let n=typeof AbortSignal<`u`?AbortSignal:void 0;if(typeof n?.any==`function`)return{signal:n.any(t),cleanup:()=>void 0};let r=new AbortController,i=()=>r.abort();for(let e of t){if(e.aborted){r.abort();break}e.addEventListener(`abort`,i)}return{signal:r.signal,cleanup:()=>{for(let e of t)e.removeEventListener(`abort`,i)}}},yl=e=>{let t=e.session?.message,n=t&&typeof t==`object`&&typeof t.get==`function`?t.get.bind(t):null;if(!n)return e;let r=Object.assign((e,t)=>n(e,t),t);return{...e,session:{...e.session,message:r}}},bl=e=>yl(te.make({baseUrl:e.baseUrl,...e.headers?{headers:e.headers}:{},fetch:(e,t)=>{let n=new URL(e instanceof Request?e.url:e.toString()),r=`${n.pathname}${n.search}`;if(e instanceof Request){let n=ml(a().api(r));return u(new Request(n,e),t)}return u(r,t)}})),xl=20971520,Sl=e=>{let{referenceOnly:t,...n}=e;return Cl(e)&&!t?n:{type:`text`,synthetic:!0,text:ts(`Attachment ${JSON.stringify(e.filename||`file`)}: ${JSON.stringify(os(e.url))}\nRead or process this file with tools as needed; its contents are not included in the message.`.replace(/</g,`\\u003c`))}},Cl=e=>typeof e.mime==`string`&&e.mime.startsWith(`image/`)?!0:typeof e.filename==`string`&&/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i.test(e.filename),wl=e=>{let t=[];for(let n of e){if(!Cl(n))continue;let e=typeof n.filename==`string`?n.filename.trim():``,r=typeof n.url==`string`?n.url:``;if(!e||!r.toLowerCase().startsWith(`file://`))continue;let i=os(r).trim();i&&t.push({filename:e,path:i})}return t},Tl=async(e,t)=>{let n=[],r=e.files?.length?await Promise.all(e.files.map(e=>t(e))):[],i=e.additionalParts?.length?await Promise.all(e.additionalParts.map(async e=>({text:e.text,synthetic:e.synthetic,files:e.files?.length?await Promise.all(e.files.map(e=>t(e))):[]}))):[],a=e=>Uo(e,wl([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r.map(Sl)),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files.map(Sl))}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},El=e=>e.replace(/\\/g,`/`),Dl=400,Ol=()=>{let e=p();return e&&e.runtime?.isDesktop&&e.files?e.files:null},q=new class{client;baseUrl;scopedClients=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();listDirectoryInFlight=new Map;configProvidersInFlight=new Map;listAgentsInFlight=new Map;configInFlight=new Map;configCache=new Map;configCacheGeneration=0;listDirectoryCache=new Map;healthInFlight=new Map;healthCache=new Map;healthCacheGeneration=0;liveLocationsFlight=null;sessionBoundaryQueues=new Map;constructor(e=tl){let t=hl()||e;this.baseUrl=ml(t),this.client=bl({baseUrl:dl(this.baseUrl)})}getBaseUrl(){return ml(hl()||this.baseUrl)}reconnectToRuntimeBaseUrl(){let e=ml(hl()||tl);e!==this.baseUrl&&(this.baseUrl=e,this.client=bl({baseUrl:dl(this.baseUrl)}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache(),this.liveLocationsFlight=null)}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}async checkLocationReleaseUse(e,t){let n=this.normalizeCandidatePath(e),r=await this.listLiveLocationDirectories();if(!r)throw Error(`Live Location inventory unavailable`);if(r&&n&&!r.has(n))return`free`;let i=this.getScopedSdkClient(e),a={location:{directory:e}},[o,s]=await Promise.all([i.shell.list(a,{signal:t}),i.form.list(a,{signal:t})]);return o.data.some(e=>e.status===`running`)||s.data.length>0?`busy`:`free`}listLiveLocationDirectories(){let e=Date.now();if(this.liveLocationsFlight&&this.liveLocationsFlight.expiresAt>e)return this.liveLocationsFlight.promise;let t=this.client.debug.location.list().then(e=>{if(!Array.isArray(e))return null;let t=new Set;for(let n of e){let e=this.normalizeCandidatePath(n?.directory??null);e&&t.add(e)}return t}).catch(()=>null);return this.liveLocationsFlight={promise:t,expiresAt:e+ol},t}async resolveBlockingRequestDirectories(e){let t=new Set;for(let n of e??[]){let e=this.normalizeCandidatePath(n??null);e&&t.add(e)}if(t.size===0)return[];let n=await this.listLiveLocationDirectories();if(!n)throw Error(`Live Location inventory unavailable`);return Array.from(t).filter(e=>n.has(e))}async releaseLocation(e,t){await this.getScopedSdkClient(e).debug.location.evict({location:{directory:e}},{signal:t})}getScopedApiClient(e){let t=(this.normalizeCandidatePath(e)??e)||``,n=this.scopedClients.get(t);if(n)return n;let r=bl({baseUrl:dl(this.baseUrl)});return this.scopedClients.set(t,r),r}normalizeCandidatePath(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return(n.length>1?n.replace(/\/+$/,``):n)||null}deriveHomeDirectory(e){let t=e.match(/^([A-Za-z]:)(?:\/|$)/);if(t){let n=t[1],r=e.slice(n.length+ +(e.charAt(n.length)===`/`)).split(`/`).filter(Boolean);return r.length>=2?{homeDirectory:`${n}/${r[0]}/${r[1]}`,username:r[1]}:r.length===1?{homeDirectory:`${n}/${r[0]}`,username:r[0]}:{homeDirectory:n,username:void 0}}let n=e.startsWith(`/`),r=e.split(`/`).filter(Boolean);return r.length>=2&&(r[0]===`Users`||r[0]===`home`)?{homeDirectory:`${n?`/`:``}${r[0]}/${r[1]}`,username:r[1]}:n?r.length===0?{homeDirectory:`/`,username:void 0}:{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:r.length>0?{homeDirectory:`/${r.join(`/`)}`,username:r[r.length-1]}:{homeDirectory:`/`,username:void 0}}setDirectory(e){let t=this.normalizeCandidatePath(e)??e;this.currentDirectory!==t&&R(`opencodeClient:setDirectory`,{previous:this.currentDirectory??null,next:t??null}),this.currentDirectory=t}getDirectory(){return this.currentDirectory}runSessionBoundary(e,t){let n=e.trim();if(!n)return t();let r=this.sessionBoundaryQueues.get(n)??Promise.resolve(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s=()=>t().then(i,a),c=r.then(s,s);return this.sessionBoundaryQueues.set(n,c.then(()=>void 0,()=>void 0)),o}assertCapturedRuntime(e,t,n){if(s()!==e||c()!==t){let e=Error(`${n}: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}}async switchSessionModel(e,t,n){let r=s(),i=c(),a=`id`in t&&typeof t.id==`string`&&t.id?t.id:t.modelID,o=t.providerID;if(!e||!a||!o)throw Error(`switchSessionModel requires sessionID, model.id, and providerID`);let l=typeof t.variant==`string`&&t.variant.trim()?t.variant.trim():void 0,u={id:a,providerID:o,...l?{variant:l}:{}},d=this.normalizeCandidatePath(n)??this.currentDirectory??``,f=this.getScopedSdkClient(d);this.assertCapturedRuntime(r,i,`session model switch`),await f.session.switchModel({sessionID:e,model:u}),this.assertCapturedRuntime(r,i,`session model switch`),uo(e,d||n,{model:u})}async switchSessionAgent(e,t,n){let r=s(),i=c(),a=typeof t==`string`?t.trim():``;if(!e||!a)throw Error(`switchSessionAgent requires sessionID and agent`);let o=this.normalizeCandidatePath(n)??this.currentDirectory??``,l=this.getScopedSdkClient(o);this.assertCapturedRuntime(r,i,`session agent switch`),await l.session.switchAgent({sessionID:e,agent:a}),this.assertCapturedRuntime(r,i,`session agent switch`),uo(e,o||n,{agent:a})}async generateSessionAside(e){let t=typeof e.sessionId==`string`?e.sessionId.trim():``;if(!t)throw Error(`generateSessionAside requires sessionId`);let n=typeof e.prompt==`string`?e.prompt:``,r=this.normalizeCandidatePath(e.directory)??this.currentDirectory??``,i=await this.getScopedSdkClient(r).session.generate({sessionID:t,prompt:n},e.signal?{signal:e.signal}:void 0);if(!i||typeof i.text!=`string`)throw Error(`session.generate returned invalid payload`);return{text:i.text}}async applySendSelection(e,t,n){t.model&&await this.switchSessionModel(e,t.model,n),t.agent&&await this.switchSessionAgent(e,t.agent,n)}async withDirectory(e,t){let n=async()=>{if(e==null)return t();let n=this.currentDirectory,r=this.normalizeCandidatePath(e)??e;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory===r&&(this.currentDirectory=n)}},r=this.directoryContextQueue.then(n,n);return this.directoryContextQueue=r.then(()=>void 0,()=>void 0),r}getApiClient(){return this.client}async getSystemInfo(){let e=new Set,t=t=>{let n=this.normalizeCandidatePath(t);n&&e.add(n)};try{let e=await this.client.location.get(K(this.currentDirectory));e&&(t(e.directory),t(e.project?.directory),t(e.project?.canonical))}catch{}if(!e.size)try{let e=await this.client.location.get(K(this.currentDirectory));t(e?.project?.directory),t(e?.project?.canonical)}catch{}if(!e.size)try{(await this.listSessions()).forEach(e=>t(e.directory))}catch{}if(t(this.currentDirectory),typeof window<`u`)try{t(ae(`lastDirectory`)),t(ae(`homeDirectory`))}catch{}if(!e.size&&typeof process<`u`&&typeof process.cwd==`function`&&t(process.cwd()),!e.size)return{homeDirectory:`/`,username:void 0};let[n]=Array.from(e);return this.deriveHomeDirectory(n)}async probeDirectory(e){let t=this.normalizeCandidatePath(e);if(!t)return!1;try{let e=await this.client.location.get({location:{directory:t}}),n=typeof e?.directory==`string`?e.directory:null;return!!(n&&n.trim().length>0)}catch{return!1}}async listSessions(){let e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data.map(v):[]}async searchSessionsByTitle(e){let t=e.search.trim(),n=await this.client.session.list({search:t||void 0,parentID:null,limit:e.limit??30,order:`desc`},e.signal?{signal:e.signal}:void 0);if(!Array.isArray(n?.data))throw Error(`session.list search returned no data`);return n.data.map(v)}async createSession(e,t){let n=this.normalizeCandidatePath(t)??this.currentDirectory;if(e?.metadata,e?.parentID){let t=await this.client.session.fork({sessionID:e.parentID});return e.title?(await this.client.session.update({sessionID:t.id,title:e.title}),v(await this.client.session.get({sessionID:t.id}))):v(t)}return v(await this.client.session.create({...n?{location:{directory:n}}:{},title:e?.title}))}async getSession(e,t){return v(await this.client.session.get({sessionID:e}))}async deleteSession(e,t){return await this.client.session.remove({sessionID:e}),!0}async deleteSessionMessage(e,t,n){throw G(`session.deleteMessage`)}async updateSession(e,t,n){let r=t.title!==void 0,i=t.metadata!==void 0,a=t.time!==void 0&&Object.prototype.hasOwnProperty.call(t.time,`archived`);if(!r&&!i&&!a)throw G(`session.update`);let o=this.normalizeCandidatePath(n)??this.currentDirectory,l=s(),d=c(),f=()=>{if(s()!==l||c()!==d){let e=Error(`session.update discarded: runtime switched`);throw e.name=`RuntimeGenerationMismatchError`,e}},p=[],m=null,h=null,g=e=>{if(p.length===0)throw e;let t=cl(e),n=Error(`session.update partial failure after ${p.join(`,`)}: ${t}`);throw n.name=`SessionUpdatePartialFailureError`,n.cause=e,n.completed=[...p],n};try{if(r&&(await this.client.session.update({sessionID:e,title:t.title}),f(),p.push(`title`),m=v(await this.client.session.get({sessionID:e})),f()),i){let n={patch:t.metadata};o&&(n.directory=o);let r=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/metadata`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(n)});if(f(),!r.ok){let e=Error(`session.metadata update failed (${r.status})`);throw e.status=r.status,e}let i=await r.json().catch(()=>null);f(),h=typeof i==`object`&&i&&!Array.isArray(i)&&`metadata`in i&&i.metadata!==null&&typeof i.metadata==`object`&&!Array.isArray(i.metadata)?i.metadata:null,p.push(`metadata`)}if(a){let n=t.time?.archived,r;if(n==null)r=0;else if(typeof n==`number`&&Number.isFinite(n))r=n>0?Math.trunc(n):0;else throw Error(`archivedAt must be a finite number or null`);let i={archivedAt:r};o&&(i.directory=o);let a=await u(`/api/yuri/sessions/${encodeURIComponent(e)}/archive`,{method:`PUT`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify(i)});if(f(),!a.ok){let e=Error(`session.archive update failed (${a.status})`);throw e.status=a.status,e}let s=await a.json().catch(()=>null);f();let c=typeof s==`object`&&s&&!Array.isArray(s)&&`session`in s?s.session:null;if(!c||typeof c!=`object`||Array.isArray(c))throw Error(`session.archive update failed: empty response`);m=v(c),p.push(`archive`)}return m||(m=await this.getSession(e,n),f()),h&&!a?{...m,metadata:h}:m}catch(e){return g(e)}}async getSessionMessages(e,t){return(await $e({sessionID:e,directory:this.currentDirectory??``,...typeof t==`number`?{limit:t}:{}})).records}async getSessionDiff(e,t){let n=this.normalizeCandidatePath(e.directory)??this.currentDirectory,r=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():void 0,i=new URLSearchParams;n&&i.set(`directory`,n),r&&i.set(`messageID`,r);let a=i.toString(),o=await u(`/api/session/${encodeURIComponent(e.sessionID)}/diff${a?`?${a}`:``}`,{method:`GET`,headers:{Accept:`application/json`},signal:t?.signal});if(!o.ok){let e=Error(`session.diff failed (${o.status})`);throw e.status=o.status,e}let s=await o.json().catch(()=>null),c=typeof s==`object`&&s&&Array.isArray(s.data)?s.data:null;if(!c)throw Error(`session.diff failed: empty response`);return c}async getSessionTodos(e){throw G(`session.todo`)}shouldNormalizeToTextPlain(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`text/`)&&t!==`text/plain`?!0:[`application/json`,`application/xml`,`application/javascript`,`application/typescript`,`application/x-yaml`,`application/yaml`,`application/toml`,`application/x-sh`,`application/x-shellscript`,`application/octet-stream`,`image/svg+xml`].includes(t)}isHeicMime(e){if(!e)return!1;let t=e.toLowerCase();return t===`image/heic`||t===`image/heif`}async convertHeicToJpeg(t){try{let n=ds(t.url,t.mime);if(!n)return t;let r=await vo(n)??await(await he(async()=>{let{default:t}=await import(`./vendor-heic2any-DgJnLT1Y.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c(),i=Cl(e)?await this.normalizeFilePart(e):e;this.assertCapturedRuntime(n,r,`prompt attachment normalize`);let a=i.url,o;if(fs(a)){let e=a.startsWith(`blob:`)?await fetch(a).then(e=>e.blob()):ds(a,i.mime);if(!e)throw Error(`Failed to materialize attachment bytes for ${i.filename??`file`}`);this.assertCapturedRuntime(n,r,`prompt attachment upload`);let t=await ps({body:e,mime:i.mime,filename:i.filename});this.assertCapturedRuntime(n,r,`prompt attachment upload`),a=t.url,o=t.size}if(Cl(i)&&o===void 0&&a.toLowerCase().startsWith(`file://`)){let e=os(a),t=p()?.files;if(t?.statFile)o=(await t.statFile(e)).size;else{let t=await u(`/api/fs/stat`,{query:{path:e}});if(!t.ok)throw Error(`Failed to inspect prompt attachment`);o=(await t.json()).size}this.assertCapturedRuntime(n,r,`prompt attachment stat`)}return{...e.id?{id:e.id}:{},type:`file`,mime:i.mime,filename:i.filename,url:a,...Cl(i)&&(o===void 0||!Number.isSafeInteger(o)||o<0||o>xl)?{referenceOnly:!0}:{}}}async buildMessageParts(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c();return Tl(e,e=>this.toNormalizedFilePartInput(e,{generation:n,runtimeKey:r}))}async sendMessage(e){let t=s(),n=c(),r=()=>{this.assertCapturedRuntime(t,n,`session prompt discarded`)};r();let i=e.messageId??ue(`msg`),a=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=Js(a??``),l=await this.buildMessageParts({text:e.text,prefaceText:e.prefaceText,prefaceTextSynthetic:e.prefaceTextSynthetic,files:e.files,additionalParts:e.additionalParts,agentMentions:e.agentMentions},{generation:t,runtimeKey:n});r(),W(o)||this.assertCapturedRuntime(t,n,`session prompt discarded`),e.format&&(e.id,e.providerID,e.modelID,e.agent,e.variant,this.baseUrl,e.format.type),el(e.providerID);let u=l.flatMap(e=>e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
5
5
  `)||e.text,d=l.flatMap(e=>e.type!==`file`||typeof e.url!=`string`?[]:[{uri:e.url,...e.filename?{name:e.filename}:{}}]),f=l.flatMap(e=>e.type===`agent`&&typeof e.name==`string`?[{name:e.name}]:[]),p=xe(l.flatMap(e=>e.type===`text`&&!e.synthetic?[e.text]:[]).join(`
@@ -1 +1 @@
1
- import{C as e,D as t,I as n,L as r,M as i,O as a,P as o,S as s,T as c,_ as l,a as u,b as d,c as f,j as p,n as m,o as h,r as g,s as _,t as v,v as y,w as b,y as x}from"./vendor-opencode-client-cQ47ywrT.js";import{i as ee}from"./vendor-tanstack-query-core-BWz0ose6.js";import{n as te,r as ne}from"./fileQueries-DWj9yB2g.js";import{o as re}from"./path-utils-jGozTg9d.js";import{a as ie,n as ae}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{n as oe}from"./pathNormalization-ewtPqJWn.js";import{n as se}from"./platform-DFJEtBlo.js";import{Dt as S,ht as C,mt as w,y as T}from"./vendor-effect-X1Hqc7ba.js";import{t as E}from"./native-errors-06if6eu-.js";import{a as ce,i as le,n as ue,o as de,r as fe}from"./appearance--vFosLNi.js";import{i as pe,o as me}from"./fileReferenceParser-1HHDBUum.js";import{n as he,t as ge}from"./vendor-solid-js-D98iXT7C.js";import{a as _e,c as ve,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as ye,s as be,t as xe,u as Se}from"./vendor-opencode-plugin-BmdTE4Te.js";var L={"@opencode/plugin/gui":F,"@opencode/plugin/gui/main":F,"@opencode/plugin/gui/file":_e,"@opencode/plugin/gui/review":j,"@opencode/plugin/gui/browser":ye,"@opencode/plugin/rpc":xe,"@opencode/schema/rpc":P,"@opencode/client":g,"@opencode/client/effect":m,"@opencode/client/solid":v,effect:T,"solid-js":o,"solid-js/web":he,"solid-js/store":_},Ce=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function we(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function Te(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(L,e))return L[e];if(e===`electron`||e.startsWith(`node:`)||Ce.has(e))return we();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!S(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function R(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=oe(t)??``;return n===`.`?``:n}var z=e=>/^(?:\/|[a-z]:\/)/i.test(e),B=()=>{throw Error(`Unsupported GUI file API: tree`)},V=class extends Error{},H=e=>new TextEncoder().encode(e).byteLength,Ee=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=R(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:z,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=a();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(a(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&R(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:B,state:B,sync:B,expand:B,collapse:B}}}resolve(e){let t=R(e);if(!z(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return z(t)?t:R(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ne(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,n){let r=this.resolve(e),a=t();if(!a||this.ended)return r;let o=`${n}:${r}`,s=this.subscriptions.get(o);s||(s={revision:c(0),listeners:new Set},this.subscriptions.set(o,s));let l=s;return l.listeners.has(a)||(l.listeners.add(a),i(a,()=>p(()=>{l.listeners.delete(a),!l.listeners.size&&this.subscriptions.get(o)===l&&this.subscriptions.delete(o)}))),l.revision[0](),r}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),l(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=a();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),p(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),l(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=te(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new V(`File does not exist`);let t=e.content;if(H(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(H(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof V?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new ee(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()},this.states.get(t)?.loaded&&this.sync(t,!0).catch(()=>{})}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},U=256,W=2097152,G=e=>structuredClone(f(e)),De=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=U)throw Error(`GUI plugin store limit exceeded`);let l=w(a.schema),u=C(a.schema),d=l(u(G(a.initial)));if(JSON.stringify(u(d)).length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=W)try{f=l(JSON.parse(p))}catch{f=d}let[m,h]=c(f),g=e=>{r();let t=JSON.stringify(u(G(e)));if(t.length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let n=l(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=G(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>G(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=U)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=u(G(t.initial)),c=[o,e=>{r();let t=G(f(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(h(t))}];return this.memory.set(i,[o,e=>{let t=G(f(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(h(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}},K=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,Oe=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,t){let n=this.clients.get(t),r=n?.get(e);if(r)return r.live;let[i,a]=c(this.api&&!t.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),o=()=>{a({status:`inactive`,reason:`disabled`}),t.removeEventListener(`abort`,o),this.clients.delete(t)},s={live:k(i),stop:o};if(this.ended||t.aborted||(n||(n=new Map,this.clients.set(t,n)),n.set(e,s),t.addEventListener(`abort`,o,{once:!0}),!this.api))return s.live;let l=this.api;return this.probe??=Promise.resolve().then(()=>l.capabilities()),this.probe.then(n=>{if(this.ended||t.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(n.version!==1||!n[r]){a({status:`inactive`,reason:`disabled`});return}let o=async(e,n={})=>{if(this.ended||t.aborted||i().status!==`active`)return{status:`cancelled`};let o=AbortSignal.any([t,...n.signal?[n.signal]:[]]);try{return await l[r](e,{...n,signal:o})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&a({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:n.limits,exportPDF:o}:{version:1,limits:n.limits,exportLongImage:o});a({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!t.aborted&&a({status:`inactive`,reason:`failed`})}),s.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}};function q(e,t){let n=new Map,r=Object.freeze({dismiss(){}});return e.addEventListener(`abort`,()=>{for(let e of[...n.values()])e.handle.dismiss()},{once:!0}),Object.freeze({show(i){if(e.aborted)return r;if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast is unavailable`);if(!i||typeof i!=`object`)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Expected toast options`);let{title:a,description:o,variant:s=`default`,duration:c=5e3,persistent:l=!1,icon:u,actions:d}=i;if(typeof a!=`string`||o!==void 0&&typeof o!=`string`||![`default`,`success`,`error`,`loading`].includes(s)||typeof l!=`boolean`||typeof c!=`number`||!Number.isFinite(c)||c<0)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Invalid toast options`);if(u!==void 0||d!==void 0)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast icon/actions are unsupported`);if(e.aborted)return r;let f=JSON.stringify([a,o??null,s,c,l]),p=n.get(f),m=()=>{let e=n.get(f);!e||e.id!==h||(clearTimeout(e.timer),n.delete(f))},h=(s==="default"?t:t[s])(a,{id:p?.id,description:o,duration:l?1/0:c,onDismiss:m,onAutoClose:m}),g=p?.handle??Object.freeze({dismiss(){m(),t.dismiss(h)}});clearTimeout(p?.timer);let _=s===`loading`&&!l?setTimeout(()=>g.dismiss(),c):void 0;return n.set(f,{id:h,handle:g,timer:_}),g}})}var ke=ie(`YuriMedia`);async function Ae(e){let t=/\.html?$/i.test(e.name)?`text/html`:`text/plain`,n=new Blob([e.content],{type:t});if(se()){if(!ae.isPluginAvailable(`YuriMedia`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Native file saving is unavailable`);if(n.size>33554432)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`File exceeds maximum size`);let r=await new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{if(typeof r.result!=`string`){t(Error(`Failed to encode file`));return}e(r.result.slice(r.result.indexOf(`,`)+1))},r.onerror=()=>t(r.error??Error(`Failed to encode file`)),r.readAsDataURL(n)});return!(await ke.saveFile({dataBase64:r,mimeType:t,filename:e.name})).cancelled}let r=URL.createObjectURL(n),i=document.createElement(`a`);try{return i.href=r,i.download=e.name,document.body.append(i),i.click(),!0}finally{i.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}}var J=d();function je(e){return{version:1,register(t){let n=r(J);if(!n||n.plugin!==e||n.signal.aborted||e.aborted)throw Error(`Preview actions require the owning mounted panel`);let i=new AbortController,a=AbortSignal.any([e,n.signal,i.signal]),o,s=()=>{a.removeEventListener(`abort`,s),i.abort(),o?.remove()};p(s),a.addEventListener(`abort`,s,{once:!0});try{o=t.render({element:t.element,signal:a,async snapshot(e={}){let r=AbortSignal.any([a,...e.signal?[e.signal]:[]]);if(r.throwIfAborted(),!n.content.contains(t.element)||n.target.contains(t.element))throw Error(`Preview capture region is no longer in its owning panel`);let i=await t.capture({...e,signal:r});if(r.throwIfAborted(),!n.content.contains(t.element))throw Error(`Preview capture region was replaced`);return i}}),a.throwIfAborted(),n.target.append(o)}catch(e){throw s(),e}return s}}}function Y(e,t){return JSON.stringify([e,t])}function Me(e){if(!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||!e.id.trim()||e.id.length>128||!(`title`in e)||typeof e.title!=`string`||!(`render`in e)||typeof e.render!=`function`)throw Error(`Invalid yuri.page contribution`);return e}var X=e=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function Ne(e,t){if(!e.fields||!t.fields)return!1;let n=Reflect.ownKeys(e.fields);return n.length===Reflect.ownKeys(t.fields).length&&n.every(n=>{let r=e.fields[n],i=t.fields[n];return i!==void 0&&`value`in r&&`value`in i&&Object.is(r.value,i.value)&&r.enumerable===i.enumerable&&r.configurable===i.configurable&&r.writable===i.writable})}function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var Pe=class{options;fileIcons=new de;appearanceCatalog=new le;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=c(0);views=c(0);session=c();currentPage=c();appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),titlebarItems:Object.freeze([]),panels:Object.freeze([]),pages:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});#e;viewExports;constructor(e){this.options=e,this.viewExports=new Oe(e.viewExport),this.appearance=c({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new De(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.#e=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(e=!1){let t=this.snapshot;this.changes[1](e=>e+1),e&&t===this.snapshot&&this.publish()}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new Ee(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=Z(`session.server`,{id:this.options.transport,name:this.options.transport,client:this.options.client}),r=e?Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:`${this.options.transport}\n${e.id}`,tab:e.id,server:n,pending:!1,visit:{},location:{directory:e.directory}})):void 0,i=this.snapshot;this.session[1](r),i===this.snapshot&&this.publish()}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}setPage(e){this.ended||this.currentPage[1](e)}install(t,r,o){let s=this.instances.get(t);if(this.ended||s?.status===`active`&&s.revision===r.revision&&s.native?.active!==!1){o?.dispose();return}s&&(this.instances.delete(t),this.release(s));let l={id:t,native:o,revision:r.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:c(0),appearanceChanges:c(0),commands:[],titlebarItems:[],panels:[],pages:[],settings:[],menus:[]};this.instances.set(t,l);try{if(t===`yuri`||t.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let s=Te(r.code,o?.activation.os);b(t=>{l.dispose=t,l.root=a(),y(()=>x(A.Provider,{value:l.context=this.context(l,s,r.options),get children(){l.owner=a();let e=n(()=>s.setup?.(l.context));if(typeof e==`function`)l.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{l.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(l,e)),l.controller.signal.aborted||i(l.owner,()=>e(()=>{if(l.iconChanges[0](),!l.controller.signal.aborted)try{let e=[...l.contributions].filter(e=>e.registry===ce).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(l.id,e),l.iconError!==void 0&&n(()=>{l.iconError=void 0,this.publish()})}catch(e){n(()=>{this.fileIcons.remove(l.id),l.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),l.controller.signal.aborted||i(l.owner,()=>e(()=>{if(l.appearanceChanges[0](),!l.controller.signal.aborted)try{let e=e=>[...l.contributions].filter(t=>t.registry===e).map(e=>e.read()).filter(e=>e!==void 0);this.appearanceCatalog.replace(l.id,e(fe),e(ue),l.native?.activation.capabilities?.dockIcon===!0)}catch(e){n(()=>this.fail(l,e))}})),l.controller.signal.aborted||i(l.owner,()=>e(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(l)}catch(e){n(()=>this.fail(l,e))}n(()=>this.publish())}))})}catch(e){this.fail(l,e)}this.changed(!0)}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.titlebarItems=[],e.panels=[],e.pages=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id),this.appearanceCatalog.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof E&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(!0)}}dispose(){this.ended||(this.ended=!0,l(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.appearanceCatalog.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}async setDockIcon(e,t){let n=this.instances.get(e),r=n?.native;if(!r?.active||!r.activation.capabilities?.dockIcon)return X(`Dock icon`);try{await r.setDockIcon(t)}catch(e){throw t!==null&&n&&this.fail(n,e),e}}own(e,t){let n=!0,i=()=>{n&&(n=!1,e.cleanups.delete(i),t())};return e.controller.signal.aborted||r(I)?.ended?(i(),i):(e.cleanups.add(i),a()&&p(i),i)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(t,i,o){let c=this.storage.forPlugin(t.id,t.controller.signal),l=Object.fromEntries(Object.entries(i.stores??{}).map(([e,t])=>[e,t.scope===`global`?c.store(e,{...t,scope:`global`}):n=>c.store(e,{...t,scope:{session:n}})])),u=(e,t)=>{let n=this.appearance[0]().locale;return(i.i18n?.[n]?.[e]??i.i18n?.[n.split(`-`)[0]]?.[e]??i.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,n)=>String(t?.[n]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(e,n,r)=>{t.controller.signal.aborted||this.openPanel(e,n,r)},close:(e,n)=>{t.controller.signal.aborted||this.closeFor(e,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(e,n)=>{if(t.controller.signal.aborted)return;let r=this.layout(n);r.active===e&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:e=>(this.changes[0](),this.layout(e).open.filter(e=>e.startsWith(`${t.id}:`)).map(e=>e.slice(t.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:e=>{if(t.controller.signal.aborted)return;let n=this.layout(e);n.shown=!n.shown,this.changed()},menu:()=>this.list(M).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(e,n,r)=>{if(t.controller.signal.aborted)return;let i=this.layout(e).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}}),f=je(t.controller.signal),m=k(()=>t.controller.signal.aborted?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:f}),h={open:e=>t.controller.signal.aborted||this.appearance[0]().narrow||!t.pages.some(t=>t.id===e)?!1:this.options.openPage?.(Y(t.id,e))??!1,current:()=>{let e=this.currentPage[0]();return t.pages.find(n=>Y(t.id,n.id)===e)?.id}},g=k(()=>t.controller.signal.aborted||!this.options.openPage||this.appearance[0]().narrow?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:h});return Z(`ctx`,{id:t.id,options:o,signal:t.controller.signal,client:this.options.client,storage:c,stores:l,toast:q(t.controller.signal,this.options.toast),app:{name:`yuri`,version:t.native?.activation.app.version??``,channel:t.native?.activation.app.packaged?`prod`:`local`,platform:t.native?`desktop`:`web`,packaged:t.native?.activation.app.packaged??!1},desktop:t.native?Z(`desktop`,{os:t.native.activation.os}):void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(i,o)=>{if(t.controller.signal.aborted||r(I)?.ended)return()=>{};if([`server`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(i.id)&&X(`registry.${i.id}`),t.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let c=()=>{},l,u=b(n=>{c=n,l=a();let r=()=>typeof o==`function`?o():o,u;if(i.id===`yuri.file-icon`){let e=s(()=>{try{return{ok:!0,value:r()}}catch(e){return{ok:!1,error:e}}});u=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else u=s(r);if(i.id===`style`){let n=document.createElement(`style`);n.dataset.yuriPluginStyle=t.id,document.head.append(n),p(()=>n.remove()),e(()=>{let e=u();n.textContent=e===void 0?``:String(e)})}return{registry:i.id,read:u}},a()??t.owner);t.contributions.add(u);let d=()=>{i.id===`yuri.file-icon`&&t.iconChanges[1](e=>e+1)},f=()=>{(i.id===`yuri.theme`||i.id===`yuri.branding`)&&t.appearanceChanges[1](e=>e+1)};return n(d),n(f),n(()=>this.changed()),this.own(t,()=>{$(l,e=>{t.error??=String(e)}),c(),t.contributions.delete(u),n(d),n(f),n(()=>this.changed())})},list:e=>this.list(e),provide:(e,n)=>{if(t.controller.signal.aborted||r(I)?.ended)return()=>{};if(K(e.id)||e.id===`yuri.previewActions`||e.id===`yuri.pages`)throw Error(`Preview/export/page contracts are provided only by the Yuri host`);if(e.kind!==`contract`||!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw Error(`Contract must belong to the providing plugin`);let i=this.contract(e.id);if(i.provider)throw Error(`Contract already provided: ${e.id}`);return i.provider=t,i.live[1]({status:`active`,value:n,generation:++i.generation}),this.own(t,()=>{i.provider===t&&(i.provider=void 0,i.live[1]({status:`inactive`,reason:t.status===`failed`?`failed`:`disabled`}))})},use:e=>e.id===`yuri.pages`?e.kind===`contract`?g:X(`pages token must be a Contract`):e.id===`yuri.previewActions`?e.kind===`contract`?m:X(`preview actions token must be a Contract`):K(e.id)?e.kind===`contract`?this.viewExports.use(e.id,t.controller.signal):X(`export token must be a Contract`):e.kind===`ipc`&&t.native?t.native.token(e).live:this.contract(e.id,e.kind===`ipc`).live[0],main:e=>{if(!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw new E(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return t.native?t.native.token(e).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new E(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.#e:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:Ae},commands:{run:e=>t.controller.signal.aborted||!this.command(e)?!1:(this.runCommand(e),!0)},links:{open:e=>!t.controller.signal.aborted&&this.navigateLink(t,e),exists:e=>n(()=>{if(t.controller.signal.aborted)return!1;let n=this.linkHandler(e);try{return Promise.resolve(n?.value.exists?.(e)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=c({status:`inactive`,reason:`disabled`});n={live:[k(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],r=[],i=[],a=[],o=[],s=[],c=this.session[0]();for(let n of e.contributions){if([`yuri.file-icon`,`yuri.theme`,`yuri.branding`].includes(n.registry))continue;let l=n.read();if(l!==void 0){if(n.registry===`yuri.page`){let e=Me(l);if(s.some(t=>t.id===e.id))throw Error(`Duplicate yuri.page id`);s.push(e)}else if(n.registry===be.id){let n=l;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,pluginId:e.id,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(n.registry===O.id){let t=l;o.push({key:JSON.stringify([e.id,t.id]),pluginId:e.id,label:t.label,title:t.title,icon:t.icon,busy:t.busy,pressed:t.pressed,actionable:!!t.run,run:t.run})}else if(n.registry===Se.id&&c){let t=l,n=`${e.id}:`,i=this.layout(c).open.filter(e=>e.startsWith(n)).map(e=>e.slice(n.length));for(let n of t.list({session:c,screen:this.#e,open:i}))r.push({plugin:e,panel:t,tab:n})}else if(n.registry===D.id){let e=l;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,i.push(e)}else if(n.registry===M.id){let e=l;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of r)e.tab.title;e.commands=t,e.titlebarItems=o,e.panels=r,e.pages=s,e.settings=i,e.menus=a,n(()=>this.views[1](e=>e+1))}publish(){let e=n(this.session[0]),t=e?this.layouts.get(e.key):void 0,r=[...this.instances.values()],i=r.filter(e=>e.status===`active`),a=i.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(r.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(i.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(a),titlebarItems:Q(i.flatMap(e=>e.titlebarItems.map(({run:e,...t})=>t))),pages:Q(i.flatMap(e=>e.pages.map(t=>({key:Y(e.id,t.id),pluginId:e.id,title:t.title,icon:t.icon})))),settings:Q(i.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(i.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&a.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=i(e.owner??null,t);if(n instanceof Promise)return n.catch(t=>this.fail(e,t))}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}runTitlebarItem(e){for(let t of this.instances.values()){let n=t.titlebarItems.find(t=>t.key===e);if(n?.run&&!n.busy)return this.invoke(t,n.run)}}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ve.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=me(t.href);if(!n||!pe(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=re(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=R(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:R(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&this.changed(!0);let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(!0)}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&this.changed(!0);let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.#e}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(!0),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(!0))}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e,t=!1){let n=this.panel(e)?.tab,r=()=>(this.views[0](),this.panel(e)?.tab??n??X(`panel no longer listed`)),i=t?s(()=>{let e=r();return{tab:e,fields:Object.getPrototypeOf(e)===Object.prototype?Object.getOwnPropertyDescriptors(e):void 0}},void 0,{equals:Ne}):void 0,a=i?()=>i().tab:r,o=()=>this.session[0]()??X(`panel without session`);return{get tab(){return a()},get session(){return o()},screen:this.#e}}mountPanel(t,r,i){let a=this.panel(t);if(!a)return()=>{};let o=new AbortController,c=()=>{let c=s(()=>{this.session[0](),this.changes[0](),this.views[0]();let e=this.panel(t)?.tab.file;return e&&this.files&&this.panelVisible(t)?{model:this.files,file:e}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});e(()=>{let e=c();e&&(p(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))});let l=()=>n(()=>a.panel.render(this.props(t,!0)));return x(J.Provider,{value:i?{plugin:a.plugin.controller.signal,signal:o.signal,content:r,target:i}:void 0,get children(){return l()}})},l=this.mount(a.plugin,r,()=>x(N.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(t)),present:()=>(this.changes[0](),this.panelVisible(t)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?a.plugin.context.layout.stored(e):[]}},get children(){return c()}})),u=()=>{this.panelMounts.delete(u),o.abort(),l()};return this.panelMounts.add(u),this.own(a.plugin,u)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mountPage(e,t){if(this.appearance[0]().narrow)return()=>{};for(let n of this.instances.values()){let r=n.pages.find(t=>Y(n.id,t.id)===e);if(r)return this.mount(n,t,()=>r.render())}return()=>{}}mount(e,t,r){if(e.controller.signal.aborted)return()=>{};let i=()=>{},o,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=ge(()=>x(A.Provider,{value:e.context,get children(){return o=a(),y(()=>n(r),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(o,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{Pe as GuiPluginHost};
1
+ import{C as e,D as t,I as n,L as r,M as i,O as a,P as o,S as s,T as c,_ as l,a as u,b as d,c as f,j as p,n as m,o as h,r as g,s as _,t as v,v as y,w as b,y as x}from"./vendor-opencode-client-cQ47ywrT.js";import{i as ee}from"./vendor-tanstack-query-core-Y_YoRHtC.js";import{n as te,r as ne}from"./fileQueries-C2Rs6TPz.js";import{o as re}from"./path-utils-jGozTg9d.js";import{a as ie,n as ae}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{n as oe}from"./pathNormalization-ewtPqJWn.js";import{n as se}from"./platform-DFJEtBlo.js";import{Dt as S,ht as C,mt as w,y as T}from"./vendor-effect-X1Hqc7ba.js";import{t as E}from"./native-errors-06if6eu-.js";import{a as ce,i as le,n as ue,o as de,r as fe}from"./appearance--vFosLNi.js";import{i as pe,o as me}from"./fileReferenceParser-1HHDBUum.js";import{n as he,t as ge}from"./vendor-solid-js-D98iXT7C.js";import{a as _e,c as ve,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as ye,s as be,t as xe,u as Se}from"./vendor-opencode-plugin-BmdTE4Te.js";var L={"@opencode/plugin/gui":F,"@opencode/plugin/gui/main":F,"@opencode/plugin/gui/file":_e,"@opencode/plugin/gui/review":j,"@opencode/plugin/gui/browser":ye,"@opencode/plugin/rpc":xe,"@opencode/schema/rpc":P,"@opencode/client":g,"@opencode/client/effect":m,"@opencode/client/solid":v,effect:T,"solid-js":o,"solid-js/web":he,"solid-js/store":_},Ce=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function we(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function Te(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(L,e))return L[e];if(e===`electron`||e.startsWith(`node:`)||Ce.has(e))return we();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!S(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function R(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=oe(t)??``;return n===`.`?``:n}var z=e=>/^(?:\/|[a-z]:\/)/i.test(e),B=()=>{throw Error(`Unsupported GUI file API: tree`)},V=class extends Error{},H=e=>new TextEncoder().encode(e).byteLength,Ee=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=R(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:z,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=a();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(a(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&R(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:B,state:B,sync:B,expand:B,collapse:B}}}resolve(e){let t=R(e);if(!z(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return z(t)?t:R(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ne(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,n){let r=this.resolve(e),a=t();if(!a||this.ended)return r;let o=`${n}:${r}`,s=this.subscriptions.get(o);s||(s={revision:c(0),listeners:new Set},this.subscriptions.set(o,s));let l=s;return l.listeners.has(a)||(l.listeners.add(a),i(a,()=>p(()=>{l.listeners.delete(a),!l.listeners.size&&this.subscriptions.get(o)===l&&this.subscriptions.delete(o)}))),l.revision[0](),r}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),l(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=a();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),p(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),l(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=te(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new V(`File does not exist`);let t=e.content;if(H(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(H(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof V?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new ee(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()},this.states.get(t)?.loaded&&this.sync(t,!0).catch(()=>{})}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},U=256,W=2097152,G=e=>structuredClone(f(e)),De=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=U)throw Error(`GUI plugin store limit exceeded`);let l=w(a.schema),u=C(a.schema),d=l(u(G(a.initial)));if(JSON.stringify(u(d)).length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=W)try{f=l(JSON.parse(p))}catch{f=d}let[m,h]=c(f),g=e=>{r();let t=JSON.stringify(u(G(e)));if(t.length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let n=l(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=G(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>G(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=U)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=u(G(t.initial)),c=[o,e=>{r();let t=G(f(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(h(t))}];return this.memory.set(i,[o,e=>{let t=G(f(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(h(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}},K=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,Oe=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,t){let n=this.clients.get(t),r=n?.get(e);if(r)return r.live;let[i,a]=c(this.api&&!t.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),o=()=>{a({status:`inactive`,reason:`disabled`}),t.removeEventListener(`abort`,o),this.clients.delete(t)},s={live:k(i),stop:o};if(this.ended||t.aborted||(n||(n=new Map,this.clients.set(t,n)),n.set(e,s),t.addEventListener(`abort`,o,{once:!0}),!this.api))return s.live;let l=this.api;return this.probe??=Promise.resolve().then(()=>l.capabilities()),this.probe.then(n=>{if(this.ended||t.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(n.version!==1||!n[r]){a({status:`inactive`,reason:`disabled`});return}let o=async(e,n={})=>{if(this.ended||t.aborted||i().status!==`active`)return{status:`cancelled`};let o=AbortSignal.any([t,...n.signal?[n.signal]:[]]);try{return await l[r](e,{...n,signal:o})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&a({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:n.limits,exportPDF:o}:{version:1,limits:n.limits,exportLongImage:o});a({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!t.aborted&&a({status:`inactive`,reason:`failed`})}),s.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}};function q(e,t){let n=new Map,r=Object.freeze({dismiss(){}});return e.addEventListener(`abort`,()=>{for(let e of[...n.values()])e.handle.dismiss()},{once:!0}),Object.freeze({show(i){if(e.aborted)return r;if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast is unavailable`);if(!i||typeof i!=`object`)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Expected toast options`);let{title:a,description:o,variant:s=`default`,duration:c=5e3,persistent:l=!1,icon:u,actions:d}=i;if(typeof a!=`string`||o!==void 0&&typeof o!=`string`||![`default`,`success`,`error`,`loading`].includes(s)||typeof l!=`boolean`||typeof c!=`number`||!Number.isFinite(c)||c<0)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Invalid toast options`);if(u!==void 0||d!==void 0)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast icon/actions are unsupported`);if(e.aborted)return r;let f=JSON.stringify([a,o??null,s,c,l]),p=n.get(f),m=()=>{let e=n.get(f);!e||e.id!==h||(clearTimeout(e.timer),n.delete(f))},h=(s==="default"?t:t[s])(a,{id:p?.id,description:o,duration:l?1/0:c,onDismiss:m,onAutoClose:m}),g=p?.handle??Object.freeze({dismiss(){m(),t.dismiss(h)}});clearTimeout(p?.timer);let _=s===`loading`&&!l?setTimeout(()=>g.dismiss(),c):void 0;return n.set(f,{id:h,handle:g,timer:_}),g}})}var ke=ie(`YuriMedia`);async function Ae(e){let t=/\.html?$/i.test(e.name)?`text/html`:`text/plain`,n=new Blob([e.content],{type:t});if(se()){if(!ae.isPluginAvailable(`YuriMedia`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Native file saving is unavailable`);if(n.size>33554432)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`File exceeds maximum size`);let r=await new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{if(typeof r.result!=`string`){t(Error(`Failed to encode file`));return}e(r.result.slice(r.result.indexOf(`,`)+1))},r.onerror=()=>t(r.error??Error(`Failed to encode file`)),r.readAsDataURL(n)});return!(await ke.saveFile({dataBase64:r,mimeType:t,filename:e.name})).cancelled}let r=URL.createObjectURL(n),i=document.createElement(`a`);try{return i.href=r,i.download=e.name,document.body.append(i),i.click(),!0}finally{i.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}}var J=d();function je(e){return{version:1,register(t){let n=r(J);if(!n||n.plugin!==e||n.signal.aborted||e.aborted)throw Error(`Preview actions require the owning mounted panel`);let i=new AbortController,a=AbortSignal.any([e,n.signal,i.signal]),o,s=()=>{a.removeEventListener(`abort`,s),i.abort(),o?.remove()};p(s),a.addEventListener(`abort`,s,{once:!0});try{o=t.render({element:t.element,signal:a,async snapshot(e={}){let r=AbortSignal.any([a,...e.signal?[e.signal]:[]]);if(r.throwIfAborted(),!n.content.contains(t.element)||n.target.contains(t.element))throw Error(`Preview capture region is no longer in its owning panel`);let i=await t.capture({...e,signal:r});if(r.throwIfAborted(),!n.content.contains(t.element))throw Error(`Preview capture region was replaced`);return i}}),a.throwIfAborted(),n.target.append(o)}catch(e){throw s(),e}return s}}}function Y(e,t){return JSON.stringify([e,t])}function Me(e){if(!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||!e.id.trim()||e.id.length>128||!(`title`in e)||typeof e.title!=`string`||!(`render`in e)||typeof e.render!=`function`)throw Error(`Invalid yuri.page contribution`);return e}var X=e=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function Ne(e,t){if(!e.fields||!t.fields)return!1;let n=Reflect.ownKeys(e.fields);return n.length===Reflect.ownKeys(t.fields).length&&n.every(n=>{let r=e.fields[n],i=t.fields[n];return i!==void 0&&`value`in r&&`value`in i&&Object.is(r.value,i.value)&&r.enumerable===i.enumerable&&r.configurable===i.configurable&&r.writable===i.writable})}function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var Pe=class{options;fileIcons=new de;appearanceCatalog=new le;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=c(0);views=c(0);session=c();currentPage=c();appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),titlebarItems:Object.freeze([]),panels:Object.freeze([]),pages:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});#e;viewExports;constructor(e){this.options=e,this.viewExports=new Oe(e.viewExport),this.appearance=c({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new De(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.#e=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(e=!1){let t=this.snapshot;this.changes[1](e=>e+1),e&&t===this.snapshot&&this.publish()}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new Ee(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=Z(`session.server`,{id:this.options.transport,name:this.options.transport,client:this.options.client}),r=e?Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:`${this.options.transport}\n${e.id}`,tab:e.id,server:n,pending:!1,visit:{},location:{directory:e.directory}})):void 0,i=this.snapshot;this.session[1](r),i===this.snapshot&&this.publish()}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}setPage(e){this.ended||this.currentPage[1](e)}install(t,r,o){let s=this.instances.get(t);if(this.ended||s?.status===`active`&&s.revision===r.revision&&s.native?.active!==!1){o?.dispose();return}s&&(this.instances.delete(t),this.release(s));let l={id:t,native:o,revision:r.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:c(0),appearanceChanges:c(0),commands:[],titlebarItems:[],panels:[],pages:[],settings:[],menus:[]};this.instances.set(t,l);try{if(t===`yuri`||t.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let s=Te(r.code,o?.activation.os);b(t=>{l.dispose=t,l.root=a(),y(()=>x(A.Provider,{value:l.context=this.context(l,s,r.options),get children(){l.owner=a();let e=n(()=>s.setup?.(l.context));if(typeof e==`function`)l.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{l.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(l,e)),l.controller.signal.aborted||i(l.owner,()=>e(()=>{if(l.iconChanges[0](),!l.controller.signal.aborted)try{let e=[...l.contributions].filter(e=>e.registry===ce).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(l.id,e),l.iconError!==void 0&&n(()=>{l.iconError=void 0,this.publish()})}catch(e){n(()=>{this.fileIcons.remove(l.id),l.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),l.controller.signal.aborted||i(l.owner,()=>e(()=>{if(l.appearanceChanges[0](),!l.controller.signal.aborted)try{let e=e=>[...l.contributions].filter(t=>t.registry===e).map(e=>e.read()).filter(e=>e!==void 0);this.appearanceCatalog.replace(l.id,e(fe),e(ue),l.native?.activation.capabilities?.dockIcon===!0)}catch(e){n(()=>this.fail(l,e))}})),l.controller.signal.aborted||i(l.owner,()=>e(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(l)}catch(e){n(()=>this.fail(l,e))}n(()=>this.publish())}))})}catch(e){this.fail(l,e)}this.changed(!0)}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.titlebarItems=[],e.panels=[],e.pages=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id),this.appearanceCatalog.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof E&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(!0)}}dispose(){this.ended||(this.ended=!0,l(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.appearanceCatalog.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}async setDockIcon(e,t){let n=this.instances.get(e),r=n?.native;if(!r?.active||!r.activation.capabilities?.dockIcon)return X(`Dock icon`);try{await r.setDockIcon(t)}catch(e){throw t!==null&&n&&this.fail(n,e),e}}own(e,t){let n=!0,i=()=>{n&&(n=!1,e.cleanups.delete(i),t())};return e.controller.signal.aborted||r(I)?.ended?(i(),i):(e.cleanups.add(i),a()&&p(i),i)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(t,i,o){let c=this.storage.forPlugin(t.id,t.controller.signal),l=Object.fromEntries(Object.entries(i.stores??{}).map(([e,t])=>[e,t.scope===`global`?c.store(e,{...t,scope:`global`}):n=>c.store(e,{...t,scope:{session:n}})])),u=(e,t)=>{let n=this.appearance[0]().locale;return(i.i18n?.[n]?.[e]??i.i18n?.[n.split(`-`)[0]]?.[e]??i.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,n)=>String(t?.[n]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(e,n,r)=>{t.controller.signal.aborted||this.openPanel(e,n,r)},close:(e,n)=>{t.controller.signal.aborted||this.closeFor(e,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(e,n)=>{if(t.controller.signal.aborted)return;let r=this.layout(n);r.active===e&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:e=>(this.changes[0](),this.layout(e).open.filter(e=>e.startsWith(`${t.id}:`)).map(e=>e.slice(t.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:e=>{if(t.controller.signal.aborted)return;let n=this.layout(e);n.shown=!n.shown,this.changed()},menu:()=>this.list(M).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(e,n,r)=>{if(t.controller.signal.aborted)return;let i=this.layout(e).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}}),f=je(t.controller.signal),m=k(()=>t.controller.signal.aborted?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:f}),h={open:e=>t.controller.signal.aborted||this.appearance[0]().narrow||!t.pages.some(t=>t.id===e)?!1:this.options.openPage?.(Y(t.id,e))??!1,current:()=>{let e=this.currentPage[0]();return t.pages.find(n=>Y(t.id,n.id)===e)?.id}},g=k(()=>t.controller.signal.aborted||!this.options.openPage||this.appearance[0]().narrow?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:h});return Z(`ctx`,{id:t.id,options:o,signal:t.controller.signal,client:this.options.client,storage:c,stores:l,toast:q(t.controller.signal,this.options.toast),app:{name:`yuri`,version:t.native?.activation.app.version??``,channel:t.native?.activation.app.packaged?`prod`:`local`,platform:t.native?`desktop`:`web`,packaged:t.native?.activation.app.packaged??!1},desktop:t.native?Z(`desktop`,{os:t.native.activation.os}):void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(i,o)=>{if(t.controller.signal.aborted||r(I)?.ended)return()=>{};if([`server`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(i.id)&&X(`registry.${i.id}`),t.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let c=()=>{},l,u=b(n=>{c=n,l=a();let r=()=>typeof o==`function`?o():o,u;if(i.id===`yuri.file-icon`){let e=s(()=>{try{return{ok:!0,value:r()}}catch(e){return{ok:!1,error:e}}});u=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else u=s(r);if(i.id===`style`){let n=document.createElement(`style`);n.dataset.yuriPluginStyle=t.id,document.head.append(n),p(()=>n.remove()),e(()=>{let e=u();n.textContent=e===void 0?``:String(e)})}return{registry:i.id,read:u}},a()??t.owner);t.contributions.add(u);let d=()=>{i.id===`yuri.file-icon`&&t.iconChanges[1](e=>e+1)},f=()=>{(i.id===`yuri.theme`||i.id===`yuri.branding`)&&t.appearanceChanges[1](e=>e+1)};return n(d),n(f),n(()=>this.changed()),this.own(t,()=>{$(l,e=>{t.error??=String(e)}),c(),t.contributions.delete(u),n(d),n(f),n(()=>this.changed())})},list:e=>this.list(e),provide:(e,n)=>{if(t.controller.signal.aborted||r(I)?.ended)return()=>{};if(K(e.id)||e.id===`yuri.previewActions`||e.id===`yuri.pages`)throw Error(`Preview/export/page contracts are provided only by the Yuri host`);if(e.kind!==`contract`||!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw Error(`Contract must belong to the providing plugin`);let i=this.contract(e.id);if(i.provider)throw Error(`Contract already provided: ${e.id}`);return i.provider=t,i.live[1]({status:`active`,value:n,generation:++i.generation}),this.own(t,()=>{i.provider===t&&(i.provider=void 0,i.live[1]({status:`inactive`,reason:t.status===`failed`?`failed`:`disabled`}))})},use:e=>e.id===`yuri.pages`?e.kind===`contract`?g:X(`pages token must be a Contract`):e.id===`yuri.previewActions`?e.kind===`contract`?m:X(`preview actions token must be a Contract`):K(e.id)?e.kind===`contract`?this.viewExports.use(e.id,t.controller.signal):X(`export token must be a Contract`):e.kind===`ipc`&&t.native?t.native.token(e).live:this.contract(e.id,e.kind===`ipc`).live[0],main:e=>{if(!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw new E(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return t.native?t.native.token(e).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new E(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.#e:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:Ae},commands:{run:e=>t.controller.signal.aborted||!this.command(e)?!1:(this.runCommand(e),!0)},links:{open:e=>!t.controller.signal.aborted&&this.navigateLink(t,e),exists:e=>n(()=>{if(t.controller.signal.aborted)return!1;let n=this.linkHandler(e);try{return Promise.resolve(n?.value.exists?.(e)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=c({status:`inactive`,reason:`disabled`});n={live:[k(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],r=[],i=[],a=[],o=[],s=[],c=this.session[0]();for(let n of e.contributions){if([`yuri.file-icon`,`yuri.theme`,`yuri.branding`].includes(n.registry))continue;let l=n.read();if(l!==void 0){if(n.registry===`yuri.page`){let e=Me(l);if(s.some(t=>t.id===e.id))throw Error(`Duplicate yuri.page id`);s.push(e)}else if(n.registry===be.id){let n=l;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,pluginId:e.id,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(n.registry===O.id){let t=l;o.push({key:JSON.stringify([e.id,t.id]),pluginId:e.id,label:t.label,title:t.title,icon:t.icon,busy:t.busy,pressed:t.pressed,actionable:!!t.run,run:t.run})}else if(n.registry===Se.id&&c){let t=l,n=`${e.id}:`,i=this.layout(c).open.filter(e=>e.startsWith(n)).map(e=>e.slice(n.length));for(let n of t.list({session:c,screen:this.#e,open:i}))r.push({plugin:e,panel:t,tab:n})}else if(n.registry===D.id){let e=l;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,i.push(e)}else if(n.registry===M.id){let e=l;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of r)e.tab.title;e.commands=t,e.titlebarItems=o,e.panels=r,e.pages=s,e.settings=i,e.menus=a,n(()=>this.views[1](e=>e+1))}publish(){let e=n(this.session[0]),t=e?this.layouts.get(e.key):void 0,r=[...this.instances.values()],i=r.filter(e=>e.status===`active`),a=i.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(r.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(i.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(a),titlebarItems:Q(i.flatMap(e=>e.titlebarItems.map(({run:e,...t})=>t))),pages:Q(i.flatMap(e=>e.pages.map(t=>({key:Y(e.id,t.id),pluginId:e.id,title:t.title,icon:t.icon})))),settings:Q(i.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(i.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&a.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=i(e.owner??null,t);if(n instanceof Promise)return n.catch(t=>this.fail(e,t))}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}runTitlebarItem(e){for(let t of this.instances.values()){let n=t.titlebarItems.find(t=>t.key===e);if(n?.run&&!n.busy)return this.invoke(t,n.run)}}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ve.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=me(t.href);if(!n||!pe(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=re(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=R(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:R(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&this.changed(!0);let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(!0)}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&this.changed(!0);let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.#e}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(!0),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(!0))}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e,t=!1){let n=this.panel(e)?.tab,r=()=>(this.views[0](),this.panel(e)?.tab??n??X(`panel no longer listed`)),i=t?s(()=>{let e=r();return{tab:e,fields:Object.getPrototypeOf(e)===Object.prototype?Object.getOwnPropertyDescriptors(e):void 0}},void 0,{equals:Ne}):void 0,a=i?()=>i().tab:r,o=()=>this.session[0]()??X(`panel without session`);return{get tab(){return a()},get session(){return o()},screen:this.#e}}mountPanel(t,r,i){let a=this.panel(t);if(!a)return()=>{};let o=new AbortController,c=()=>{let c=s(()=>{this.session[0](),this.changes[0](),this.views[0]();let e=this.panel(t)?.tab.file;return e&&this.files&&this.panelVisible(t)?{model:this.files,file:e}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});e(()=>{let e=c();e&&(p(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))});let l=()=>n(()=>a.panel.render(this.props(t,!0)));return x(J.Provider,{value:i?{plugin:a.plugin.controller.signal,signal:o.signal,content:r,target:i}:void 0,get children(){return l()}})},l=this.mount(a.plugin,r,()=>x(N.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(t)),present:()=>(this.changes[0](),this.panelVisible(t)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?a.plugin.context.layout.stored(e):[]}},get children(){return c()}})),u=()=>{this.panelMounts.delete(u),o.abort(),l()};return this.panelMounts.add(u),this.own(a.plugin,u)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mountPage(e,t){if(this.appearance[0]().narrow)return()=>{};for(let n of this.instances.values()){let r=n.pages.find(t=>Y(n.id,t.id)===e);if(r)return this.mount(n,t,()=>r.render())}return()=>{}}mount(e,t,r){if(e.controller.signal.aborted)return()=>{};let i=()=>{},o,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=ge(()=>x(A.Provider,{value:e.context,get children(){return o=a(),y(()=>n(r),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(o,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{Pe as GuiPluginHost};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-DBn9yahL.js";import{c as r,i}from"./runtime-switch-DEZ1K7qW.js";import{st as a}from"./vendor-base-ui-CzHs0bHY.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-DlzBev0S.js";import{t as s}from"./runtime-file-resource-qB_oVdE6.js";import{a as c,o as l,r as u}from"./path-utils-jGozTg9d.js";var d=e(a(),1),f=o(),p=[0,250,750],m=e=>{try{return decodeURIComponent(e)}catch{return e}},h=e=>{try{let t=new URL(e),n=m(t.hostname),r=m(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),c(r)}catch{let t=m(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),c(t)}},g=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:h(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=m(n);return{kind:`runtime-file`,source:n,path:u(r)?c(r):l(t,r)}},_=(e,t)=>v(()=>s(e,t),t),v=async(e,t)=>{let r=i(),a=n(),o;for(let s of p){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},y=()=>!1,b=e=>e.startsWith(`relay:`)||y(),x=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&b(e),S=()=>d.useSyncExternalStore(w,i,i),C=e=>e.kind===`runtime-file`&&!!e.path,w=e=>r(()=>e()),T=e=>t(()=>e()),E=(e,t,r)=>{let a=(0,f.c)(21),o=r===void 0?`inline`:r,c=d.useSyncExternalStore(T,n,n),l=d.useSyncExternalStore(w,i,i),u;a[0]!==t||a[1]!==e?(u=g(e,t),a[0]=t,a[1]=e,a[2]=u):u=a[2];let p=u,m;a[3]===p?m=a[4]:(m=C(p),a[3]=p,a[4]=m);let h=m,_=`${l}\n${c}\n${t}\n${e}\n${o}`,v=h?``:p.source,y=h,b;a[5]!==y||a[6]!==v||a[7]!==_?(b={key:_,source:v,loading:y,error:null},a[5]=y,a[6]=v,a[7]=_,a[8]=b):b=a[8];let[x,S]=d.useState(b),E,D;a[9]!==o||a[10]!==_||a[11]!==p||a[12]!==l||a[13]!==h?(E=()=>{if(!h||!C(p)){S({key:_,source:p.source,loading:!1,error:null});return}S({key:_,source:``,loading:!0,error:null});let e=new AbortController,t;return s(p.path,e.signal,o).then(n=>{if(e.signal.aborted||i()!==l){n.release();return}t=n.release,S({key:_,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||S({key:_,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},D=[_,p,l,h,o],a[9]=o,a[10]=_,a[11]=p,a[12]=l,a[13]=h,a[14]=E,a[15]=D):(E=a[14],D=a[15]),d.useEffect(E,D);let O;return a[16]!==x||a[17]!==y||a[18]!==v||a[19]!==_?(O=x.key===_?x:{key:_,source:v,loading:y,error:null},a[16]=x,a[17]=y,a[18]=v,a[19]=_,a[20]=O):O=a[20],O},D=(e,t,n)=>E(e,t,n===void 0?`inline`:n).source;export{g as a,S as c,C as i,x as n,E as o,b as r,D as s,_ as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-DBn9yahL.js";import{c as r,i}from"./runtime-switch-DEZ1K7qW.js";import{st as a}from"./vendor-base-ui-CzHs0bHY.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-DlzBev0S.js";import{t as s}from"./runtime-file-resource-BP4P52ry.js";import{a as c,o as l,r as u}from"./path-utils-jGozTg9d.js";var d=e(a(),1),f=o(),p=[0,250,750],m=e=>{try{return decodeURIComponent(e)}catch{return e}},h=e=>{try{let t=new URL(e),n=m(t.hostname),r=m(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),c(r)}catch{let t=m(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),c(t)}},g=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:h(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=m(n);return{kind:`runtime-file`,source:n,path:u(r)?c(r):l(t,r)}},_=(e,t)=>v(()=>s(e,t),t),v=async(e,t)=>{let r=i(),a=n(),o;for(let s of p){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},y=()=>!1,b=e=>e.startsWith(`relay:`)||y(),x=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&b(e),S=()=>d.useSyncExternalStore(w,i,i),C=e=>e.kind===`runtime-file`&&!!e.path,w=e=>r(()=>e()),T=e=>t(()=>e()),E=(e,t,r)=>{let a=(0,f.c)(21),o=r===void 0?`inline`:r,c=d.useSyncExternalStore(T,n,n),l=d.useSyncExternalStore(w,i,i),u;a[0]!==t||a[1]!==e?(u=g(e,t),a[0]=t,a[1]=e,a[2]=u):u=a[2];let p=u,m;a[3]===p?m=a[4]:(m=C(p),a[3]=p,a[4]=m);let h=m,_=`${l}\n${c}\n${t}\n${e}\n${o}`,v=h?``:p.source,y=h,b;a[5]!==y||a[6]!==v||a[7]!==_?(b={key:_,source:v,loading:y,error:null},a[5]=y,a[6]=v,a[7]=_,a[8]=b):b=a[8];let[x,S]=d.useState(b),E,D;a[9]!==o||a[10]!==_||a[11]!==p||a[12]!==l||a[13]!==h?(E=()=>{if(!h||!C(p)){S({key:_,source:p.source,loading:!1,error:null});return}S({key:_,source:``,loading:!0,error:null});let e=new AbortController,t;return s(p.path,e.signal,o).then(n=>{if(e.signal.aborted||i()!==l){n.release();return}t=n.release,S({key:_,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||S({key:_,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},D=[_,p,l,h,o],a[9]=o,a[10]=_,a[11]=p,a[12]=l,a[13]=h,a[14]=E,a[15]=D):(E=a[14],D=a[15]),d.useEffect(E,D);let O;return a[16]!==x||a[17]!==y||a[18]!==v||a[19]!==_?(O=x.key===_?x:{key:_,source:v,loading:y,error:null},a[16]=x,a[17]=y,a[18]=v,a[19]=_,a[20]=O):O=a[20],O},D=(e,t,n)=>E(e,t,n===void 0?`inline`:n).source;export{g as a,S as c,C as i,x as n,E as o,b as r,D as s,_ as t};
@@ -1 +1 @@
1
- import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-CzHs0bHY.js";import{n}from"./vendor-react-DlzBev0S.js";import{r}from"./button-BF2cNEuq.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};
1
+ import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-CzHs0bHY.js";import{n}from"./vendor-react-DlzBev0S.js";import{r}from"./button-DC4BhJtL.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};