@openchambery/web 2.0.0-beta.18 → 2.0.0-beta.19

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 (47) hide show
  1. package/dist/assets/{AssistantView-CV7caMrh.js → AssistantView-DcnZ020v.js} +3 -3
  2. package/dist/assets/{DiagramView-CDfSTjyI.js → DiagramView-IciqbBQL.js} +1 -1
  3. package/dist/assets/{MarkdownRenderer-TW-h0HHu.js → MarkdownRenderer-CNDoKYhC.js} +2 -2
  4. package/dist/assets/{MarkdownRendererImpl-BDhsNSZZ.js → MarkdownRendererImpl-MwxehP-f.js} +1 -1
  5. package/dist/assets/{MarkstreamRendererImpl-CTRQuEcK.js → MarkstreamRendererImpl-DWg5olbY.js} +1 -1
  6. package/dist/assets/{MobileDetailNavigation-Ba4FGle-.js → MobileDetailNavigation-CDIhNSXT.js} +1 -1
  7. package/dist/assets/{MobileShareBridge-CbLWGJA7.js → MobileShareBridge-DywdGhnV.js} +1 -1
  8. package/dist/assets/{MobileSurface-C62mL-z4.js → MobileSurface-B3TwLSD8.js} +1 -1
  9. package/dist/assets/{MultiRunWindow--Kog5jbS.js → MultiRunWindow-D9zSluS2.js} +1 -1
  10. package/dist/assets/{OverlayScrollbar-SUdC3Pqe.js → OverlayScrollbar-IEHPY5wy.js} +1 -1
  11. package/dist/assets/{SettingsView-DrHDWxUP.js → SettingsView-B6XM6SjZ.js} +1 -1
  12. package/dist/assets/{SettingsWindow-Dj3oYcuF.js → SettingsWindow-C64N7asK.js} +1 -1
  13. package/dist/assets/{TerminalView-BrQT3zTi.js → TerminalView-CZkQhHRy.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-zTkbimFp.js → ToolOutputDialog-KWiIFR-d.js} +1 -1
  15. package/dist/assets/{appThemeRegistry-Dd-Mc_ae.js → appThemeRegistry-Cpuh1f4h.js} +1 -1
  16. package/dist/assets/{fileMentionTouchSelection-CZkJTpTW.js → fileMentionTouchSelection-DNsbRHU9.js} +1 -1
  17. package/dist/assets/{gitApi-DDZeOQ0N.js → gitApi-BOhg5Bz_.js} +1 -1
  18. package/dist/assets/{insertionBoundaries-6cEF7UND.js → insertionBoundaries-BQ3SfsPe.js} +1 -1
  19. package/dist/assets/{main-B839_vtF.js → main-CDFpn3jQ.js} +2 -2
  20. package/dist/assets/{main-CboaV0z3.js → main-DcPhdAAo.js} +9 -9
  21. package/dist/assets/{mcpQueries-Cirhjpkq.js → mcpQueries-DuXHOnX2.js} +1 -1
  22. package/dist/assets/{miniChat-B0lH1mgT.js → miniChat-CXYSaHX0.js} +2 -2
  23. package/dist/assets/{mobile-DCMqyVbF.js → mobile-BAox2MyA.js} +2 -2
  24. package/dist/assets/{multirun-D45JAYPn.js → multirun-yEwF9wsU.js} +1 -1
  25. package/dist/assets/platform-CKIStkm5.js +6 -0
  26. package/dist/assets/{projectMeta-BZj0Lqsc.js → projectMeta-_AcbokQy.js} +1 -1
  27. package/dist/assets/{renderElectronMiniChatApp-KxK13wGq.js → renderElectronMiniChatApp-mI7tFw7r.js} +2 -2
  28. package/dist/assets/{renderMobileApp-DLwJp7Ef.js → renderMobileApp-d3J8FKQC.js} +5 -5
  29. package/dist/assets/{runtimeConfig-Dfmu3VWa.js → runtimeConfig-C5IUkpAF.js} +1 -1
  30. package/dist/assets/{runtimeEndpointReset-D4tNIDTD.js → runtimeEndpointReset-CvfuetgK.js} +1 -1
  31. package/dist/assets/{sessionChangeSummary-BUya3rIx.js → sessionChangeSummary-BAMnNkFo.js} +1 -1
  32. package/dist/assets/{sessionLookup-Ba9vzhFN.js → sessionLookup-C_8aOG5T.js} +1 -1
  33. package/dist/assets/{sortable-tabs-strip-Bc0lATi8.js → sortable-tabs-strip-C1avMLUr.js} +1 -1
  34. package/dist/assets/{terminalApi-C6zlKnK1.js → terminalApi-DVj_hL-2.js} +1 -1
  35. package/dist/assets/{textarea-B9pCxe-7.js → textarea-4em_Fprz.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-C4YijXq2.js → useAppFontEffects-D2_pOoR1.js} +53 -53
  37. package/dist/assets/{useDesktopWindowControlsLayout-hhGCbHKE.js → useDesktopWindowControlsLayout-CBK8ajHA.js} +1 -1
  38. package/dist/assets/{useEffectiveDirectory-DB10GDme.js → useEffectiveDirectory-DRs4aWaY.js} +1 -1
  39. package/dist/assets/{useFontPreferences-DFsjAsxC.js → useFontPreferences-K4sEJPsT.js} +1 -1
  40. package/dist/assets/{useMobileNavigationStore-DXxkpRmA.js → useMobileNavigationStore-BEqX-JUL.js} +13 -13
  41. package/dist/assets/{useSessionAutoCleanup-C7ONq7C-.js → useSessionAutoCleanup-DHUSC8Xf.js} +1 -1
  42. package/dist/assets/{useWorkerHighlightedLines-DWR_fwgu.js → useWorkerHighlightedLines-BqGJFJHF.js} +1 -1
  43. package/dist/index.html +4 -4
  44. package/dist/mini-chat.html +4 -4
  45. package/dist/mobile.html +4 -4
  46. package/package.json +1 -1
  47. package/dist/assets/platform-BxU3ZvQ0.js +0 -6
