@openchambery/web 2.0.0-beta.17 → 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.
- package/dist/assets/{AssistantView-DfdYRwe9.js → AssistantView-DcnZ020v.js} +3 -3
- package/dist/assets/{DiagramView-DgPSfFEr.js → DiagramView-IciqbBQL.js} +1 -1
- package/dist/assets/{MarkdownRenderer-Cgoat7nw.js → MarkdownRenderer-CNDoKYhC.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-DMhCX4I4.js → MarkdownRendererImpl-MwxehP-f.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BiEn8urF.js → MarkstreamRendererImpl-DWg5olbY.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-CRb0QjWl.js → MobileDetailNavigation-CDIhNSXT.js} +1 -1
- package/dist/assets/{MobileShareBridge-C1KkUsa1.js → MobileShareBridge-DywdGhnV.js} +1 -1
- package/dist/assets/{MobileSurface-GAmsjEQX.js → MobileSurface-B3TwLSD8.js} +1 -1
- package/dist/assets/{MultiRunWindow-1J5N1_xP.js → MultiRunWindow-D9zSluS2.js} +1 -1
- package/dist/assets/{OverlayScrollbar-SUdC3Pqe.js → OverlayScrollbar-IEHPY5wy.js} +1 -1
- package/dist/assets/{SettingsView-BTWtI6gk.js → SettingsView-B6XM6SjZ.js} +1 -1
- package/dist/assets/{SettingsWindow-5NrNotTs.js → SettingsWindow-C64N7asK.js} +1 -1
- package/dist/assets/{TerminalView-CNHjj_km.js → TerminalView-CZkQhHRy.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DDVMsHzT.js → ToolOutputDialog-KWiIFR-d.js} +1 -1
- package/dist/assets/{appThemeRegistry-D7-4hz-r.js → appThemeRegistry-Cpuh1f4h.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-CxmALWLE.js → fileMentionTouchSelection-DNsbRHU9.js} +1 -1
- package/dist/assets/{gitApi-Bx8o0qYf.js → gitApi-BOhg5Bz_.js} +1 -1
- package/dist/assets/{insertionBoundaries-B7WuxOpo.js → insertionBoundaries-BQ3SfsPe.js} +1 -1
- package/dist/assets/{main-fFwuYFwA.js → main-CDFpn3jQ.js} +2 -2
- package/dist/assets/{main-Df1hgMj6.js → main-DcPhdAAo.js} +9 -9
- package/dist/assets/{mcpQueries-5RQLxGkS.js → mcpQueries-DuXHOnX2.js} +1 -1
- package/dist/assets/{miniChat-ByXFq9Gm.js → miniChat-CXYSaHX0.js} +2 -2
- package/dist/assets/{mobile-DzYPMFOV.js → mobile-BAox2MyA.js} +2 -2
- package/dist/assets/{multirun-CbKpafUJ.js → multirun-yEwF9wsU.js} +1 -1
- package/dist/assets/platform-CKIStkm5.js +6 -0
- package/dist/assets/{projectMeta-DR8jWQPj.js → projectMeta-_AcbokQy.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-BH_HOhiH.js → renderElectronMiniChatApp-mI7tFw7r.js} +2 -2
- package/dist/assets/{renderMobileApp-CdvHmHtu.js → renderMobileApp-d3J8FKQC.js} +5 -5
- package/dist/assets/{runtimeConfig-C2r3lwvo.js → runtimeConfig-C5IUkpAF.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-C4E7DYmZ.js → runtimeEndpointReset-CvfuetgK.js} +1 -1
- package/dist/assets/{sessionChangeSummary-BvaUzmH5.js → sessionChangeSummary-BAMnNkFo.js} +1 -1
- package/dist/assets/{sessionLookup-D6SUfHqi.js → sessionLookup-C_8aOG5T.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-Bc0lATi8.js → sortable-tabs-strip-C1avMLUr.js} +1 -1
- package/dist/assets/{terminalApi-C6zlKnK1.js → terminalApi-DVj_hL-2.js} +1 -1
- package/dist/assets/{textarea-B9pCxe-7.js → textarea-4em_Fprz.js} +1 -1
- package/dist/assets/{useAppFontEffects-DO-sih8X.js → useAppFontEffects-D2_pOoR1.js} +55 -55
- package/dist/assets/{useDesktopWindowControlsLayout-DFAvkRtr.js → useDesktopWindowControlsLayout-CBK8ajHA.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-o1wBFa-2.js → useEffectiveDirectory-DRs4aWaY.js} +1 -1
- package/dist/assets/{useFontPreferences-DFsjAsxC.js → useFontPreferences-K4sEJPsT.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-Brjbv-jq.js → useMobileNavigationStore-BEqX-JUL.js} +13 -13
- package/dist/assets/{useSessionAutoCleanup-uEly8Hxf.js → useSessionAutoCleanup-DHUSC8Xf.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-DWYhz9_o.js → useWorkerHighlightedLines-BqGJFJHF.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +1 -1
- package/server/lib/opencode/DOCUMENTATION.md +4 -0
- package/server/lib/opencode/config-entity-routes.js +1 -1
- package/server/lib/opencode/config-entity-routes.test.js +16 -0
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -1
- package/server/lib/scheduled-tasks/runtime.js +10 -1
- package/server/lib/scheduled-tasks/runtime.test.js +81 -6
- package/dist/assets/platform-BxU3ZvQ0.js +0 -6
|
@@ -0,0 +1,6 @@
|
|
|
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 O=e=>Object.freeze(e),fn=Object.freeze({initial:O({id:`initial`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),prepend:O({id:`history`,onStale:`drop`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),recovery:O({id:`recovery`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`}),"reconcile-page":O({id:`reconcile-page`,onStale:`backfill`,messages:`upsert`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`keep-unless-full`}),materialize:O({id:`materialize`,onStale:`backfill`,messages:`insert-only`,parts:`replace`,preserveStreaming:`assistant`,protectOptimistic:`none`})}),pn=O({id:`recovery-backfill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),mn=O({id:`send-gap-fill`,onStale:`backfill`,messages:`insert-only`,parts:`skip-existing`,preserveStreaming:`assistant`,protectOptimistic:`none`}),hn=fn.initial;function gn(e){let t=fn[e.purpose]??hn;return!e.stale||t.onStale===`drop`?t:pn}function _n(e,t){return e.preserveStreaming===`none`?!1:e.preserveStreaming===`all`||t===`assistant`}var vn=e=>structuredClone(e),yn=e=>({transport:e.transport,generation:e.generation,directory:e.directory,sessionID:e.sessionID});function bn(e){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID])}function xn(e,t){return JSON.stringify([e.transport,e.generation,e.directory,e.sessionID,t])}function Sn(e){return JSON.stringify([e.transport,e.generation])}function Cn(e,t){return e.created===t.created?e.messageID<t.messageID?-1:+(e.messageID>t.messageID):e.created-t.created}function wn(e){let t=e.time?.created;return{created:typeof t==`number`&&Number.isFinite(t)?t:0,messageID:e.id}}function Tn(e){return un(e)}function En(e){return D(e)?`slim`:`full`}function Dn(e){return e.some(e=>D(e))?`slim`:`full`}var On=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(On);let t=e,n={};for(let e of Object.keys(t).sort()){let r=t[e];r!==void 0&&(n[e]=On(r))}return n},kn=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n};async function An(e,t){let n=JSON.stringify(On({info:e,parts:t})),r=new TextEncoder().encode(n);return{hash:kn(await crypto.subtle.digest(`SHA-256`,r)),byteSize:r.byteLength}}var jn=e=>({scope:yn(e.scope),messageID:e.messageID,info:vn(e.info),parts:vn(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}}),Mn=e=>{let t=0;return()=>{let n=e();return t=n>t?n:t+1,t}},Nn=(e,t)=>{let n=t.slice().sort((e,t)=>Cn(e.sortKey,t.sortKey)).map(jn);return{scope:yn(e),records:n,byteSize:n.reduce((e,t)=>e+t.byteSize,0)}},Pn=e=>vn(e),Fn=e=>yn(e),In=(e=Date.now)=>Mn(e),Ln=e=>jn(e),Rn=(e,t)=>Nn(e,t.slice());function zn(e){return Tn(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 Bn=[`text`,`output`],Vn={pending:1,started:2,running:3,completed:4,error:4};function Hn(e,t){return e.filter(e=>!!e?.id&&!t.has(e.type))}function Un(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 Wn(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 Gn(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Kn(e){return Wn(e)===void 0&&Bn.some(t=>{let n=Gn(e,t);return typeof n==`string`&&n.length>0})}function qn(e){let t=e.state;if(!(!t||typeof t!=`object`))return t}function Jn(e){let t=qn(e)?.status;return typeof t==`string`?t:void 0}function Yn(e){return e?Vn[e]??0:0}function Xn(e,t){if(Kn(e))return!0;if(Wn(e)===void 0){if(e.type===`tool`){let n=Jn(e);return n===`completed`||n===`error`?t:!0}return!0}return t}function Zn(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 Qn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0}function $n(e,t,n){if(e.type!==`tool`||t.type!==`tool`)return n;let r=qn(e);if(!r)return n;let i=qn(n)??{},a=qn(t)??{},o={...i},s=!1,c=Jn(e),l=Jn(t);Yn(c)>Yn(l)&&c&&(o={...o,status:c},s=!0);let u=r.input,d=a.input;Qn(u)&&!Qn(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 Qn(m)&&!Qn(a.metadata)&&(o={...o,metadata:m},s=!0),s?n===t?{...t,state:o}:{...n,state:o}:n}function er(e,t){if(!e||Wn(t)!==void 0)return t;let n=t;for(let r of Bn){let i=Gn(e,r);if(!i)continue;let a=Gn(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=Zn(e);if(r){let e=Zn(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=$n(e,t,n),n}function tr(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 nr(e){return e.__openchamberOptimistic===!0}function rr(e){return!!(e&&e.length>0&&e.some(nr))}function ir(e){return e.length===0||e.some(e=>D(e))}function ar(e,t,n,r,i,a){if(a===`keep-unless-full`&&e&&rr(e)&&ir(t))return e;let o=tr(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=er(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)&&(Xn(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 or=e=>e,sr=e=>{let t=or(e).finish;return typeof t==`string`&&t.length>0},cr=e=>typeof or(e).time?.completed==`number`,lr=e=>!!or(e).error;function ur(e,t){let n=or(t),r=n.finish,i=n.time?.completed,a=n.error,o=e.tokens,s=t.tokens,c=!sr(e)&&typeof r==`string`&&r.length>0,l=!cr(e)&&typeof i==`number`,u=!lr(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={...or(e).time,completed:i}),u&&(f.error=a),d&&(f.tokens=s),f}function dr(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`?fr(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 fr(e,t){let n=e.slice();for(let e of t){let t=wn(e),r=n.length;for(let e=0;e<n.length;e+=1)if(Cn(t,wn(n[e]))<0){r=e;break}n.splice(r,0,e)}return n}function pr(e,t,n){return dr(e,t,(e,t)=>t?ur(e,t):e,n)}function mr(e,t,n){return dr(e,t,(e,t)=>!t||JSON.stringify(e)===JSON.stringify(t)?e:Rt(e,t),n)}function hr(e,t,n,r={}){let i=r.skipPartTypes??new Set,a=r.merge??hn,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`?mr(u,c,o):pr(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=ar(r,Hn(e.parts??[],i),i,_n(a,e.info.role),an(e.info),a.protectOptimistic);(r?Un(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 gr(e){if(typeof e.time?.completed==`number`)return!1;let t=e.finish;return!(typeof t==`string`&&t.length>0)}function _r(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&&gr(i)||r.push(i.id));return{hasMessages:!0,renderable:r.length===0,missingPartMessageIDs:r}}var vr=(e,t)=>e<t?-1:+(e>t);function yr(e){return e.filter(e=>!!e?.id)}function br(e,t){if(t.length===0)return{...e,confirmed:[]};let n=[...e.session],r=new Map(e.part.map(e=>[e.id,yr(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,yr(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,yr(e.parts))}return{cursor:e.cursor,complete:e.complete,session:n,part:[...r.entries()].sort((e,t)=>vr(e[0],t[0])).map(([e,t])=>({id:e,part:t})),confirmed:i}}var xr={kind:`unknown`,loadedTurns:0},Sr=3e4,Cr=12e5,wr={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},Tr={ready:!1,path:{state:``,config:``,worktree:``,directory:``,home:``},projects:[],providers:{all:[],connected:[],default:{}},providerAuth:{},config:{},reload:void 0,sessionTodo:{}};function Er(e,t){return e===void 0||t===void 0?!1:t>e}var Dr=class extends Error{};function Or(e,t,n){if(n===`reconcile-page`)return e??xr;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 Dr(`session message page: complete=false requires non-empty cursor`);if(n===`prepend`&&e?.kind===`has-more`&&e.cursor===o)throw new Dr(`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 Dr(`session message page: complete=false with zero records makes no progress`);return{kind:`has-more`,cursor:o,loadedTurns:a}}function kr(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 Ar(e,t,n,r){let i=Er(r.capturedRevision,r.liveRevision),a=gn({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=br({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=hr(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=Or(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 Dr))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=!kr(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 jr=new Set([`tool`,`reasoning`,`file`,`text`]),Mr=new Set([`tool`,`reasoning`,`file`]);function Nr(e){return e.some(e=>D(e)&&jr.has(e.type))}function Pr(e,t){let n=!1,r=!1;for(let t of e)Mr.has(t.type)&&(n=!0,D(t)&&(r=!0));return n?r?!0:t?an(t):!1:!1}var Fr=e=>{if(!e)return``;let t=e.clientRole??e.role;return typeof t==`string`?t:``};function Ir(e,t){return Ve(e,t)}function Lr(e){let t=0;for(let n of e.messageOrder)Ir(e.messagesByID[n],e.partsByMessageID[n])&&(t+=1);return t}var Rr=(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(Ir(a,e.partsByMessageID[n]))break;if(Fr(a)!==`assistant`)continue;let o=a.parentID;typeof o==`string`&&o.length>0&&o!==t||r.push(a)}return r},zr=(e,t)=>an(e)?!0:Array.isArray(t)&&t.length>0;function Br(e){let t;for(let n=e.messageOrder.length-1;n>=0;--n){let r=e.messageOrder[n];if(Ir(e.messagesByID[r],e.partsByMessageID[r])){t=r;break}}return t?Rr(e,t).some(t=>zr(t,e.partsByMessageID[t.id])):!1}function Vr(e){return e.materializeActive?`p2`:e.prependActive||e.earlierHistoryLoaded?`p1`:e.p0Satisfied?`p0`:`idle`}var Hr=new Set([`stop`,`length`]);function Ur(e){let t=e.messageOrder[e.messageOrder.length-1];if(!t)return!1;let n=e.messagesByID[t];if(!n||Fr(n)!==`assistant`||n.error)return!1;let r=n.finish;return typeof r!=`string`||!Hr.has(r)?!1:typeof n.time?.completed!=`number`||r===`stop`&&!Ft(n.tokens)}function Wr(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 Gr(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 Kr=`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 qr(e){return Kr.includes(e)}function k(e){return e.trim()}function Jr(e){return`${k(e.directory)}\n${e.sessionID}`}function Yr(e,t){return e.session_history_boundary?.[t]??xr}function Xr(e){return e.filter(e=>!!e?.id)}function Zr(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 Qr(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||!Zr(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 $r(e,t,n){let r=e.getState(),i=n.page,a=Ar(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?(Qr(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 ei(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(!qr(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 ti(e,t){return ei(e,[t.event])}function ni(e,t){return ei(e,t.events)}function ri(e,t,n){if(n.records.length===0)return{applied:!1,changed:!1};let r=e.getState(),i=hr({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 ii(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 ai(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]=Xr(n.parts),e.setState({message:o,part:s}),{applied:!0,changed:!0}}function oi(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 si(e,t,n,r){return n.clearOptimisticShadow?.({directory:r,sessionID:e,messageID:t}),{applied:!0,changed:!1}}function ci(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 li(e,t,n){let r=ci(e,t);if(!n.page)return{applied:!0,changed:r};let i=$r(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 ui(e){let t=new Map,n=new Map,r=r=>{let i=Jr(r);if(n.has(i))return;let a=k(r.directory),o=e.getStore(a),s=r.sessionID,c=o.getState().message?.[s],l=Yr(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=Yr(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=Zr(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=k(t.directory),r=e.getStore(n).getState(),i=t.sessionID,a=r.message?.[i]??[],o=e.getLiveRevision?.(n,i)??0;return Gr({sessionID:i,messages:a,parts:r.part??{},boundary:Yr(r,i),liveRevision:o})},getPagination(t){let n=k(t.directory),r=e.getStore(n).getState();return Wr(t.sessionID,Yr(r,t.sessionID))},getRequestState(t){let n=k(t.directory);return e.getRequestState?.(n,t.sessionID)??{sessionID:t.sessionID,status:`idle`}},getHydrationState(e){let t=a.getTranscript(e),n=Br(t);return{sessionID:e.sessionID,p0Satisfied:n,phase:Vr({p0Satisfied:n,earlierHistoryLoaded:Lr(t)>1})}},getMessage(e,t){return a.getTranscript(e).messagesByID[t]},getParts(t,n){let r=k(t.directory);return e.getStore(r).getState().part?.[n]??[]},hasSession(t){let n=k(t.directory),r=e.getStore(n).getState().message;return r?Object.prototype.hasOwnProperty.call(r,t.sessionID):!1},apply(t,n){let r=k(t.directory),i=e.getStore(r),a=t.sessionID;switch(n.type){case`http-page`:return $r(i,a,n);case`sse-event`:return ti(i,n);case`sse-event-batch`:return ni(i,n);case`optimistic-add`:return ai(i,a,n,e,r);case`optimistic-confirm`:return si(a,n.messageID,e,r);case`optimistic-remove`:return oi(i,a,n.messageID,e,r);case`reset`:return li(i,a,n);case`materialize-snapshots`:return ri(i,a,n);case`remove-message`:return ii(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=Jr(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 di=new Set,fi=new Set;function pi(e,t){return`${e}\n${t}`}function mi(){for(let e of fi)e()}function hi(e,t){!e||!t||(di.add(pi(e,t)),mi())}function gi(e,t){!e||!t||di.delete(pi(e,t))&&mi()}function _i(e,t){if(!e)return!1;if(t)return di.has(pi(t,e));let n=`\n${e}`;for(let e of di)if(e.endsWith(n))return!0;return!1}function vi(e){return fi.add(e),()=>{fi.delete(e)}}var yi=[],bi=new Map,xi=new Map,Si=0,Ci=()=>{let e=yi.findIndex(e=>e.priority===`user`);if(e>=0){let[t]=yi.splice(e,1);return t}return yi.shift()},wi=()=>{for(;Si<4;){let e=Ci();if(!e)return;bi.delete(e.key),Si+=1,Promise.resolve().then(()=>e.run()).then(t=>{e.resolve(t)},t=>{e.reject(t)}).finally(()=>{--Si,xi.delete(e.key),wi()})}};function Ti(e,t,n){let r=n?.priority??`background`,i=xi.get(e);if(i){let t=bi.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 yi.push(c),bi.set(e,c),xi.set(e,s),wi(),s}var Ei=null,Di=0,Oi=new Set;function ki(){Di+=1;for(let e of Oi)e()}function Ai(e){return e}function ji(e){return Oi.add(e),()=>{Oi.delete(e)}}function Mi(){return Di}function Ni(e){return Ei?.repository===e?e:(Ei={kind:`query`,repository:e},ki(),e)}function Pi(){Ei&&(Ei=null,ki())}function A(){return Ei?.repository??null}function Fi(){let e=A();if(!e)throw Error(`TranscriptRepository is not bound — SyncProvider must mount first`);return e}function Ii(e,t){let n=A();if(n)return n;let r=Ai(t);return ui({getStore:e=>r})}function j(e,t,n){return{directory:e.trim(),sessionID:t,...n?.transport===void 0?{}:{transport:n.transport},...n?.generation===void 0?{}:{generation:n.generation}}}function Li(e){try{let t=A(),n=o(),r=s();return t?.getCacheBudget?.().listCanonicalScopesForSession(e,{transport:n,generation:r})?.map(e=>j(e.directory,e.sessionID,{transport:e.transport,generation:e.generation}))??[]}catch{return[]}}function Ri(e,t){let n=A();return n?n.apply(e,t):null}async function zi(e,t){let n=Fi();if(typeof n.fetchPreviousPage!=`function`)throw Error(`TranscriptRepository does not support fetchPreviousPage`);await n.fetchPreviousPage(j(e,t))}async function Bi(e,t){let n=Fi();if(typeof n.ensureInitial!=`function`)throw Error(`TranscriptRepository does not support ensureInitial`);await n.ensureInitial(j(e,t))}async function Vi(e,t){let n=Fi(),r=j(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 Hi(e,t){let n=Fi();if(typeof n.refreshFromAuthority!=`function`)throw Error(`TranscriptRepository does not support refreshFromAuthority`);hi(e,t);try{await n.refreshFromAuthority(j(e,t))}finally{gi(e,t)}}async function Ui(e,t,n,r){let i=Fi();if(typeof i.materializeMessage!=`function`)throw Error(`TranscriptRepository does not support materializeMessage`);let a=j(e,t);await Ti(`${e}\n${t}\n${n}`,()=>i.materializeMessage(a,n),{priority:r?.priority??`background`})}function Wi(e,t,n){let r=A();return!r||typeof r.getMessageMaterializationState!=`function`?{sessionID:t,messageID:n,status:`idle`}:r.getMessageMaterializationState(j(e,t),n)}function Gi(e,t){A()?.purgeSession?.(j(e,t))}var M=null;function Ki(e){M&&M!==e&&M.cancelAll(`reregister`),M=e}function qi(e){M?.captureCheckpoints(e)}function Ji(e){M?.onCompensation(e)}async function Yi(e){return M?M.ensureOnObserve(e):null}function Xi(e){M?.cancelAll(e)}var Zi=[],Qi=[],$i={sessionID:``,messageOrder:[],messagesByID:{},partsByMessageID:{},boundary:xr,liveRevision:0};Wr(``,xr);var ea={sessionID:``,phase:`idle`,p0Satisfied:!1};function N(e,t){return Ii(e,t)}var ta=new Set;function na(e,t){return`${e}\n${t}`}function ra(e,t){if(!t)return;let n=na(e,t);ta.has(n)||(ta.add(n),Yi(j(e,t)).catch(()=>{}).finally(()=>{ta.delete(n)}))}function ia(e,t){if(e&&t){ta.delete(na(e,t));return}ta.clear()}function aa(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($i);return(c.current===void 0||!s.current(c.current,e))&&(c.current=e),c.current}let r=N(t,n).getTranscript(j(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;ra(t,e);let i=N(t,n).subscribe(j(t,e),()=>{r()}),a=ji(()=>{i(),c.current=void 0,ia(t,e),ra(t,e),i=N(t,n).subscribe(j(t,e),()=>{r()}),r()});return()=>{a(),i()}},[t,l,e,n]);return y.useSyncExternalStore(d,u,u)}function oa(e,t,n,r,i,a){return aa(e,t,n,r,i===void 0?Object.is:i,a)}function sa(e,t){if(e.messageOrder.length===0)return Zi;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 ca(e,t){return e.messageOrder.length===0?t?.resolved===!0?_r({messages:Zi,parts:e.partsByMessageID}):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}:_r({messages:sa(e),parts:e.partsByMessageID})}function la(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=N(t,n).hasSession?.(j(t,e));return ca(r,{resolved:i===!0||void 0})},i[0]=t,i[1]=e,i[2]=n,i[3]=a):a=i[3],aa(e,t,n,a,ua,r)}function ua(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 da(e,t,n,r){return aa(e,t,n,pa,fa,r)}function fa(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 pa(e){return sa(e)}function ma(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 ha(e,t,n,r){return aa(e,t,n,ga,ma,r)}function ga(e){return e}function _a(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=A();if(o){i.push(o.subscribe(j(a.directory,a.sessionID),t));continue}let s=n?.(a.directory);if(!s)continue;let c=Ii(a.directory,s);i.push(c.subscribe(j(a.directory,a.sessionID),t))}},s=()=>{a(),o(),t()};o();let c=ji(s),l=r?.subscribeRebuild?.(s);return()=>{l?.(),c(),a()}}function va(e,t){return e.length===0?``:e.map(e=>{let n=Aa(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 ya(e,t,n){return aa(e,t,n,ba)}function ba(e){return e.messageOrder.length}function xa(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=N(t,n),a=r.hasSession?.(j(t,e))??r.getTranscript(j(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?N(t,n).subscribe(j(t,e),()=>{r()}):Sa,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 Sa(){}function Ca(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=Qi,Qi;let i=N(t,n),o=r||e,s=i.getParts(j(t,o),e),c=s.length===0?Qi: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 Ta;let a=N(t,n);return r?a.subscribe(j(t,r),()=>{i()}):wa},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 wa(){}function Ta(){}function Ea(e,t,n){let r=(0,Ce.c)(8),i=(0,y.useRef)(ea),a;r[0]!==t||r[1]!==e||r[2]!==n?(a=()=>{if(!e)return i.current!==ea&&(i.current=ea),i.current;let r=N(t,n).getHydrationState?.(j(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 Da;ra(t,e);let a=N(t,n).subscribe(j(t,e),()=>{r()}),o=ji(()=>{a(),i.current=ea,ia(t,e),ra(t,e),a=N(t,n).subscribe(j(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 Da(){}function Oa(e,t,n){let r=(0,Ce.c)(2),i;return r[0]===e?i=r[1]:(i=t=>Wr(e,t.boundary),r[0]=e,r[1]=i),aa(e,t,n,i,ka)}function ka(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 Aa(e,t,n){if(!t)return[];let r=A();if(r){let n=r.getTranscript(j(e,t));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}if(!n)return[];let i=Ii(e,n).getTranscript(j(e,t));return i.messageOrder.map(e=>i.messagesByID[e]).filter(e=>!!e)}var P=null,ja=``,Ma=null,Na=new Set,Pa=null,Fa=new Map,Ia=new Map;function La(e,t,n,r){P=t,Pa!==t&&(Pa=null,Fa=new Map,Ia=new Map),ja=n,r&&(Ma=r)}function Ra(e,t){Ma?.(e,t)}function za(){if(!P)throw Error(`ChildStoreManager not initialized — is SyncProvider mounted?`);return P}function Ba(e){let t=P;if(!t)return;let n=e||ja;if(n)return t.getState(n)}function Va(e){let t=Ba(e)?.config;return t&&Object.keys(t).length>0?t:void 0}function Ha(e){return Na.add(e),()=>{Na.delete(e)}}function Ua(e,t){if(e)for(let n of Na)n(e,t)}function Wa(e){return Ba(e)?.session??[]}function Ga(){return Array.from(Ka().values())}function Ka(){let e=P;if(!e)return Ia;let t=Pa!==e||Fa.size!==e.children.size;for(let[n,r]of e.children)if(Fa.get(n)!==r.getState().session){t=!0;break}if(!t)return Ia;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 Pa=e,Fa=n,Ia=r,Ia}function qa(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=A();if(P){for(let[i,a]of P.children)if(a.getState().session.some(t=>t.id===e)&&(n??Ii(i,a)).hasSession?.(j(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 Ja(e,t){if(!e)return[];try{let n=A(),r=t??ja;if(n){let t=n.getTranscript(j(r,e));return t.messageOrder.map(e=>t.messagesByID[e]).filter(e=>!!e)}if(P){let t=P.getChild(r);if(t){let n=Ii(r,t).getTranscript(j(r,e));return n.messageOrder.map(e=>n.messagesByID[e]).filter(e=>!!e)}}}catch{}return[]}function Ya(e,t){if(!e)return[];try{let n=A(),r=t??ja;if(n)return[...n.getParts(j(r,e),e)];if(P){let t=P.getChild(r);if(t)return[...Ii(r,t).getParts(j(r,e),e)]}}catch{}return[]}function Xa(e,t){return Ba(t)?.session_status[e]}var F=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},Za=`default`;function Qa(e){let t=F(e);if(t&&t!==Za)return t}function $a(e){let t=e?.model;return F(t?.id)??F(t?.modelID)}function eo(e){let t=e?.model;return F(t?.providerID)}function to(e){let t=e?.model;return Qa(t?.variant)}function no(e){let t=Qa(e.variant);return{id:e.modelID.trim(),providerID:e.providerID.trim(),...t?{variant:t}:{}}}function ro(e,t,n){let r=F(n.providerID),i=F(n.modelID);if(!r||!i)return{agent:F(n.agent)};let a=(Ba(t)?.session??Ga()).find(t=>t.id===e),o=no({providerID:r,modelID:i,variant:n.variant}),s=$a(a),c=eo(a),l=to(a),u=Qa(o.variant),d=!a||!s||!c||c!==o.providerID||s!==o.id||l!==u,f=F(n.agent),p=F(a?.agent);return{model:d?o:void 0,agent:f&&p!==f?f:void 0}}function io(e,t,n){if(e&&!(!n.model&&!n.agent))try{let r=za(),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 ao=new Set([`image/heic`,`image/heif`]),oo=!1,so=()=>{let e=globalThis.window?.Capacitor;return e&&typeof e==`object`?e:null},co=e=>ao.has((e.type||``).toLowerCase()),lo=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)},uo=(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})},fo=async e=>{if(!co(e)||oo)return null;let t=so();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 lo(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 uo(t.data,r)}catch(e){return oo=!0,console.warn(`Native HEIC transcode failed`,e),null}},po=e=>e.trim().toLowerCase(),mo=e=>e.source===`local`||e.source===`server`||e.source===`vscode`,ho=(e,t)=>{if(!e||!e.includes(`[`)||t.length===0)return[];let n=new Set(t.map(po)),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(po(i))&&r.push({start:t,end:a+1})}i=a+1}return r},go=(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}},_o=(e,t,n,r)=>{let i=ho(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}=go(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}},vo=new Set([`image`,`screenshot`,`screen-shot`,`clipboard`,`pasted-image`,`pastedimage`,`untitled`,`unknown`,`file`,`blob`]),yo={"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`},bo=e=>e.trim().toLowerCase(),xo=e=>e.charCodeAt(0)<32||`<>:"/\\|?*[]`.includes(e),So=e=>{let t=e.replace(/\\/g,`/`).split(`/`).pop()??``;return Array.from(t).map(e=>xo(e)?`-`:e).join(``).replace(/\s+/g,` `).replace(/-+/g,`-`).trim()},Co=e=>yo[e?.trim().toLowerCase()??``]??`png`,wo=e=>{let t=So(e.name),n=Co(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}},To=e=>{let{base:t}=wo({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(vo.has(n))return!0;let r=n.replace(/-\(\d+\)$/g,``);return r!==n&&vo.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Eo=(e,t)=>`${e}.${t}`,Do=(e,t,n)=>{let r=Eo(e,t);if(!n.has(bo(r)))return r;for(let r=2;r<2**53-1;r+=1){let i=Eo(`${e}-${r}`,t);if(!n.has(bo(i)))return i}return Eo(`${e}-${Date.now()}`,t)},Oo=(e,t)=>{for(let n=1;n<2**53-1;n+=1){let r=Eo(`image-${n}`,e);if(!Array.from(t).some(e=>e.startsWith(`image-${n}.`))&&!t.has(bo(r)))return r}return Eo(`image-${Date.now()}`,e)},ko=(e,t)=>{let n=new Set(t.map(bo));return e.map(e=>{let{base:t,ext:r}=wo(e),i=To(Eo(t,r))?Oo(r,n):Do(t,r,n);return n.add(bo(i)),i})},Ao=e=>e.map(e=>ie(e)).join(` `),jo=(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},Mo=(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}},No=(e,t,n)=>{if(e===t||n.length===0)return null;let r=[...n],i=Mo(e,t);if(i){let t=Wo(e,r,{key:`Backspace`,selectionStart:i.start,selectionEnd:i.end});if(t)return t}let a=jo(r,e,t);return a.length===0?null:{text:t,caret:t.length,removedFilenames:a}},Po=e=>e.replaceAll(`[${te}`,`[`),Fo=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|heic|heif|tiff?)$/i,Io=e=>{let t=e.trim();return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)},Lo=(e,t)=>{let n=e;for(let e of t){let t=e.filename.trim(),r=e.path.trim();if(!t||!r||t===r||Io(t)||!Fo.test(t)&&!Fo.test(r))continue;let i=`[${r}]`;n=n.split(ie(t)).join(i).split(`[${t}]`).join(i)}return n},Ro=(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},zo=e=>e.mime===`text/plain`&&typeof e.filename==`string`&&/:\d+(?:-\d+)?$/.test(e.filename),Bo=`application/x-directory`,Vo=e=>typeof e==`string`&&e.trim().toLowerCase()===`application/x-directory`,Ho=e=>typeof e==`string`&&/[/\\]$/.test(e.trim()),Uo=(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}},Wo=(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?Uo(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=ho(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())}},I=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}},Go=`file://`,Ko=e=>{let t=e.trim();if(t.toLowerCase().startsWith(Go))return t;let n=me(t).split(`/`).map(e=>/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`);return/^[A-Za-z]:/.test(n)?`${Go}/${n}`:`${Go}${n}`},qo=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(Go))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},Jo=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()))].map(e=>e.toString(16).padStart(2,`0`)).join(``),Yo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Xo=async e=>{let t;try{t=await e.json()}catch{throw new I(e.status,`unavailable`)}if(!Yo(t)||typeof t.path!=`string`||!t.path)throw new I(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:Ko(t.path),mime:n,size:r,sha256:i}},Zo=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}`},Qo=(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}},$o=e=>e.startsWith(`data:`)||e.startsWith(`blob:`),es=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 I(413,`too-large`);let r=await Jo(n),i=Zo(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 I(0,`unavailable`)}if(a.status===413)throw new I(413,`too-large`);if(!a.ok)throw new I(a.status,a.status>=500||a.status===0?`unavailable`:`rejected`);let o=await Xo(a);if(o.size!==n.size)throw new I(a.status,`unavailable`);return{...o,mime:t}},ts=500,ns=()=>{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}},rs=()=>ns(),L=(e,t)=>{if(!ns())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>ts&&window.__OPENCHAMBER_STARTUP_TRACE__.splice(0,window.__OPENCHAMBER_STARTUP_TRACE__.length-ts)};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 is=async(e,t,n)=>{let r=typeof performance<`u`?performance.now():Date.now();L(`${e}:start`,n);try{let n=await t(),i=typeof performance<`u`?performance.now():Date.now();return L(`${e}:end`,{durationMs:Math.round(i-r)}),n}catch(t){let n=typeof performance<`u`?performance.now():Date.now();throw L(`${e}:error`,{durationMs:Math.round(n-r),error:t instanceof Error?t.message:String(t)}),t}},as=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}),os=[],ss=[],R=new Map,cs=512,ls=0;function us(){return ls}function z(){return{transportIdentity:o(),generation:s()}}function ds(e){return o()===e.transportIdentity&&s()===e.generation}function fs(e,t,n){return`${n?.transportIdentity??o()}\0${n?.generation??s()}\0${e}\0${t}`}function ps(e=z()){if(R.size===0)return;let t=`${e.transportIdentity}\0${e.generation}\0`;for(let e of R.keys())e.startsWith(t)||R.delete(e);for(;R.size>cs;){let e=R.keys().next().value;if(e===void 0)break;R.delete(e)}}function ms(e,t,n,r){let i=r??z();ps(i),ls+=1,R.set(fs(e,t,i),{kind:n,mark:ls})}function hs(e,t,n){let r=n?.scope;ps(r??z());let i=R.get(fs(e,t,r));if(!i)return!0;let a=n?.startedMark;return a!==void 0&&i.mark>a?!1:(R.delete(fs(e,t,r)),!0)}function gs(e,t,n){return ps(n??z()),R.get(fs(e,t,n))?.kind??null}var _s=(e,t,n)=>{let r={...e};return n.length===0?delete r[t]:r[t]=n,r},B=oe((e,t)=>({bySession:{},remember(t){return!gs(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&&ms(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:_s(e.bySession,t,i)}})},forgetSession(t){e(e=>{if(!e.bySession[t])return e;let n={...e.bySession};return delete n[t],{bySession:n}})},forgetPromoted(t,n){let r=new Set(n);e(e=>{let n=e.bySession[t];if(!n?.length)return e;let i=new Set(n.filter(e=>r.has(e.id)).map(e=>e.id));if(i.size===0)return e;for(let e of i)ms(t,e,`consumed`);return{bySession:_s(e.bySession,t,n.filter(e=>!i.has(e.id)))}})},replaceFromAuthority(t,n,r){let i=r?.startedMark,a=[];for(let e of n)hs(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:_s(e.bySession,t,r)}})},updateDelivery(t,n,r){e(e=>{if(gs(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]??os}}));function vs(e){return B.getState().remember(e)}function ys(e,t){return hs(e.sessionID,e.id,t)?B.getState().remember(e):!1}function bs(e,t,n){B.getState().forget(e,t,n)}function xs(e,t){B.getState().forgetPromoted(e,t)}function Ss(e,t,n){B.getState().replaceFromAuthority(e,t,n)}function Cs(e,t,n){B.getState().updateDelivery(e,t,n)}function ws(e){return!!e&&typeof e==`object`&&e.kind===`session-inbox`}var Ts=e=>e?e.toLowerCase().includes(`application/json`):!1,Es=e=>e?e.toLowerCase().includes(`text/html`):!1;function V(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function H(e){return typeof e==`string`&&e.length>0?e:void 0}function Ds(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Os(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function ks(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 As(e){return e?{directory:e}:{}}function js(e,t){let n=`/api/session/${encodeURIComponent(e)}/inbox`;return t?`${n}/${encodeURIComponent(t)}`:n}async function Ms(e,t){let n=e.headers.get(`content-type`);if(Es(n))throw Error(`${t}: unexpected HTML response`);let r;try{r=await e.json()}catch{throw Error(`${t}: malformed JSON`)}if(!Ts(n)&&r==null)throw Error(`${t}: empty response`);return r}function Ns(e){let t=V(e)?e:null,n=t&&V(t.data)?t.data:t;if(!n)throw Error(`session prompt: expected inbox item`);let r=H(n.type);if(r&&r!==`user`)throw Error(`session prompt: expected user inbox item, got ${r}`);let i=H(n.id),a=H(n.sessionID);if(!i||!a)throw Error(`session prompt: inbox item missing id`);let o=V(n.payload)?n.payload:{},s=n.delivery===`queue`?`queue`:`steer`,c=V(n.time)?n.time:null;return{id:i,sessionID:a,timeCreated:Ds(n.timeCreated)??Ds(c?.created)??Date.now(),type:`user`,delivery:s,payload:{text:H(o.text)??H(n.text)??``,...o.files===void 0?{}:{files:o.files},...o.agents===void 0?{}:{agents:o.agents},...o.skills===void 0?{}:{skills:o.skills},...V(o.metadata)?{metadata:o.metadata}:{}}}}function Ps(e){let t=V(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)V(e)&&(e.type&&e.type!==`user`||r.push(Ns(e)));return r}function Fs(e){return{runtimeKey:c(),generation:s(),directory:e,overlay:z()}}function U(e){return c()===e.runtimeKey&&s()===e.generation&&ds(e.overlay)}function Is(e){let t=Error(`${e}: runtime switched`);throw t.name=`RuntimeGenerationMismatchError`,t}async function Ls(e){let t=e.commit??Fs(e.directory);U(t)||Is(`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(U(t)||Is(`session prompt`),!i.ok){let e=await ks(i);Os(`Failed to send message`,i.status,e)}let a=Ns(await Ms(i,`session prompt`));return U(t)||Is(`session prompt`),e.delivery===`queue`&&a.delivery!==`queue`?(vs({...a,delivery:`queue`}),Cs(a.sessionID,a.id,`steer`)):vs(a),a}function Rs(e){let t=e?.status;return typeof t!=`number`||!Number.isFinite(t)||t===408||t===429?!1:t>=400&&t<500}async function zs(e){let t=e.inputID.trim();if(!t)return{status:`unknown`};let n=e.commit??Fs(e.directory??``);if(!U(n))return{status:`unknown`};try{let r=await Vs({sessionID:e.sessionID,directory:n.directory||e.directory,signal:e.signal});if(!U(n)||!r.current)return{status:`unknown`};let i=r.items.find(e=>e.id===t);if(i)return ys(i,{startedMark:r.startedMark})?{status:`pending`,item:i}:{status:`unknown`}}catch{}if(!U(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(!U(n))return{status:`unknown`};if(r.records.some(e=>e?.info?.id===t))return bs(e.sessionID,t,`consumed`),{status:`promoted`,id:t}}catch{}return{status:`unknown`}}function Bs(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=H(n.sessionID),i=H(n.inboxID)??H(n.id);if(!r||!i)return!1;if(t===`session.inbox.enqueued`){let e=n.item,t=V(e)?H(e.type):void 0;if(t&&t!==`user`)return!1;try{return ys(Ns(V(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 bs(r,i,`cancelled`),!0;if(t===`session.inbox.delivered`)return bs(r,i,`consumed`),!0;if(t===`session.inbox.delivery.changed`){let e=n.delivery===`queue`?`queue`:n.delivery===`steer`?`steer`:null;return e?(Cs(r,i,e),!0):!1}return!1}async function Vs(e){let t=z(),n=us(),r=await u(js(e.sessionID),{method:`GET`,query:As(e.directory),signal:e.signal});r.ok||Os(`session inbox`,r.status,await ks(r));let i=await Ms(r,`session inbox`),a=Ps(i),o=ds(t);return o&&ht(e.sessionID,mt(i)),{items:a,startedMark:n,scope:t,current:o}}async function Hs(e){let t=z(),n=await u(js(e.sessionID,e.inboxID),{method:`PATCH`,headers:{"Content-Type":`application/json`},query:As(e.directory),body:JSON.stringify({delivery:e.delivery}),signal:e.signal});n.ok||Os(e.delivery===`steer`?`session inbox steer`:`session inbox queue`,n.status,await ks(n)),ds(t)&&(gs(e.sessionID,e.inboxID)||Cs(e.sessionID,e.inboxID,e.delivery))}async function Us(e){await Hs({...e,delivery:`steer`})}async function Ws(e){await Hs({...e,delivery:`queue`})}async function Gs(e){let t=await u(js(e.sessionID,e.inboxID),{method:`DELETE`,query:As(e.directory),signal:e.signal});t.ok||Os(`session inbox cancel`,t.status,await ks(t))}function Ks(e,t,n){Ss(e,t,n)}async function qs(e){let t=z();if(await Gs(e),!ds(t))return{overlay:B.getState().list(e.sessionID),transcriptRows:[]};bs(e.sessionID,e.inboxID,`cancelled`);try{let n=await Vs({sessionID:e.sessionID,directory:e.directory,signal:e.signal});if(!ds(t)||!n.current)return{overlay:B.getState().list(e.sessionID),transcriptRows:[]};Ks(e.sessionID,n.items,{startedMark:n.startedMark})}catch{}return{overlay:B.getState().list(e.sessionID),transcriptRows:[]}}async function Js(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 Ys(e){return e.promotedIDs.includes(e.optimisticID)?`confirmed`:(e.removeOptimistic(e.optimisticID),await e.refreshFromAuthority(),`refreshed`)}var Xs=`session-revert-busy`,Zs=e=>e?e.toLowerCase().includes(`text/html`):!1;function Qs(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function W(e){return typeof e==`string`&&e.length>0?e:void 0}function $s(e,t,n){if(t===409)throw ec();let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}function ec(){let e=Error(Xs);return e.name=`SessionRevertBusyError`,e}function tc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`SessionRevertBusyError`||t.message===`session-revert-busy`}async function nc(e){try{return(await e.text()).trim()}catch{return``}}async function rc(e,t){if(Zs(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 ic(e){return e?{directory:e}:{}}function ac(e,t){return`/api/session/${encodeURIComponent(e)}/revert/${t}`}function oc(e){let t=Qs(e)?e:null,n=t&&Qs(t.data)?t.data:t;if(!n)throw Error(`session revert: expected revert payload`);let r=W(n.messageID);if(!r)throw Error(`session revert: missing messageID`);let i=Array.isArray(n.files)?n.files.flatMap(e=>{if(!Qs(e))throw Error(`session revert: invalid file diff`);let t=W(e.file)??W(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,...W(n.partID)?{partID:W(n.partID)}:{},...W(n.snapshot)?{snapshot:W(n.snapshot)}:{},...i?{files:i}:{}}}function sc(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 cc(e){let t=await u(ac(e.sessionID,`stage`),{method:`POST`,headers:{"Content-Type":`application/json`},query:ic(e.directory),body:JSON.stringify({messageID:e.messageID,files:e.files!==!1}),signal:e.signal});return t.ok||$s(`session revert stage`,t.status,await nc(t)),oc(await rc(t,`session revert stage`))}async function lc(e){let t=await u(`/api/session/${encodeURIComponent(e.sessionID)}/revert`,{method:`DELETE`,query:ic(e.directory),signal:e.signal});t.ok||$s(`session revert clear`,t.status,await nc(t))}async function uc(e){let t=await u(ac(e.sessionID,`commit`),{method:`POST`,query:ic(e.directory),signal:e.signal});t.ok||$s(`session revert commit`,t.status,await nc(t))}var dc=e=>e?e.toLowerCase().includes(`text/html`):!1;function fc(e,t,n){let r=n?`: ${n}`:``,i=Error(`${e} (${t})${r}`);throw i.status=t,i}async function pc(e){try{return(await e.text()).trim()}catch{return``}}function mc(e){return e?{directory:e}:{}}function hc(e,t){return`/api/session/${encodeURIComponent(e)}/permission/${encodeURIComponent(t)}/reply`}async function gc(e){let t=await u(hc(e.sessionID,e.requestID),{method:`POST`,headers:{"Content-Type":`application/json`},query:mc(e.directory),body:JSON.stringify({decision:e.reply,...e.message?{message:e.message}:{}}),signal:e.signal});if(t.ok||fc(`session permission reply`,t.status,await pc(t)),t.status!==204&&dc(t.headers.get(`content-type`)))throw Error(`session permission reply: unexpected HTML response`)}function _c(e){let t=Error(`${e} is not available on OpenCode v2`);return t.name=`V2CapabilityUnavailableError`,t}function vc(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 yc(e){return{id:e.id,worktree:e.canonical,canonical:e.canonical,sandboxes:e.sandboxes,name:e.name}}function bc(e){return e.worktree||e.canonical||``}function xc(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 Sc(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 Cc(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.kind===`question`}function wc(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 Tc(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 Ec(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}:{}})):Tc(e),n=wc(e);return{id:e.id,sessionID:e.sessionID,questions:t,...n?{tool:n}:{}}}function Dc(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 Oc=3,kc=3e4,Ac=32e3,jc=36e5,Mc=6e5,Nc=new Set([429,502,503,504]),Pc=new Map;function Fc(){let e=Date.now();for(let[t,n]of Pc)n.consecutiveErrors===0&&e-n.lastErrorAt>jc&&Pc.delete(t)}typeof setInterval<`u`&&setInterval(Fc,Mc).unref?.();function Ic(e){let t=Pc.get(e);return t||(t={consecutiveErrors:0,lastErrorAt:0,circuitOpen:!1,circuitOpenAt:0,circuitCooldownMs:kc},Pc.set(e,t)),t}function Lc(e){if(!e)return;let t=Pc.get(e);t&&(t.consecutiveErrors=0,t.lastErrorAt=0)}function Rc(e,t){if(!e)return;let n=Ic(e);n.consecutiveErrors+=1,n.lastErrorAt=Date.now(),zc(t)&&n.consecutiveErrors>=Oc&&(n.circuitOpen=!0,n.circuitOpenAt=Date.now(),console.warn(`[provider-tracker] Circuit opened for ${e} after ${n.consecutiveErrors} consecutive errors`))}function zc(e){return e!==void 0&&Nc.has(e)}function Bc(e){let t=Pc.get(e);return t?.circuitOpen?Date.now()-t.circuitOpenAt>=t.circuitCooldownMs?(t.circuitOpen=!1,t.consecutiveErrors=0,t.circuitCooldownMs=Math.min(t.circuitCooldownMs*2,Ac*4),!1):!0:!1}function Vc(e){if(!(!e||!Bc(e)))throw Error(`Provider ${e} is temporarily unavailable after repeated errors. Please retry shortly.`)}var Hc=`/api`,Uc=1e4,Wc=4e3,Gc=3e3,Kc=1e3,qc=12e3;function Jc(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 Yc(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 Xc(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 Zc(e){let t=e.replace(/\/+$/,``);if(t.endsWith(`/api`)){let e=t.slice(0,-4);if(e.length>0)return e}return el(nl()||`/`)}function Qc(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 $c=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,el=e=>{let t=typeof e==`string`&&e.trim().length>0?e.trim():`/api`;if($c.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}},tl=()=>{try{return a().api(`/api`)}catch{return null}},nl=()=>{try{return a().api(`/`)}catch{return null}},rl=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)}},il=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)}}},al=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}}},ol=e=>al(de.make({baseUrl:e.baseUrl,...e.headers?{headers:e.headers}:{},fetch:u})),sl=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),cl=e=>{let t=[];for(let n of e){if(!sl(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=qo(r).trim();i&&t.push({filename:e,path:i})}return t},ll=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=>Lo(e,cl([...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},ul=e=>e.replace(/\\/g,`/`),dl=400,fl=()=>{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=Hc){let t=tl()||e;this.baseUrl=el(t),this.client=ol({baseUrl:Zc(this.baseUrl)})}getBaseUrl(){return this.baseUrl}reconnectToRuntimeBaseUrl(){let e=el(tl()||Hc);e!==this.baseUrl&&(this.baseUrl=e,this.client=ol({baseUrl:Zc(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=ol({baseUrl:Zc(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&&L(`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`),io(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`),io(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=Jc(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=Qo(t.url,t.mime);if(!n)return t;let r=await fo(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($o(a)){let e=Qo(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 es({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 ll(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=Fs(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(),U(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),Vc(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 Ls(n);return r(),e.id};try{let t=await s();return Lc(e.providerID),t}catch(t){if(r(),Rs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await zs({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Lc(e.providerID),i;try{let t=await s();return Lc(e.providerID),t}catch(t){if(r(),Rs(t)||t?.name===`RuntimeGenerationMismatchError`)throw t;let n=await zs({sessionID:e.id,directory:o.directory,inputID:i,commit:o});if(r(),n.status===`pending`||n.status===`promoted`)return Lc(e.providerID),i;throw t}}})}catch(t){throw Rc(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 Js({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 cc({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 lc({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 Xc(Yc(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 gc({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)||Yc(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: ${Jc(t)}`);return t.data.flatMap(e=>{let t=Qc(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:Dc(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: ${Jc(t)}`);return t.data.flatMap(e=>Cc(e.metadata)?[Ec({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 L(`opencodeClient.getConfig:cacheHit`,{directory:t??null}),r.config;let i=this.configInFlight.get(n);if(i)return L(`opencodeClient.getConfig:deduped`,{directory:t??null}),i;let a=this.configCacheGeneration,o=(async()=>{L(`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 L(`opencodeClient.getConfig:end`,{directory:t??null,durationMs:Math.round(o-e)}),a===this.configCacheGeneration&&this.configCache.set(n,{config:i,expiresAt:Date.now()+Uc}),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: ${Jc(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=rl(qc),r=il(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: ${Jc(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: ${Jc(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: ${Jc(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`;L(`opencodeClient.checkHealth:url`,{baseUrl:this.baseUrl,healthUrl:n});let r=rl(Wc),i=await u(n,{signal:r.signal}).finally(r.cleanup);if(L(`opencodeClient.checkHealth:response`,{status:i.status}),i.ok){let e=await i.json();L(`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?Gc:Kc)}),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=fl();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`?ul(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=fl();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:ul(e.path),isDirectory:!!e.isDirectory,isFile:!e.isDirectory,isSymbolicLink:!1}));return this.listDirectoryCache.set(n,{entries:a,expiresAt:Date.now()+dl}),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()+dl}),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?ul(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=ul(e.path),n=t.split(`/`).filter(Boolean).pop()||t;return{name:n,path:ul(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}}},pl=3e4,ml=40,hl=60,gl=(e,t,n,r,i,a)=>{let o=e.trim(),s=t.trim().toLowerCase();return JSON.stringify([o,s,n,r,i,a])},_l=(e,t)=>{try{let n=JSON.parse(e);return Array.isArray(n)&&n[0]===t}catch{return!1}},vl=oe()(se((e,t)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,i=hl,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=gl(o,s,i,c,l,u),f=Date.now(),p=t().cache[d];if(p&&f-p.timestamp<pl)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>ml;){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=>!_l(e,n)||(delete t[e],!1)),i=Object.entries(e.inFlight).filter(([e])=>!_l(e,n));return{cache:t,cacheKeys:r,inFlight:Object.fromEntries(i)}})}}),{name:`file-search-store`})),yl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`openchamber_stream_debug`)===`1`}catch{return!1}},bl=`openchamber_stream_perf`,xl=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(bl)===`1`}catch{return!1}},Sl=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),Cl=()=>{if(!xl()||typeof window>`u`)return null;if(!window.__openchamberStreamPerfState){let e=Date.now();window.__openchamberStreamPerfState={counters:new Map,startedAt:e,lastUpdatedAt:e}}return window.__openchamberStreamPerfState},wl=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),Tl=(e,t)=>{let n=Cl();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()},El=e=>{if(!(typeof window>`u`))try{if(e){window.localStorage.setItem(bl,`1`),window.__openchamberStreamPerfState={counters:new Map,startedAt:Date.now(),lastUpdatedAt:Date.now()};return}window.localStorage.removeItem(bl),delete window.__openchamberStreamPerfState,delete window.__openchamberVsCodeStreamPerfState}catch{}},Dl=()=>{typeof window>`u`||(xl()&&(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()}))},Ol=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberStreamPerfState;return!xl()||!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:wl(e.counters)}},kl=()=>{if(typeof window>`u`)return{enabled:!1,startedAt:null,lastUpdatedAt:null,durationMs:0,entries:[]};let e=window.__openchamberVsCodeStreamPerfState;if(!xl()||!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:wl(e.counters)}},Al=(e,t=1)=>{Tl(e,t)},jl=(e,t)=>{Tl(e,t)},Ml=(e,t)=>{if(!xl())return t();let n=Sl();try{return t()}finally{Tl(e,Sl()-n)}},J=null,Nl=0,Y=fe(),Pl=f(`lastDirectory`,{storage:Y}),Fl=typeof Pl==`string`&&Pl.length>0,Il=e=>{try{vl.getState().invalidateDirectory(e)}catch(e){console.warn(`Failed to invalidate file search cache:`,e)}},Ll=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},Rl=(e,t)=>{let n=e.trim();return n.startsWith(`~`)?n===`~`?t||n:(n.startsWith(`~/`)||n.startsWith(`~\\`))&&t?`${t}${n.slice(1)}`:n:n},zl=(e,t)=>Ll(Rl(e,t)),Bl=()=>{let e=f(`homeDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=Ll(e);return t.length>0?t:null},Vl=()=>{let e=f(`lastDirectory`,{storage:Y});if(typeof e!=`string`||e.trim().length===0)return null;let t=Ll(e);return t.length>0?t:null},Hl=()=>{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=Ll(t);return e.length>0?e:null}let n=process?.cwd?.();if(typeof n==`string`&&n.trim().length>0){let e=Ll(n);return e.length>0?e:null}return null},Ul=()=>{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=Bl();if(t&&!ee())return J=t,t}return Hl()||`/`},Wl=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},Gl=e=>(J=e,typeof window<`u`&&ae(`homeDirectory`,e,{storage:Y}),ne({homeDirectory:e}),e),Kl=async()=>{let e=e=>{let t=Wl(e);return t?Gl(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=Ul();return e(t)||t},ql=(()=>{if(!ee())return null;let e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!=`string`||e.trim().length===0)return null;let t=Ll(e);return t.length>0?t:null})()||Ul(),Jl=(()=>{let e=Vl();return e&&!ee()?zl(e,ql):ql})();Jl&&q.setDirectory(Jl);var Yl=!!(ql&&ql!==`/`),Xl=oe()(se((e,t)=>({currentDirectory:Jl,directoryHistory:[Jl],historyIndex:0,homeDirectory:ql,hasPersistedDirectory:Fl,isHomeReady:Yl,isSwitchingDirectory:!1,setDirectory:(n,r)=>{let i=zl(n,J||t().homeDirectory||f(`homeDirectory`,{storage:Y}));yl(),ge(t().currentDirectory,i)&&(q.setDirectory(i),Il(),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),Il(),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),Il(),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||Ul())||e===`/`)return;let r=e.endsWith(`/`)?e.slice(0,-1):e,i=r.lastIndexOf(`/`);n(i===-1?J||Ul():i===0?`/`:r.substring(0,i))},goHome:async()=>{let e=J||t().homeDirectory||await Kl();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?zl(r.currentDirectory,i):r.currentDirectory,d=r.directoryHistory.map(e=>zl(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),Il(),ae(`lastDirectory`,e,{storage:Y}),ne({lastDirectory:e})}ne({homeDirectory:i})}}),{name:`directory-store`}));typeof window<`u`&&(Kl().then(e=>{Xl.getState().synchronizeHomeDirectory(e)}),i(e=>{J=null;let t=++Nl;if(l(e)){let e=Bl(),t=Vl(),n=e||`/`,r=t||n;J=e,Xl.setState({currentDirectory:r,directoryHistory:[r],historyIndex:0,homeDirectory:n,hasPersistedDirectory:!!t,isHomeReady:!!(e&&e!==`/`),isSwitchingDirectory:!1}),r&&(q.setDirectory(r),Il())}Kl().then(e=>{t===Nl&&Xl.getState().synchronizeHomeDirectory(e)})}));var Zl=(e,i)=>{let a=t();return a?a.openWebSocket(r(e),i):n(i?new WebSocket(e,i):new WebSocket(e))},X=`/api/git`,Ql=1200,$l=5e3,eu=2,tu=5e3,nu=`${X}/worktrees/queue-activation`,ru=`message_queue_activation_pending`,iu=`worktree_lifecycle_busy`,au=`worktree_activation_stale`,ou=5e3,su=3e4,cu=[0,500,1e3,2e3,4e3,8e3,14e3],lu=new Map,uu=new Map,du=new Map,fu=new Map,pu=new Map,mu=new Map,hu=new Map,gu=new Map,_u=new Map,vu=new Map,yu=new Set,bu=0,xu=[],Su=()=>bu<eu?(bu+=1,Promise.resolve()):new Promise(e=>{xu.push(e)}),Cu=()=>{let e=xu.shift();if(e){e();return}bu=Math.max(0,bu-1)},wu=async e=>{await Su();try{return await e()}finally{Cu()}},Tu=Symbol.for(`openchamber.git.discoveryGated`),Eu=e=>(Object.defineProperty(e,Tu,{value:!0,configurable:!0}),e),Du=e=>typeof e==`function`&&e[Tu]===!0,Z=e=>e.trim(),Ou=(e,t)=>t===`light`?`${Z(e)}::light`:Z(e),ku=e=>du.get(Z(e))??0,Q=e=>{let t=Z(e);du.set(t,ku(e)+1);for(let e of Array.from(lu.keys()))(e===t||e.startsWith(`${t}::`))&&lu.delete(e);for(let e of Array.from(uu.keys()))(e===t||e.startsWith(`${t}::`))&&uu.delete(e)},Au=e=>vu.get(Z(e))??0,ju=e=>{let t=Z(e);t&&(vu.set(t,Au(e)+1),gu.delete(t),_u.delete(t))};function $(e,t,n){let r={...n};return t&&(r.directory=t),a().api(e,r)}var Mu=(e,t,n)=>{let r=Z(e);if(!r)return;let i=Date.now()+tu;fu.set(r,{value:t,expiresAt:i});let a=typeof n==`string`&&n?n:e;mu.set(r,{value:{root:a},expiresAt:i})};async function Nu(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=fu.get(e),a=mu.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;Mu(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([Pu(e),Iu(e).then(e=>e.root).catch(()=>e)]);Mu(e,t,t?r:null),n.set(e,{isGitRepository:t,primaryRoot:t?r:null})}catch{Mu(e,!1,null),n.set(e,{isGitRepository:!1,primaryRoot:null})}}))};try{await wu(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 Pu(e){let t=Z(e),n=Date.now(),r=fu.get(t);if(r&&r.expiresAt>n)return r.value;let i=pu.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 fu.set(t,{value:r,expiresAt:Date.now()+$l}),r})();pu.set(t,a);try{return await a}finally{pu.get(t)===a&&pu.delete(t)}}async function Fu(e,t){let n=t?.mode,r=Ou(e,n),i=Date.now(),a=lu.get(r);if(a&&a.expiresAt>i)return a.value;let o=uu.get(r);if(o)return o;let s=(async()=>{let t=ku(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 ku(e)===t&&lu.set(r,{value:a,expiresAt:Date.now()+Ql}),a})();uu.set(r,s);try{return await s}finally{uu.get(r)===s&&uu.delete(r)}}async function Iu(e){let t=Z(e),n=Date.now(),r=mu.get(t);if(r&&r.expiresAt>n)return r.value;let i=hu.get(t);if(i)return i;let a=wu(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 mu.set(t,{value:i,expiresAt:Date.now()+tu}),i});hu.set(t,a);try{return await a}finally{hu.get(t)===a&&hu.delete(t)}}async function Lu(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 Ru(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 zu(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 Bu(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 Vu(e,t){await Hu(e,[t])}async function Hu(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 Uu(e,t){await Wu(e,[t])}async function Wu(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 Gu(e,t,n){await Ju(e,t,n,`stage`)}async function Ku(e,t,n){await Ju(e,t,n,`unstage`)}async function qu(e,t,n){await Ju(e,t,n,`discard`)}async function Ju(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 Yu(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 Xu(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 Zu(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 Qu(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 $u(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 ed(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 td(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 nd(e){let t=Z(e),n=Date.now(),r=gu.get(t);if(r&&r.expiresAt>n)return r.value;let i=_u.get(t);if(i)return i;let a=Au(e),o=wu(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===Au(e)&&gu.set(t,{value:r,expiresAt:Date.now()+tu}),r});_u.set(t,o);try{return await o}finally{_u.get(t)===o&&_u.delete(t)}}Eu(nd);async function rd(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 id(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 ad(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 od=e=>typeof e==`string`&&e.length>0,sd=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(!od(t.name)||!od(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},cd=(e,t,n)=>{if(e!==503||!t||typeof t!=`object`)return null;let r=t;if(r.code!==ru)return null;let i=sd(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!==nu)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},ld=(e,t,n,r)=>`${e}\u0000${t}\u0000${n}\u0000${r}`,ud=e=>new Promise(t=>{setTimeout(t,e)}),dd=async e=>{if(e.status===409){let t=await e.json().catch(()=>null);return t?.code===iu||t?.code===au}return e.status===503&&(await e.json().catch(()=>null))?.code===ru},fd=e=>e===400||e===401||e===403||e===501,pd=(e,t)=>{let n=o(),r=s(),i=ld(n,r,e,t);if(yu.has(i))return;yu.add(i);let a=()=>o()===n&&s()===r;(async()=>{let n=Date.now(),r=0;for(;Date.now()-n<su;){if(!a())return;let i=cu[Math.min(r,cu.length-1)]??0;if(i>0){let e=su-(Date.now()-n);if(e<=0||(await ud(Math.min(i,e)),!a()))return}let o=new AbortController,s=setTimeout(()=>o.abort(),ou);try{let n=await u($(nu,void 0),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectDirectory:e,directory:t}),signal:o.signal});if(n.ok||fd(n.status))return;if(await dd(n)){r+=1;continue}return}catch{r+=1}finally{clearTimeout(s)}}})().catch(()=>{}).finally(()=>{yu.delete(i)})};async function md(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=sd(r);if(t)return ju(e),t;if(r&&typeof r==`object`)return ju(e),r;throw Error(`Failed to create worktree`)}let i=cd(n.status,r,e);if(i)return ju(e),pd(e,i.path),i;let a=r&&typeof r==`object`?r:{error:n.statusText};throw Error(a.error||`Failed to create worktree`)}async function hd(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 ju(e),r}async function gd(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 _d(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 vd(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 yd(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 bd(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 xd(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 Sd(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 Cd=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()},wd=(e,t)=>Cd(e,`stash/apply`,t),Td=(e,t)=>Cd(e,`stash/pop`,t),Ed=(e,t)=>Cd(e,`stash/drop`,t);async function Dd(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 Od(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 kd(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 Ad(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 jd(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 Md(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 Nd(){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 Pd(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 Fd(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 Id(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 Ld(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 Rd(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 zd(){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 Bd(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 Vd(){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 Hd(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 Ud(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 Wd(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 Gd(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 Kd(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 qd(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 Jd(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 Yd(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 Xd(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 Zd(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 Qd(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 $d(e,t){return await Sd(e,{message:t?.message}),{success:!0}}async function ef(e){return await Td(e,{ref:`stash@{0}`}),{success:!0}}async function tf(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 nf(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 rf(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 af=()=>typeof window>`u`?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol===`capacitor:`,of=()=>{if(typeof window>`u`||!af()||sf()!==`ios`)return!1;let e=navigator.userAgent||``,t=navigator.maxTouchPoints??0;return/iPad/i.test(e)||/Macintosh|MacIntel/i.test(e)&&t>1},sf=()=>{if(typeof window<`u`){let e=window.Capacitor?.getPlatform?.();if(e===`ios`||e===`android`)return e}return ee()?`vscode`:re()?`desktop`:`web`};export{Ud as $,_a as $n,An as $r,Vs as $t,tf as A,Se as Ai,mo as An,Ti as Ar,Ml as At,Hd as B,Ya as Bn,Vr as Br,Ec as Bt,Vd as C,Xe as Ci,zo as Cn,Hi as Cr,Xl as Ct,td as D,we as Di,Wo as Dn,ji as Dr,El as Dt,ed as E,Te as Ei,No as En,Vi as Er,Dl as Et,Nd as F,_e as Fi,Ga as Fn,Ur as Fr,Dc as Ft,ju as G,La as Gn,wr as Gr,lc as Gt,vd as H,Wa as Hn,Cr as Hr,_c as Ht,Ad as I,be as Ii,Ba as In,qr as Ir,Cc as It,bd as J,sa as Jn,Fn as Jr,sc as Jt,Du as K,Ha as Kn,xr as Kr,uc as Kt,Fu as L,za as Ln,Nr as Lr,vc as Lt,Xu as M,xe as Mi,ro as Mn,vi as Mr,vl as Mt,Ru as N,ve as Ni,Ua as Nn,Lr as Nr,q as Nt,Md as O,De as Oi,Po as On,j as Or,yl as Ot,zu as P,ye as Pi,Ka as Pn,Br as Pr,xc as Pt,ad as Q,ra as Qn,zn as Qr,Ys as Qt,id as R,Va as Rn,Pr as Rr,Sc as Rt,Qu as S,Ne as Si,Ro as Sn,Gi as Sr,Zl as St,Ed as T,je as Ti,Ho as Tn,Ii as Tr,kl as Tt,_d as U,Ra as Un,Sr as Ur,gc as Ut,yd as V,Xa as Vn,Ar as Vr,bc as Vt,Rd as W,qa as Wn,Tr as Wr,tc as Wt,Gd as X,Aa as Xn,Cn as Xr,Gs as Xt,nd as Y,va as Yn,Pn as Yr,Bs as Yt,Td as Z,ia as Zn,In as Zr,qs as Zt,Pd as _,ut as _i,rs as _n,Wi as _r,Ku as _t,Wd as a,En as ai,xs as an,xa as ar,Jd as at,Id as b,Pe as bi,Ao as bn,Li as br,nf as bt,Pu as c,mn as ci,ds as cn,oa as cr,Bd as ct,qd as d,dn as di,ys as dn,qi as dr,Gu as dt,Rn as ei,Js as en,ha as er,$u as et,Qd as f,Vt as fi,as as fn,Ki as fr,$d as ft,gd as g,gt as gi,is as gn,zi as gr,Wu as gt,Od as h,ft as hi,L as hn,Bi as hr,Uu as ht,Xd as i,bn as ii,z as in,da as ir,Lu as it,Ld as j,v as ji,_o as jn,_i as jr,jl as jt,jd as k,Ee as ki,ho as kn,Pi as kr,Al as kt,Dd as l,gn as li,ws as ln,Xi as lr,Vu as lt,xd as m,Rt as mi,B as mn,Ni as mr,ef as mt,af as n,Sn as ni,Us as nn,la as nr,Yd as nt,wd as o,Dn as oi,bs as on,Oa as or,Bu as ot,Zd as p,nn as pi,Cs as pn,Ri as pr,Sd as pt,Yu as q,ca as qn,hr as qr,cc as qt,of as r,xn as ri,ss as rn,ya as rr,Iu as rt,rf as s,wn as si,gs as sn,Ca as sr,qu as st,sf as t,Ln as ti,Ws as tn,Ea as tr,kd as tt,Kd as u,an as ui,vs as un,Ji as ur,Hu as ut,md as v,et as vi,Bo as vn,A as vr,Fd as vt,Nu as w,tt as wi,Vo as wn,Fi as wr,Ol as wt,hd as x,Ve as xi,jo as xn,Ui as xr,wu as xt,Zu as y,Qe as yi,ko as yn,Mi as yr,rd as yt,zd as z,Ja as zn,Wr as zr,yc as zt};
|