@openchambery/web 1.19.0-beta.20 → 1.19.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/AgentAvatar-mwB5XUVi.js +1 -0
- package/dist/assets/{AssistantView-DTY0uClL.js → AssistantView-C7mpM6eZ.js} +1 -1
- package/dist/assets/{ChatContainer-lf6PJ6pZ.js → ChatContainer-obK8ZBxN.js} +41 -40
- package/dist/assets/{ContextPanel-Dt-wKUkr.js → ContextPanel-zp0wnzQr.js} +7 -7
- package/dist/assets/{DiagramView-CFM5yMXi.js → DiagramView-D_UgqMBZ.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-DeZNYLiU.js → MarkdownRendererImpl-BWsesd63.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-4n5esfc-.js → MobileDetailNavigation-CsyOt6sI.js} +1 -1
- package/dist/assets/{MobileShareBridge-BE8HQDQz.js → MobileShareBridge-xFcAYp5Y.js} +1 -1
- package/dist/assets/{MobileSurface-DQMXgHi-.js → MobileSurface-BDXyT5lH.js} +1 -1
- package/dist/assets/{MultiRunWindow-B7g3pbE3.js → MultiRunWindow-VNCTQxir.js} +1 -1
- package/dist/assets/{OnboardingScreen-CzxsmiJZ.js → OnboardingScreen-C0DduEDx.js} +1 -1
- package/dist/assets/OverlayScrollbar-BR0ifid5.js +2 -0
- package/dist/assets/{SettingsView-xsK-pu7I.js → SettingsView-dSH_LSe8.js} +8 -8
- package/dist/assets/{SettingsWindow-BuUvqJ7R.js → SettingsWindow-DTuDa8VV.js} +1 -1
- package/dist/assets/{TerminalView-BmplPryl.js → TerminalView-DqHOdqxB.js} +1 -1
- package/dist/assets/{ToolOutputDialog-WziQTumo.js → ToolOutputDialog-KSB9plm-.js} +4 -4
- package/dist/assets/appThemeRegistry-DcWBea7B.js +2 -0
- package/dist/assets/{clipboard-DyCy8o-j.js → clipboard-C7zcAKyC.js} +1 -1
- package/dist/assets/dialog-D1Ng5yQe.js +1 -0
- package/dist/assets/{es-L71xM_T9.js → es-CcbKrwi9.js} +1 -1
- package/dist/assets/{fr-DDeqVFFE.js → fr-D1YIDHP6.js} +1 -1
- package/dist/assets/{gitApi-DkCXX5jR.js → gitApi-DGNLIAdE.js} +1 -1
- package/dist/assets/{insertionBoundaries-CQybmLB1.js → insertionBoundaries-DXyrsxRu.js} +1 -1
- package/dist/assets/{ja-Cb5UuJfO.js → ja-xE7L_-ZU.js} +1 -1
- package/dist/assets/{ko-BOQuwJW9.js → ko-QUUzIgbd.js} +1 -1
- package/dist/assets/{main-CXMA3Lla.js → main-CRpXQ6WZ.js} +6 -6
- package/dist/assets/{main-D4Jdy0hL.js → main-DYLq9MqL.js} +2 -2
- package/dist/assets/{miniChat-B745kvGv.js → miniChat-Ivb2We5Z.js} +2 -2
- package/dist/assets/{mobile-DVgUFTgs.js → mobile-DPV00pm2.js} +2 -2
- package/dist/assets/multirun-CLWktezk.js +4 -0
- package/dist/assets/{pl-CPR51X8e.js → pl-BQfz-_HE.js} +1 -1
- package/dist/assets/platform-ulFAVx1H.js +2 -0
- package/dist/assets/projectMeta-CGWgdtzY.js +3 -0
- package/dist/assets/{pt-BR-CCmlB4Wg.js → pt-BR-DaY3UW5q.js} +1 -1
- package/dist/assets/radio-BJ-X57r_.js +1 -0
- package/dist/assets/{renderElectronMiniChatApp-CGMVL3Ys.js → renderElectronMiniChatApp-DR5AYWAI.js} +2 -2
- package/dist/assets/renderMobileApp-BtLrFYfl.js +23 -0
- package/dist/assets/{runtimeConfig-saxbdlQ4.js → runtimeConfig-DCTxn3UZ.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-Cu3_ziCo.js → runtimeEndpointReset-BEH1It6F.js} +2 -2
- package/dist/assets/{shikiHighlight-CMeJJlmK.js → shikiHighlight-D_nH5nU9.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-1_gUDGL6.js → sortable-tabs-strip-BsIz5zKp.js} +1 -1
- package/dist/assets/{src-Brv0DCpZ.css → src-Dlj9wgET.css} +1 -1
- package/dist/assets/{store--ZgdDfa2.js → store-upwbPNfx.js} +2 -2
- package/dist/assets/{terminalApi-B36I-z14.js → terminalApi-HsIEks5U.js} +1 -1
- package/dist/assets/{uk-DWxkhZMt.js → uk-yWcUag_v.js} +1 -1
- package/dist/assets/{useAppFontEffects-DgsMZYcE.js → useAppFontEffects-CVy0YR-R.js} +2 -2
- package/dist/assets/{useDesktopWindowControlsLayout-DYhh2xv2.js → useDesktopWindowControlsLayout-Bk1__c3_.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-e5Lo-_80.js → useEffectiveDirectory-D71yjOxf.js} +1 -1
- package/dist/assets/{useFontPreferences-D9h4M7x4.js → useFontPreferences-DaFspdDd.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-C0HJyjhV.js → useMobileNavigationStore-CBHZdTh6.js} +8 -8
- package/dist/assets/{useSessionAutoCleanup-B_NyRYz6.js → useSessionAutoCleanup-BHDVDveQ.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-CZINylU6.js → useWorkerHighlightedLines-C37YlH2o.js} +1 -1
- package/dist/assets/{zh-CN-CnBbxYt8.js → zh-CN-jktTX6F0.js} +1 -1
- package/dist/assets/{zh-TW-B6McpMc8.js → zh-TW-DS3LNe1V.js} +1 -1
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +1 -1
- package/dist/assets/AgentAvatar-CWn_73qY.js +0 -1
- package/dist/assets/OverlayScrollbar-Cx1Gzt7g.js +0 -2
- package/dist/assets/appThemeRegistry-YEW4aNBC.js +0 -2
- package/dist/assets/dialog-BpUGcA8h.js +0 -1
- package/dist/assets/multirun-Bcdynrz8.js +0 -4
- package/dist/assets/platform-DxNH_0Fj.js +0 -2
- package/dist/assets/projectMeta-BE3RLLLp.js +0 -3
- package/dist/assets/radio-D7SyEJSZ.js +0 -1
- package/dist/assets/renderMobileApp-DWwtGDBn.js +0 -23
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as e,U as t}from"./useUIStore-Wyu09VUF.js";import{kn as n}from"./persistence-aCOlo6ew.js";import{St as r}from"./platform-DxNH_0Fj.js";var i=1,a=1,o=0,s=`/api/terminal/ws`,c=1200,l=250,u=2e4,d=5e3,f=`__openchamberTerminalTransportState`,p=new TextEncoder,m=new TextDecoder,h=t=>e().websocket(t),g=e=>{let t=p.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=i,n.set(t,1),n},_=e=>e?((e.transports??[]).includes(`ws`)||e.preferred===`ws`)&&typeof e.ws?.path==`string`&&e.ws.path.length>0:!1,v=e=>e.streamCapability?.ws?.path??e.inputCapability?.ws?.path??s,y=e=>{switch(e){case`SESSION_NOT_FOUND`:return Error(`Terminal session not found`);case`NOT_BOUND`:return Error(`Terminal session is not bound`);case`WRITE_FAIL`:return Error(`Failed to write to terminal`);case`RATE_LIMIT`:return Error(`Terminal websocket is rate limited`);case`BAD_FRAME`:return Error(`Terminal websocket protocol violation`);default:return Error(`Terminal websocket error`)}},b=class{socket=null;socketUrl=``;boundSessionId=null;requestedSessionId=null;openPromise=null;reconnectTimeout=null;keepaliveInterval=null;closed=!1;subscriptions=new Map;activeSubscriptionToken=null;replayCursorBySession=new Map;configure(e){if(e){if(this.socketUrl===e){this.closed=!1,this.isConnectedOrConnecting()||this.ensureConnected();return}this.socketUrl=e,this.closed=!1,this.resetConnection(),this.ensureConnected()}}subscribe(e,t,n,r){let i=Symbol(e),o={token:i,sessionId:e,onEvent:t,onError:n,maxRetries:r?.maxRetries??3,initialRetryDelay:r?.initialRetryDelay??1e3,maxRetryDelay:r?.maxRetryDelay??8e3,connectionTimeout:r?.connectionTimeout??1e4,retryCount:0,connected:!1,connectionTimeoutId:null};return this.subscriptions.set(i,o),this.activeSubscriptionToken=i,this.requestedSessionId=e,this.ensureConnected(),this.boundSessionId===e&&this.socket&&this.socket.readyState===a?(o.retryCount=0,o.connected=!0,o.onEvent({type:`connected`})):(this.boundSessionId=null,this.startConnectionTimeout(o),this.bindActiveSession()),()=>{if(this.clearConnectionTimeout(o),this.subscriptions.delete(i),this.activeSubscriptionToken===i&&(this.activeSubscriptionToken=null),this.hasSubscriptionForSession(e)||(this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null)),this.subscriptions.size===0){this.clearReconnectTimeout(),this.resetConnection();return}this.promoteActiveSubscription()}}async sendInput(e,t){if(!e||!t||this.closed||!this.socketUrl)return!1;let n=await this.getOpenSocket(c);if(!n||n.readyState!==a)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,n.send(g({t:`b`,s:e,r:this.replayCursorBySession.get(e)??0,v:2}))),n.send(t),!0}catch{return this.handleSocketFailure(Error(`Terminal websocket send failed`)),!1}}unbindSession(e){e&&(this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null))}close(){this.closed=!0,this.clearReconnectTimeout();for(let e of this.subscriptions.values())this.clearConnectionTimeout(e);this.resetConnection(),this.socketUrl=``,this.subscriptions.clear(),this.activeSubscriptionToken=null,this.replayCursorBySession.clear()}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(e){return this.closed||e&&this.socketUrl!==e?!1:this.socket&&(this.socket.readyState===a||this.socket.readyState===o)?!0:this.openPromise!==null}getActiveSubscription(){return this.activeSubscriptionToken?this.subscriptions.get(this.activeSubscriptionToken)??null:null}hasSubscriptionForSession(e){for(let t of this.subscriptions.values())if(t.sessionId===e)return!0;return!1}promoteActiveSubscription(){if(this.getActiveSubscription())return;let e=this.subscriptions.values().next().value;if(!e){this.activeSubscriptionToken=null;return}this.activeSubscriptionToken=e.token,this.requestedSessionId=e.sessionId,this.boundSessionId===e.sessionId?e.connected||(e.retryCount=0,e.connected=!0,this.clearConnectionTimeout(e),e.onEvent({type:`connected`})):(this.boundSessionId=null,this.startConnectionTimeout(e),this.bindActiveSession())}emitToSession(e,t){for(let n of this.subscriptions.values())n.sessionId===e&&n.onEvent(t)}markSessionConnected(e,t){for(let n of this.subscriptions.values())n.sessionId===e&&(n.retryCount=0,n.connected=!0,this.clearConnectionTimeout(n),n.onEvent(t))}emitErrorToSession(e,t,n){for(let r of this.subscriptions.values())r.sessionId===e&&(r.connected=!1,n&&this.clearConnectionTimeout(r),r.onError?.(t,n))}startConnectionTimeout(e){this.clearConnectionTimeout(e),e.connectionTimeoutId=setTimeout(()=>{e.connected||!this.subscriptions.has(e.token)||this.getActiveSubscription()?.token===e.token&&this.handleSocketFailure(Error(`Connection timeout`))},e.connectionTimeout)}clearConnectionTimeout(e){e.connectionTimeoutId&&=(clearTimeout(e.connectionTimeoutId),null)}async getOpenSocket(e){if(this.socket&&this.socket.readyState===a||(this.ensureConnected(),this.socket&&this.socket.readyState===a))return this.socket;let t=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(t=>{setTimeout(()=>t(null),e)})]);return t&&t.readyState===a?t:this.socket&&this.socket.readyState===a?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===a||this.socket.readyState===o)||(this.openPromise||=(this.clearReconnectTimeout(),(async()=>{try{await t()}catch{}return new Promise(e=>{let t=!1,n=null,i=r=>{t||(t=!0,n&&=(clearTimeout(n),null),this.openPromise=null,e(r))};try{let e=r(h(this.socketUrl));e.binaryType=`arraybuffer`,e.onopen=()=>{this.socket=e,this.startKeepalive(),i(e)},e.onmessage=e=>{this.handleSocketMessage(e.data)},e.onerror=()=>{!this.closed&&!this.getActiveSubscription()&&this.scheduleReconnect(Error(`Terminal websocket error`))},e.onclose=()=>{this.socket===e&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect(Error(`Terminal stream connection error`))),i(null)},this.socket=e,n=setTimeout(()=>{e.readyState===o&&(e.close(),i(null))},d)}catch{i(null),this.closed||this.scheduleReconnect(Error(`Terminal websocket open failed`))}})})()))}bindActiveSession(){let e=this.getActiveSubscription();if(!(!e||!this.socket||this.socket.readyState!==a)){this.requestedSessionId=e.sessionId;try{this.socket.send(g({t:`b`,s:e.sessionId,r:this.replayCursorBySession.get(e.sessionId)??0,v:2}))}catch{this.handleSocketFailure(Error(`Terminal websocket bind failed`))}}}scheduleReconnect(e){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;this.promoteActiveSubscription();let t=this.getActiveSubscription();if(!t)return;let n=t.retryCount+1,r=t.initialRetryDelay,i=t.maxRetryDelay,a=t.maxRetries;if(n>a){this.clearConnectionTimeout(t),this.emitErrorToSession(t.sessionId,e,!0);return}t.retryCount=n;for(let e of this.subscriptions.values())e.sessionId===t.sessionId&&(e.connected=!1,e.retryCount=n,e.onEvent({type:`reconnecting`,attempt:n,maxAttempts:a}));this.startConnectionTimeout(t);let o=Math.min(r*2**Math.max(n-1,0),i)+Math.floor(Math.random()*l);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},o)}clearReconnectTimeout(){this.reconnectTimeout&&=(clearTimeout(this.reconnectTimeout),null)}sendControl(e){if(!this.socket||this.socket.readyState!==a)return!1;try{return this.socket.send(g(e)),!0}catch{return this.handleSocketFailure(Error(`Terminal websocket control send failed`)),!1}}startKeepalive(){this.stopKeepalive(),this.keepaliveInterval=setInterval(()=>{this.closed||this.sendControl({t:`p`,v:2})},u)}stopKeepalive(){this.keepaliveInterval&&=(clearInterval(this.keepaliveInterval),null)}async handleSocketMessage(e){let t=await this.asUint8Array(e);if(t&&t.length>0&&t[0]===i){this.handleControlMessage(t);return}let n=await this.asText(e);if(!n)return;let r=this.boundSessionId??this.requestedSessionId??this.getActiveSubscription()?.sessionId;r&&this.emitToSession(r,{type:`data`,data:n})}handleControlMessage(e){if(e.length<2)return;let t;try{t=JSON.parse(m.decode(e.subarray(1)))}catch{this.handleSocketFailure(Error(`Terminal websocket control parse failed`));return}let n=this.getActiveSubscription();switch(t.t){case`ok`:this.bindActiveSession();return;case`po`:return;case`d`:{let e=t.s??this.boundSessionId??this.requestedSessionId;if(!e)return;typeof t.i==`number`&&Number.isFinite(t.i)&&this.replayCursorBySession.set(e,Math.max(this.replayCursorBySession.get(e)??0,Math.trunc(t.i))),typeof t.d==`string`&&t.d.length>0&&this.emitToSession(e,{type:`data`,data:t.d});return}case`bok`:{let e=t.s??this.requestedSessionId;if(this.boundSessionId=e,!e)return;this.markSessionConnected(e,{type:`connected`,runtime:t.runtime,ptyBackend:t.ptyBackend});return}case`x`:{let e=t.s??this.boundSessionId??n?.sessionId??null;if(!e){this.boundSessionId=null;return}this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null),this.replayCursorBySession.delete(e);for(let n of this.subscriptions.values())n.sessionId===e&&(n.connected=!1,this.clearConnectionTimeout(n),n.onEvent({type:`exit`,exitCode:t.exitCode,signal:t.signal??null}));return}case`e`:{let e=y(t.c),r=t.f===!0;(t.c===`NOT_BOUND`||t.c===`SESSION_NOT_FOUND`)&&(this.boundSessionId=null);let i=t.s??this.requestedSessionId??n?.sessionId??null;if(i){if(t.c===`SESSION_NOT_FOUND`){this.emitErrorToSession(i,e,!0);return}this.emitErrorToSession(i,e,r)}else n&&(n.connected=!1,r&&this.clearConnectionTimeout(n),n.onError?.(e,r));t.f===!0&&this.handleSocketFailure(e);return}default:return}}async asUint8Array(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return e;if(typeof Blob<`u`&&e instanceof Blob){let t=await e.arrayBuffer();return new Uint8Array(t)}return null}async asText(e){if(typeof e==`string`)return e;let t=await this.asUint8Array(e);return t?m.decode(t):``}handleSocketFailure(e){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(e)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){let e=this.socket;this.socket=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,(e.readyState===a||e.readyState===o)&&e.close()}this.boundSessionId=null}},x=()=>{let e=globalThis;return e[f]||(e[f]={inputCapability:null,streamCapability:null,manager:null}),e[f]},S=()=>{let e=x();return e.manager||=new b,e.manager},C=e=>{let t=x();if(t.inputCapability=e?.input??null,t.streamCapability=e?.stream??null,!_(t.inputCapability)&&!_(t.streamCapability)){t.manager?.close(),t.manager=null;return}let n=h(v(t));n&&S().configure(n)},w=async(e,t)=>{let r=await n(`/api/terminal/${e}/input`,{method:`POST`,headers:{"Content-Type":`text/plain`},body:t});if(!r.ok){let e=await r.json().catch(()=>({error:`Failed to send terminal input`}));throw Error(e.error||`Failed to send terminal input`)}};async function T(e){let t=await n(`/api/terminal/create`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cwd:e.cwd,cols:e.cols??80,rows:e.rows??24})});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to create terminal`}));throw Error(e.error||`Failed to create terminal session`)}let r=await t.json();return C(r.capabilities),r}var E=(t,n,r,i={})=>{let a=i.maxRetries??3,o=i.initialRetryDelay??1e3,s=i.maxRetryDelay??8e3,c=i.connectionTimeout??1e4,l=null,u=0,d=null,f=null,p=!1,m=!1,h=()=>{d&&=(clearTimeout(d),null),f&&=(clearTimeout(f),null)},g=()=>{p||(p=!0,h(),l&&=(l.close(),null))},_=(e,t)=>{if(!(p||m)){if(u<a&&!t){u+=1;let e=Math.min(o*2**(u-1),s);n({type:`reconnecting`,attempt:u,maxAttempts:a}),d=setTimeout(()=>{!p&&!m&&v()},e);return}r?.(e,!0),g()}},v=()=>{if(p||m||l&&l.readyState!==EventSource.CLOSED)return;l=new EventSource(e().sse(`/api/terminal/${t}/stream`));let i=!1;f=setTimeout(()=>{!i&&l?.readyState!==EventSource.OPEN&&(l?.close(),_(Error(`Connection timeout`),!1))},c),l.onopen=()=>{i||(i=!0,u=0,h(),n({type:`connected`}))},l.onmessage=e=>{try{let r=JSON.parse(e.data);r.type===`exit`&&(x().manager?.unbindSession(t),m=!0,g()),n(r)}catch(e){r?.(e,!1)}},l.onerror=()=>{h();let e=m||l?.readyState===EventSource.CLOSED;l?.close(),l=null,m||_(Error(`Terminal stream connection error`),e)}};return v(),g};function D(e,t,n,r={}){let i=x();if(i.streamCapability&&!_(i.streamCapability))return E(e,t,n,r);let a=S(),o=h(v(i));return o?(a.configure(o),a.subscribe(e,t,n,r)):E(e,t,n,r)}async function O(e,t){let n=x();n.manager&&await n.manager.sendInput(e,t)||await w(e,t)}async function k(e,t,r){let i=await n(`/api/terminal/${e}/resize`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cols:t,rows:r})});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to resize terminal`}));throw Error(e.error||`Failed to resize terminal`)}}async function A(e){x().manager?.unbindSession(e);let t=await n(`/api/terminal/${e}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to close terminal`}));throw Error(e.error||`Failed to close terminal`)}}async function j(e,t){x().manager?.unbindSession(e);let r=await n(`/api/terminal/${e}/restart`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cwd:t.cwd,cols:t.cols??80,rows:t.rows??24})});if(!r.ok){let e=await r.json().catch(()=>({error:`Failed to restart terminal`}));throw Error(e.error||`Failed to restart terminal`)}let i=await r.json();return C(i.capabilities),i}async function M(e){let t=await n(`/api/terminal/force-kill`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to force kill terminal`}));throw Error(e.error||`Failed to force kill terminal`)}e.sessionId&&x().manager?.unbindSession(e.sessionId)}function N(){let e=x();e.manager?.close(),e.manager=null,e.inputCapability=null,e.streamCapability=null}function P(){let e=x();if(e.inputCapability&&e.streamCapability&&!_(e.inputCapability)&&!_(e.streamCapability))return;let t=h(v(e)||s);if(!t)return;let n=S();n.isConnectedOrConnecting(t)||(n.configure(t),n.prime())}export{M as a,j as c,N as i,O as l,D as n,P as o,T as r,k as s,A as t};
|
|
1
|
+
import{P as e,U as t}from"./useUIStore-Wyu09VUF.js";import{kn as n}from"./persistence-aCOlo6ew.js";import{St as r}from"./platform-ulFAVx1H.js";var i=1,a=1,o=0,s=`/api/terminal/ws`,c=1200,l=250,u=2e4,d=5e3,f=`__openchamberTerminalTransportState`,p=new TextEncoder,m=new TextDecoder,h=t=>e().websocket(t),g=e=>{let t=p.encode(JSON.stringify(e)),n=new Uint8Array(t.length+1);return n[0]=i,n.set(t,1),n},_=e=>e?((e.transports??[]).includes(`ws`)||e.preferred===`ws`)&&typeof e.ws?.path==`string`&&e.ws.path.length>0:!1,v=e=>e.streamCapability?.ws?.path??e.inputCapability?.ws?.path??s,y=e=>{switch(e){case`SESSION_NOT_FOUND`:return Error(`Terminal session not found`);case`NOT_BOUND`:return Error(`Terminal session is not bound`);case`WRITE_FAIL`:return Error(`Failed to write to terminal`);case`RATE_LIMIT`:return Error(`Terminal websocket is rate limited`);case`BAD_FRAME`:return Error(`Terminal websocket protocol violation`);default:return Error(`Terminal websocket error`)}},b=class{socket=null;socketUrl=``;boundSessionId=null;requestedSessionId=null;openPromise=null;reconnectTimeout=null;keepaliveInterval=null;closed=!1;subscriptions=new Map;activeSubscriptionToken=null;replayCursorBySession=new Map;configure(e){if(e){if(this.socketUrl===e){this.closed=!1,this.isConnectedOrConnecting()||this.ensureConnected();return}this.socketUrl=e,this.closed=!1,this.resetConnection(),this.ensureConnected()}}subscribe(e,t,n,r){let i=Symbol(e),o={token:i,sessionId:e,onEvent:t,onError:n,maxRetries:r?.maxRetries??3,initialRetryDelay:r?.initialRetryDelay??1e3,maxRetryDelay:r?.maxRetryDelay??8e3,connectionTimeout:r?.connectionTimeout??1e4,retryCount:0,connected:!1,connectionTimeoutId:null};return this.subscriptions.set(i,o),this.activeSubscriptionToken=i,this.requestedSessionId=e,this.ensureConnected(),this.boundSessionId===e&&this.socket&&this.socket.readyState===a?(o.retryCount=0,o.connected=!0,o.onEvent({type:`connected`})):(this.boundSessionId=null,this.startConnectionTimeout(o),this.bindActiveSession()),()=>{if(this.clearConnectionTimeout(o),this.subscriptions.delete(i),this.activeSubscriptionToken===i&&(this.activeSubscriptionToken=null),this.hasSubscriptionForSession(e)||(this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null)),this.subscriptions.size===0){this.clearReconnectTimeout(),this.resetConnection();return}this.promoteActiveSubscription()}}async sendInput(e,t){if(!e||!t||this.closed||!this.socketUrl)return!1;let n=await this.getOpenSocket(c);if(!n||n.readyState!==a)return!1;try{return this.boundSessionId!==e&&(this.requestedSessionId=e,n.send(g({t:`b`,s:e,r:this.replayCursorBySession.get(e)??0,v:2}))),n.send(t),!0}catch{return this.handleSocketFailure(Error(`Terminal websocket send failed`)),!1}}unbindSession(e){e&&(this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null))}close(){this.closed=!0,this.clearReconnectTimeout();for(let e of this.subscriptions.values())this.clearConnectionTimeout(e);this.resetConnection(),this.socketUrl=``,this.subscriptions.clear(),this.activeSubscriptionToken=null,this.replayCursorBySession.clear()}prime(){this.closed||!this.socketUrl||this.isConnectedOrConnecting()||this.ensureConnected()}isConnectedOrConnecting(e){return this.closed||e&&this.socketUrl!==e?!1:this.socket&&(this.socket.readyState===a||this.socket.readyState===o)?!0:this.openPromise!==null}getActiveSubscription(){return this.activeSubscriptionToken?this.subscriptions.get(this.activeSubscriptionToken)??null:null}hasSubscriptionForSession(e){for(let t of this.subscriptions.values())if(t.sessionId===e)return!0;return!1}promoteActiveSubscription(){if(this.getActiveSubscription())return;let e=this.subscriptions.values().next().value;if(!e){this.activeSubscriptionToken=null;return}this.activeSubscriptionToken=e.token,this.requestedSessionId=e.sessionId,this.boundSessionId===e.sessionId?e.connected||(e.retryCount=0,e.connected=!0,this.clearConnectionTimeout(e),e.onEvent({type:`connected`})):(this.boundSessionId=null,this.startConnectionTimeout(e),this.bindActiveSession())}emitToSession(e,t){for(let n of this.subscriptions.values())n.sessionId===e&&n.onEvent(t)}markSessionConnected(e,t){for(let n of this.subscriptions.values())n.sessionId===e&&(n.retryCount=0,n.connected=!0,this.clearConnectionTimeout(n),n.onEvent(t))}emitErrorToSession(e,t,n){for(let r of this.subscriptions.values())r.sessionId===e&&(r.connected=!1,n&&this.clearConnectionTimeout(r),r.onError?.(t,n))}startConnectionTimeout(e){this.clearConnectionTimeout(e),e.connectionTimeoutId=setTimeout(()=>{e.connected||!this.subscriptions.has(e.token)||this.getActiveSubscription()?.token===e.token&&this.handleSocketFailure(Error(`Connection timeout`))},e.connectionTimeout)}clearConnectionTimeout(e){e.connectionTimeoutId&&=(clearTimeout(e.connectionTimeoutId),null)}async getOpenSocket(e){if(this.socket&&this.socket.readyState===a||(this.ensureConnected(),this.socket&&this.socket.readyState===a))return this.socket;let t=await Promise.race([this.openPromise??Promise.resolve(null),new Promise(t=>{setTimeout(()=>t(null),e)})]);return t&&t.readyState===a?t:this.socket&&this.socket.readyState===a?this.socket:null}ensureConnected(){this.closed||!this.socketUrl||this.socket&&(this.socket.readyState===a||this.socket.readyState===o)||(this.openPromise||=(this.clearReconnectTimeout(),(async()=>{try{await t()}catch{}return new Promise(e=>{let t=!1,n=null,i=r=>{t||(t=!0,n&&=(clearTimeout(n),null),this.openPromise=null,e(r))};try{let e=r(h(this.socketUrl));e.binaryType=`arraybuffer`,e.onopen=()=>{this.socket=e,this.startKeepalive(),i(e)},e.onmessage=e=>{this.handleSocketMessage(e.data)},e.onerror=()=>{!this.closed&&!this.getActiveSubscription()&&this.scheduleReconnect(Error(`Terminal websocket error`))},e.onclose=()=>{this.socket===e&&(this.socket=null,this.boundSessionId=null,this.stopKeepalive(),this.closed||this.scheduleReconnect(Error(`Terminal stream connection error`))),i(null)},this.socket=e,n=setTimeout(()=>{e.readyState===o&&(e.close(),i(null))},d)}catch{i(null),this.closed||this.scheduleReconnect(Error(`Terminal websocket open failed`))}})})()))}bindActiveSession(){let e=this.getActiveSubscription();if(!(!e||!this.socket||this.socket.readyState!==a)){this.requestedSessionId=e.sessionId;try{this.socket.send(g({t:`b`,s:e.sessionId,r:this.replayCursorBySession.get(e.sessionId)??0,v:2}))}catch{this.handleSocketFailure(Error(`Terminal websocket bind failed`))}}}scheduleReconnect(e){if(this.closed||!this.socketUrl||this.reconnectTimeout)return;this.promoteActiveSubscription();let t=this.getActiveSubscription();if(!t)return;let n=t.retryCount+1,r=t.initialRetryDelay,i=t.maxRetryDelay,a=t.maxRetries;if(n>a){this.clearConnectionTimeout(t),this.emitErrorToSession(t.sessionId,e,!0);return}t.retryCount=n;for(let e of this.subscriptions.values())e.sessionId===t.sessionId&&(e.connected=!1,e.retryCount=n,e.onEvent({type:`reconnecting`,attempt:n,maxAttempts:a}));this.startConnectionTimeout(t);let o=Math.min(r*2**Math.max(n-1,0),i)+Math.floor(Math.random()*l);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.ensureConnected(),this.bindActiveSession()},o)}clearReconnectTimeout(){this.reconnectTimeout&&=(clearTimeout(this.reconnectTimeout),null)}sendControl(e){if(!this.socket||this.socket.readyState!==a)return!1;try{return this.socket.send(g(e)),!0}catch{return this.handleSocketFailure(Error(`Terminal websocket control send failed`)),!1}}startKeepalive(){this.stopKeepalive(),this.keepaliveInterval=setInterval(()=>{this.closed||this.sendControl({t:`p`,v:2})},u)}stopKeepalive(){this.keepaliveInterval&&=(clearInterval(this.keepaliveInterval),null)}async handleSocketMessage(e){let t=await this.asUint8Array(e);if(t&&t.length>0&&t[0]===i){this.handleControlMessage(t);return}let n=await this.asText(e);if(!n)return;let r=this.boundSessionId??this.requestedSessionId??this.getActiveSubscription()?.sessionId;r&&this.emitToSession(r,{type:`data`,data:n})}handleControlMessage(e){if(e.length<2)return;let t;try{t=JSON.parse(m.decode(e.subarray(1)))}catch{this.handleSocketFailure(Error(`Terminal websocket control parse failed`));return}let n=this.getActiveSubscription();switch(t.t){case`ok`:this.bindActiveSession();return;case`po`:return;case`d`:{let e=t.s??this.boundSessionId??this.requestedSessionId;if(!e)return;typeof t.i==`number`&&Number.isFinite(t.i)&&this.replayCursorBySession.set(e,Math.max(this.replayCursorBySession.get(e)??0,Math.trunc(t.i))),typeof t.d==`string`&&t.d.length>0&&this.emitToSession(e,{type:`data`,data:t.d});return}case`bok`:{let e=t.s??this.requestedSessionId;if(this.boundSessionId=e,!e)return;this.markSessionConnected(e,{type:`connected`,runtime:t.runtime,ptyBackend:t.ptyBackend});return}case`x`:{let e=t.s??this.boundSessionId??n?.sessionId??null;if(!e){this.boundSessionId=null;return}this.boundSessionId===e&&(this.boundSessionId=null),this.requestedSessionId===e&&(this.requestedSessionId=null),this.replayCursorBySession.delete(e);for(let n of this.subscriptions.values())n.sessionId===e&&(n.connected=!1,this.clearConnectionTimeout(n),n.onEvent({type:`exit`,exitCode:t.exitCode,signal:t.signal??null}));return}case`e`:{let e=y(t.c),r=t.f===!0;(t.c===`NOT_BOUND`||t.c===`SESSION_NOT_FOUND`)&&(this.boundSessionId=null);let i=t.s??this.requestedSessionId??n?.sessionId??null;if(i){if(t.c===`SESSION_NOT_FOUND`){this.emitErrorToSession(i,e,!0);return}this.emitErrorToSession(i,e,r)}else n&&(n.connected=!1,r&&this.clearConnectionTimeout(n),n.onError?.(e,r));t.f===!0&&this.handleSocketFailure(e);return}default:return}}async asUint8Array(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array)return e;if(typeof Blob<`u`&&e instanceof Blob){let t=await e.arrayBuffer();return new Uint8Array(t)}return null}async asText(e){if(typeof e==`string`)return e;let t=await this.asUint8Array(e);return t?m.decode(t):``}handleSocketFailure(e){this.boundSessionId=null,this.requestedSessionId=null,this.resetConnection(),this.scheduleReconnect(e)}resetConnection(){if(this.openPromise=null,this.stopKeepalive(),this.socket){let e=this.socket;this.socket=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,(e.readyState===a||e.readyState===o)&&e.close()}this.boundSessionId=null}},x=()=>{let e=globalThis;return e[f]||(e[f]={inputCapability:null,streamCapability:null,manager:null}),e[f]},S=()=>{let e=x();return e.manager||=new b,e.manager},C=e=>{let t=x();if(t.inputCapability=e?.input??null,t.streamCapability=e?.stream??null,!_(t.inputCapability)&&!_(t.streamCapability)){t.manager?.close(),t.manager=null;return}let n=h(v(t));n&&S().configure(n)},w=async(e,t)=>{let r=await n(`/api/terminal/${e}/input`,{method:`POST`,headers:{"Content-Type":`text/plain`},body:t});if(!r.ok){let e=await r.json().catch(()=>({error:`Failed to send terminal input`}));throw Error(e.error||`Failed to send terminal input`)}};async function T(e){let t=await n(`/api/terminal/create`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cwd:e.cwd,cols:e.cols??80,rows:e.rows??24})});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to create terminal`}));throw Error(e.error||`Failed to create terminal session`)}let r=await t.json();return C(r.capabilities),r}var E=(t,n,r,i={})=>{let a=i.maxRetries??3,o=i.initialRetryDelay??1e3,s=i.maxRetryDelay??8e3,c=i.connectionTimeout??1e4,l=null,u=0,d=null,f=null,p=!1,m=!1,h=()=>{d&&=(clearTimeout(d),null),f&&=(clearTimeout(f),null)},g=()=>{p||(p=!0,h(),l&&=(l.close(),null))},_=(e,t)=>{if(!(p||m)){if(u<a&&!t){u+=1;let e=Math.min(o*2**(u-1),s);n({type:`reconnecting`,attempt:u,maxAttempts:a}),d=setTimeout(()=>{!p&&!m&&v()},e);return}r?.(e,!0),g()}},v=()=>{if(p||m||l&&l.readyState!==EventSource.CLOSED)return;l=new EventSource(e().sse(`/api/terminal/${t}/stream`));let i=!1;f=setTimeout(()=>{!i&&l?.readyState!==EventSource.OPEN&&(l?.close(),_(Error(`Connection timeout`),!1))},c),l.onopen=()=>{i||(i=!0,u=0,h(),n({type:`connected`}))},l.onmessage=e=>{try{let r=JSON.parse(e.data);r.type===`exit`&&(x().manager?.unbindSession(t),m=!0,g()),n(r)}catch(e){r?.(e,!1)}},l.onerror=()=>{h();let e=m||l?.readyState===EventSource.CLOSED;l?.close(),l=null,m||_(Error(`Terminal stream connection error`),e)}};return v(),g};function D(e,t,n,r={}){let i=x();if(i.streamCapability&&!_(i.streamCapability))return E(e,t,n,r);let a=S(),o=h(v(i));return o?(a.configure(o),a.subscribe(e,t,n,r)):E(e,t,n,r)}async function O(e,t){let n=x();n.manager&&await n.manager.sendInput(e,t)||await w(e,t)}async function k(e,t,r){let i=await n(`/api/terminal/${e}/resize`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cols:t,rows:r})});if(!i.ok){let e=await i.json().catch(()=>({error:`Failed to resize terminal`}));throw Error(e.error||`Failed to resize terminal`)}}async function A(e){x().manager?.unbindSession(e);let t=await n(`/api/terminal/${e}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to close terminal`}));throw Error(e.error||`Failed to close terminal`)}}async function j(e,t){x().manager?.unbindSession(e);let r=await n(`/api/terminal/${e}/restart`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cwd:t.cwd,cols:t.cols??80,rows:t.rows??24})});if(!r.ok){let e=await r.json().catch(()=>({error:`Failed to restart terminal`}));throw Error(e.error||`Failed to restart terminal`)}let i=await r.json();return C(i.capabilities),i}async function M(e){let t=await n(`/api/terminal/force-kill`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>({error:`Failed to force kill terminal`}));throw Error(e.error||`Failed to force kill terminal`)}e.sessionId&&x().manager?.unbindSession(e.sessionId)}function N(){let e=x();e.manager?.close(),e.manager=null,e.inputCapability=null,e.streamCapability=null}function P(){let e=x();if(e.inputCapability&&e.streamCapability&&!_(e.inputCapability)&&!_(e.streamCapability))return;let t=h(v(e)||s);if(!t)return;let n=S();n.isConnectedOrConnecting(t)||(n.configure(t),n.prime())}export{M as a,j as c,N as i,O as l,D as n,P as o,T as r,k as s,A as t};
|