@@ -1,4 +1,4 @@
1
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{n as t}from"./runtime-fetch-CiqQd__Y.js";import{En as n,in as r}from"./persistence-CMWO3jFo.js";import{nt as i,rt as a}from"./vendor-base-ui-CnHfUmDN.js";import{n as o}from"./platform-BxU3ZvQ0.js";import{v as s}from"./useUIStore-Brsa2mKs.js";import{n as c}from"./vendor-react-DLPElpoQ.js";import{a as l,n as u}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{f as d,r as f,t as p}from"./button-EzCcYrQl.js";import{n as m}from"./Icon-DKd015RD.js";import{i as h,n as g,t as _}from"./tooltip-DwUy2erJ.js";import{n as v}from"./useThemeSystem-DMzWVJaW.js";import{n as y}from"./markdownTheme-DM5h1i18.js";import{n as b}from"./MarkdownRenderer-TW-h0HHu.js";import{n as x,o as S,s as C,t as w}from"./markdown-worker-bS5OgGO3.js";import{a as T,i as E,o as D,t as ee}from"./imageSource-BpUsiwFd.js";import{t as te}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";var O=e(a(),1),k=c(),A=i(),ne=`w-[min(30rem,calc(100cqw-1rem))] min-w-[280px] max-w-full overflow-hidden rounded-xl shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]`,j={maxWidth:`min(28rem, calc(100cqw - 4ch))`,backgroundColor:`var(--surface-elevated)`,color:`var(--surface-elevated-foreground)`},M=`flex items-center justify-between gap-3 border-b border-[var(--surface-subtle)] px-3 py-2.5`,N=`text-xs font-medium leading-4 text-foreground md:text-[0.8125rem] md:leading-5`,re=`text-xs tabular-nums leading-4 text-muted-foreground md:text-[0.8125rem] md:leading-5`,P=`m-0 list-none divide-y divide-[var(--surface-subtle)] p-0`,F=`${P} max-h-[min(22rem,50vh)] overflow-y-auto`,ie=`${P} w-full`,ae={className:`p-0 rounded-none`,maxHeightClass:`max-h-[46vh]`,disableHorizontal:!0},I=`px-2.5 py-1.5 text-xs leading-4 md:py-2 md:text-[0.8125rem] md:leading-5`,oe=`flex min-w-0 items-center gap-1 text-xs leading-4 text-muted-foreground md:gap-1.5 md:text-[0.8125rem] md:leading-5`,se=`min-w-0 truncate text-xs leading-4 text-foreground md:text-[0.8125rem] md:leading-5`,ce=`inline-flex shrink-0 items-center gap-1 text-xs leading-4 tabular-nums text-muted-foreground md:text-[0.8125rem] md:leading-5`,le=`h-3 w-3 shrink-0 md:h-3.5 md:w-3.5`,ue={in_progress:`text-foreground`,pending:`text-foreground`,completed:`text-muted-foreground line-through`,cancelled:`text-muted-foreground line-through`},L={in_progress:`chat.statusRow.todo.status.inProgress`,pending:`chat.statusRow.todo.status.pending`,completed:`chat.statusRow.todo.status.completed`,cancelled:`chat.statusRow.todo.status.cancelled`},R=e=>{let t=(0,k.c)(26),{todo:n,isActive:r,activeRef:i}=e,{t:a}=d(),o=z.has(n.status)?n.status:`pending`,s=L[o],c;t[0]!==a||t[1]!==s?(c=a(s),t[0]=a,t[1]=s,t[2]=c):c=t[2];let l=c,u;t[3]===o?u=t[4]:(u=o===`in_progress`?(0,A.jsx)(m,{name:`record-circle`,className:`h-3.5 w-3.5 text-[var(--status-info)]`,"aria-hidden":`true`}):o===`completed`?(0,A.jsx)(m,{name:`checkbox-circle`,className:`h-3.5 w-3.5 text-[var(--status-success)]`,"aria-hidden":`true`}):(0,A.jsx)(m,{name:`time`,className:`h-3.5 w-3.5 text-muted-foreground`,"aria-hidden":`true`}),t[3]=o,t[4]=u);let p=u,v=r?`step`:void 0,y=r&&`bg-[var(--surface-muted)] before:absolute before:inset-y-2 before:left-0 before:w-0.5 before:rounded-full before:bg-[var(--status-info)]`,b;t[5]===y?b=t[6]:(b=f(`group relative grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] items-start gap-2.5`,I,y),t[5]=y,t[6]=b);let x;t[7]!==p||t[8]!==l?(x=(0,A.jsx)(h,{asChild:!0,children:(0,A.jsx)(`span`,{className:`flex size-4 items-center justify-center`,"aria-label":l,children:p})}),t[7]=p,t[8]=l,t[9]=x):x=t[9];let S;t[10]===l?S=t[11]:(S=(0,A.jsx)(g,{side:`left`,sideOffset:6,children:l}),t[10]=l,t[11]=S);let C;t[12]!==x||t[13]!==S?(C=(0,A.jsxs)(_,{children:[x,S]}),t[12]=x,t[13]=S,t[14]=C):C=t[14];let w=ue[o],T;t[15]===w?T=t[16]:(T=f(`block whitespace-normal break-words`,w),t[15]=w,t[16]=T);let E;t[17]!==T||t[18]!==n.content?(E=(0,A.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,A.jsx)(`span`,{className:T,children:n.content})}),t[17]=T,t[18]=n.content,t[19]=E):E=t[19];let D;return t[20]!==i||t[21]!==E||t[22]!==v||t[23]!==b||t[24]!==C?(D=(0,A.jsxs)(`li`,{ref:i,"aria-current":v,className:b,children:[C,E]}),t[20]=i,t[21]=E,t[22]=v,t[23]=b,t[24]=C,t[25]=D):D=t[25],D},z=new Set([`in_progress`,`pending`,`completed`,`cancelled`]),B=`image/png`,V=l(`OpenChamberMedia`),H=e=>{let t=e.toLowerCase().split(`;`)[0]?.trim()||B;if(t===`image/jpeg`||t===`image/jpg`)return`jpg`;if(t===`image/webp`)return`webp`;if(t===`image/gif`)return`gif`;if(t===`image/svg+xml`)return`svg`;if(t===`image/png`)return`png`;let n=t.split(`/`)[1];return n&&/^[a-z0-9.+-]+$/i.test(n)?n:`png`},U=(e,t)=>{let n=`image.${H(t)}`,r=(((e||``).trim()||n).split(/[\\/]/).pop()||n).replace(/[^\w.\- ()[\]]+/g,`_`).replace(/^\.+/,``);return r?/\.[a-z0-9]{1,8}$/i.test(r)?r:`${r}.${H(t)}`:n},W=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{if(typeof r.result==`string`){t(r.result);return}n(Error(`Failed to encode image`))},r.onerror=()=>n(r.error??Error(`Failed to encode image`)),r.readAsDataURL(e)}),de=async e=>{let t=await W(e),n=t.indexOf(`,`);return n>=0?t.slice(n+1):t},fe=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.setTimeout(()=>URL.revokeObjectURL(n),1e3)},G=async(e,t)=>{let n=await fetch(e,{signal:t,cache:`no-store`});if(!n.ok)throw Error(`Image fetch failed (${n.status})`);return n.blob()},pe=async(e,t=B)=>{if(!e.naturalWidth||!e.naturalHeight)return null;let n=e.currentSrc||e.src;if(n&&(/^(?:blob:|data:|openchamber-asset:)/i.test(n)||/^https?:/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n)))try{let e=await G(n);if(e.size>0)return e}catch{}try{let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`);if(!r)return null;r.drawImage(e,0,0);let i=t.startsWith(`image/`)?t:B,a=await new Promise(e=>{n.toBlob(t=>e(t),i===`image/jpg`?`image/jpeg`:i)});return a&&a.size>0?a:null}catch{return null}},me=async(e,t)=>{let n=``;try{return n=await ee(e,t??new AbortController().signal),await G(n,t)}finally{n&&T(n)}},he=async(e,n)=>{let r=e.effectiveDirectory??``,i=null;e.prefetchedBlob&&e.prefetchedBlob.size>0&&(i=e.prefetchedBlob);let a=e.displayUrl?.trim();if(!i&&a)try{i=await G(a,n)}catch{i=null}if(!i){let a=e.sourceUrl.trim();if(!a)throw Error(`Image source is empty`);if(/^(?:data|blob):/i.test(a)||/^https?:/i.test(a)||/^\/api(?=\/|[?#]|$)/.test(a))i=await G(a,n);else{let e=D(a,r);if(E(e))try{i=await me(e.path,n)}catch{let r=await t(`/api/fs/raw`,{method:`GET`,cache:`no-store`,query:{path:e.path},signal:n});if(!r.ok)throw Error(`Image source request failed with status ${r.status}`);i=await r.blob()}else i=await G(e.source,n)}}if(!i||i.size<=0)throw Error(`Image is empty`);let o=(e.mimeType||(i.type&&i.type.startsWith(`image/`)?i.type:``)||B).split(`;`)[0].trim()||B;return{blob:i,filename:U(e.filename,o),mimeType:o}},ge=()=>!o()||u===void 0?!1:u.isPluginAvailable(`OpenChamberMedia`),_e=async(e,t)=>{let{blob:i,filename:a,mimeType:o}=await he(e,t);if(ge()){let e=await de(i);return await V.saveImage({dataBase64:e,mimeType:o,filename:a}),`saved`}if(r()){let e=n()?.vscode;if(e?.saveImage){let t=await W(i);return await e.saveImage({fileName:a,dataUrl:t}),`saved`}}return fe(i,a),`downloaded`},ve=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),ye=e=>e?Object.entries(e).map(([e,t])=>t==null?``:`${e.startsWith(`--`)?e:e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}:${typeof t==`number`?`${t}px`:t};`).join(``):``,K=(e,t,n)=>{let r=e.querySelector(`pre`);r&&(r.style.margin=`0`,r.style.background=`transparent`,r.style.whiteSpace=t?`pre-wrap`:`pre`,t&&(r.style.wordBreak=`break-word`,r.style.overflowWrap=`break-word`));let i=e.querySelector(`code`);if(i){let e=ye(n);e&&i.setAttribute(`style`,`${i.getAttribute(`style`)??``}${e}`)}},be=e=>`<pre><code>${ve(e)}</code></pre>`,xe=e=>{let t=(0,k.c)(21),{code:n,language:r,className:i,style:a,codeStyle:o,wrap:s}=e,c=s!==void 0&&s,{currentTheme:l}=v(),u=O.useRef(null),d;t[0]===l?d=t[1]:(d=y(l),t[0]=l,t[1]=d);let p=d,m,h;t[2]!==n||t[3]!==o||t[4]!==c?(m=()=>{let e=u.current;e&&(e.innerHTML=be(n),K(e,c,o))},h=[n,c,o],t[2]=n,t[3]=o,t[4]=c,t[5]=m,t[6]=h):(m=t[5],h=t[6]),O.useLayoutEffect(m,h);let g,_;t[7]!==n||t[8]!==o||t[9]!==r||t[10]!==c?(g=()=>{let e=u.current;if(!e)return;let t=!0,i=new AbortController;return w(n,(r||`text`).toLowerCase(),{signal:i.signal,priority:`visible`}).then(n=>{!t||!e||!n||(e.innerHTML=n,K(e,c,o))}),()=>{t=!1,i.abort()}},_=[n,r,c,o],t[7]=n,t[8]=o,t[9]=r,t[10]=c,t[11]=g,t[12]=_):(g=t[11],_=t[12]),O.useEffect(g,_);let b;t[13]===i?b=t[14]:(b=f(`typography-code`,i),t[13]=i,t[14]=b);let x=p,S;t[15]!==a||t[16]!==x?(S={...x,...a},t[15]=a,t[16]=x,t[17]=S):S=t[17];let C;return t[18]!==b||t[19]!==S?(C=(0,A.jsx)(`div`,{ref:u,className:b,style:S}),t[18]=b,t[19]=S,t[20]=C):C=t[20],C},Se=e=>{let t=e.replace(/^<file>\s*\n?/,``).replace(/\n?<\/file>\s*$/,``);return t=t.replace(/^\s*\d{5}\|\s?/gm,``),t.trim()},Ce=(e,t=``)=>{if(typeof e==`string`)return e;if(e==null)return t;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)}catch{return t}},we=e=>e?e.includes(`<diagnostics`)||e.includes(`<file_diagnostics>`)||e.includes(`LSP errors detected`)||e.includes(`This file has errors`):!1,Te=e=>e?e.replace(/\n{0,2}LSP errors detected[\s\S]*?<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,``).replace(/\n{0,2}This file has errors[\s\S]*?<\/file_diagnostics>/g,``).replace(/<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,``).replace(/<file_diagnostics>[\s\S]*?<\/file_diagnostics>/g,``).trim():``,Ee=(e,t)=>!e||typeof e!=`object`?String(e):C(e,t||``),q=e=>{if(typeof e==`string`){let t=e.trim();return t.length>0?t:void 0}if(e&&typeof e==`object`){let t=e.patch;if(typeof t==`string`){let e=t.trim();return e.length>0?e:void 0}}},De=e=>{if(!e||typeof e!=`object`)return;let t=q(e.patch)??q(e.diff);if(t)return t;let n=Array.isArray(e.files)?e.files:[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=q(e.patch)??q(e.diff);if(t)return t}},Oe=e=>{if(!e||typeof e!=`string`)return{data:null,isJson:!1};let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`)||!t.endsWith(`}`)&&!t.endsWith(`]`)||t.length<2)return{data:null,isJson:!1};try{let e=JSON.parse(t);return typeof e==`object`&&e?{data:e,isJson:!0}:{data:null,isJson:!1}}catch{return{data:null,isJson:!1}}},ke=(e,t,n)=>{let r=Se(e);if((t===`edit`||t===`multiedit`||t===`write`||t===`apply_patch`)&&we(r)&&(r=Te(r)),(t===`edit`||t===`multiedit`||t===`apply_patch`)&&r.trim().length===0){let e=De(n);if(e)return e}return r},Ae=e=>{let t=e.match(/<type>(file|directory)<\/type>/i)?.[1]?.toLowerCase()??`unknown`,n=(e.match(/<content>([\s\S]*?)<\/content>/i)?.[1]??e).replace(/\r\n/g,`
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{n as t}from"./runtime-fetch-CiqQd__Y.js";import{En as n,in as r}from"./persistence-CMWO3jFo.js";import{nt as i,rt as a}from"./vendor-base-ui-CnHfUmDN.js";import{n as o}from"./platform-CKIStkm5.js";import{v as s}from"./useUIStore-Brsa2mKs.js";import{n as c}from"./vendor-react-DLPElpoQ.js";import{a as l,n as u}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{f as d,r as f,t as p}from"./button-EzCcYrQl.js";import{n as m}from"./Icon-DKd015RD.js";import{i as h,n as g,t as _}from"./tooltip-DwUy2erJ.js";import{n as v}from"./useThemeSystem-DMzWVJaW.js";import{n as y}from"./markdownTheme-DM5h1i18.js";import{n as b}from"./MarkdownRenderer-CNDoKYhC.js";import{n as x,o as S,s as C,t as w}from"./markdown-worker-bS5OgGO3.js";import{a as T,i as E,o as D,t as ee}from"./imageSource-BpUsiwFd.js";import{t as te}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";var O=e(a(),1),k=c(),A=i(),ne=`w-[min(30rem,calc(100cqw-1rem))] min-w-[280px] max-w-full overflow-hidden rounded-xl shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]`,j={maxWidth:`min(28rem, calc(100cqw - 4ch))`,backgroundColor:`var(--surface-elevated)`,color:`var(--surface-elevated-foreground)`},M=`flex items-center justify-between gap-3 border-b border-[var(--surface-subtle)] px-3 py-2.5`,N=`text-xs font-medium leading-4 text-foreground md:text-[0.8125rem] md:leading-5`,re=`text-xs tabular-nums leading-4 text-muted-foreground md:text-[0.8125rem] md:leading-5`,P=`m-0 list-none divide-y divide-[var(--surface-subtle)] p-0`,F=`${P} max-h-[min(22rem,50vh)] overflow-y-auto`,ie=`${P} w-full`,ae={className:`p-0 rounded-none`,maxHeightClass:`max-h-[46vh]`,disableHorizontal:!0},I=`px-2.5 py-1.5 text-xs leading-4 md:py-2 md:text-[0.8125rem] md:leading-5`,oe=`flex min-w-0 items-center gap-1 text-xs leading-4 text-muted-foreground md:gap-1.5 md:text-[0.8125rem] md:leading-5`,se=`min-w-0 truncate text-xs leading-4 text-foreground md:text-[0.8125rem] md:leading-5`,ce=`inline-flex shrink-0 items-center gap-1 text-xs leading-4 tabular-nums text-muted-foreground md:text-[0.8125rem] md:leading-5`,le=`h-3 w-3 shrink-0 md:h-3.5 md:w-3.5`,ue={in_progress:`text-foreground`,pending:`text-foreground`,completed:`text-muted-foreground line-through`,cancelled:`text-muted-foreground line-through`},L={in_progress:`chat.statusRow.todo.status.inProgress`,pending:`chat.statusRow.todo.status.pending`,completed:`chat.statusRow.todo.status.completed`,cancelled:`chat.statusRow.todo.status.cancelled`},R=e=>{let t=(0,k.c)(26),{todo:n,isActive:r,activeRef:i}=e,{t:a}=d(),o=z.has(n.status)?n.status:`pending`,s=L[o],c;t[0]!==a||t[1]!==s?(c=a(s),t[0]=a,t[1]=s,t[2]=c):c=t[2];let l=c,u;t[3]===o?u=t[4]:(u=o===`in_progress`?(0,A.jsx)(m,{name:`record-circle`,className:`h-3.5 w-3.5 text-[var(--status-info)]`,"aria-hidden":`true`}):o===`completed`?(0,A.jsx)(m,{name:`checkbox-circle`,className:`h-3.5 w-3.5 text-[var(--status-success)]`,"aria-hidden":`true`}):(0,A.jsx)(m,{name:`time`,className:`h-3.5 w-3.5 text-muted-foreground`,"aria-hidden":`true`}),t[3]=o,t[4]=u);let p=u,v=r?`step`:void 0,y=r&&`bg-[var(--surface-muted)] before:absolute before:inset-y-2 before:left-0 before:w-0.5 before:rounded-full before:bg-[var(--status-info)]`,b;t[5]===y?b=t[6]:(b=f(`group relative grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] items-start gap-2.5`,I,y),t[5]=y,t[6]=b);let x;t[7]!==p||t[8]!==l?(x=(0,A.jsx)(h,{asChild:!0,children:(0,A.jsx)(`span`,{className:`flex size-4 items-center justify-center`,"aria-label":l,children:p})}),t[7]=p,t[8]=l,t[9]=x):x=t[9];let S;t[10]===l?S=t[11]:(S=(0,A.jsx)(g,{side:`left`,sideOffset:6,children:l}),t[10]=l,t[11]=S);let C;t[12]!==x||t[13]!==S?(C=(0,A.jsxs)(_,{children:[x,S]}),t[12]=x,t[13]=S,t[14]=C):C=t[14];let w=ue[o],T;t[15]===w?T=t[16]:(T=f(`block whitespace-normal break-words`,w),t[15]=w,t[16]=T);let E;t[17]!==T||t[18]!==n.content?(E=(0,A.jsx)(`span`,{className:`min-w-0 flex-1`,children:(0,A.jsx)(`span`,{className:T,children:n.content})}),t[17]=T,t[18]=n.content,t[19]=E):E=t[19];let D;return t[20]!==i||t[21]!==E||t[22]!==v||t[23]!==b||t[24]!==C?(D=(0,A.jsxs)(`li`,{ref:i,"aria-current":v,className:b,children:[C,E]}),t[20]=i,t[21]=E,t[22]=v,t[23]=b,t[24]=C,t[25]=D):D=t[25],D},z=new Set([`in_progress`,`pending`,`completed`,`cancelled`]),B=`image/png`,V=l(`OpenChamberMedia`),H=e=>{let t=e.toLowerCase().split(`;`)[0]?.trim()||B;if(t===`image/jpeg`||t===`image/jpg`)return`jpg`;if(t===`image/webp`)return`webp`;if(t===`image/gif`)return`gif`;if(t===`image/svg+xml`)return`svg`;if(t===`image/png`)return`png`;let n=t.split(`/`)[1];return n&&/^[a-z0-9.+-]+$/i.test(n)?n:`png`},U=(e,t)=>{let n=`image.${H(t)}`,r=(((e||``).trim()||n).split(/[\\/]/).pop()||n).replace(/[^\w.\- ()[\]]+/g,`_`).replace(/^\.+/,``);return r?/\.[a-z0-9]{1,8}$/i.test(r)?r:`${r}.${H(t)}`:n},W=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{if(typeof r.result==`string`){t(r.result);return}n(Error(`Failed to encode image`))},r.onerror=()=>n(r.error??Error(`Failed to encode image`)),r.readAsDataURL(e)}),de=async e=>{let t=await W(e),n=t.indexOf(`,`);return n>=0?t.slice(n+1):t},fe=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.setTimeout(()=>URL.revokeObjectURL(n),1e3)},G=async(e,t)=>{let n=await fetch(e,{signal:t,cache:`no-store`});if(!n.ok)throw Error(`Image fetch failed (${n.status})`);return n.blob()},pe=async(e,t=B)=>{if(!e.naturalWidth||!e.naturalHeight)return null;let n=e.currentSrc||e.src;if(n&&(/^(?:blob:|data:|openchamber-asset:)/i.test(n)||/^https?:/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n)))try{let e=await G(n);if(e.size>0)return e}catch{}try{let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`);if(!r)return null;r.drawImage(e,0,0);let i=t.startsWith(`image/`)?t:B,a=await new Promise(e=>{n.toBlob(t=>e(t),i===`image/jpg`?`image/jpeg`:i)});return a&&a.size>0?a:null}catch{return null}},me=async(e,t)=>{let n=``;try{return n=await ee(e,t??new AbortController().signal),await G(n,t)}finally{n&&T(n)}},he=async(e,n)=>{let r=e.effectiveDirectory??``,i=null;e.prefetchedBlob&&e.prefetchedBlob.size>0&&(i=e.prefetchedBlob);let a=e.displayUrl?.trim();if(!i&&a)try{i=await G(a,n)}catch{i=null}if(!i){let a=e.sourceUrl.trim();if(!a)throw Error(`Image source is empty`);if(/^(?:data|blob):/i.test(a)||/^https?:/i.test(a)||/^\/api(?=\/|[?#]|$)/.test(a))i=await G(a,n);else{let e=D(a,r);if(E(e))try{i=await me(e.path,n)}catch{let r=await t(`/api/fs/raw`,{method:`GET`,cache:`no-store`,query:{path:e.path},signal:n});if(!r.ok)throw Error(`Image source request failed with status ${r.status}`);i=await r.blob()}else i=await G(e.source,n)}}if(!i||i.size<=0)throw Error(`Image is empty`);let o=(e.mimeType||(i.type&&i.type.startsWith(`image/`)?i.type:``)||B).split(`;`)[0].trim()||B;return{blob:i,filename:U(e.filename,o),mimeType:o}},ge=()=>!o()||u===void 0?!1:u.isPluginAvailable(`OpenChamberMedia`),_e=async(e,t)=>{let{blob:i,filename:a,mimeType:o}=await he(e,t);if(ge()){let e=await de(i);return await V.saveImage({dataBase64:e,mimeType:o,filename:a}),`saved`}if(r()){let e=n()?.vscode;if(e?.saveImage){let t=await W(i);return await e.saveImage({fileName:a,dataUrl:t}),`saved`}}return fe(i,a),`downloaded`},ve=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),ye=e=>e?Object.entries(e).map(([e,t])=>t==null?``:`${e.startsWith(`--`)?e:e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}:${typeof t==`number`?`${t}px`:t};`).join(``):``,K=(e,t,n)=>{let r=e.querySelector(`pre`);r&&(r.style.margin=`0`,r.style.background=`transparent`,r.style.whiteSpace=t?`pre-wrap`:`pre`,t&&(r.style.wordBreak=`break-word`,r.style.overflowWrap=`break-word`));let i=e.querySelector(`code`);if(i){let e=ye(n);e&&i.setAttribute(`style`,`${i.getAttribute(`style`)??``}${e}`)}},be=e=>`<pre><code>${ve(e)}</code></pre>`,xe=e=>{let t=(0,k.c)(21),{code:n,language:r,className:i,style:a,codeStyle:o,wrap:s}=e,c=s!==void 0&&s,{currentTheme:l}=v(),u=O.useRef(null),d;t[0]===l?d=t[1]:(d=y(l),t[0]=l,t[1]=d);let p=d,m,h;t[2]!==n||t[3]!==o||t[4]!==c?(m=()=>{let e=u.current;e&&(e.innerHTML=be(n),K(e,c,o))},h=[n,c,o],t[2]=n,t[3]=o,t[4]=c,t[5]=m,t[6]=h):(m=t[5],h=t[6]),O.useLayoutEffect(m,h);let g,_;t[7]!==n||t[8]!==o||t[9]!==r||t[10]!==c?(g=()=>{let e=u.current;if(!e)return;let t=!0,i=new AbortController;return w(n,(r||`text`).toLowerCase(),{signal:i.signal,priority:`visible`}).then(n=>{!t||!e||!n||(e.innerHTML=n,K(e,c,o))}),()=>{t=!1,i.abort()}},_=[n,r,c,o],t[7]=n,t[8]=o,t[9]=r,t[10]=c,t[11]=g,t[12]=_):(g=t[11],_=t[12]),O.useEffect(g,_);let b;t[13]===i?b=t[14]:(b=f(`typography-code`,i),t[13]=i,t[14]=b);let x=p,S;t[15]!==a||t[16]!==x?(S={...x,...a},t[15]=a,t[16]=x,t[17]=S):S=t[17];let C;return t[18]!==b||t[19]!==S?(C=(0,A.jsx)(`div`,{ref:u,className:b,style:S}),t[18]=b,t[19]=S,t[20]=C):C=t[20],C},Se=e=>{let t=e.replace(/^<file>\s*\n?/,``).replace(/\n?<\/file>\s*$/,``);return t=t.replace(/^\s*\d{5}\|\s?/gm,``),t.trim()},Ce=(e,t=``)=>{if(typeof e==`string`)return e;if(e==null)return t;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)}catch{return t}},we=e=>e?e.includes(`<diagnostics`)||e.includes(`<file_diagnostics>`)||e.includes(`LSP errors detected`)||e.includes(`This file has errors`):!1,Te=e=>e?e.replace(/\n{0,2}LSP errors detected[\s\S]*?<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,``).replace(/\n{0,2}This file has errors[\s\S]*?<\/file_diagnostics>/g,``).replace(/<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,``).replace(/<file_diagnostics>[\s\S]*?<\/file_diagnostics>/g,``).trim():``,Ee=(e,t)=>!e||typeof e!=`object`?String(e):C(e,t||``),q=e=>{if(typeof e==`string`){let t=e.trim();return t.length>0?t:void 0}if(e&&typeof e==`object`){let t=e.patch;if(typeof t==`string`){let e=t.trim();return e.length>0?e:void 0}}},De=e=>{if(!e||typeof e!=`object`)return;let t=q(e.patch)??q(e.diff);if(t)return t;let n=Array.isArray(e.files)?e.files:[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=q(e.patch)??q(e.diff);if(t)return t}},Oe=e=>{if(!e||typeof e!=`string`)return{data:null,isJson:!1};let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`)||!t.endsWith(`}`)&&!t.endsWith(`]`)||t.length<2)return{data:null,isJson:!1};try{let e=JSON.parse(t);return typeof e==`object`&&e?{data:e,isJson:!0}:{data:null,isJson:!1}}catch{return{data:null,isJson:!1}}},ke=(e,t,n)=>{let r=Se(e);if((t===`edit`||t===`multiedit`||t===`write`||t===`apply_patch`)&&we(r)&&(r=Te(r)),(t===`edit`||t===`multiedit`||t===`apply_patch`)&&r.trim().length===0){let e=De(n);if(e)return e}return r},Ae=e=>{let t=e.match(/<type>(file|directory)<\/type>/i)?.[1]?.toLowerCase()??`unknown`,n=(e.match(/<content>([\s\S]*?)<\/content>/i)?.[1]??e).replace(/\r\n/g,`
2
2
  `).split(`
3
3
  `),r=e=>/\(\s*File has more lines\..*offset.*\)/i.test(e.trim());return{type:t,lines:n.map(e=>{let n=e.trim(),i=n.startsWith(`(`)&&n.endsWith(`)`)||r(n);if(t!==`directory`){let t=e.match(/^(\d+):\s?(.*)$/);if(t){let e=t[2],n=e.trim(),i=n.startsWith(`(`)&&n.endsWith(`)`)||r(n);return{lineNumber:i?null:Number(t[1]),text:e,isInfo:i}}}return{lineNumber:null,text:e,isInfo:i}}).filter((e,t,n)=>{if(e.text.trim().length>0)return!0;let r=n[t-1],i=n[t+1],a=!!(r?.isInfo||i?.isInfo),o=e.lineNumber!==null;return!(a&&o)})}},je=(e,t)=>{try{let n=e.trim().split(`
4
4
  `).filter(Boolean);if(n.length===0)return null;let r=[];return n.forEach(e=>{let t=e.match(/^(\s*)(.+)$/);if(t){let[,e,n]=t,i=Math.floor(e.length/2),a=!n.endsWith(`/`);r.push({name:n.replace(/\/$/,``),depth:i,isFile:a})}}),(0,A.jsx)(`div`,{className:f(`w-full min-w-0 font-mono space-y-0.5`,t?.unstyled?null:`p-3 bg-muted/20 rounded-xl border border-border/30`),style:s.tool.popup,children:r.map((e,t)=>(0,A.jsx)(`div`,{className:`min-w-0`,style:{paddingLeft:`${e.depth*20}px`},children:e.isFile?(0,A.jsx)(`span`,{className:`text-foreground/90 block truncate`,children:e.name}):(0,A.jsxs)(`span`,{className:`font-semibold text-foreground block truncate`,children:[e.name,`/`]})},t))})}catch{return null}},Me={backgroundColor:`var(--status-info)`,opacity:.6},Ne=(e,t,n)=>{try{let r=e.trim().split(`
package/dist/index.html CHANGED
@@ -552,7 +552,7 @@
552
552
  opacity: 0.72;
553
553
  }
554
554
  </style>
555
- <script type="module" crossorigin src="/assets/main-B839_vtF.js"></script>
555
+ <script type="module" crossorigin src="/assets/main-CDFpn3jQ.js"></script>
556
556
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-C0FnF6B9.js">
557
557
  <link rel="modulepreload" crossorigin href="/assets/runtime-auth-D66yq6ie.js">
558
558
  <link rel="modulepreload" crossorigin href="/assets/runtime-switch-BJM2k_uH.js">
@@ -568,11 +568,11 @@
568
568
  <link rel="modulepreload" crossorigin href="/assets/desktopRelayRestore-DDJtljeu.js">
569
569
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-client-C12gfjag.js">
570
570
  <link rel="modulepreload" crossorigin href="/assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js">
571
- <link rel="modulepreload" crossorigin href="/assets/platform-BxU3ZvQ0.js">
572
- <link rel="modulepreload" crossorigin href="/assets/terminalApi-C6zlKnK1.js">
571
+ <link rel="modulepreload" crossorigin href="/assets/platform-CKIStkm5.js">
572
+ <link rel="modulepreload" crossorigin href="/assets/terminalApi-DVj_hL-2.js">
573
573
  <link rel="modulepreload" crossorigin href="/assets/types-BuiqMmh_.js">
574
574
  <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-DCowZ2ab.js">
575
- <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-Dfmu3VWa.js">
575
+ <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-C5IUkpAF.js">
576
576
  <link rel="stylesheet" crossorigin href="/assets/src-iyTfdRD7.css">
577
577
  </head>
578
578
  <body class="h-full bg-background text-foreground">
@@ -74,7 +74,7 @@
74
74
  }
75
75
  </style>
76
76
 
77
- <script type="module" crossorigin src="/assets/miniChat-B0lH1mgT.js"></script>
77
+ <script type="module" crossorigin src="/assets/miniChat-CXYSaHX0.js"></script>
78
78
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-C0FnF6B9.js">
79
79
  <link rel="modulepreload" crossorigin href="/assets/runtime-auth-D66yq6ie.js">
80
80
  <link rel="modulepreload" crossorigin href="/assets/runtime-switch-BJM2k_uH.js">
@@ -90,11 +90,11 @@
90
90
  <link rel="modulepreload" crossorigin href="/assets/desktopRelayRestore-DDJtljeu.js">
91
91
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-client-C12gfjag.js">
92
92
  <link rel="modulepreload" crossorigin href="/assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js">
93
- <link rel="modulepreload" crossorigin href="/assets/platform-BxU3ZvQ0.js">
94
- <link rel="modulepreload" crossorigin href="/assets/terminalApi-C6zlKnK1.js">
93
+ <link rel="modulepreload" crossorigin href="/assets/platform-CKIStkm5.js">
94
+ <link rel="modulepreload" crossorigin href="/assets/terminalApi-DVj_hL-2.js">
95
95
  <link rel="modulepreload" crossorigin href="/assets/types-BuiqMmh_.js">
96
96
  <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-DCowZ2ab.js">
97
- <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-Dfmu3VWa.js">
97
+ <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-C5IUkpAF.js">
98
98
  <link rel="stylesheet" crossorigin href="/assets/src-iyTfdRD7.css">
99
99
  </head>
100
100
  <body class="h-full bg-background text-foreground">
package/dist/mobile.html CHANGED
@@ -63,7 +63,7 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-DCMqyVbF.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-BAox2MyA.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-C0FnF6B9.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/runtime-auth-D66yq6ie.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/runtime-switch-BJM2k_uH.js">
@@ -79,11 +79,11 @@
79
79
  <link rel="modulepreload" crossorigin href="/assets/desktopRelayRestore-DDJtljeu.js">
80
80
  <link rel="modulepreload" crossorigin href="/assets/vendor-opencode-client-C12gfjag.js">
81
81
  <link rel="modulepreload" crossorigin href="/assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js">
82
- <link rel="modulepreload" crossorigin href="/assets/platform-BxU3ZvQ0.js">
83
- <link rel="modulepreload" crossorigin href="/assets/terminalApi-C6zlKnK1.js">
82
+ <link rel="modulepreload" crossorigin href="/assets/platform-CKIStkm5.js">
83
+ <link rel="modulepreload" crossorigin href="/assets/terminalApi-DVj_hL-2.js">
84
84
  <link rel="modulepreload" crossorigin href="/assets/types-BuiqMmh_.js">
85
85
  <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-DCowZ2ab.js">
86
- <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-Dfmu3VWa.js">
86
+ <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-C5IUkpAF.js">
87
87
  <link rel="stylesheet" crossorigin href="/assets/src-iyTfdRD7.css">
88
88
  </head>
89
89
  <body class="h-full bg-background text-foreground">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openchambery/web",
3
- "version": "2.0.0-beta.18",
3
+ "version": "2.0.0-beta.19",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./server/index.js",
@@ -1,6 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-CUPf3g2A.js","assets/rolldown-runtime-C0FnF6B9.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{C as t,D as n,k as r}from"./runtime-auth-D66yq6ie.js";import{c as i,f as a,i as o,n as s,r as c,s as l}from"./runtime-switch-BJM2k_uH.js";import{n as u}from"./runtime-fetch-CiqQd__Y.js";import{En as d,Lt as f,St as p,Wt as m,at as h,gt as g,in as ee,lt as te,r as ne,tn as re,ut as ie,zt as ae}from"./persistence-CMWO3jFo.js";import{a as oe,r as se}from"./vendor-zustand-B4dlGEM2.js";import{rt as ce}from"./vendor-base-ui-CnHfUmDN.js";import{n as le,r as ue,t as de}from"./vendor-opencode-client-C12gfjag.js";import{x as fe}from"./useUIStore-Brsa2mKs.js";import{n as pe}from"./vendor-react-DLPElpoQ.js";import{i as me}from"./vendor-pathe-vBmvQE8f.js";import{o as he}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.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(p()),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(ce(),1),Ce=pe();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=`openchamber: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)}},Me=`desc`;function Ne(e){return!S(e)||e.type!==`compaction`?!1:e.status===`running`||e.status===`completed`||e.status===`failed`}function Pe(e){if(e)return e.find(Ne)}var Fe=e=>e?e.toLowerCase().includes(`application/json`):!1,Ie=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 Le(e){if(!S(e))return null;let t=C(e.id);return t?{...e,id:t}:null}function Re(e,t,n){return`${e}:${t}:${n}`}function ze(e,t,n,r,i=`text`,a){return i===`reasoning`?{id:Re(t,i,n),sessionID:e,messageID:t,type:`reasoning`,text:r}:{id:Re(t,i,n),sessionID:e,messageID:t,type:`text`,text:r,...a?.synthetic===!0?{synthetic:!0}:{}}}function Be(e){return e?e.nativeType===`synthetic`||e.type===`synthetic`:!1}function Ve(e,t){return!e?.id||Be(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 He(e){if(typeof e==`string`&&e.length!==0)return e.replace(/^evt_/,`msg_`)}function Ue(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
- `):typeof e.output==`string`?e.output:void 0}function We(e){return e===`patch`?`apply_patch`:e}function Ge(e,t,n){let r=C(n.id)??`${t}:tool`,i=We(C(n.name))??`tool`,a=S(n.state)?n.state:{},o=C(a.status)??`completed`;return{id:r,sessionID:e,messageID:t,type:`tool`,tool:i,callID:r,state:{status:o===`streaming`?`pending`:o,input:a.input??{},output:Ue(a),error:S(a.error)?C(a.error.message):C(a.error),metadata:S(a.metadata)?a.metadata:{}}}}function Ke(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 qe(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 Je(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 Ye(e,t,n){return{id:t.id,sessionID:e,role:n,time:Ke(t.time)}}function Xe(e,t){let n=Le(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=Ye(e,n,`user`);Je(t,n);let i=[],a=C(n.text);a&&i.push(ze(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=Ye(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=qe(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(ze(e,r,l++,t.text));continue}if(n===`reasoning`&&typeof t.text==`string`){s.push(ze(e,r,u++,t.text,`reasoning`));continue}n===`tool`&&s.push(Ge(e,r,t))}return{info:t,parts:s}}if(i===`shell`){let t=Ye(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:Re(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={...Ye(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?[ze(e,r,0,s,`text`,{synthetic:!0})]:[{id:Re(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={...Ye(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:Ye(e,n,`assistant`),parts:[ze(e,r,0,C(n.text)??`[${i}]`)]}}function Ze(e,t,n=Me,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=Xe(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=>Ve(e.info,e.parts)).length;return{records:i,cursor:s?void 0:o,complete:s,turnCount:c}}async function Qe(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=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(Ie(o))throw Error(`session projection: unexpected HTML response`);Fe(o);let s;try{s=await a.json()}catch{throw Error(`session projection: malformed JSON`)}return Ze(s,e.sessionID,n,t)}function $e(e,t){if(!S(e))throw Error(`session context: expected JSON object`);if(!Array.isArray(e.data))throw Error(`session context: data must be an array`);let n=[];for(let r of e.data){let e=Xe(t,r);e&&n.push(e)}return{records:n,cursor:void 0,complete:!1,turnCount:n.filter(e=>Ve(e.info,e.parts)).length}}async function et(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/context`,n=await u(t,{method:`GET`,query:{directory:e.directory},signal:e.signal});if(!n.ok)throw Error(`session context failed (${n.status})`);if(Ie(n.headers.get(`content-type`)))throw Error(`session context: unexpected HTML response`);let r;try{r=await n.json()}catch{throw Error(`session context: malformed JSON`)}return $e(r,e.sessionID)}function tt(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=[],l=new Set;for(let e of n)!i.has(e.info.id)||l.has(e.info.id)||(c.push(e.info.id),l.add(e.info.id));for(let e of t)!i.has(e.info.id)||l.has(e.info.id)||(c.push(e.info.id),l.add(e.info.id));for(let e of i.keys())l.has(e)||c.push(e);return c.map(e=>i.get(e))}var nt=e=>e?e.toLowerCase().includes(`application/json`):!1,rt=e=>e?e.toLowerCase().includes(`text/html`):!1;function it(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function at(e){return typeof e==`string`&&e.length>0?e:void 0}function ot(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function st(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function ct(e){try{return(await e.text()).trim()}catch{return``}}async function lt(e,t){let n=e.headers.get(`content-type`);if(rt(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!nt(n)&&r==null)throw Error(`${t}: empty response`);return r}var ut=oe((e,t)=>({runningBySession:{},setRunning(t,n){e(e=>{let r={...e.runningBySession};return n?r[t]=!0:delete r[t],{runningBySession:r}})},isRunning(e){return t().runningBySession[e]===!0},reset(){e({runningBySession:{}})}}));function w(e,t){ut.getState().setRunning(e,t)}function dt(e){return ut.getState().isRunning(e)}function ft(e){return!dt(e.sessionID)}function pt(e){let t=it(e)?e:null,n=t&&it(t.data)?t.data:t;if(!n)throw Error(`session compact: expected inbox item`);let r=at(n.id),i=at(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:ot(n.timeCreated)}}function mt(e){let t=it(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)!it(e)||e.type!==`compaction`||r.push(pt(e));return r}function ht(e,t){t.some(e=>e.type===`compaction`)&&w(e,!0)}function gt(e,t){t.some(e=>(e.parts??[]).find(Ne)?.status===`running`)&&w(e,!0)}async function _t(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||st(`session compact`,r.status,await ct(r));let i=pt(await lt(r,`session compact`));return w(i.sessionID,!0),i}var vt=`compaction:`;function yt(e,t){return t&&t.length>0?t:`${vt}${e}`}function bt(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=>Ne(e)&&e.status===`running`))return r.id}}function xt(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(Ne),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 St(e,t){let n=String(t.type??``);if(!n.startsWith(`session.compaction.`))return!1;let r=it(t.properties)?t.properties:null;if(!r)return!1;let i=at(r.sessionID);if(!i)return!1;let a=at(r.inputID),o=bt(e,i),s=n===`session.compaction.started`?a??He(t.id)??yt(i):a??o??He(t.id)??yt(i);if(n===`session.compaction.started`)return!e.part[s]?.some(Ne)&&(xt(e,i,s,e=>({...e,status:`running`,reason:r.reason===`auto`?`auto`:`manual`,...typeof r.recent==`string`?{recent:r.recent}:{}}),ot(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?(xt(e,i,s,e=>({...e,status:`running`,summary:(e.summary??``)+t})),w(i,!0),!0):!1}if(n===`session.compaction.ended`)return xt(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}:{}}),ot(r.eventCreated)),w(i,!1),!0;if(n===`session.compaction.failed`){let t=it(r.error)?r.error:{};return xt(e,i,s,e=>({...e,status:`failed`,reason:r.reason===`auto`?`auto`:`manual`,error:{type:at(t.type)??`error`,message:at(t.message)??``,...typeof t.status==`number`?{status:t.status}:{}}}),ot(r.eventCreated)),w(i,!1),!0}return!1}var Ct=new Set([`patch`,`step-start`,`step-finish`]),wt=[`text`,`output`],Tt=new Set([`completed`,`error`,`aborted`,`failed`,`timeout`,`cancelled`]);function Et(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 Dt(e,t){let n=[];for(let r of wt){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 Ot(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 kt(e){if(e.type!==`tool`)return;let t=e.state?.status;return typeof t==`string`?t:void 0}function At(e,t){if(e.type!==`tool`||t.type!==`tool`)return!1;let n=kt(e),r=kt(t);if(n&&Tt.has(n)&&(!r||!Tt.has(r)))return!0;let i=Ot(e),a=Ot(t);return typeof i==`number`&&typeof a!=`number`}function jt(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 Mt=[`agent`,`mode`,`providerID`,`modelID`,`variant`],Nt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Pt=[`input`,`output`,`reasoning`];function Ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return Pt.some(e=>typeof t[e]==`number`&&Number.isFinite(t[e])&&t[e]>0)}function It(e){if(!e||typeof e!=`object`)return!1;let t=e;return Pt.every(e=>typeof t[e]!=`number`||!Number.isFinite(t[e])||t[e]<=0)}function Lt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Rt(e,t){let n={...e,...t},r=e,i=t,a=n;for(let e of Mt){let t=Lt(i[e]),n=Lt(r[e]);t?a[e]=t:n?a[e]=n:delete a[e]}let o=i.model,s=r.model;return Nt(o)?a.model=o:Nt(s)?a.model=s:delete a.model,(e.time||t.time)&&(n.time={...e.time,...t.time}),Ft(r.tokens)&&It(i.tokens)&&(a.tokens=r.tokens),n}function zt(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(!jt(e[n],t[n]))return!1;return!0}function Bt(e,t,n){if(!t)return!1;let r=e.message[t];return r?b(r,n)>=0:!1}function Vt(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=Rt(t,n);if(zt(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(Ct.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=!Bt(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(At(e,r))return!1;let t=Dt(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.__openchamberOptimistic===!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?Et(o,n.delta):(o??``)+n.delta,__dedupeNextDeltaFields:s.filter(e=>e!==n.field)},e.part[n.messageID]=l,!0}default:return rn(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 Ht(e,t,n){return`${e}:${t}:${n}`}function Ut(e){return typeof e?.created==`number`&&Number.isFinite(e.created)&&e.created>0?e.created:Date.now()}function Wt(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),!Lt(n.agent)&&r?.agent&&(c.agent=r.agent,s=!0),!Lt(n.modelID)&&r?.modelID&&(c.modelID=r.modelID,s=!0),!Lt(n.providerID)&&r?.providerID&&(c.providerID=r.providerID,s=!0),!Lt(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:Ut(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=Rt(o,r);if(zt(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=Wt(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)??Ut({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)??Ut({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
- `)}function Qt(e,t,n,r){let i=Ht(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:Ht(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 tn(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:We(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 nn(e,t,n){return e.message[t]?.find(t=>e.part[t.id]?.some(e=>e.type===`text`&&e.shellAction?.shellID===n))?.id}function rn(e,t){let n=String(t.type);if(n.startsWith(`session.compaction.`))return St(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=nn(e,i,o),l=c?s.find(e=>e.id===c):void 0,u=l?.id??(n===`session.shell.started`?He(t.id):void 0);if(!u||n===`session.shell.started`&&l)return!1;let d=Xe(i,{id:u,type:`shell`,shellID:o,command:a.command,status:a.status,exit:a.exit,output:r.output,time:{created:l?.time.created??Wt(r),...n===`session.shell.ended`?{completed:Wt(r)}:{}}});return!d||l&&jt(l,d.info)&&jt(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=He(t.id);if(!n)return!1;let a=Xe(i,{id:n,type:`synthetic`,text:r.text,description:r.description,metadata:r.metadata,time:{created:Wt(r)}});if(!a)return!1;let o=e.message[i]??[],s=o.find(e=>e.id===n);return s&&jt(s,a.info)&&jt(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:Wt(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 tn(e,i,a,c,l,e=>e,s);if(n===`session.tool.input.delta`){let t=typeof r.delta==`string`?r.delta:``;return t?tn(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 tn(e,i,a,c,l,e=>{let n=T(e.state)??{};return{...e,state:{...n,input:t}}},s)}return n===`session.tool.called`?tn(e,i,a,c,l,e=>{let t=T(e.state)??{};return{...e,state:{...t,status:`pending`,input:r.input??t.input??{},metadata:T(t.metadata)??{}}}},s):n===`session.tool.progress`?tn(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`?tn(e,i,a,c,l,e=>{let t=T(e.state)??{};return{...e,state:{...t,status:`completed`,input:t.input??r.input??{},output:Zt(r.content),metadata:T(r.metadata)??T(t.metadata)??{}}}},s):n===`session.tool.failed`&&tn(e,i,a,c,l,e=>{let t=T(e.state)??{},n=T(r.error);return{...e,state:{...t,status:`error`,input:t.input??{},output:Zt(r.content),error:n?E(n.message)??E(r.error):E(r.error),metadata:T(r.metadata)??T(t.metadata)??{}}}},s)}function an(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function on(e){let t=e.id;return typeof t==`string`&&t.length>0?t:void 0}function D(e){return e.slim===!0}function sn(e,t){if(!e||e.length===0||!t.some(e=>D(e)))return t;let n=new Map;for(let t of e){let e=on(t);e&&!D(t)&&n.set(e,t)}if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!D(e))return e;let t=on(e);if(!t)return e;let i=n.get(t);return i?(r=!0,i):e});return r?i:t}function cn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])?t:e}function ln(e){let t=e.clientRole??e.role;return typeof t==`string`?t:``}function un(e){return ln(e)!==`assistant`||!an(e)}function dn(e,t,n){if(!e||e.length===0)return t;let r=sn(e,t);if(un(n))return cn(r,e);let i=new Set;for(let e of r){let t=on(e);t&&i.add(t)}let a=new Map,o=[],s,c=0;for(let t of e){let e=on(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 cn(r,e);let l=[...o];for(let e of r){l.push(e);let t=on(e);if(!t)continue;let n=a.get(t);n&&l.push(...n)}return cn(l,e)}var fn=e=>Object.freeze(e),pn=Object.freeze({initial:fn({id:`initial`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),prepend:fn({id:`history`,onStale:`drop`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),recovery:fn({id:`recovery`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),"reconcile-page":fn({id:`reconcile-page`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`keep-unless-full`}),materialize:fn({id:`materialize`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`})}),mn=fn({id:`recovery-backfill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),hn=fn({id:`send-gap-fill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),gn=pn.initial;function _n(e){let t=pn[e.purpose]??gn;return!e.stale||t.onStale===`drop`?t:mn}function vn(e,t){return e.preserveStreaming===`none`?!1:e.preserveStreaming===`all`||t===`assistant`}var yn=e=>structuredClone(e),bn=e=>({transport:e.transport,generation:e.generation,directory:e.directory,sessionID:e.sessionID});function xn(e){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID])}function Sn(e,t){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID,t])}function Cn(e){return JSON.stringify([e.transport,e.generation])}function wn(e,t){return e.created===t.created?e.messageID<t.messageID?-1:+(e.messageID>t.messageID):e.created-t.created}function Tn(e){let t=e.time?.created;return{created:typeof t==`number`&&Number.isFinite(t)?t:0,messageID:e.id}}function En(e){return un(e)}function Dn(e){return D(e)?`slim`:`full`}function On(e){return e.some(e=>D(e))?`slim`:`full`}var kn=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(kn);let t=e,n={};for(let e of Object.keys(t).sort()){let r=t[e];r!==void 0&&(n[e]=kn(r))}return n},An=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n};async function jn(e,t){let n=JSON.stringify(kn({info:e,parts:t})),r=new TextEncoder().encode(n);return{hash:An(await crypto.subtle.digest(`SHA-256`,r)),byteSize:r.byteLength}}var Mn=e=>({scope:bn(e.scope),messageID:e.messageID,info:yn(e.info),parts:yn(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}}),Nn=e=>{let t=0;return()=>{let n=e();return t=n>t?n:t+1,t}},Pn=(e,t)=>{let n=t.slice().sort((e,t)=>wn(e.sortKey,t.sortKey)).map(Mn);return{scope:bn(e),records:n,byteSize:n.reduce((e,t)=>e+t.byteSize,0)}},Fn=e=>yn(e),In=e=>bn(e),Ln=(e=Date.now)=>Nn(e),Rn=e=>Mn(e),zn=(e,t)=>Pn(e,t.slice());function Bn(e){return En(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 Vn=[`text`,`output`],Hn={pending:1,started:2,running:3,completed:4,error:4};function Un(e,t){return e.filter(e=>!!e?.id&&!t.has(e.type))}function Wn(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 Gn(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 Kn(e,t){let n=e[t];return typeof n==`string`?n:void 0}function qn(e){return Gn(e)===void 0&&Vn.some(t=>{let n=Kn(e,t);return typeof n==`string`&&n.length>0})}function Jn(e){let t=e.state;if(!(!t||typeof t!=`object`))return t}function Yn(e){let t=Jn(e)?.status;return typeof t==`string`?t:void 0}function Xn(e){return e?Hn[e]??0:0}function Zn(e,t){if(qn(e))return!0;if(Gn(e)===void 0){if(e.type===`tool`){let n=Yn(e);return n===`completed`||n===`error`?t:!0}return!0}return t}function Qn(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 $n(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0}function er(e,t,n){if(e.type!==`tool`||t.type!==`tool`)return n;let r=Jn(e);if(!r)return n;let i=Jn(n)??{},a=Jn(t)??{},o={...i},s=!1,c=Yn(e),l=Yn(t);Xn(c)>Xn(l)&&c&&(o={...o,status:c},s=!0);let u=r.input,d=a.input;$n(u)&&!$n(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 $n(m)&&!$n(a.metadata)&&(o={...o,metadata:m},s=!0),s?n===t?{...t,state:o}:{...n,state:o}:n}function tr(e,t){if(!e||Gn(t)!==void 0)return t;let n=t;for(let r of Vn){let i=Kn(e,r);if(!i)continue;let a=Kn(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=Qn(e);if(r){let e=Qn(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=er(e,t,n),n}function nr(e,t){if(!e||e.length===0||!t.some(e=>D(e)))return t;let n=new Map;for(let t of e)t.id&&!D(t)&&n.set(t.id,t);if(n.size===0)return t;let r=!1,i=t.map(e=>{if(!D(e)||!e.id)return e;let t=n.get(e.id);return t?(r=!0,t):e});return r?i:t}function rr(e){return e.__openchamberOptimistic===!0}function ir(e){return!!(e&&e.length>0&&e.some(rr))}function ar(e){return e.length===0||e.some(e=>D(e))}function or(e,t,n,r,i,a){if(a===`keep-unless-full`&&e&&ir(e)&&ar(t))return e;let o=nr(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=tr(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=>D(e)),f=e.filter(e=>!!e?.id&&!u.has(e.id)&&!n.has(e.type)&&(Zn(e,i)||d&&!D(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 sr=e=>e,cr=e=>{let t=sr(e).finish;return typeof t==`string`&&t.length>0},lr=e=>typeof sr(e).time?.completed==`number`,ur=e=>!!sr(e).error;function dr(e,t){let n=sr(t),r=n.finish,i=n.time?.completed,a=n.error,o=e.tokens,s=t.tokens,c=!cr(e)&&typeof r==`string`&&r.length>0,l=!lr(e)&&typeof i==`number`,u=!ur(e)&&!!a,d=!Ft(o)&&Ft(s);if(!c&&!l&&!u&&!d)return e;let f={...e};return c&&(f.finish=r),l&&(f.time={...sr(e).time,completed:i}),u&&(f.error=a),d&&(f.tokens=s),f}function fr(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)),c=t.filter(e=>!s.has(e.id));if(c.length===0)return a?o:e;if(!t.some(e=>s.has(e.id)))return r===`prepend`?[...c,...o]:r===`by-created`?pr(o,c):[...o,...c];let l=-1;for(let e of t){let t=o.findIndex(t=>t.id===e.id);if(t>=0){l=t;continue}l+=1,o.splice(l,0,e)}return o}function pr(e,t){let n=e.slice();for(let e of t){let t=Tn(e),r=n.length;for(let e=0;e<n.length;e+=1)if(wn(t,Tn(n[e]))<0){r=e;break}n.splice(r,0,e)}return n}function mr(e,t,n){return fr(e,t,(e,t)=>t?dr(e,t):e,n)}function hr(e,t,n){return fr(e,t,(e,t)=>!t||JSON.stringify(e)===JSON.stringify(t)?e:Rt(e,t),n)}function gr(e,t,n,r={}){let i=r.skipPartTypes??new Set,a=r.merge??gn,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`?hr(u,c,o):mr(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=or(r,Un(e.parts??[],i),i,vn(a,e.info.role),an(e.info),a.protectOptimistic);(r?Wn(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 _r(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function vr(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&&_r(i)||r.push(i.id));return{hasMessages:!0,renderable:r.length===0,missingPartMessageIDs:r}}var yr=(e,t)=>e<t?-1:+(e>t);function br(e){return e.filter(e=>!!e?.id)}function xr(e,t){if(t.length===0)return{...e,confirmed:[]};let n=[...e.session],r=new Map(e.part.map(e=>[e.id,br(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,br(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,br(e.parts))}return{cursor:e.cursor,complete:e.complete,session:n,part:[...r.entries()].sort((e,t)=>yr(e[0],t[0])).map(([e,t])=>({id:e,part:t})),confirmed:i}}var Sr={kind:`unknown`,loadedTurns:0},Cr=3e4,wr=12e5,Tr={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_snapshot_at:void 0,session_error_at:{},session_execution_recovery:{},session_diff:{},todo:{},permission:{},question:{},lsp:[],vcs:void 0,limit:20},Er={ready:!1,path:{state:``,config:``,worktree:``,directory:``,home:``},projects:[],providers:{all:[],connected:[],default:{}},providerAuth:{},config:{},reload:void 0,sessionTodo:{}};function Dr(e,t){return e===void 0||t===void 0?!1:t>e}var Or=class extends Error{};function kr(e,t,n){if(n===`reconcile-page`)return e??Sr;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 Or(`session message page: complete=false requires non-empty cursor`);if(n===`prepend`&&e?.kind===`has-more`&&e.cursor===o)throw new Or(`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 Or(`session message page: complete=false with zero records makes no progress`);return{kind:`has-more`,cursor:o,loadedTurns:a}}function Ar(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 jr(e,t,n,r){let i=Dr(r.capturedRevision,r.liveRevision),a=_n({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=xr({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=gr(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=kr(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 Or))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=!Ar(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 Mr=new Set([`tool`,`reasoning`,`file`,`text`]),Nr=new Set([`tool`,`reasoning`,`file`]);function Pr(e){return e.some(e=>D(e)&&Mr.has(e.type))}function Fr(e,t){let n=!1,r=!1;for(let t of e)Nr.has(t.type)&&(n=!0,D(t)&&(r=!0));return n?r?!0:t?an(t):!1:!1}var Ir=e=>{if(!e)return``;let t=e.clientRole??e.role;return typeof t==`string`?t:``};function Lr(e,t){return Ve(e,t)}function Rr(e){let t=0;for(let n of e.messageOrder)Lr(e.messagesByID[n],e.partsByMessageID[n])&&(t+=1);return t}var zr=(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(Lr(a,e.partsByMessageID[n]))break;if(Ir(a)!==`assistant`)continue;let o=a.parentID;typeof o==`string`&&o.length>0&&o!==t||r.push(a)}return r},Br=(e,t)=>an(e)?!0:Array.isArray(t)&&t.length>0;function Vr(e){let t;for(let n=e.messageOrder.length-1;n>=0;--n){let r=e.messageOrder[n];if(Lr(e.messagesByID[r],e.partsByMessageID[r])){t=r;break}}return t?zr(e,t).some(t=>Br(t,e.partsByMessageID[t.id])):!1}function Hr(e){return e.materializeActive?`p2`:e.prependActive||e.earlierHistoryLoaded?`p1`:e.p0Satisfied?`p0`:`idle`}var Ur=new Set([`stop`,`length`]);function Wr(e){let t=e.messageOrder[e.messageOrder.length-1];if(!t)return!1;let n=e.messagesByID[t];if(!n||Ir(n)!==`assistant`||n.error)return!1;let r=n.finish;return typeof r!=`string`||!Ur.has(r)?!1:typeof n.time?.completed!=`number`||r===`stop`&&!Ft(n.tokens)}function Gr(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 Kr(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 qr=`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 Jr(e){return qr.includes(e)}function O(e){return e.trim()}function Yr(e){return`${O(e.directory)}\n${e.sessionID}`}function Xr(e,t){return e.session_history_boundary?.[t]??Sr}function Zr(e){return e.filter(e=>!!e?.id)}function Qr(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 $r(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||!Qr(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 ei(e,t,n){let r=e.getState(),i=n.page,a=jr(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?($r(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 ti(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(!Jr(e.type))continue;i=!0;let t=Vt(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 ni(e,t){return ti(e,[t.event])}function ri(e,t){return ti(e,t.events)}function ii(e,t,n){if(n.records.length===0)return{applied:!1,changed:!1};let r=e.getState(),i=gr({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 ai(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 oi(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]=Zr(n.parts),e.setState({message:o,part:s}),{applied:!0,changed:!0}}function si(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 ci(e,t,n,r){return n.clearOptimisticShadow?.({directory:r,sessionID:e,messageID:t}),{applied:!0,changed:!1}}function li(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 ui(e,t,n){let r=li(e,t);if(!n.page)return{applied:!0,changed:r};let i=ei(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 di(e){let t=new Map,n=new Map,r=r=>{let i=Yr(r);if(n.has(i))return;let a=O(r.directory),o=e.getStore(a),s=r.sessionID,c=o.getState().message?.[s],l=Xr(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=Xr(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=Qr(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=O(t.directory),r=e.getStore(n).getState(),i=t.sessionID,a=r.message?.[i]??[],o=e.getLiveRevision?.(n,i)??0;return Kr({sessionID:i,messages:a,parts:r.part??{},boundary:Xr(r,i),liveRevision:o})},getPagination(t){let n=O(t.directory),r=e.getStore(n).getState();return Gr(t.sessionID,Xr(r,t.sessionID))},getRequestState(t){let n=O(t.directory);return e.getRequestState?.(n,t.sessionID)??{sessionID:t.sessionID,status:`idle`}},getHydrationState(e){let t=a.getTranscript(e),n=Vr(t);return{sessionID:e.sessionID,p0Satisfied:n,phase:Hr({p0Satisfied:n,earlierHistoryLoaded:Rr(t)>1})}},getMessage(e,t){return a.getTranscript(e).messagesByID[t]},getParts(t,n){let r=O(t.directory);return e.getStore(r).getState().part?.[n]??[]},hasSession(t){let n=O(t.directory),r=e.getStore(n).getState().message;return r?Object.prototype.hasOwnProperty.call(r,t.sessionID):!1},apply(t,n){let r=O(t.directory),i=e.getStore(r),a=t.sessionID;switch(n.type){case`http-page`:return ei(i,a,n);case`sse-event`:return ni(i,n);case`sse-event-batch`:return ri(i,n);case`optimistic-add`:return oi(i,a,n,e,r);case`optimistic-confirm`:return ci(a,n.messageID,e,r);case`optimistic-remove`:return si(i,a,n.messageID,e,r);case`reset`:return ui(i,a,n);case`materialize-snapshots`:return ii(i,a,n);case`remove-message`:return ai(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=Yr(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 fi=new Set,pi=new Set;function mi(e,t){return`${e}\n${t}`}function hi(){for(let e of pi)e()}function gi(e,t){!e||!t||(fi.add(mi(e,t)),hi())}function _i(e,t){!e||!t||fi.delete(mi(e,t))&&hi()}function vi(e,t){if(!e)return!1;if(t)return fi.has(mi(t,e));let n=`\n${e}`;for(let e of fi)if(e.endsWith(n))return!0;return!1}function yi(e){return pi.add(e),()=>{pi.delete(e)}}var bi=[],xi=new Map,Si=new Map,Ci=0,wi=()=>{let e=bi.findIndex(e=>e.priority===`user`);if(e>=0){let[t]=bi.splice(e,1);return t}return bi.shift()},Ti=()=>{for(;Ci<4;){let e=wi();if(!e)return;xi.delete(e.key),Ci+=1,Promise.resolve().then(()=>e.run()).then(t=>{e.resolve(t)},t=>{e.reject(t)}).finally(()=>{--Ci,Si.delete(e.key),Ti()})}};function Ei(e,t,n){let r=n?.priority??`background`,i=Si.get(e);if(i){let t=xi.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 bi.push(c),xi.set(e,c),Si.set(e,s),Ti(),s}var Di=null,Oi=0,ki=new Set;function Ai(){Oi+=1;for(let e of ki)e()}function ji(e){return e}function Mi(e){return ki.add(e),()=>{ki.delete(e)}}function Ni(){return Oi}function Pi(e){return Di?.repository===e?e:(Di={kind:`query`,repository:e},Ai(),e)}function Fi(){Di&&(Di=null,Ai())}function k(){return Di?.repository??null}function Ii(){let e=k();if(!e)throw Error(`TranscriptRepository is not bound — SyncProvider must mount first`);return e}function Li(e,t){let n=k();if(n)return n;let r=ji(t);return di({getStore:e=>r})}function A(e,t,n){return{directory:e.trim(),sessionID:t,...n?.transport===void 0?{}:{transport:n.transport},...n?.generation===void 0?{}:{generation:n.generation}}}function Ri(e){try{let t=k(),n=o(),r=s();return t?.getCacheBudget?.().listCanonicalScopesForSession(e,{transport:n,generation:r})?.map(e=>A(e.directory,e.sessionID,{transport:e.transport,generation:e.generation}))??[]}catch{return[]}}function zi(e,t){let n=k();return n?n.apply(e,t):null}async function Bi(e,t){let n=Ii();if(typeof n.fetchPreviousPage!=`function`)throw Error(`TranscriptRepository does not support fetchPreviousPage`);await n.fetchPreviousPage(A(e,t))}async function Vi(e,t){let n=Ii();if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support ensureInitial`);await n.ensureInitial(A(e,t))}async function Hi(e,t){let n=Ii(),r=A(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 Ui(e,t){let n=Ii();if(typeof n.refreshFromAuthority!=`function`)throw Error(`TranscriptRepository does not support refreshFromAuthority`);gi(e,t);try{await n.refreshFromAuthority(A(e,t))}finally{_i(e,t)}}async function Wi(e,t,n,r){let i=Ii();if(typeof i.materializeMessage!=`function`)throw Error(`TranscriptRepository does not support materializeMessage`);let a=A(e,t);await Ei(`${e}\n${t}\n${n}`,()=>i.materializeMessage(a,n),{priority:r?.priority??`background`})}function Gi(e,t,n){let r=k();return!r||typeof r.getMessageMaterializationState!=`function`?{sessionID:t,messageID:n,status:`idle`}:r.getMessageMaterializationState(A(e,t),n)}function Ki(e,t){k()?.purgeSession?.(A(e,t))}var j=null;function qi(e){j&&j!==e&&j.cancelAll(`reregister`),j=e}function Ji(e){j?.captureCheckpoints(e)}function Yi(e){j?.onCompensation(e)}async function Xi(e){return j?j.ensureOnObserve(e):null}function Zi(e){j?.cancelAll(e)}var Qi=[],$i=[],ea={sessionID:``,messageOrder:[],messagesByID:{},partsByMessageID:{},boundary:Sr,liveRevision:0};Gr(``,Sr);var ta={sessionID:``,phase:`idle`,p0Satisfied:!1};function M(e,t){return Li(e,t)}var na=new Set;function ra(e,t){return`${e}\n${t}`}function ia(e,t){if(!t)return;let n=ra(e,t);na.has(n)||(na.add(n),Xi(A(e,t)).catch(()=>{}).finally(()=>{na.delete(n)}))}function aa(e,t){if(e&&t){na.delete(ra(e,t));return}na.clear()}function oa(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=a?.enabled!==!1,u=(0,y.useCallback)(()=>{if(!e||!l){let e=o.current(ea);return(c.current===void 0||!s.current(c.current,e))&&(c.current=e),c.current}let r=M(t,n).getTranscript(A(t,e)),i=o.current(r);return(c.current===void 0||!s.current(c.current,i))&&(c.current=i),c.current},[t,l,e,n]),d=(0,y.useCallback)(r=>{if(!e||!l)return()=>void 0;ia(t,e);let i=M(t,n).subscribe(A(t,e),()=>{r()}),a=Mi(()=>{i(),c.current=void 0,aa(t,e),ia(t,e),i=M(t,n).subscribe(A(t,e),()=>{r()}),r()});return()=>{a(),i()}},[t,l,e,n]);return y.useSyncExternalStore(d,u,u)}function sa(e,t,n,r,i,a){return oa(e,t,n,r,i===void 0?Object.is:i,a)}function ca(e,t){if(e.messageOrder.length===0)return Qi;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 la(e,t){return e.messageOrder.length===0?t?.resolved===!0?vr({messages:Qi,parts:e.partsByMessageID}):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}:vr({messages:ca(e),parts:e.partsByMessageID})}function ua(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=M(t,n).hasSession?.(A(t,e));return la(r,{resolved:i===!0||void 0})},i[0]=t,i[1]=e,i[2]=n,i[3]=a):a=i[3],oa(e,t,n,a,da,r)}function da(e,t){return e.hasMessages===t.hasMessages&&e.renderable===t.renderable&&e.missingPartMessageIDs.length===t.missingPartMessageIDs.length&&e.missingPartMessageIDs.every((e,n)=>e===t.missingPartMessageIDs[n])}function fa(e,t,n,r){return oa(e,t,n,ma,pa,r)}function pa(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 ma(e){return ca(e)}function ha(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 ga(e,t,n,r){return oa(e,t,n,_a,ha,r)}function _a(e){return e}function va(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=k();if(o){i.push(o.subscribe(A(a.directory,a.sessionID),t));continue}let s=n?.(a.directory);if(!s)continue;let c=Li(a.directory,s);i.push(c.subscribe(A(a.directory,a.sessionID),t))}},s=()=>{a(),o(),t()};o();let c=Mi(s),l=r?.subscribeRebuild?.(s);return()=>{l?.(),c(),a()}}function ya(e,t){return e.length===0?``:e.map(e=>{let n=ja(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 ba(e,t,n){return oa(e,t,n,xa)}function xa(e){return e.messageOrder.length}function Sa(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=M(t,n),a=r.hasSession?.(A(t,e))??r.getTranscript(A(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?M(t,n).subscribe(A(t,e),()=>{r()}):Ca,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 Ca(){}function wa(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=$i,$i;let i=M(t,n),o=r||e,s=i.getParts(A(t,o),e),c=s.length===0?$i: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 Ea;let a=M(t,n);return r?a.subscribe(A(t,r),()=>{i()}):Ta},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 Ta(){}function Ea(){}function Da(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(ta),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current!==ta&&(i.current=ta),i.current;let r=M(t,n).getHydrationState?.(A(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 Oa;ia(t,e);let a=M(t,n).subscribe(A(t,e),()=>{r()}),o=Mi(()=>{a(),i.current=ta,aa(t,e),ia(t,e),a=M(t,n).subscribe(A(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 Oa(){}function ka(e,t,n){let r=(0,Ce.c)(2),i;return r[0]===e?i=r[1]:(i=t=>Gr(e,t.boundary),r[0]=e,r[1]=i),oa(e,t,n,i,Aa)}function Aa(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 ja(e,t,n){if(!t)return[];let r=k();if(r){let n=r.getTranscript(A(e,t));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}if(!n)return[];let i=Li(e,n).getTranscript(A(e,t));return i.messageOrder.map(e=>i.messagesByID[e]).filter(e=>!!e)}var N=null,Ma=``,Na=null,Pa=new Set,Fa=null,Ia=new Map,La=new Map;function Ra(e,t,n,r){N=t,Fa!==t&&(Fa=null,Ia=new Map,La=new Map),Ma=n,r&&(Na=r)}function za(e,t){Na?.(e,t)}function Ba(){if(!N)throw Error(`ChildStoreManager not initialized — is SyncProvider mounted?`);return N}function Va(e){let t=N;if(!t)return;let n=e||Ma;if(n)return t.getState(n)}function Ha(e){let t=Va(e)?.config;return t&&Object.keys(t).length>0?t:void 0}function Ua(e){return Pa.add(e),()=>{Pa.delete(e)}}function Wa(e,t){if(e)for(let n of Pa)n(e,t)}function Ga(e){return Va(e)?.session??[]}function Ka(){return Array.from(qa().values())}function qa(){let e=N;if(!e)return La;let t=Fa!==e||Ia.size!==e.children.size;for(let[n,r]of e.children)if(Ia.get(n)!==r.getState().session){t=!0;break}if(!t)return La;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 Fa=e,Ia=n,La=r,La}function Ja(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=k();if(N){for(let[i,a]of N.children)if(a.getState().session.some(t=>t.id===e)&&(n??Li(i,a)).hasSession?.(A(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 Ya(e,t){if(!e)return[];try{let n=k(),r=t??Ma;if(n){let t=n.getTranscript(A(r,e));return t.messageOrder.map(e=>t.messagesByID[e]).filter(e=>!!e)}if(N){let t=N.getChild(r);if(t){let n=Li(r,t).getTranscript(A(r,e));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}}}catch{}return[]}function Xa(e,t){if(!e)return[];try{let n=k(),r=t??Ma;if(n)return[...n.getParts(A(r,e),e)];if(N){let t=N.getChild(r);if(t)return[...Li(r,t).getParts(A(r,e),e)]}}catch{}return[]}function Za(e,t){return Va(t)?.session_status[e]}var P=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},Qa=`default`;function $a(e){let t=P(e);if(t&&t!==Qa)return t}function eo(e){let t=e?.model;return P(t?.id)??P(t?.modelID)}function to(e){let t=e?.model;return P(t?.providerID)}function no(e){let t=e?.model;return $a(t?.variant)}function ro(e){let t=$a(e.variant);return{id:e.modelID.trim(),providerID:e.providerID.trim(),...t?{variant:t}:{}}}function io(e,t,n){let r=P(n.providerID),i=P(n.modelID);if(!r||!i)return{agent:P(n.agent)};let a=(Va(t)?.session??Ka()).find(t=>t.id===e),o=ro({providerID:r,modelID:i,variant:n.variant}),s=eo(a),c=to(a),l=no(a),u=$a(o.variant),d=!a||!s||!c||c!==o.providerID||s!==o.id||l!==u,f=P(n.agent),p=P(a?.agent);return{model:d?o:void 0,agent:f&&p!==f?f:void 0}}function ao(e,t,n){if(e&&!(!n.model&&!n.agent))try{let r=Ba(),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 oo=new Set([`image/heic`,`image/heif`]),so=!1,co=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},lo=e=>oo.has((e.type||``).toLowerCase()),uo=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)},fo=(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})},po=async e=>{if(!lo(e)||so)return null;let t=co();if(!t||typeof t.isNativePlatform!=`function`||!t.isNativePlatform())return null;let n=t.Plugins?.OpenChamberMedia?.transcode;if(typeof n!=`function`)return null;try{let t=await n({data:await uo(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 fo(t.data,r)}catch(e){return so=!0,console.warn(`Native HEIC transcode failed`,e),null}},mo=e=>e.trim().toLowerCase(),ho=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,go=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(mo)),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=g(e.slice(t+1,a)).trim();n.has(mo(i))&&r.push({start:t,end:a+1})}i=a+1}return r},_o=(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}},vo=(e,t,n,r)=>{let i=go(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}=_o(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}},yo=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),bo={"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`},xo=e=>e.trim().toLowerCase(),So=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),Co=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>So(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},wo=e=>bo[e?.trim().toLowerCase()??``]??`png`,To=e=>{let t=Co(e.name),n=wo(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}},Eo=e=>{let{base:t}=To({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(yo.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&yo.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Do=(e,t)=>`${e}.${t}`,Oo=(e,t,n)=>{let r=Do(e,t);if(!n.has(xo(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=Do(`${e}-${r}`,t);if(!n.has(xo(i)))return i}return Do(`${e}-${Date.now()}`,t)},ko=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=Do(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(xo(r)))return r}return Do(`image-${Date.now()}`,e)},Ao=(e,t)=>{let n=new Set(t.map(xo));return e.map(e=>{let{base:t,ext:r}=To(e),i=Eo(Do(t,r))?ko(r,n):Oo(t,r,n);return n.add(xo(i)),i})},jo=e=>e.map(e=>ie(e)).join(` `),Mo=(e,t,n)=>{if(t===n)return[];let r=[];for(let i of e){let e=[ie(i),`[${i}]`],a=e.some(e=>t.includes(e)),o=e.some(e=>n.includes(e));a&&!o&&r.push(i)}return r},No=(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}},Po=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=No(e,t);if(i){let t=Go(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=Mo(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Fo=e=>e.replaceAll(`[${te}`,`[`),Io=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Lo=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Ro=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Lo(t)||!Io.test(t)&&!Io.test(r))continue;let i=`[${r}]`;n=n.split(ie(t)).join(i).split(`[${t}]`).join(i)}return n},zo=(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(ie(e.filename)).join(r).split(`[${e.filename}]`).join(r)}return n},Bo=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Vo=`application/x-directory`,Ho=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Uo=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Wo=(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}},Go=(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?Wo(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=go(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=>g(e.slice(t.start+1,t.end-1)).trim())}},F=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}},Ko=`file://`,qo=e=>{let t=e.trim();if(t.toLowerCase().startsWith(Ko))return t;let n=me(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${Ko}/${n}`:`${Ko}${n}`},Jo=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(Ko))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},Yo=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),Xo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zo=async e=>{let t;try{t=await e.json()}catch{throw new F(e.status,`unavailable`)}if(!Xo(t)||typeof t.path!=`string`||!t.path)throw new F(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:qo(t.path),mime:n,size:r,sha256:i}},Qo=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}`},$o=(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}},es=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),ts=async e=>{let t=e.mime||e.body.type||`application/octet-stream`,n=e.body.type===t?e.body:new Blob([e.body],{type:t});if(!Number.isSafeInteger(n.size)||n.size<0||n.size>26214400)throw new F(413,`too-large`);let r=await Yo(n),i=Qo(e.filename),a;try{a=await u(`/api/fs/prompt-attachments/${encodeURIComponent(i)}`,{method:`PUT`,headers:{"Content-Type":t,"Content-Length":String(n.size),"X-OpenChamber-Content-Length":String(n.size),"X-OpenChamber-Sha256":r,"X-OpenChamber-Mime":t,...e.filename?{"X-OpenChamber-Filename":encodeURIComponent(e.filename)}:{}},body:n,signal:e.signal})}catch{throw new F(0,`unavailable`)}if(a.status===413)throw new F(413,`too-large`);if(!a.ok)throw new F(a.status,a.status>=500||a.status===0?`unavailable`:`rejected`);let o=await Zo(a);if(o.size!==n.size)throw new F(a.status,`unavailable`);return{...o,mime:t}},ns=500,rs=()=>{if(typeof window>`u`)return!1;try{return new URLSearchParams(window.location.search).get(`startupTrace`)===`1`||window.localStorage?.getItem(`OPENCHAMBER_STARTUP_TRACE`)===`1`}catch{return!1}},is=()=>rs(),I=(e,t)=>{if(!rs())return;let n=typeof performance<`u`?performance.now():Date.now();window.__OPENCHAMBER_STARTUP_TRACE_START__??=n,window.__OPENCHAMBER_STARTUP_TRACE__??=[],window.__OPENCHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__OPENCHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__OPENCHAMBER_STARTUP_TRACE__.length>ns&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-ns)};typeof window<`u`&&(window.__OPENCHAMBER_STARTUP_TRACE_SUMMARY__=()=>{let e=typeof window<`u`?window.__OPENCHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(e=>e.name===`ModelControls:ready`),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(e=>e.name.includes(`checkConnection`)||e.name.includes(`checkHealth`)||e.name.includes(`initializeApp`)||e.name.includes(`initApp`)||e.name.includes(`loadProviders`)||e.name.includes(`loadAgents`)||e.name.includes(`config.defaults`)||e.name.includes(`ModelControls`)||e.name.includes(`activateDirectory`)||e.name.includes(`opencodeClient:setDirectory`))});var as=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();I(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return I(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw I(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},os=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}),ss=[],cs=[],L=new Map,ls=512,us=new Set,ds=(e,t)=>`${e}\0${t}`;function fs(e,t){!e||!t||us.add(ds(e,t))}function ps(e,t){return us.has(ds(e,t))}function ms(e){let t=`${e}\0`,n=[];for(let e of us)e.startsWith(t)&&n.push(e.slice(t.length));return n}function hs(e,t){if(e){if(t){us.delete(ds(e,t));return}for(let t of ms(e))us.delete(ds(e,t))}}var gs=0;function _s(){return gs}function R(){return{transportIdentity:o(),generation:s()}}function vs(e){return o()===e.transportIdentity&&s()===e.generation}function ys(e,t,n){return`${n?.transportIdentity??o()}\0${n?.generation??s()}\0${e}\0${t}`}function bs(e=R()){if(L.size===0)return;let t=`${e.transportIdentity}\0${e.generation}\0`;for(let e of L.keys())e.startsWith(t)||L.delete(e);for(;L.size>ls;){let e=L.keys().next().value;if(e===void 0)break;L.delete(e)}}function xs(e,t,n,r){let i=r??R();bs(i),gs+=1,L.set(ys(e,t,i),{kind:n,mark:gs})}function Ss(e,t,n){let r=n?.scope;bs(r??R());let i=L.get(ys(e,t,r));if(!i)return!0;let a=n?.startedMark;return a!==void 0&&i.mark>a?!1:(L.delete(ys(e,t,r)),!0)}function Cs(e,t,n){return bs(n??R()),L.get(ys(e,t,n))?.kind??null}var ws=(e,t,n)=>{let r={...e};return n.length===0?delete r[t]:r[t]=n,r},z=oe((e,t)=>({bySession:{},remember(t){return!Cs(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,wasQueued:t.delivery===`queue`||n[r]?.wasQueued===!0};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===`consumed`&&ps(t,n)||(r&&xs(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:ws(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)&&!e.wasQueued&&!ps(t,e.id)).map(e=>e.id));if(i.size===0)return e;for(let e of i)xs(t,e,`consumed`);return{bySession:ws(e.bySession,t,n.filter(e=>!i.has(e.id)))}})},replaceFromAuthority(t,n,r){let i=r?.startedMark,a=[];for(let e of n)Ss(t,e.id,{startedMark:i})&&a.push(e);e(e=>{let n=new Map((e.bySession[t]??[]).map(e=>[e.id,e])),r=a.map(e=>({...e,requestID:e.id,wasQueued:e.delivery===`queue`||n.get(e.id)?.wasQueued===!0}));return{bySession:ws(e.bySession,t,r)}})},updateDelivery(t,n,r){e(e=>{if(Cs(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,wasQueued:r===`queue`||i[a].wasQueued},{bySession:{...e.bySession,[t]:o}}})},list(e){return t().bySession[e]??ss}}));function Ts(e){return z.getState().remember(e)}function Es(e,t){return Ss(e.sessionID,e.id,t)?z.getState().remember(e):!1}function Ds(e,t,n){z.getState().forget(e,t,n)}function Os(e,t){z.getState().forgetPromoted(e,t)}function ks(e,t,n){z.getState().replaceFromAuthority(e,t,n)}function As(e,t,n){z.getState().updateDelivery(e,t,n)}function js(e){return!!e&&typeof e==`object`&&e.kind===`session-inbox`}var Ms=e=>e?e.toLowerCase().includes(`application/json`):!1,Ns=e=>e?e.toLowerCase().includes(`text/html`):!1;function B(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function V(e){return typeof e==`string`&&e.length>0?e:void 0}function Ps(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Fs(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function Is(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 Ls(e){return e?{directory:e}:{}}function Rs(e,t){let n=`/api/session/${encodeURIComponent(e)}/inbox`;return t?`${n}/${encodeURIComponent(t)}`:n}async function zs(e,t){let n=e.headers.get(`content-type`);if(Ns(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!Ms(n)&&r==null)throw Error(`${t}: empty response`);return r}function Bs(e){let t=B(e)?e:null,n=t&&B(t.data)?t.data:t;if(!n)throw Error(`session prompt: expected inbox item`);let r=V(n.type);if(r&&r!==`user`)throw Error(`session prompt: expected user inbox item, got ${r}`);let i=V(n.id),a=V(n.sessionID);if(!i||!a)throw Error(`session prompt: inbox item missing id`);let o=B(n.payload)?n.payload:{},s=n.delivery===`queue`?`queue`:`steer`,c=B(n.time)?n.time:null;return{id:i,sessionID:a,timeCreated:Ps(n.timeCreated)??Ps(c?.created)??Date.now(),type:`user`,delivery:s,payload:{text:V(o.text)??V(n.text)??``,...o.files===void 0?{}:{files:o.files},...o.agents===void 0?{}:{agents:o.agents},...o.skills===void 0?{}:{skills:o.skills},...B(o.metadata)?{metadata:o.metadata}:{}}}}function Vs(e){let t=B(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)B(e)&&(e.type&&e.type!==`user`||r.push(Bs(e)));return r}function Hs(e){return{runtimeKey:c(),generation:s(),directory:e,overlay:R()}}function H(e){return c()===e.runtimeKey&&s()===e.generation&&vs(e.overlay)}function Us(e){let t=Error(`${e}: runtime switched`);throw t.name=`RuntimeGenerationMismatchError`,t}async function Ws(e){let t=e.commit??Hs(e.directory);H(t)||Us(`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(H(t)||Us(`session prompt`),!i.ok){let e=await Is(i);Fs(`Failed to send message`,i.status,e)}let a=Bs(await zs(i,`session prompt`));return H(t)||Us(`session prompt`),e.delivery===`queue`&&a.delivery!==`queue`?(Ts({...a,delivery:`queue`}),As(a.sessionID,a.id,`steer`)):Ts(a),a}function Gs(e){let t=e?.status;return typeof t!=`number`||!Number.isFinite(t)||t===408||t===429?!1:t>=400&&t<500}async function Ks(e){let t=e.inputID.trim();if(!t)return{status:`unknown`};let n=e.commit??Hs(e.directory??``);if(!H(n))return{status:`unknown`};try{let r=await Js({sessionID:e.sessionID,directory:n.directory||e.directory,signal:e.signal});if(!H(n)||!r.current)return{status:`unknown`};let i=r.items.find(e=>e.id===t);if(i)return Es(i,{startedMark:r.startedMark})?{status:`pending`,item:i}:{status:`unknown`}}catch{}if(!H(n))return{status:`unknown`};try{let r=await Qe({sessionID:e.sessionID,directory:n.directory||e.directory||``,limit:40,...e.signal?{signal:e.signal}:{}});if(!H(n))return{status:`unknown`};if(r.records.some(e=>e?.info?.id===t))return Ds(e.sessionID,t,`consumed`),{status:`promoted`,id:t}}catch{}return{status:`unknown`}}function qs(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=V(n.sessionID),i=V(n.inboxID)??V(n.id);if(!r||!i)return!1;if(t===`session.inbox.enqueued`){let e=n.item,t=B(e)?V(e.type):void 0;if(t&&t!==`user`)return!1;try{return Es(Bs(B(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 Ds(r,i,`cancelled`),!0;if(t===`session.inbox.delivered`)return Ds(r,i,`consumed`),!0;if(t===`session.inbox.delivery.changed`){let e=n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:null;return e?(As(r,i,e),!0):!1}return!1}async function Js(e){let t=R(),n=_s(),r=await u(Rs(e.sessionID),{method:`GET`,query:Ls(e.directory),signal:e.signal});r.ok||Fs(`session inbox`,r.status,await Is(r));let i=await zs(r,`session inbox`),a=Vs(i),o=vs(t);return o&&ht(e.sessionID,mt(i)),{items:a,startedMark:n,scope:t,current:o}}async function Ys(e){let t=R(),n=await u(Rs(e.sessionID,e.inboxID),{method:`PATCH`,headers:{"Content-Type":`application/json`},query:Ls(e.directory),body:JSON.stringify({delivery:e.delivery}),signal:e.signal});n.ok||Fs(e.delivery===`steer`?`session inbox steer`:`session inbox queue`,n.status,await Is(n)),vs(t)&&(Cs(e.sessionID,e.inboxID)||As(e.sessionID,e.inboxID,e.delivery))}async function Xs(e){await Ys({...e,delivery:`steer`})}async function Zs(e){await Ys({...e,delivery:`queue`})}async function Qs(e){let t=await u(Rs(e.sessionID,e.inboxID),{method:`DELETE`,query:Ls(e.directory),signal:e.signal});t.ok||Fs(`session inbox cancel`,t.status,await Is(t))}function $s(e,t,n){ks(e,t,n)}async function ec(e){let t=R();if(await Qs(e),!vs(t))return{overlay:z.getState().list(e.sessionID),transcriptRows:[]};Ds(e.sessionID,e.inboxID,`cancelled`);try{let n=await Js({sessionID:e.sessionID,directory:e.directory,signal:e.signal});if(!vs(t)||!n.current)return{overlay:z.getState().list(e.sessionID),transcriptRows:[]};$s(e.sessionID,n.items,{startedMark:n.startedMark})}catch{}return{overlay:z.getState().list(e.sessionID),transcriptRows:[]}}async function tc(e){let t=`/api/session/${encodeURIComponent(e.sessionID)}/interrupt`,n={};e.directory&&(n.directory=e.directory);let r=await u(t,{method:`POST`,query:n,signal:e.signal});if(!r.ok)throw Error(`Session interrupt failed (${r.status})`)}async function nc(e){return e.promotedIDs.includes(e.optimisticID)?`confirmed`:(e.removeOptimistic(e.optimisticID),await e.refreshFromAuthority(),`refreshed`)}var rc=`session-revert-busy`,ic=e=>e?e.toLowerCase().includes(`text/html`):!1;function ac(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function U(e){return typeof e==`string`&&e.length>0?e:void 0}function oc(e,t,n){if(t===409)throw sc();let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}function sc(){let e=Error(rc);return e.name=`SessionRevertBusyError`,e}function cc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`SessionRevertBusyError`||t.message===`session-revert-busy`}async function lc(e){try{return(await e.text()).trim()}catch{return``}}async function uc(e,t){if(ic(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 dc(e){return e?{directory:e}:{}}function fc(e,t){return`/api/session/${encodeURIComponent(e)}/revert/${t}`}function pc(e){let t=ac(e)?e:null,n=t&&ac(t.data)?t.data:t;if(!n)throw Error(`session revert: expected revert payload`);let r=U(n.messageID);if(!r)throw Error(`session revert: missing messageID`);let i=Array.isArray(n.files)?n.files.flatMap(e=>{if(!ac(e))throw Error(`session revert: invalid file diff`);let t=U(e.file)??U(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,...U(n.partID)?{partID:U(n.partID)}:{},...U(n.snapshot)?{snapshot:U(n.snapshot)}:{},...i?{files:i}:{}}}function mc(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 hc(e){let t=await u(fc(e.sessionID,`stage`),{method:`POST`,headers:{"Content-Type":`application/json`},query:dc(e.directory),body:JSON.stringify({messageID:e.messageID,files:e.files!==!1}),signal:e.signal});return t.ok||oc(`session revert stage`,t.status,await lc(t)),pc(await uc(t,`session revert stage`))}async function gc(e){let t=await u(`/api/session/${encodeURIComponent(e.sessionID)}/revert`,{method:`DELETE`,query:dc(e.directory),signal:e.signal});t.ok||oc(`session revert clear`,t.status,await lc(t))}async function _c(e){let t=await u(fc(e.sessionID,`commit`),{method:`POST`,query:dc(e.directory),signal:e.signal});t.ok||oc(`session revert commit`,t.status,await lc(t))}var vc=e=>e?e.toLowerCase().includes(`text/html`):!1;function yc(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function bc(e){try{return(await e.text()).trim()}catch{return``}}function xc(e){return e?{directory:e}:{}}function Sc(e,t){return`/api/session/${encodeURIComponent(e)}/permission/${encodeURIComponent(t)}/reply`}async function Cc(e){let t=await u(Sc(e.sessionID,e.requestID),{method:`POST`,headers:{"Content-Type":`application/json`},query:xc(e.directory),body:JSON.stringify({decision:e.reply,...e.message?{message:e.message}:{}}),signal:e.signal});if(t.ok||yc(`session permission reply`,t.status,await bc(t)),t.status!==204&&vc(t.headers.get(`content-type`)))throw Error(`session permission reply: unexpected HTML response`)}function wc(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function Tc(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 Ec(e){return{id:e.id,worktree:e.canonical,canonical:e.canonical,sandboxes:e.sandboxes,name:e.name}}function Dc(e){return e.worktree||e.canonical||``}function Oc(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 kc(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 Ac(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.kind===`question`}function jc(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 Mc(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 Nc(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}:{}})):Mc(e),n=jc(e);return{id:e.id,sessionID:e.sessionID,questions:t,...n?{tool:n}:{}}}function Pc(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 Fc=3,Ic=3e4,Lc=32e3,Rc=36e5,zc=6e5,Bc=new Set([429,502,503,504]),Vc=new Map;function Hc(){let e=Date.now();for(let[t,n]of Vc)n.consecutiveErrors===0&&e-n.lastErrorAt>Rc&&Vc.delete(t)}typeof setInterval<`u`&&setInterval(Hc,zc).unref?.();function Uc(e){let t=Vc.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:Ic},Vc.set(e,t)),t}function Wc(e){if(!e)return;let t=Vc.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function Gc(e,t){if(!e)return;let n=Uc(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),Kc(t)&&n.consecutiveErrors>=Fc&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function Kc(e){return e!==void 0&&Bc.has(e)}function qc(e){let t=Vc.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Lc*4),!1):!0:!1}function Jc(e){if(!(!e||!qc(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var Yc=`/api`,Xc=1e4,Zc=4e3,Qc=3e3,$c=1e3,el=12e3;function W(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 tl(e){if(e instanceof ue&&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 nl(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 rl(e){let t=e.replace(/\/+$/,``);if(t.endsWith(`/api`)){let e=t.slice(0,-4);if(e.length>0)return e}return ol(cl()||`/`)}function il(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 al=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ol=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if(al.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}},sl=()=>{try{return a().api(`/api`)}catch{return null}},cl=()=>{try{return a().api(`/`)}catch{return null}},ll=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)}},ul=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)}}},dl=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}}},fl=e=>dl(de.make({baseUrl:e.baseUrl,...e.headers?{headers:e.headers}:{},fetch:u})),pl=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),ml=e=>{let t=[];for(let n of e){if(!pl(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=Jo(r).trim();i&&t.push({filename:e,path:i})}return t},hl=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=>Ro(e,ml([...r,...i.flatMap(e=>e.files)]));if(e.prefaceText&&e.prefaceText.trim()&&n.push({type:`text`,text:a(e.prefaceText),synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()&&n.push({type:`text`,text:a(e.text)}),n.push(...r),i.length>0)for(let e of i){if(e.text&&e.text.trim()){let t={type:`text`,text:a(e.text)};e.synthetic&&(t.synthetic=!0),n.push(t)}n.push(...e.files)}if(e.agentMentions&&e.agentMentions.length>0)for(let t of e.agentMentions){if(!t?.name)continue;let e={type:`agent`,name:t.name};t.source&&(e.source=t.source),n.push(e)}if(n.length===0)throw Error(`Message must have at least one part (text or file)`);return n},gl=e=>e.replace(/\\/g,`/`),_l=400,vl=()=>{let e=d();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;sessionBoundaryQueues=new Map;constructor(e=Yc){let t=sl()||e;this.baseUrl=ol(t),this.client=fl({baseUrl:rl(this.baseUrl)})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){let e=ol(sl()||Yc);e!==this.baseUrl&&(this.baseUrl=e,this.client=fl({baseUrl:rl(this.baseUrl)}),this.scopedClients.clear(),this.listDirectoryInFlight.clear(),this.configProvidersInFlight.clear(),this.listAgentsInFlight.clear(),this.clearConfigCache(),this.listDirectoryCache.clear(),this.clearHealthCache())}getSdkClient(){return this.client}getScopedSdkClient(e){return this.getScopedApiClient(e)}getScopedApiClient(e){let t=(this.normalizeCandidatePath(e)??e)||``,n=this.scopedClients.get(t);if(n)return n;let r=fl({baseUrl:rl(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&&I(`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`),ao(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`),ao(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(f(`lastDirectory`)),t(f(`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();if(!t)return[];let n=await this.client.session.list({search:t,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=W(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(`${this.baseUrl}/openchamber/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(`${this.baseUrl}/openchamber/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 Qe({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(`${this.baseUrl}/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=$o(t.url,t.mime);if(!n)return t;let r=await po(n)??await(await he(async()=>{let{default:t}=await import(`./vendor-heic2any-CUPf3g2A.js`).then(t=>e(t.t(),1));return{default:t}},__vite__mapDeps([0,1]))).default({blob:n,toType:`image/jpeg`,quality:.9}),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)}),a=t.filename;return a&&=a.replace(/\.heic$/i,`.jpg`).replace(/\.heif$/i,`.jpg`),{mime:`image/jpeg`,filename:a,url:i}}catch(e){return console.warn(`Failed to convert HEIC to JPEG:`,e),t}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let t=e.url;if(e.url.startsWith(`data:`)){let n=e.url.indexOf(`,`);if(n!==-1){let r=e.url.substring(5,n),i=e.url.substring(n);t=`data:${r.replace(/^[^;,]+/,`text/plain`)}${i}`}}return{mime:`text/plain`,filename:e.filename,url:t}}async toNormalizedFilePartInput(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c(),i=await this.normalizeFilePart(e);this.assertCapturedRuntime(n,r,`prompt attachment normalize`);let a=i.url;if(es(a)){let e=$o(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 ts({body:e,mime:i.mime,filename:i.filename});this.assertCapturedRuntime(n,r,`prompt attachment upload`),a=t.url}return{...e.id?{id:e.id}:{},type:`file`,mime:i.mime,filename:i.filename,url:a}}async buildMessageParts(e,t){let n=t?.generation??s(),r=t?.runtimeKey??c();return hl(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??h(`msg`),a=this.normalizeCandidatePath(e.directory??null)??this.currentDirectory,o=Hs(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(),H(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),Jc(e.providerID);let u=l.flatMap(e=>e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(`
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(`
6
- `));try{return await this.runSessionBoundary(e.id,async()=>{r();let t=e.delivery===`queue`?`queue`:`steer`;t!==`queue`&&(await this.applySendSelection(e.id,{model:e.switchModel,agent:e.switchAgent},a),r());let n={sessionID:e.id,directory:o.directory,messageID:i,text:u,delivery:t,commit:o,...d.length>0?{files:d}:{},...f.length>0?{agents:f}:{},...p.length>0?{skills:p}:{},...e.agent||e.variant||e.format||e.providerID?{metadata:{...e.agent?{agent:e.agent}:{},...e.variant?{variant:e.variant}:{},model:{providerID:e.providerID,modelID:e.modelID},...e.format?{format:e.format}:{}}}:{}},s=async()=>{r();let e=await Ws(n);return r(),e.id};try{let t=await s();return Wc(e.providerID),t}catch(t){if(r(),Gs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await Ks({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Wc(e.providerID),i;try{let t=await s();return Wc(e.providerID),t}catch(t){if(r(),Gs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await Ks({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Wc(e.providerID),i;throw t}}})}catch(t){throw Gc(e.providerID,t.status),t}}async sendCommand(e){let t=e.messageId??h(`msg`),n=[];if(e.files&&e.files.length>0)for(let t of e.files){let e=await this.toNormalizedFilePartInput(t);n.push({uri:e.url,...e.filename?{name:e.filename}:{}})}return e.directory,e.providerID,e.modelID,e.agent,e.variant,await this.client.session.command({sessionID:e.id,name:e.command,text:e.arguments??``,...n.length>0?{files:n}:{}}),t}async abortSession(e){return await tc({sessionID:e,directory:this.currentDirectory}),!0}async shellSession(e){return e.directory,await this.client.session.shell({sessionID:e.sessionId,command:e.command,...e.messageId?{id:e.messageId}:{}}),{info:{id:e.messageId??``,sessionID:e.sessionId,role:`assistant`,time:{created:Date.now()},clientRole:`shell`,agent:e.agent,modelID:e.model.modelID,providerID:e.model.providerID},parts:[]}}async revertSession(e,t,n,r){let i=await hc({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory,messageID:t,files:!0});return{id:e,time:{created:0,updated:Date.now()},revert:i}}async summarizeSession(e,t,n,r){return await _t({sessionID:e,directory:this.normalizeCandidatePath(r)??this.currentDirectory??``}),!0}async unrevertSession(e,t){return await gc({sessionID:e,directory:this.normalizeCandidatePath(t)??this.currentDirectory}),{id:e,time:{created:0,updated:Date.now()}}}async forkSession(e,t,n){this.normalizeCandidatePath(n)??this.currentDirectory;let r=await this.client.session.fork({sessionID:e,...t?{before:t}:{}});return r.id,v(r)}async getSessionStatus(){return await this.getSessionStatusForDirectory(this.currentDirectory??null)??{}}async getSessionStatusForDirectory(e,t){return null}async getSessionActive(e){try{let t=await this.client.session.active(e?{signal:e}:void 0),n=t&&typeof t==`object`&&`data`in t&&t.data!==void 0?t.data:t;if(!n||typeof n!=`object`||Array.isArray(n))return{state:`unknown`};let r={};for(let[e,t]of Object.entries(n)){if(typeof e!=`string`||e.length===0||!t||typeof t!=`object`||t.type!==`running`)return{state:`unknown`};r[e]={type:`running`}}return{state:`supported`,membership:r}}catch(e){return nl(tl(e))?{state:`unsupported`}:{state:`unknown`}}}async getGlobalSessionStatus(){return await this.getSessionStatusForDirectory(null)??{}}async getWebServerSessionActivity(){try{let e=await u(`/api/session-activity`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json().catch(()=>null);return!t||typeof t!=`object`?null:t}catch{return null}}async listToolIds(e){throw G(`tool.ids`)}async replyToPermission(e,t,n){let r=this.normalizeCandidatePath(n?.directory??null)??this.currentDirectory;if(!n?.sessionID)throw G(`permission.reply (sessionID required)`);return await Cc({sessionID:n.sessionID,requestID:e,reply:t,...n.message?{message:n.message}:{},directory:r}),!0}async createPermission(e,t,n,r){try{let i=await this.client.permission.create({sessionID:e,action:t,resources:n,...r?.id?{id:r.id}:{},...r?.save?{save:r.save}:{},...r?.metadata?{metadata:r.metadata}:{},...r?.source?{source:r.source}:{},...r?.agent?{agent:r.agent}:{}});return!i||typeof i.id!=`string`?null:{id:i.id,effect:i.effect}}catch{return null}}async fetchPermission(e,t){try{let n=await this.client.permission.get({sessionID:e,requestID:t});return n===void 0?{state:`unknown`}:{state:`ok`,permission:n}}catch(e){return le(e)||tl(e)===404?{state:`resolved`}:{state:`unknown`}}}async listPendingPermissions(e){let t=[],n=async e=>{let t=await this.client.permission.request.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`permission.list failed: ${W(t)}`);return t.data.flatMap(e=>{let t=il(e);return t?[t]:[]})};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}async replyToQuestion(e,t,n,r){let i=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];if(!r)throw G(`session.form.reply (sessionID required)`);let a=this.client,o=await a.session.form.get({sessionID:r,formID:e});return await a.session.form.reply({sessionID:r,formID:e,answer:Pc(i,o.fields)}),!0}async rejectQuestion(e,t){if(!t)throw G(`session.form.cancel (sessionID required)`);return await this.client.session.form.cancel({sessionID:t,formID:e}),!0}async listPendingQuestions(e){let t=[],n=async e=>{let t=await this.client.form.list(K(e));if(!t||!Array.isArray(t.data))throw Error(`form.list failed: ${W(t)}`);return t.data.flatMap(e=>Ac(e.metadata)?[Nc({id:e.id,sessionID:e.sessionID,title:e.title,fields:e.fields,...e.metadata?{metadata:e.metadata}:{}})]:[])};t.push(n(null));let r=new Set;for(let t of e?.directories??[]){let e=this.normalizeCandidatePath(t??null);e&&r.add(e)}for(let e of r)t.push(n(e));let i=await Promise.all(t),a=[],o=new Set;for(let e of i)for(let t of e){if(!t||typeof t!=`object`)continue;let e=t.id;typeof e==`string`&&e.length!==0&&(o.has(e)||(o.add(e),a.push(t)))}return a}clearConfigCache(){this.configCacheGeneration+=1,this.configInFlight.clear(),this.configCache.clear()}clearHealthCache(){this.healthCacheGeneration+=1,this.healthInFlight.clear(),this.healthCache.clear()}async getConfig(e){let t=this.normalizeCandidatePath(e)??e??this.currentDirectory??void 0,n=t??``,r=this.configCache.get(n);if(r&&r.expiresAt>Date.now())return I(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return I(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{I(`opencodeClient.getConfig:start`,{directory:t??null});let e=typeof performance<`u`?performance.now():Date.now(),r=await this.client.config.get(K(t));if(!Array.isArray(r))throw Error(`Failed to get config`);let i=Se(r),o=typeof performance<`u`?performance.now():Date.now();return I(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(o-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:i,expiresAt:Date.now()+Xc}),i})();this.configInFlight.set(n,o);try{return await o}finally{this.configInFlight.get(n)===o&&this.configInFlight.delete(n)}}async updateConfig(e){throw G(`config.update`)}async updateConfigPartial(e){let t=e(await this.getConfig());return await this.updateConfig(t)}async getProviders(){return this.getProvidersForConfig(this.currentDirectory)}async getProvidersForConfig(e){let t=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,n=t??``,r=this.configProvidersInFlight.get(n);if(r)return r;let i=(async()=>{let e=await this.client.provider.list(K(t));if(!e||!Array.isArray(e.data))throw Error(`config.providers failed: ${W(e)}`);let n={};try{let e=await this.client.model.default(K(t));e?.data&&(n[e.data.providerID]=e.data.modelID)}catch{}return{providers:e.data,default:n}})();this.configProvidersInFlight.set(n,i);try{return await i}finally{this.configProvidersInFlight.delete(n)}}async getApp(){return{version:`0.0.3`,config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(e,t){let n=e===void 0?this.currentDirectory??void 0:this.normalizeCandidatePath(e)??void 0,r=n??``;if(!t){let e=this.listAgentsInFlight.get(r);if(e)return e}let i=(async()=>{let e=ll(el),r=ul(t?[t,e.signal]:[e.signal]);try{let e=K(n),t=await this.client.agent.list(e,{signal:r.signal});if(!t||!Array.isArray(t.data))throw Error(`app.agents failed: ${W(t)}`);return t.data.map(e=>_e(e))}finally{e.cleanup(),r.cleanup()}})();if(t)return i;this.listAgentsInFlight.set(r,i);try{return await i}finally{this.listAgentsInFlight.delete(r)}}async readFile(e){try{let t=await this.client.file.read({path:e,...K(this.currentDirectory)});return new TextDecoder().decode(t)}catch{return`// Content of ${e}\n// This would be loaded from the server`}}async listFiles(e){try{let t=e||this.currentDirectory||`/`,n=(await this.client.file.list({path:t,...K(this.currentDirectory)})).data;return Array.isArray(n)?n:[]}catch{return[]}}async listCommands(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${W(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0}))}async listCommandsWithDetails(){let e=await this.client.command.list(K(this.currentDirectory)),t=e.data;if(!Array.isArray(t))throw Error(`command.list failed: ${W(e)}`);return t.map(e=>({name:e.name,description:e.description,agent:void 0,model:void 0,source:void 0,template:``}))}async listSkillsWithDetails(){try{let e=(await this.client.skill.list(K(this.currentDirectory))).data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n.id==`string`?n.id:``,r=typeof n.path==`string`?n.path:``;if(!e||!r)continue;let i={name:e,location:r};typeof n.description==`string`&&(i.description=n.description),typeof n.content==`string`&&(i.content=n.content),t.push(i)}return t}catch{return[]}}async getCommandDetails(e){try{let t=await this.client.command.list(K(this.currentDirectory));if(t.data){let n=t.data.find(t=>t.name===e);if(n)return{name:n.name,template:``,description:n.description,agent:void 0,model:void 0}}return null}catch{return null}}async checkHealth(){let e=c(),t=this.healthCache.get(e);if(t&&t.expiresAt>Date.now())return t.healthy;let n=this.healthInFlight.get(e);if(n)return n;let r=this.healthCacheGeneration,i=(async()=>{let t=!1;try{let e=this.baseUrl.endsWith(`/`)?this.baseUrl.replace(/\/+$/,``):this.baseUrl,n=e===`/api`||e.endsWith(`/api`)?`/api/opencode/health`:`${e}/opencode/health`;I(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:n});let r=ll(Zc),i=await u(n,{signal:r.signal}).finally(r.cleanup);if(I(`opencodeClient.checkHealth:response`,{status:i.status}),i.ok){let e=await i.json();I(`opencodeClient.checkHealth:result`,{healthy:e?.healthy}),t=e?.healthy===!0}}catch{t=!1}return r!==this.healthCacheGeneration||e!==c()?!1:(this.healthCache.set(e,{healthy:t,expiresAt:Date.now()+(t?Qc:$c)}),t)})();this.healthInFlight.set(e,i);try{return await i}finally{this.healthInFlight.get(e)===i&&this.healthInFlight.delete(e)}}async createDirectory(e,t){let n=vl();if(n?.createDirectory)try{return await n.createDirectory(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(t||`Failed to create directory`)}let r={path:e,...t?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},i=await u(`${this.baseUrl}/fs/mkdir`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to create directory`}));throw Error(e.error||`Failed to create directory`)}return await i.json()}async cloneRepository(e){let t=await u(`${this.baseUrl}/fs/clone`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to clone repository`}));throw Error(e.error||`Failed to clone repository`)}return await t.json()}async listLocalDirectory(e,t){let n=`${typeof e==`string`?gl(e.trim()):``}|${t?.respectGitignore?`1`:`0`}`,r=Date.now(),i=this.listDirectoryCache.get(n);if(i&&i.expiresAt>r)return i.entries;let a=this.listDirectoryInFlight.get(n);if(a)return a;let o=(async()=>{let r=vl();if(r)try{let i=await r.listDirectory(e||``,t);if(!i||!Array.isArray(i.entries))return[];let a=i.entries.map(e=>({name:e.name,path:gl(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+_l}),a}catch(e){throw console.error(`Failed to list directory contents:`,e),e}try{let r=new URLSearchParams;e&&e.trim().length>0&&r.set(`path`,e),t?.respectGitignore&&r.set(`respectGitignore`,`true`);let i=r.toString(),a=await u(`${this.baseUrl}/fs/list${i?`?${i}`:``}`);if(!a.ok){let e=await a.json().catch(()=>({})),t=typeof e.error==`string`?e.error:`Failed to list directory`;throw Error(t)}let o=await a.json();if(!o||!Array.isArray(o.entries))return[];let s=o.entries;return this.listDirectoryCache.set(n,{entries:s,expiresAt:Date.now()+_l}),s}catch(e){throw console.error(`Failed to list directory contents:`,e),e}})().finally(()=>{this.listDirectoryInFlight.get(n)===o&&this.listDirectoryInFlight.delete(n)});return this.listDirectoryInFlight.set(n,o),o}async searchFiles(e,t){let n=typeof t?.directory==`string`&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,r=n?gl(n):null;try{let i=await this.client.file.find({query:e,...K(n),limit:typeof t?.limit==`number`&&Number.isFinite(t.limit)?t.limit:void 0,type:t?.type});return(Array.isArray(i?.data)?i.data:[]).map(e=>{let t=gl(e.path),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:gl(r?`${r}/${t}`:t),relativePath:t,extension:n.includes(`.`)?n.split(`.`).pop()?.toLowerCase():void 0,isDirectory:e.type===`directory`}})}catch(e){throw console.error(`Failed to search files:`,e),e}}async getFilesystemHome(){let e=c();if(!e||e===`local`){let e=await m();if(e)return e}try{let e=await u(`${this.baseUrl}/fs/home`,{method:`GET`,headers:{Accept:`application/json`}});if(!e.ok){let t=await e.json().catch(()=>({})),n=typeof t.error==`string`&&t.error.length>0?t.error:`Failed to resolve home directory`;throw Error(n)}let t=await e.json();return t&&typeof t.home==`string`&&t.home.length>0?t.home:null}catch(e){return console.warn(`Failed to resolve filesystem home directory:`,e),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!=`string`||!e.trim())return console.warn(`[OpencodeClient] setOpenCodeWorkingDirectory: invalid path`,e),null;let t=`${this.baseUrl}/opencode/directory`;try{let n=await u(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})}),r=await n.json().catch(()=>null);if(!n.ok){let e=r??{},t=typeof e.error==`string`&&e.error.length>0?e.error:`Failed to update OpenCode working directory`;throw Error(t)}return r&&typeof r==`object`?r:{success:!0,restarted:!1,path:e}}catch(e){throw console.warn(`Failed to update OpenCode working directory:`,e),e}}},yl=3e4,bl=40,xl=60,Sl=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},Cl=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},wl=oe()(se((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=xl,a){if(!n||n.trim().length===0)return[];let o=n.trim(),s=typeof r==`string`?r.trim():``,c=!!a?.includeHidden,l=a?.respectGitignore??!0,u=a?.type===`directory`?`directory`:`file`,d=Sl(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<yl)return p.files;let m=t().inFlight[d];if(m)return m;let h=q.searchFiles(s,{directory:o,limit:i,includeHidden:c,respectGitignore:l,dirs:u!==`file`,type:u}).then(t=>(e(e=>{if(e.inFlight[d]!==h)return e;let n={...e.cache,[d]:{files:t,timestamp:Date.now()}},r=e.cacheKeys.filter(e=>e!==d);for(r.push(d);r.length>bl;){let e=r.shift();e&&delete n[e]}return{cache:n,cacheKeys:r}}),t)).finally(()=>{e(e=>{if(e.inFlight[d]!==h)return e;let t={...e.inFlight};return delete t[d],{inFlight:t}})});return e(e=>({inFlight:{...e.inFlight,[d]:h}})),h},invalidateDirectory(t){if(!t||t.trim().length===0){e({cache:{},cacheKeys:[],inFlight:{}});return}let n=t.trim();e(e=>{let t={...e.cache},r=e.cacheKeys.filter(e=>!Cl(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!Cl(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),Tl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`openchamber_stream_debug`)===`1`}catch{return!1}},El=`openchamber_stream_perf`,Dl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(El)===`1`}catch{return!1}},Ol=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),kl=()=>{if(!Dl()||typeof window>`u`)return null;if(!window.__openchamberStreamPerfState){let e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},Al=e=>Array.from(e.entries()).map(([e,t])=>({metric:e,count:t.count,avg:t.count>0?Number((t.total/t.count).toFixed(3)):0,max:Number(t.max.toFixed(3)),total:Number(t.total.toFixed(3)),last:Number(t.last.toFixed(3))})).sort((e,t)=>t.total-e.total||t.count-e.count),jl=(e,t)=>{let n=kl();if(!n)return;let r=n.counters.get(e)??{count:0,total:0,max:0,last:0};r.count+=1,r.total+=t,r.max=Math.max(r.max,t),r.last=t,n.counters.set(e,r),n.lastUpdatedAt=Date.now()},Ml=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(El,`1`),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(El),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Nl=()=>{typeof window>`u`||(Dl()&&(window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}),window.__openchamberVsCodeStreamPerfState&&(window.__openchamberVsCodeStreamPerfState={...window.__openchamberVsCodeStreamPerfState,counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()}))},Pl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberStreamPerfState;return!Dl()||!e?{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]}:{enabled:!0,startedAt:e.startedAt,lastUpdatedAt:e.lastUpdatedAt,durationMs:Math.max(0,Date.now()-e.startedAt),entries:Al(e.counters)}},Fl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberVsCodeStreamPerfState;if(!Dl()||!e)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let t=typeof e.startedAt==`number`?e.startedAt:null;return{enabled:!0,startedAt:t,lastUpdatedAt:typeof e.lastUpdatedAt==`number`?e.lastUpdatedAt:null,durationMs:t?Math.max(0,Date.now()-t):0,entries:Al(e.counters)}},Il=(e,t=1)=>{jl(e,t)},Ll=(e,t)=>{jl(e,t)},Rl=(e,t)=>{if(!Dl())return t();let n=Ol();try{return t()}finally{jl(e,Ol()-n)}},J=null,zl=0,Y=fe(),Bl=f(`lastDirectory`,{storage:Y}),Vl=typeof Bl==`string`&&Bl.length>0,Hl=e=>{try{wl.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},Ul=e=>{let t=e.trim();if(!t)return t;let n=t.replace(/\\/g,`/`).replace(/^([a-z]):/,(e,t)=>t.toUpperCase()+`:`);return n.length>1?n.replace(/\/+$/,``):n},Wl=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},Gl=(e,t)=>Ul(Wl(e,t)),Kl=()=>{let e=f(`homeDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=Ul(e);return t.length>0?t:null},ql=()=>{let e=f(`lastDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=Ul(e);return t.length>0?t:null},Jl=()=>{if(typeof process>`u`)return null;let e={},t=e?.HOME||e?.USERPROFILE||(e?.HOMEDRIVE&&e?.HOMEPATH?`${e.HOMEDRIVE}${e.HOMEPATH}`:void 0);if(typeof t==`string`&&t.trim().length>0){let e=Ul(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=Ul(n);return e.length>0?e:null}return null},Yl=()=>{if(typeof window<`u`){if(J)return J;let e=typeof window.__OPENCHAMBER_HOME__==`string`&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return J=e,ae(`homeDirectory`,e,{storage:Y}),e;let t=Kl();if(t&&!ee())return J=t,t}return Jl()||`/`},Xl=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);if(n.length>1){let e=n.replace(/\/+$/,``);if(e&&e.length>0)return e===`/`?null:e}return n===`/`||n.length===0?null:n},Zl=e=>(J=e,typeof window<`u`&&ae(`homeDirectory`,e,{storage:Y}),ne({homeDirectory:e}),e),Ql=async()=>{let e=e=>{let t=Xl(e);return t?Zl(t):null};try{let t=e(await q.getFilesystemHome());if(t)return t}catch(e){console.warn(`Failed to obtain filesystem home directory:`,e)}try{let t=e((await q.getSystemInfo())?.homeDirectory);if(t)return t}catch(e){console.warn(`Failed to get home directory from system info:`,e)}try{let t=e(await m());if(t)return t}catch(e){console.warn(`Failed to obtain desktop-integrated home directory:`,e)}let t=Yl();return e(t)||t},$l=(()=>{if(!ee())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=Ul(e);return t.length>0?t:null})()||Yl(),eu=(()=>{let e=ql();return e&&!ee()?Gl(e,$l):$l})();eu&&q.setDirectory(eu);var tu=!!($l&&$l!==`/`),nu=oe()(se((e,t)=>({currentDirectory:eu,directoryHistory:[eu],historyIndex:0,homeDirectory:$l,hasPersistedDirectory:Vl,isHomeReady:tu,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=Gl(n,J||t().homeDirectory||f(`homeDirectory`,{storage:Y}));Tl(),ge(t().currentDirectory,i)&&(q.setDirectory(i),Hl(),e(e=>{let t=[...e.directoryHistory.slice(0,e.historyIndex+1),i];return ae(`lastDirectory`,i,{storage:Y}),ne({lastDirectory:i}),{currentDirectory:i,directoryHistory:t,historyIndex:t.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}}))},goBack:()=>{let n=t();if(n.historyIndex>0){let t=n.historyIndex-1,r=n.directoryHistory[t];q.setDirectory(r),Hl(),ae(`lastDirectory`,r,{storage:Y}),ne({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{let n=t();if(n.historyIndex<n.directoryHistory.length-1){let t=n.historyIndex+1,r=n.directoryHistory[t];q.setDirectory(r),Hl(),ae(`lastDirectory`,r,{storage:Y}),ne({lastDirectory:r}),e({currentDirectory:r,historyIndex:t,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{let{currentDirectory:e,setDirectory:n}=t();if(e===(J||t().homeDirectory||Yl())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?J||Yl():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=J||t().homeDirectory||await Ql();t().setDirectory(e)},synchronizeHomeDirectory:n=>{let r=t(),i=n;J=i;let a=r.homeDirectory!==i,o=f(`lastDirectory`,{storage:Y}),s=typeof o==`string`&&o.length>0,c=!s&&(r.currentDirectory===`/`||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||e({isHomeReady:!0});return}let l=typeof i==`string`&&i!==``&&i!==`/`,u=r.currentDirectory?Gl(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>Gl(e,i)),p=d.some((e,t)=>e!==r.directoryHistory[t]),m=!!(u&&u!==r.currentDirectory),h={homeDirectory:i,hasPersistedDirectory:s,isHomeReady:l};if(c?(h.currentDirectory=i,h.directoryHistory=[i],h.historyIndex=0,h.isSwitchingDirectory=!1):(m||p)&&(h.currentDirectory=u,h.directoryHistory=d,h.historyIndex=Math.min(r.historyIndex,d.length-1),h.isSwitchingDirectory=!1),e(()=>h),(c||m)&&l){let e=c?i:u;q.setDirectory(e),Hl(),ae(`lastDirectory`,e,{storage:Y}),ne({lastDirectory:e})}ne({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(Ql().then(e=>{nu.getState().synchronizeHomeDirectory(e)}),i(e=>{J=null;let t=++zl;if(l(e)){let e=Kl(),t=ql(),n=e||`/`,r=t||n;J=e,nu.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(q.setDirectory(r),Hl())}Ql().then(e=>{t===zl&&nu.getState().synchronizeHomeDirectory(e)})}));var ru=(e,i)=>{let a=t();return a?a.openWebSocket(r(e),i):n(i?new WebSocket(e,i):new WebSocket(e))},X=`/api/git`,iu=1200,au=5e3,ou=2,su=5e3,cu=`${X}/worktrees/queue-activation`,lu=`message_queue_activation_pending`,uu=`worktree_lifecycle_busy`,du=`worktree_activation_stale`,fu=5e3,pu=3e4,mu=[0,500,1e3,2e3,4e3,8e3,14e3],hu=new Map,gu=new Map,_u=new Map,vu=new Map,yu=new Map,bu=new Map,xu=new Map,Su=new Map,Cu=new Map,wu=new Map,Tu=new Set,Eu=0,Du=[],Ou=()=>Eu<ou?(Eu+=1,Promise.resolve()):new Promise(e=>{Du.push(e)}),ku=()=>{let e=Du.shift();if(e){e();return}Eu=Math.max(0,Eu-1)},Au=async e=>{await Ou();try{return await e()}finally{ku()}},ju=Symbol.for(`openchamber.git.discoveryGated`),Mu=e=>(Object.defineProperty(e,ju,{value:!0,configurable:!0}),e),Nu=e=>typeof e==`function`&&e[ju]===!0,Z=e=>e.trim(),Pu=(e,t)=>t===`light`?`${Z(e)}::light`:Z(e),Fu=e=>_u.get(Z(e))??0,Q=e=>{let t=Z(e);_u.set(t,Fu(e)+1);for(let e of Array.from(hu.keys()))(e===t||e.startsWith(`${t}::`))&&hu.delete(e);for(let e of Array.from(gu.keys()))(e===t||e.startsWith(`${t}::`))&&gu.delete(e)},Iu=e=>wu.get(Z(e))??0,Lu=e=>{let t=Z(e);t&&(wu.set(t,Iu(e)+1),Su.delete(t),Cu.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),a().api(e,r)}var Ru=(e,t,n)=>{let r=Z(e);if(!r)return;let i=Date.now()+su;vu.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;bu.set(r,{value:{root:a},expiresAt:i})};async function zu(e){let t=Array.from(new Set(e.map(e=>Z(e)).filter(Boolean))),n=new Map;if(t.length===0)return n;let r=Date.now(),i=[];for(let e of t){let t=vu.get(e),a=bu.get(e);if(t&&t.expiresAt>r&&a&&a.expiresAt>r){n.set(e,{isGitRepository:t.value,primaryRoot:a.value.root});continue}i.push(e)}if(i.length===0)return n;let o=e=>{for(let t of e){let e=typeof t.directory==`string`?Z(t.directory):``;if(!e)continue;let r=!!t.isGitRepository,i=typeof t.primaryRoot==`string`&&t.primaryRoot?t.primaryRoot:null;Ru(e,r,i),n.set(e,{isGitRepository:r,primaryRoot:i})}},s=async e=>{await Promise.all(e.map(async e=>{try{let[t,r]=await Promise.all([Bu(e),Hu(e).then(e=>e.root).catch(()=>e)]);Ru(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Ru(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await Au(async()=>{let e=new URLSearchParams;for(let t of i)e.append(`directories`,t);let t=a().api(`${X}/discover`),n=e.toString(),r=n?t.includes(`?`)?`${t}&${n}`:`${t}?${n}`:t,s=await u(r);if(s.status===501||!s.ok)throw Error(`Batch git discover unavailable: ${s.status} ${s.statusText}`);let c=await s.json().catch(()=>null),l=Array.isArray(c)?c:[];if(l.length===0&&i.length>0)throw Error(`Batch git discover returned empty payload`);o(l)})}catch{}let c=i.filter(e=>!n.has(e));return c.length>0&&await s(c),n}async function Bu(e){let t=Z(e),n=Date.now(),r=vu.get(t);if(r&&r.expiresAt>n)return r.value;let i=yu.get(t);if(i)return i;let a=(async()=>{let n=await u($(`${X}/check`,e));if(!n.ok)throw Error(`Failed to check git repository: ${n.statusText}`);let r=!!(await n.json()).isGitRepository;return vu.set(t,{value:r,expiresAt:Date.now()+au}),r})();yu.set(t,a);try{return await a}finally{yu.get(t)===a&&yu.delete(t)}}async function Vu(e,t){let n=t?.mode,r=Pu(e,n),i=Date.now(),a=hu.get(r);if(a&&a.expiresAt>i)return a.value;let o=gu.get(r);if(o)return o;let s=(async()=>{let t=Fu(e),i=await u($(`${X}/status`,e,n?{mode:n}:void 0));if(!i.ok)throw Error(`Failed to get git status: ${i.statusText}`);let a=await i.json();return Fu(e)===t&&hu.set(r,{value:a,expiresAt:Date.now()+iu}),a})();gu.set(r,s);try{return await s}finally{gu.get(r)===s&&gu.delete(r)}}async function Hu(e){let t=Z(e),n=Date.now(),r=bu.get(t);if(r&&r.expiresAt>n)return r.value;let i=xu.get(t);if(i)return i;let a=Au(async()=>{let n=await u($(`${X}/primary-root`,e));if(!n.ok)throw Error(`Failed to resolve git primary root: ${n.statusText}`);let r=await n.json().catch(()=>({})),i={root:typeof r.root==`string`&&r.root?r.root:e};return bu.set(t,{value:i,expiresAt:Date.now()+su}),i});xu.set(t,a);try{return await a}finally{xu.get(t)===a&&xu.delete(t)}}async function Uu(e){let t=await u($(`${X}/toplevel`,e));if(!t.ok)throw Error(`Failed to resolve git toplevel: ${t.statusText}`);let n=await t.json().catch(()=>({}));return{root:typeof n.root==`string`&&n.root?n.root:e}}async function Wu(e,t){let{path:n,staged:r,contextLines:i}=t;if(!n)throw Error(`path is required to fetch git diff`);let a=await u($(`${X}/diff`,e,{path:n,staged:r?`true`:void 0,context:i}));if(!a.ok)throw Error(`Failed to get git diff: ${a.statusText}`);return a.json()}async function Gu(e,t){let{path:n,staged:r}=t;if(!n)throw Error(`path is required to fetch git file diff`);let i=await u($(`${X}/file-diff`,e,{path:n,staged:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get git file diff: ${i.statusText}`);return i.json()}async function Ku(e,t,n){if(!t)throw Error(`path is required to revert git changes`);let r=await u($(`${X}/revert`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,scope:n?.scope})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to revert git changes`)}Q(e)}async function qu(e,t){await Ju(e,[t])}async function Ju(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to stage git changes`);let r=await u($(`${X}/stage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to stage git changes`)}Q(e)}async function Yu(e,t){await Xu(e,[t])}async function Xu(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`path is required to unstage git changes`);let r=await u($(`${X}/unstage`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({paths:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to unstage git changes`)}Q(e)}async function Zu(e,t,n){await ed(e,t,n,`stage`)}async function Qu(e,t,n){await ed(e,t,n,`unstage`)}async function $u(e,t,n){await ed(e,t,n,`discard`)}async function ed(e,t,n,r){if(!t)throw Error(`path is required to apply a git hunk`);if(typeof n!=`string`||!n.trim())throw Error(`patch is required to apply a git hunk`);let i=await u($(`${X}/apply-hunk`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t,patch:n,action:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to apply git hunk`)}Q(e)}async function td(e){if(!e)return!1;let t=await u($(`${X}/worktree-type`,e));if(!t.ok)throw Error(`Failed to detect worktree type: ${t.statusText}`);return!!(await t.json()).linked}async function nd(e,t){let n=await u($(`${X}/branches`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get branches: ${n.statusText}`);return n.json()}async function rd(e,t){if(!t?.branch)throw Error(`branch is required to delete a branch`);let n=await u($(`${X}/branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete branch`)}return n.json()}async function id(e,t){if(!t?.branch)throw Error(`branch is required to delete remote branch`);let n=await u($(`${X}/remote-branches`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete remote branch`)}return n.json()}async function ad(e,t){let n=t?.remote?.trim();if(!n)throw Error(`remote is required to remove a remote`);let r=await u($(`${X}/remotes`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remote:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to remove remote`)}return r.json()}async function od(e,t,n){if(!Array.isArray(t)||t.length===0)throw Error(`No files provided to generate commit message`);let r={files:t};n?.zenModel&&(r.zenModel=n.zenModel),n?.providerId&&(r.providerId=n.providerId),n?.modelId&&(r.modelId=n.modelId);let i=await u($(`${X}/commit-message`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));console.error(`[git-generation][browser] http error`,{status:i.status,statusText:i.statusText,error:e});let t=typeof e?.traceId==`string`&&e.traceId?` (traceId: ${e.traceId})`:``;throw Error(`${e.error||`Failed to generate commit message`}${t}`)}let a=await i.json();if(!a?.message||typeof a.message!=`object`)throw Error(`Malformed commit generation response`);return{message:{subject:typeof a.message.subject==`string`&&a.message.subject.trim().length>0?a.message.subject.trim():``,highlights:Array.isArray(a.message.highlights)?a.message.highlights.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim()):[]}}}async function sd(e,t){let{base:n,head:r,context:i,zenModel:a,providerId:o,modelId:s}=t;if(!n||!r)throw Error(`base and head are required`);let c={base:n,head:r};i?.trim()&&(c.context=i.trim()),a&&(c.zenModel=a),o&&(c.providerId=o),s&&(c.modelId=s);let l=await u($(`${X}/pr-description`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c)});if(!l.ok){let e=await l.json().catch(()=>({error:l.statusText}));throw Error(e.error||`Failed to generate PR description`)}let d=await l.json().catch(()=>null),f=typeof d?.title==`string`?d.title:``,p=typeof d?.body==`string`?d.body:``;if(!f&&!p)throw Error(`Malformed PR description response`);return{title:f,body:p}}async function cd(e){let t=Z(e),n=Date.now(),r=Su.get(t);if(r&&r.expiresAt>n)return r.value;let i=Cu.get(t);if(i)return i;let a=Iu(e),o=Au(async()=>{let n=await u($(`${X}/worktrees`,e));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to list worktrees`)}let r=await n.json();return a===Iu(e)&&Su.set(t,{value:r,expiresAt:Date.now()+su}),r});Cu.set(t,o);try{return await o}finally{Cu.get(t)===o&&Cu.delete(t)}}Mu(cd);async function ld(e,t){let n=await u($(`${X}/worktrees/validate`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to validate worktree`)}return n.json()}async function ud(e){let t=await u($(`${X}/worktrees/bootstrap-status`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to get worktree bootstrap status`)}return t.json()}async function dd(e,t){let n=await u($(`${X}/worktrees/preview`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to preview worktree`)}return n.json()}var fd=e=>typeof e==`string`&&e.length>0,pd=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!fd(t.name)||!fd(t.path))return null;let n={head:typeof t.head==`string`?t.head:``,name:t.name,branch:typeof t.branch==`string`?t.branch:``,path:t.path};return t.directoryCreated===!0&&(n.directoryCreated=!0),t.bootstrapStatus&&typeof t.bootstrapStatus==`object`&&(n.bootstrapStatus=t.bootstrapStatus),n},md=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==lu)return null;let i=pd(r.worktree);if(!i)return null;let a=r.repair;if(!a||typeof a!=`object`)return null;let o=a;if(o.method!==`POST`||o.path!==cu)return null;let s=o.body;if(!s||typeof s!=`object`)return null;let c=s;return c.projectDirectory!==n||c.directory!==i.path?null:i},hd=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,gd=e=>new Promise(t=>{setTimeout(t,e)}),_d=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===uu||t?.code===du}return e.status===503&&(await e.json().catch(()=>null))?.code===lu},vd=e=>e===400||e===401||e===403||e===501,yd=(e,t)=>{let n=o(),r=s(),i=hd(n,r,e,t);if(Tu.has(i))return;Tu.add(i);let a=()=>o()===n&&s()===r;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<pu;){if(!a())return;let i=mu[Math.min(r,mu.length-1)]??0;if(i>0){let e=pu-(Date.now()-n);if(e<=0||(await gd(Math.min(i,e)),!a()))return}let o=new AbortController,s=setTimeout(()=>o.abort(),fu);try{let n=await u($(cu,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:o.signal});if(n.ok||vd(n.status))return;if(await _d(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(s)}}})().catch(()=>{}).finally(()=>{Tu.delete(i)})};async function bd(e,t){let n=await u($(`${X}/worktrees`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})}),r=await n.json().catch(()=>null);if(n.ok){let t=pd(r);if(t)return Lu(e),t;if(r&&typeof r==`object`)return Lu(e),r;throw Error(`Failed to create worktree`)}let i=md(n.status,r,e);if(i)return Lu(e),yd(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function xd(e,t){let n=await u($(`${X}/worktrees`,e),{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to delete worktree`)}let r=await n.json();return Lu(e),r}async function Sd(e,t,n={}){let r=await u($(`${X}/commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({message:t,addAll:n.addAll??!1,files:n.files,stageFiles:n.stageFiles})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create commit`)}let i=await r.json();return Q(e),i}async function Cd(e,t={}){let n=await u($(`${X}/push`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to push`)}let r=await n.json();return Q(e),r}async function wd(e,t={}){let n=await u($(`${X}/pull`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to pull`)}let r=await n.json();return Q(e),r}async function Td(e,t={}){let n=await u($(`${X}/fetch`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to fetch`)}let r=await n.json();return Q(e),r}async function Ed(e){let t=await u($(`${X}/stashes`,e));if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to list stashes`)}return t.json()}async function Dd(e,t){let n=await u($(`${X}/stashes/file-counts`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refs:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to count stash files`)}return n.json()}async function Od(e,t={}){let n=await u($(`${X}/stash`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to stash changes`)}return n.json()}var kd=async(e,t,n)=>{let r=await u($(`${X}/${t}`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to ${t}`)}return r.json()},Ad=(e,t)=>kd(e,`stash/apply`,t),jd=(e,t)=>kd(e,`stash/pop`,t),Md=(e,t)=>kd(e,`stash/drop`,t);async function Nd(e,t){let n=await u($(`${X}/checkout`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({branch:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout branch`)}return n.json()}async function Pd(e,t,n){let r=await u($(`${X}/branches`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t,startPoint:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to create branch`)}return r.json()}async function Fd(e,t,n){let r=await u($(`${X}/branches/rename`,e),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({oldName:t,newName:n})});if(!r.ok){let e=await r.json().catch(()=>({error:r.statusText}));throw Error(e.error||`Failed to rename branch`)}return r.json()}async function Id(e,t={}){let n=await u($(`${X}/log`,e,{maxCount:t.maxCount,from:t.from,to:t.to,file:t.file,all:t.all?`true`:void 0}));if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(`Failed to get git log: ${e.error||n.statusText}`)}return n.json()}async function Ld(e,t){let n=await u($(`${X}/commit-files`,e,{hash:t}));if(!n.ok)throw Error(`Failed to get commit files: ${n.statusText}`);return n.json()}async function Rd(e,t,n,r){let i=await u($(`${X}/commit-file-diff`,e,{hash:t,path:n,binary:r?`true`:void 0}));if(!i.ok)throw Error(`Failed to get commit file diff: ${i.statusText}`);return i.json()}async function zd(){let e=await u($(`${X}/identities`,void 0));if(!e.ok)throw Error(`Failed to get git identities: ${e.statusText}`);return e.json()}async function Bd(e){let t=await u($(`${X}/identities`,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to create git identity`)}return t.json()}async function Vd(e,t){let n=await u($(`${X}/identities/${e}`,void 0),{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to update git identity`)}return n.json()}async function Hd(e){let t=await u($(`${X}/identities/${e}`,void 0),{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to delete git identity`)}}async function Ud(e){if(!e)return null;let t=await u($(`${X}/current-identity`,e));if(!t.ok)throw Error(`Failed to get current git identity: ${t.statusText}`);let n=await t.json();return n?{userName:n.userName??null,userEmail:n.userEmail??null,sshCommand:n.sshCommand??null}:null}async function Wd(e){if(!e)return!1;let t=await u($(`${X}/has-local-identity`,e));if(!t.ok)throw Error(`Failed to check local identity: ${t.statusText}`);return(await t.json().catch(()=>null))?.hasLocalIdentity===!0}async function Gd(){let e=await u($(`${X}/global-identity`,void 0));if(!e.ok)throw Error(`Failed to get global git identity: ${e.statusText}`);let t=await e.json();return!t||!t.userName&&!t.userEmail?null:{userName:t.userName??null,userEmail:t.userEmail??null,sshCommand:t.sshCommand??null}}async function Kd(e,t){let n=await u($(`${X}/set-identity`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profileId:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to set git identity`)}return n.json()}async function qd(){let e=await u($(`${X}/discover-credentials`,void 0));if(!e.ok)throw Error(`Failed to discover git credentials: ${e.statusText}`);return e.json()}async function Jd(e,t){let n=await u($(`${X}/remotes`,e),{signal:t?.signal});if(!n.ok)throw Error(`Failed to get remotes: ${n.statusText}`);return n.json()}async function Yd(e,t){let n=await u($(`${X}/rebase`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to rebase`)}return n.json()}async function Xd(e){let t=await u($(`${X}/rebase/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort rebase`)}return t.json()}async function Zd(e,t){let n=await u($(`${X}/merge`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to merge`)}return n.json()}async function Qd(e,t){let n=await u($(`${X}/checkout-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to checkout commit`)}return n.json()}async function $d(e,t){let n=await u($(`${X}/cherry-pick`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to cherry-pick`)}return n.json()}async function ef(e,t){let n=await u($(`${X}/revert-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t})});if(!n.ok){let e=await n.json().catch(()=>({error:n.statusText}));throw Error(e.error||`Failed to revert commit`)}return n.json()}async function tf(e,t,n,r){let i=await u($(`${X}/reset-to-commit`,e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({hash:t,mode:n,force:r})});if(!i.ok){let e=await i.json().catch(()=>({error:i.statusText}));throw Error(e.error||`Failed to reset`)}return i.json()}async function nf(e){let t=await u($(`${X}/merge/abort`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to abort merge`)}return t.json()}async function rf(e){let t=await u($(`${X}/rebase/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue rebase`)}return t.json()}async function af(e){let t=await u($(`${X}/merge/continue`,e),{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({error:t.statusText}));throw Error(e.error||`Failed to continue merge`)}return t.json()}async function of(e,t){return await Od(e,{message:t?.message}),{success:!0}}async function sf(e){return await jd(e,{ref:`stash@{0}`}),{success:!0}}async function cf(e){let t=await u($(`${X}/conflict-details`,e));if(!t.ok)throw Error(`Failed to get conflict details: ${t.statusText}`);return t.json()}async function lf(e,t){let n=await u(`${X}/validate-directory`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e,worktreeRoot:t})});if(!n.ok)throw Error(`Failed to validate worktree directory: ${n.statusText}`);return n.json()}async function uf(e){let t=await u(`${X}/canonicalize-worktree-state`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({directory:e})});if(!t.ok)throw Error(`Failed to canonicalize worktree state: ${t.statusText}`);return t.json()}var df=()=>typeof window>`u`?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol===`capacitor:`,ff=()=>{if(typeof window>`u`||!df()||pf()!==`ios`)return!1;let e=navigator.userAgent||``,t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},pf=()=>{if(typeof window<`u`){let e=window.Capacitor?.getPlatform?.();if(e===`ios`||e===`android`)return e}return ee()?`vscode`:re()?`desktop`:`web`};export{Yd as $,ja as $n,wn as $r,Js as $t,cf as A,we as Ai,Go as An,Mi as Ar,Rl as At,Jd as B,Ba as Bn,Pr as Br,Nc as Bt,qd as C,Pe as Ci,jo as Cn,Ri as Cr,nu as Ct,sd as D,tt as Di,Ho as Dn,Ii as Dr,Ml as Dt,od as E,Xe as Ei,Bo as En,Ui as Er,Nl as Et,zd as F,xe as Fi,io as Fn,yi as Fr,Pc as Ft,Lu as G,Ga as Gn,wr as Gr,gc as Gt,wd as H,Ya as Hn,Gr as Hr,wc as Ht,Id as I,ve as Ii,Wa as In,Rr as Ir,Ac as It,Ed as J,Ra as Jn,Tr as Jr,mc as Jt,Nu as K,za as Kn,Cr as Kr,_c as Kt,Vu as L,ye as Li,qa as Ln,Vr as Lr,Tc as Lt,nd as M,Ee as Mi,go as Mn,Fi as Mr,wl as Mt,Wu as N,Se as Ni,ho as Nn,Ei as Nr,q as Nt,Rd as O,je as Oi,Uo as On,Li as Or,Tl as Ot,Gu as P,v as Pi,vo as Pn,vi as Pr,Oc as Pt,dd as Q,ya as Qn,Fn as Qr,nc as Qt,ud as R,_e as Ri,Ka as Rn,Wr as Rr,kc as Rt,id as S,Qe as Si,Ao as Sn,Ni as Sr,ru as St,Md as T,Ne as Ti,zo as Tn,Ki as Tr,Fl as Tt,Cd as U,Xa as Un,Hr as Ur,Cc as Ut,Td as V,Ha as Vn,Fr as Vr,Dc as Vt,Wd as W,Za as Wn,jr as Wr,cc as Wt,Zd as X,la as Xn,gr as Xr,Qs as Xt,cd as Y,Ua as Yn,Sr as Yr,qs as Yt,jd as Z,ca as Zn,In as Zr,ec as Zt,Bd as _,Rt as _i,z as _n,Pi as _r,Qu as _t,Xd as a,Cn as ai,Os as an,ua as ar,ef as at,Hd as b,ut as bi,is as bn,Gi as br,lf as bt,Bu as c,Dn as ci,fs as cn,Sa as cr,Kd as ct,$d as d,hn as di,ms as dn,sa as dr,Zu as dt,Ln as ei,tc as en,aa as er,ad as et,af as f,_n as fi,hs as fn,Zi as fr,of as ft,Sd as g,nn as gi,As as gn,zi as gr,Xu as gt,Pd as h,Vt as hi,os as hn,qi as hr,Yu as ht,nf as i,Rn as ii,R as in,Da as ir,Uu as it,Ud as j,De as ji,Fo as jn,A as jr,Ll as jt,Ld as k,Te as ki,Po as kn,Hi as kr,Il as kt,Nd as l,On as li,vs as ln,ka as lr,qu as lt,Dd as m,dn as mi,Es as mn,Ji as mr,sf as mt,df as n,jn as ni,Xs as nn,va as nr,tf as nt,Ad as o,Sn as oi,Ds as on,ba as or,Ku as ot,rf as p,an as pi,Ts as pn,Yi as pr,Od as pt,td as q,Ja as qn,Er as qr,hc as qt,ff as r,zn as ri,cs as rn,ga as rr,Hu as rt,uf as s,xn as si,Cs as sn,fa as sr,$u as st,pf as t,Bn as ti,Zs as tn,ia as tr,Fd as tt,Qd as u,Tn as ui,js as un,wa as ur,Ju as ut,bd as v,ft as vi,I as vn,Vi as vr,Vd as vt,zu as w,Ve as wi,Mo as wn,Wi as wr,Pl as wt,xd as x,et as xi,Vo as xn,k as xr,Au as xt,rd as y,gt as yi,as as yn,Bi as yr,ld as yt,Gd as z,be as zi,Va as zn,Jr as zr,Ec as zt};