agl 21.0.0 → 21.0.2

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/changelog.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-08-20 - 21.0.2
4
+
5
+ ### Fixes
6
+
7
+ - stabilize transport and git revision tests (test)
8
+ - Run transport tests on an OS-assigned port and build the public origin from the actual listening port.
9
+ - Allow the bounded git revision test to pass when either the file-output limit or transient quota guard rejects first.
10
+ - Update @api.global/typedserver to 11.1.0 and @push.rocks/smartserve to 6.0.1.
11
+
12
+ ## 2026-08-20 - 21.0.1
13
+
14
+ ### Fixes
15
+
16
+ - retry concurrent worktree record replacements during reads (gitreversion)
17
+ - Detect private worktree record replacement or removal during bounded reads and retry transient concurrent changes.
18
+ - Revalidate file metadata, ownership, and pathname identity after reads before accepting a worktree record.
19
+ - Add regression coverage for atomic worktree record replacement during listing.
20
+
3
21
  ## 2026-08-20 - 21.0.0
4
22
 
5
23
  ### Breaking Changes
@@ -41189,7 +41189,7 @@ html\`&lt;dees-button&gt;Click me&lt;/dees-button&gt;\`</code></pre>
41189
41189
  <p>Content will appear here when markdown is parsed.</p>
41190
41190
  </div>
41191
41191
  `}async firstUpdated(n){await super.firstUpdated(n),this.outlet=this.shadowRoot.querySelector(".outlet")}async updateHtmlText(n){await this.updateComplete,this.outlet||(this.outlet=this.shadowRoot.querySelector(".outlet")),this.outlet.innerHTML=n}static{pKt(s,t)}};return o=s})();Te();wa();ot();Pae();var T2t={name:"@design.estate/dees-catalog",version:"6.10.1",description:"A comprehensive library that provides dynamic web components for building sophisticated and modern web applications using JavaScript and TypeScript."};Il();Oh();var cy={};Bt(cy,{WebAuthnAbortService:()=>zY,WebAuthnError:()=>Ti,_browserSupportsWebAuthnAutofillInternals:()=>qae,_browserSupportsWebAuthnInternals:()=>k2t,base64URLStringToBuffer:()=>uf,browserSupportsWebAuthn:()=>Sp,browserSupportsWebAuthnAutofill:()=>aGe,bufferToBase64URLString:()=>Yn,platformAuthenticatorIsAvailable:()=>gKt,startAuthentication:()=>mKt,startRegistration:()=>fKt});function Yn(r){let e=new Uint8Array(r),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}a(Yn,"bufferToBase64URLString");function uf(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,s=e.padEnd(e.length+t,"="),i=atob(s),o=new ArrayBuffer(i.length),n=new Uint8Array(o);for(let l=0;l<i.length;l++)n[l]=i.charCodeAt(l);return o}a(uf,"base64URLStringToBuffer");function Sp(){return k2t.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}a(Sp,"browserSupportsWebAuthn");var k2t={stubThis:a(r=>r,"stubThis")};function zae(r){let{id:e}=r;return{...r,id:uf(e),transports:r.transports}}a(zae,"toPublicKeyCredentialDescriptor");function Uae(r){return r==="localhost"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(r)}a(Uae,"isValidDomain");var Ti=class extends Error{static{a(this,"WebAuthnError")}constructor({message:e,code:t,cause:s,name:i}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??s.name,this.code=t}};function M2t({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Ti({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(t.authenticatorSelection?.requireResidentKey===!0)return new Ti({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&t.authenticatorSelection?.userVerification==="required")return new Ti({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(t.authenticatorSelection?.userVerification==="required")return new Ti({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new Ti({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new Ti({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return t.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new Ti({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new Ti({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){let s=globalThis.location.hostname;if(Uae(s)){if(t.rp.id!==s)return new Ti({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new Ti({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(t.user.id.byteLength<1||t.user.id.byteLength>64)return new Ti({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new Ti({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}a(M2t,"identifyRegistrationError");var sGe=class{static{a(this,"BaseWebAuthnAbortService")}constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},zY=new sGe;var hKt=["cross-platform","platform"];function Hae(r){if(r&&!(hKt.indexOf(r)<0))return r}a(Hae,"toAuthenticatorAttachment");async function fKt(r){!r.optionsJSON&&r.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});let{optionsJSON:e,useAutoRegister:t=!1}=r;if(!Sp())throw new Error("WebAuthn is not supported in this browser");let s={...e,challenge:uf(e.challenge),user:{...e.user,id:uf(e.user.id)},excludeCredentials:e.excludeCredentials?.map(zae)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=zY.createNewAbortSignal();let o;try{o=await navigator.credentials.create(i)}catch(g){throw M2t({error:g,options:i})}if(!o)throw new Error("Registration was not completed");let{id:n,rawId:l,response:c,type:d}=o,u;typeof c.getTransports=="function"&&(u=c.getTransports());let p;if(typeof c.getPublicKeyAlgorithm=="function")try{p=c.getPublicKeyAlgorithm()}catch(g){iGe("getPublicKeyAlgorithm()",g)}let h;if(typeof c.getPublicKey=="function")try{let g=c.getPublicKey();g!==null&&(h=Yn(g))}catch(g){iGe("getPublicKey()",g)}let v;if(typeof c.getAuthenticatorData=="function")try{v=Yn(c.getAuthenticatorData())}catch(g){iGe("getAuthenticatorData()",g)}return{id:n,rawId:Yn(l),response:{attestationObject:Yn(c.attestationObject),clientDataJSON:Yn(c.clientDataJSON),transports:u,publicKeyAlgorithm:p,publicKey:h,authenticatorData:v},type:d,clientExtensionResults:o.getClientExtensionResults(),authenticatorAttachment:Hae(o.authenticatorAttachment)}}a(fKt,"startRegistration");function iGe(r,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${r}. You should report this error to them.
41192
- `,e)}a(iGe,"warnOnBrokenImplementation");function aGe(){if(!Sp())return qae.stubThis(new Promise(e=>e(!1)));let r=globalThis.PublicKeyCredential;return r?.isConditionalMediationAvailable===void 0?qae.stubThis(new Promise(e=>e(!1))):qae.stubThis(r.isConditionalMediationAvailable())}a(aGe,"browserSupportsWebAuthnAutofill");var qae={stubThis:a(r=>r,"stubThis")};function I2t({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Ti({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new Ti({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let s=globalThis.location.hostname;if(Uae(s)){if(t.rpId!==s)return new Ti({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new Ti({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new Ti({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}a(I2t,"identifyAuthenticationError");async function mKt(r){!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});let{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!Sp())throw new Error("WebAuthn is not supported in this browser");let i;e.allowCredentials?.length!==0&&(i=e.allowCredentials?.map(zae));let o={...e,challenge:uf(e.challenge),allowCredentials:i},n={};if(t){if(!await aGe())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');n.mediation="conditional",o.allowCredentials=[]}n.publicKey=o,n.signal=zY.createNewAbortSignal();let l;try{l=await navigator.credentials.get(n)}catch(v){throw I2t({error:v,options:n})}if(!l)throw new Error("Authentication was not completed");let{id:c,rawId:d,response:u,type:p}=l,h;return u.userHandle&&(h=Yn(u.userHandle)),{id:c,rawId:Yn(d),response:{authenticatorData:Yn(u.authenticatorData),clientDataJSON:Yn(u.clientDataJSON),signature:Yn(u.signature),userHandle:h},type:p,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:Hae(l.authenticatorAttachment)}}a(mKt,"startAuthentication");function gKt(){return Sp()?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():new Promise(r=>r(!1))}a(gKt,"platformAuthenticatorIsAvailable");var yGe=xo(IDt(),1),soe=yGe.default;var uqa=128,pqa=16,hqa=2,fqa=12288,mqa=8294400,gqa=34226176,vqa=4096,bqa=4096,_qa=3,yqa=.001,xqa=1e4,hy=class extends Error{static{a(this,"LiveBrowserOperationTimeoutError")}},Qo=class extends Error{static{a(this,"LiveBrowserRunAbortedError")}},Wa=class extends Error{static{a(this,"LiveBrowserFrameProtocolError")}},ioe=class extends Error{static{a(this,"LiveBrowserFrameIntegrityError")}},hf=a((r,e)=>r.width===e.width&&r.height===e.height&&r.deviceScaleFactor===e.deviceScaleFactor,"viewportEquals"),GY=a(r=>({alt:r.altKey,control:r.ctrlKey,meta:r.metaKey,shift:r.shiftKey}),"createModifiers"),Her=a(r=>({tabId:r.tabId,sequence:r.sequence,generation:r.generation,viewportRevision:r.viewportRevision}),"createFrameAcknowledgementRequest"),aw=a(r=>({tabId:r.tabId,generation:r.generation,viewportRevision:r.viewportRevision}),"createInputIdentity"),wp=a(r=>r instanceof Error?r.message:String(r),"getErrorMessage"),fy=class{static{a(this,"LiveBrowserCanvasRenderer")}constructor(e){this.lifecycleTail=Promise.resolve(),this.runEpoch=0,this.running=!1,this.suspended=!1,this.stopping=!1,this.interruptionRequested=!1,this.operationControllers=new Set,this.acceptingFrames=!1,this.focusWasAdjusted=!1,this.focusHadTabIndex=!1,this.focusTabIndexValue=null,this.highestFrameSequence=-1,this.acknowledgementPromises=new Set,this.rawDecodeSettlementPromises=new Set,this.inputBlocked=!0,this.inputCommands=[],this.inputProcessing=!1,this.inputIdleResolvers=[],this.inputResetTail=Promise.resolve(),this.inputResetCount=0,this.inputOverflowRecoveryPending=!1,this.pressedKeys=new Map,this.pressedMouseButtons=new Map,this.capturedPointerIds=new Set,this.viewportProcessing=!1,this.canvas=e.canvas,this.client=e.client,this.focusTarget=e.focusTarget??this.canvas,this.resizeTarget=e.resizeTarget,this.getDeviceScaleFactor=e.getDeviceScaleFactor??(()=>window.devicePixelRatio||1),this.operationTimeoutMs=this.validateTimeout(e.operationTimeoutMs??1e4,"operationTimeoutMs"),this.frameDecodeTimeoutMs=this.validateTimeout(e.frameDecodeTimeoutMs??this.operationTimeoutMs,"frameDecodeTimeoutMs"),this.onError=e.onError,this.onFrameRendered=e.onFrameRendered,this.initialCanvasWidth=this.canvas.width,this.initialCanvasHeight=this.canvas.height;let t=this.canvas.getContext("2d");if(!t)throw new Error("LiveBrowserCanvasRenderer requires a 2D canvas context");this.canvasContext=t}get isRunning(){return this.running}get isSuspended(){return this.suspended}start(){return this.enqueueLifecycle(async()=>{if(!this.running){if(this.suspended)throw new Error("Live browser renderer is suspended; call resume() to start a fresh run");await this.startRun(!1)}})}stop(){return this.interruptRun(this.runEpoch),this.enqueueLifecycle(async()=>{let e=this.runEpoch;if(this.interruptRun(e),this.stopping){await this.finishRun(e,!1);return}this.suspended&&(this.suspended=!1,this.restoreCanvasAndFocus())})}suspend(){return this.interruptRun(this.runEpoch),this.enqueueLifecycle(async()=>{let e=this.runEpoch;this.interruptRun(e),this.stopping&&await this.finishRun(e,!0)})}resume(){return this.enqueueLifecycle(async()=>{if(!this.running){if(!this.suspended)throw new Error("Live browser renderer is not suspended");await this.startRun(!0)}})}async insertText(e){let t=this.requireInputFrame(),s=aw(t);await this.enqueueInputCommand({kind:"text",runEpoch:this.runEpoch,execute:a(async i=>{await this.client.insertText({...s,text:e},i)},"execute")})}syncViewport(){if(!this.running||this.stopping||this.interruptionRequested||!this.resizeTarget)return;let e=Math.floor(this.resizeTarget.clientWidth),t=Math.floor(this.resizeTarget.clientHeight);this.queueViewport(e,t,this.runEpoch)}enqueueLifecycle(e){let t=this.lifecycleTail.then(e,e);return this.lifecycleTail=t.then(()=>{},()=>{}),t}async startRun(e){await Promise.all([...this.rawDecodeSettlementPromises]);let t=++this.runEpoch;this.runController=new AbortController,this.running=!0,this.suspended=!1,this.stopping=!1,this.interruptionRequested=!1,this.acceptingFrames=!0,this.inputBlocked=!0,this.state=void 0,this.displayedFrame=void 0,this.highestFrameSequence=-1,this.clearCanvas();try{this.makeFocusTargetFocusable(),this.installDomListeners(t),this.unsubscribe=this.client.onEvent(s=>{this.handleEvent(s,t)}),this.applyState(this.client.getState(),t),this.installResizeObserver(t)}catch(s){throw this.interruptRun(t),await this.finishRun(t,e),s}}interruptRun(e){if(e!==this.runEpoch||!this.running&&!this.stopping)return;this.running=!1,this.stopping=!0,this.interruptionRequested=!0,this.acceptingFrames=!1,this.inputBlocked=!0,this.pendingViewport=void 0,this.queuedFrame=void 0,this.displayedFrame=void 0,this.resizeFence=void 0,this.releasePointerCaptures(),this.clearCanvas();let t=new Qo(`Live browser renderer run ${e} was interrupted`);this.runController?.abort(t);for(let i of this.operationControllers)i.abort(t);let s=this.inputCommands.splice(0);for(let i of s)i.reject(t);this.pressedKeys.clear(),this.pressedMouseButtons.clear(),this.inputOverflowRecoveryPending=!1}async finishRun(e,t){if(e===this.runEpoch)try{this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.listenerController?.abort(),this.listenerController=void 0;let s=this.unsubscribe;if(this.unsubscribe=void 0,s)try{s()}catch(i){this.reportError({code:"renderer_cleanup_failed",message:`Could not unsubscribe the live browser renderer: ${wp(i)}`,cause:i},e)}await Promise.allSettled([this.viewportProcessingPromise,this.inputResetTail,this.waitForInputIdle(),this.frameProcessingPromise,...this.acknowledgementPromises])}finally{for(let o of this.operationControllers)o.abort(new Qo(`Live browser renderer run ${e} finished`));this.operationControllers.clear(),this.runController=void 0,this.running=!1,this.suspended=t,this.acceptingFrames=!1,this.state=void 0,this.displayedFrame=void 0,this.highestFrameSequence=-1,this.queuedFrame=void 0,this.frameProcessingPromise=void 0,this.acknowledgementPromises.clear(),this.resizeFence=void 0,this.pendingViewport=void 0,this.inFlightViewport=void 0,this.viewportProcessing=!1,this.viewportProcessingPromise=void 0,this.inputResetPromise=void 0,this.inputResetTail=Promise.resolve(),this.inputResetCount=0,this.inputBlocked=!0,this.pressedKeys.clear(),this.pressedMouseButtons.clear(),this.releasePointerCaptures();let s=this.inputCommands.splice(0);for(let o of s)o.reject(new Error("Live browser renderer stopped before dispatching input"));let i=this.inputIdleResolvers;this.inputIdleResolvers=[];for(let o of i)o();this.restoreCanvasAndFocus(),this.interruptionRequested=!1,this.stopping=!1}}restoreCanvasAndFocus(){this.canvas.width=this.initialCanvasWidth,this.canvas.height=this.initialCanvasHeight,this.restoreFocusTarget()}installDomListeners(e){let t=new AbortController,s=t.signal;this.listenerController=t,this.canvas.addEventListener("pointerdown",i=>{this.handlePointerDown(i,e)},{signal:s}),this.canvas.addEventListener("pointermove",i=>{this.handlePointerMove(i,e)},{signal:s}),this.canvas.addEventListener("pointerup",i=>{this.handlePointerUp(i,e)},{signal:s}),this.canvas.addEventListener("pointercancel",i=>{this.releasePointerCapture(i.pointerId),this.scheduleInputReset(!1,e)},{signal:s}),this.canvas.addEventListener("lostpointercapture",i=>{this.capturedPointerIds.delete(i.pointerId),this.pressedMouseButtons.size>0&&this.scheduleInputReset(!1,e)},{signal:s}),this.canvas.addEventListener("contextmenu",i=>{i.preventDefault()},{signal:s}),this.canvas.addEventListener("wheel",i=>{this.handleWheel(i,e)},{passive:!1,signal:s}),this.focusTarget.addEventListener("keydown",i=>{this.handleKey(i,"down",e)},{signal:s}),this.focusTarget.addEventListener("keyup",i=>{this.handleKey(i,"up",e)},{signal:s}),this.focusTarget.addEventListener("compositionend",i=>{!this.inputBlocked&&i.data&&this.insertText(i.data).catch(()=>{})},{signal:s}),window.addEventListener("blur",()=>{this.scheduleInputReset(!1,e)},{signal:s}),window.addEventListener("resize",()=>{this.syncViewport()},{signal:s}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.scheduleInputReset(!1,e)},{signal:s})}installResizeObserver(e){this.resizeTarget&&(this.resizeObserver=new ResizeObserver(t=>{let s=t.find(i=>i.target===this.resizeTarget);s&&this.queueViewport(Math.floor(s.contentRect.width),Math.floor(s.contentRect.height),e)}),this.resizeObserver.observe(this.resizeTarget),this.syncViewport())}handleEvent(e,t){if(e.type==="frame"){this.queueFrame(e.frame,t);return}if(!(!this.running||t!==this.runEpoch)){if(e.type==="state"){this.applyState(e.state,t);return}this.reportError({code:"remote_browser_error",message:`${e.error.code}: ${e.error.message}`,cause:e.error},t)}}applyState(e,t){if(!(!this.running||t!==this.runEpoch)){if(this.state=e,this.displayedFrame&&this.isStateAheadOfDisplayedFrame(e,this.displayedFrame)){this.displayedFrame=void 0,this.clearCanvas(),this.scheduleInputReset(!1,t);return}this.updateInputAvailability()}}isStateAheadOfDisplayedFrame(e,t){if(e.status!=="running"||e.activeTabId!==t.tabId)return!0;let s=e.tabs.find(i=>i.id===t.tabId);return!s||s.status!=="open"?!0:e.viewportRevision>t.viewportRevision||s.generation>t.generation}queueFrame(e,t){if(!this.running||!this.acceptingFrames||t!==this.runEpoch)return;try{if(this.validateFrame(e),e.sequence<=this.highestFrameSequence)throw new Wa(`frame.sequence ${e.sequence} must be strictly greater than current run high-water ${this.highestFrameSequence}`)}catch(i){this.requestSuspend(t),this.reportError({code:"frame_render_failed",message:`Rejected invalid live browser frame: ${wp(i)}`,cause:i,frame:e},t);return}this.highestFrameSequence=e.sequence;let s={frame:e,runEpoch:t,acknowledgementAttempted:!1};if(this.queuedFrame){let i=this.queuedFrame;this.queuedFrame=void 0,this.acknowledgeFrame(i)}this.queuedFrame=s,this.ensureFrameProcessor()}ensureFrameProcessor(){if(this.frameProcessingPromise||!this.queuedFrame)return;let e=this.processFrameQueue().finally(()=>{this.frameProcessingPromise===e&&(this.frameProcessingPromise=void 0,this.queuedFrame&&this.ensureFrameProcessor())});this.frameProcessingPromise=e}async processFrameQueue(){for(;this.queuedFrame;){let e=this.queuedFrame;this.queuedFrame=void 0,await this.processFrame(e)}}async processFrame(e){let{frame:t,runEpoch:s}=e,i,o=!1,n;try{if(!this.canRenderFrame(t,s))return;let l=new Uint8Array(t.data.byteLength);if(l.set(t.data),i=await this.decodeFrame(new Blob([l.buffer],{type:t.mimeType}),s),i.width!==t.width||i.height!==t.height)throw new ioe(`decoded frame dimensions ${i.width}x${i.height} do not match ${t.width}x${t.height}`);if(!this.canRenderFrame(t,s)||t.sequence!==this.highestFrameSequence)return;this.canvas.width=t.width,this.canvas.height=t.height,this.canvasContext.clearRect(0,0,t.width,t.height),this.canvasContext.drawImage(i,0,0,t.width,t.height),this.displayedFrame={tabId:t.tabId,sequence:t.sequence,generation:t.generation,viewportRevision:t.viewportRevision,viewport:{...t.viewport}},this.resizeFence&&!this.viewportProcessing&&t.viewportRevision>=this.resizeFence.minimumViewportRevision&&hf(t.viewport,this.resizeFence.target)&&(this.resizeFence=void 0),this.updateInputAvailability(),this.callFrameRendered(t,s)}catch(l){if(l instanceof Qo)return;o=!0,n=l}finally{i?.close(),await this.acknowledgeFrame(e),o&&(this.requestSuspend(s),this.reportError({code:"frame_render_failed",message:`Could not render live browser frame: ${wp(n)}`,cause:n,frame:t},s))}}canRenderFrame(e,t){if(!this.running||!this.acceptingFrames||t!==this.runEpoch||this.viewportProcessing)return!1;let s=this.state;if(!s||s.status!=="running"||s.activeTabId!==e.tabId)return!1;let i=s.tabs.find(o=>o.id===e.tabId);return!i||i.status!=="open"||s.viewportRevision>e.viewportRevision||i.generation>e.generation?!1:this.resizeFence?e.viewportRevision>=this.resizeFence.minimumViewportRevision&&hf(e.viewport,this.resizeFence.target):!0}acknowledgeFrame(e){if(e.acknowledgementAttempted||(e.acknowledgementAttempted=!0,!this.isRunActive(e.runEpoch)))return Promise.resolve();if(this.acknowledgementPromises.size>=16)return this.requestSuspend(e.runEpoch),this.reportError({code:"frame_acknowledgement_failed",message:"Live browser frame acknowledgement capacity of 16 was reached"},e.runEpoch),Promise.resolve();let t=this.runClientOperation(i=>this.client.acknowledgeFrame(Her(e.frame),i),"frame acknowledgement",e.runEpoch).then(()=>{}).catch(i=>{i instanceof Qo||(this.requestSuspend(e.runEpoch),this.reportError({code:"frame_acknowledgement_failed",message:`Could not acknowledge live browser frame: ${wp(i)}`,cause:i,frame:e.frame},e.runEpoch))}),s;return s=t.finally(()=>{this.acknowledgementPromises.delete(s)}),this.acknowledgementPromises.add(s),s}handlePointerDown(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getMouseButton(e.button);if(!s)return;let i=this.getInputFrame();if(!i||t!==this.runEpoch)return;e.preventDefault();let o=this.mapCoordinates(e,i.viewport);if(!o)return;this.focusTarget.focus({preventScroll:!0});try{this.canvas.setPointerCapture(e.pointerId),this.capturedPointerIds.add(e.pointerId)}catch{}let n={...aw(i),type:"down",...o,button:s,buttons:e.buttons,clickCount:Math.min(3,Math.max(1,e.detail||1)),modifiers:GY(e)};this.enqueueInputCommand({kind:"mouse",runEpoch:t,execute:a(async l=>this.client.dispatchMouse(n,l),"execute"),onAttempt:a(()=>this.pressedMouseButtons.set(s,n),"onAttempt")}).catch(()=>{})}handlePointerMove(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getInputFrame();if(!s||t!==this.runEpoch)return;e.preventDefault();let i=this.mapCoordinates(e,s.viewport);if(!i){this.releasePointerCapture(e.pointerId),this.scheduleInputReset(!1,t);return}let o={...aw(s),type:"move",...i,button:"none",buttons:e.buttons,modifiers:GY(e)};this.enqueueInputCommand({kind:"mouseMove",runEpoch:t,execute:a(async n=>this.client.dispatchMouse(o,n),"execute")}).catch(()=>{})}handlePointerUp(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getMouseButton(e.button),i=this.getInputFrame();if(!s||!i||t!==this.runEpoch){this.releasePointerCapture(e.pointerId);return}e.preventDefault();let o=this.mapCoordinates(e,i.viewport);if(!o){this.releasePointerCapture(e.pointerId),this.scheduleInputReset(!1,t);return}let n={...aw(i),type:"up",...o,button:s,buttons:e.buttons,clickCount:Math.min(3,Math.max(1,e.detail||1)),modifiers:GY(e)};this.enqueueInputCommand({kind:"mouse",runEpoch:t,execute:a(async l=>this.client.dispatchMouse(n,l),"execute"),onSuccess:a(()=>this.pressedMouseButtons.delete(s),"onSuccess")}).catch(()=>{}),this.releasePointerCapture(e.pointerId)}handleWheel(e,t){let s=this.getInputFrame();if(!s||t!==this.runEpoch)return;e.preventDefault();let i=this.mapCoordinates(e,s.viewport);if(!i)return;let o=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?s.viewport.height:1,n=a(l=>Math.max(-1e6,Math.min(1e6,l)),"clampDelta");this.enqueueInputCommand({kind:"wheel",runEpoch:t,execute:a(async l=>this.client.dispatchWheel({...aw(s),...i,deltaX:n(e.deltaX*o),deltaY:n(e.deltaY*o),modifiers:GY(e)},l),"execute")}).catch(()=>{})}handleKey(e,t,s){let i=this.getInputFrame();if(!i||s!==this.runEpoch||e.isComposing||e.key==="Process")return;e.preventDefault();let o=t==="down"&&e.key.length===1&&!e.metaKey&&(!e.ctrlKey||e.altKey)?e.key:void 0,n={...aw(i),type:t,key:e.key,code:e.code||void 0,text:o,windowsVirtualKeyCode:e.keyCode||void 0,autoRepeat:e.repeat,isKeypad:e.location===KeyboardEvent.DOM_KEY_LOCATION_NUMPAD,location:e.location,modifiers:GY(e)},l=e.code||e.key;this.enqueueInputCommand({kind:"key",runEpoch:s,execute:a(async c=>this.client.dispatchKey(n,c),"execute"),onAttempt:t==="down"?()=>this.pressedKeys.set(l,n):void 0,onSuccess:a(()=>{t==="up"&&this.pressedKeys.delete(l)},"onSuccess")}).catch(()=>{})}mapCoordinates(e,t){let s=this.canvas.getBoundingClientRect();if(s.width<=0||s.height<=0)return;let i=(e.clientX-s.left)/s.width*t.width,o=(e.clientY-s.top)/s.height*t.height;return{x:Math.max(0,Math.min(t.width-.001,i)),y:Math.max(0,Math.min(t.height-.001,o))}}getMouseButton(e){return e===0?"left":e===1?"middle":e===2?"right":e===3?"back":e===4?"forward":void 0}getInputFrame(){return this.inputBlocked||!this.isDisplayedFrameCurrent()?void 0:this.displayedFrame}requireInputFrame(){let e=this.getInputFrame();if(!e)throw new Error("Live browser input is unavailable until a current frame is displayed");return e}isDisplayedFrameCurrent(){let e=this.state,t=this.displayedFrame;if(!e||!t||e.status!=="running"||e.activeTabId!==t.tabId||e.viewportRevision>t.viewportRevision)return!1;let s=e.tabs.find(i=>i.id===t.tabId);return!!(s&&s.status==="open"&&s.generation<=t.generation)}enqueueInputCommand(e){return!this.running||this.inputBlocked||e.runEpoch!==this.runEpoch?Promise.reject(new Error("Live browser input is currently blocked")):new Promise((t,s)=>{let i={...e,resolve:t,reject:s},o=this.inputCommands.at(-1);if(i.kind==="mouseMove"&&o?.kind==="mouseMove")o.resolve(),this.inputCommands[this.inputCommands.length-1]=i;else if(this.inputCommands.length>=128){if(i.kind==="mouseMove"){t();return}let n=new Error("Live browser input queue reached its capacity");this.reportError({code:"input_queue_capacity_exceeded",message:n.message,cause:n},i.runEpoch),s(n),this.recoverFromInputOverflow(i.runEpoch);return}else this.inputCommands.push(i);this.processInputCommands()})}processInputCommands(){this.inputProcessing||(this.inputProcessing=!0,(async()=>{try{for(;this.inputCommands.length>0;){let e=this.inputCommands.shift();if(!this.isRunActive(e.runEpoch)){e.reject(new Qo(`Live browser input belongs to inactive run ${e.runEpoch}`));continue}try{if(e.onAttempt?.(),await this.runClientOperation(e.execute,"input dispatch",e.runEpoch),!this.isRunActive(e.runEpoch))throw new Qo(`Live browser input belongs to inactive run ${e.runEpoch}`);e.onSuccess?.(),e.resolve()}catch(t){if(e.reject(t),t instanceof Qo)continue;t instanceof hy&&this.requestSuspend(e.runEpoch),this.reportError({code:"input_dispatch_failed",message:`Could not dispatch live browser input: ${wp(t)}`,cause:t},e.runEpoch);let s=this.inputCommands.splice(0);for(let i of s)i.reject(new Error("Live browser input was abandoned after a dispatch failure"));!(t instanceof hy)&&!this.stopping&&this.scheduleInputReset(!1,e.runEpoch)}}}finally{if(this.inputProcessing=!1,this.inputCommands.length>0)this.processInputCommands();else{let e=this.inputIdleResolvers;this.inputIdleResolvers=[];for(let t of e)t()}}})())}waitForInputIdle(){return!this.inputProcessing&&this.inputCommands.length===0?Promise.resolve():new Promise(e=>{this.inputIdleResolvers.push(e)})}scheduleInputReset(e,t){if(t!==this.runEpoch||this.stopping)return Promise.resolve();if(this.inputBlocked=!0,this.releasePointerCaptures(),e&&(this.displayedFrame=void 0,this.clearCanvas()),this.inputResetPromise)return this.inputResetPromise;this.inputResetCount++;let s;return s=this.inputResetTail.then(async()=>{await this.waitForInputIdle(),await this.releasePressedInput(t)}).finally(()=>{this.inputResetCount--,this.inputResetPromise===s&&(this.inputResetPromise=void 0),this.updateInputAvailability()}),this.inputResetPromise=s,this.inputResetTail=s.then(()=>{},()=>{}),s}recoverFromInputOverflow(e){this.inputOverflowRecoveryPending||(this.inputOverflowRecoveryPending=!0,this.inputBlocked=!0,this.scheduleInputReset(!1,e).finally(()=>{this.inputOverflowRecoveryPending=!1}))}async releasePressedInput(e){for(let[t,s]of[...this.pressedKeys.entries()])await this.tryInputRelease(o=>this.client.dispatchKey({...s,type:"up",text:void 0,autoRepeat:!1,modifiers:{}},o),e)&&this.pressedKeys.get(t)===s&&this.pressedKeys.delete(t);for(let[t,s]of[...this.pressedMouseButtons.entries()])await this.tryInputRelease(o=>this.client.dispatchMouse({...s,type:"up",buttons:0,clickCount:1,modifiers:{}},o),e)&&this.pressedMouseButtons.get(t)===s&&this.pressedMouseButtons.delete(t)}async tryInputRelease(e,t){let s;for(let i=0;i<2;i++)try{return await this.runClientOperation(e,"input release",t),!0}catch(o){if(o instanceof Qo)return!1;s=o}return this.requestSuspend(t),this.reportInputReleaseError(s,t),!1}reportInputReleaseError(e,t){this.reportError({code:"input_dispatch_failed",message:`Could not release live browser input: ${wp(e)}`,cause:e},t)}queueViewport(e,t,s){if(!this.running||this.stopping||this.interruptionRequested||s!==this.runEpoch||e<=0||t<=0)return;let i=this.getDeviceScaleFactor();if(!Number.isFinite(i)||i<=0){this.reportError({code:"viewport_update_failed",message:"Live browser device scale factor must be a positive finite number"},s);return}let o={width:e,height:t,deviceScaleFactor:i};if(!(this.pendingViewport&&hf(o,this.pendingViewport))){if(this.inFlightViewport&&hf(o,this.inFlightViewport)){this.pendingViewport=void 0;return}if(!this.inFlightViewport&&this.resizeFence&&hf(o,this.resizeFence.target)){this.pendingViewport=void 0;return}if(!this.inFlightViewport&&!this.resizeFence&&this.state&&hf(o,this.state.viewport)){this.pendingViewport=void 0,this.updateInputAvailability();return}this.pendingViewport=o,this.inputBlocked=!0,this.ensureViewportProcessor(s)}}ensureViewportProcessor(e){if(this.viewportProcessingPromise||!this.pendingViewport)return;let t=this.processViewportQueue(e).finally(()=>{this.viewportProcessingPromise===t&&(this.viewportProcessingPromise=void 0,this.pendingViewport&&this.running&&!this.stopping&&e===this.runEpoch&&this.ensureViewportProcessor(e))});this.viewportProcessingPromise=t}async processViewportQueue(e){this.viewportProcessing=!0;try{for(;this.pendingViewport&&this.running&&!this.stopping&&e===this.runEpoch;){let t=this.pendingViewport;if(this.pendingViewport=void 0,this.inFlightViewport=t,!this.resizeFence&&this.state&&hf(t,this.state.viewport)){this.inFlightViewport=void 0;continue}if(await this.scheduleInputReset(!0,e),!this.running||this.stopping||e!==this.runEpoch)return;let s=this.state?.viewportRevision??0,i=this.resizeFence?.minimumViewportRevision??s;try{if(await this.runClientOperation(o=>this.client.setViewport(t,o),"viewport update",e),!this.running||this.stopping||e!==this.runEpoch)return;this.resizeFence={target:t,minimumViewportRevision:Math.max(s,i)+1}}catch(o){e===this.runEpoch&&!(o instanceof Qo)&&(this.resizeFence=void 0,o instanceof hy&&this.requestSuspend(e),this.reportError({code:"viewport_update_failed",message:`Could not update live browser viewport: ${wp(o)}`,cause:o},e))}finally{this.inFlightViewport&&hf(this.inFlightViewport,t)&&(this.inFlightViewport=void 0)}}}finally{this.viewportProcessing=!1,this.updateInputAvailability()}}updateInputAvailability(){this.inputBlocked=!(this.running&&this.acceptingFrames&&!this.viewportProcessing&&!this.resizeFence&&this.inputResetCount===0&&this.isDisplayedFrameCurrent())}makeFocusTargetFocusable(){this.focusWasAdjusted=!1,!(this.focusTarget.tabIndex>=0)&&(this.focusHadTabIndex=this.focusTarget.hasAttribute("tabindex"),this.focusTabIndexValue=this.focusTarget.getAttribute("tabindex"),this.focusTarget.setAttribute("tabindex","0"),this.focusWasAdjusted=!0)}restoreFocusTarget(){this.focusWasAdjusted&&(this.focusHadTabIndex&&this.focusTabIndexValue!==null?this.focusTarget.setAttribute("tabindex",this.focusTabIndexValue):this.focusTarget.removeAttribute("tabindex"),this.focusWasAdjusted=!1)}clearCanvas(){this.canvasContext.clearRect(0,0,this.canvas.width,this.canvas.height)}callFrameRendered(e,t){if(!(!this.onFrameRendered||t!==this.runEpoch||!this.running))try{this.onFrameRendered(e)}catch(s){this.reportError({code:"renderer_callback_failed",message:`Live browser frame callback failed: ${wp(s)}`,cause:s,frame:e},t)}}reportError(e,t){if(!(!this.onError||t!==this.runEpoch))try{this.onError(e)}catch{}}requestSuspend(e){!this.isRunActive(e)||this.interruptionRequested||(this.interruptRun(e),this.suspend())}validateTimeout(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`${t} must be a positive finite number`);return e}runClientOperation(e,t,s){return this.runAbortableOperation(i=>e({signal:i}),this.operationTimeoutMs,t,s)}runAbortableOperation(e,t,s,i){let o=this.runController;if(!o||!this.isRunActive(i)||o.signal.aborted)return Promise.reject(new Qo(`Cannot start ${s} for inactive run ${i}`));let n=new AbortController;this.operationControllers.add(n);let l=a(()=>{let p=o.signal.reason instanceof Error?o.signal.reason:new Qo(`Live browser renderer run ${i} was interrupted`);n.abort(p)},"abortFromRun");o.signal.addEventListener("abort",l,{once:!0});let c=globalThis.setTimeout(()=>{n.abort(new hy(`${s} timed out after ${t}ms`))},t),d=a(()=>{},"abortOperation");return new Promise((p,h)=>{let v=!1,g=a(m=>{v||(v=!0,m())},"settle");d=a(()=>{let m=n.signal.reason instanceof Error?n.signal.reason:new Qo(`${s} was aborted`);g(()=>h(m))},"abortOperation"),n.signal.addEventListener("abort",d,{once:!0});let f;try{f=e(n.signal)}catch(m){g(()=>h(m));return}f.then(m=>{g(()=>p(m))},m=>{g(()=>h(m))})}).finally(()=>{globalThis.clearTimeout(c),o.signal.removeEventListener("abort",l),n.signal.removeEventListener("abort",d),this.operationControllers.delete(n)})}async decodeFrame(e,t){let s;try{s=createImageBitmap(e)}catch(o){throw o}let i;i=s.then(()=>{},()=>{}).finally(()=>{this.rawDecodeSettlementPromises.delete(i)}),this.rawDecodeSettlementPromises.add(i);try{return await this.runAbortableOperation(async()=>s,this.frameDecodeTimeoutMs,"frame decode",t)}catch(o){throw o instanceof hy||o instanceof Qo?(s.then(n=>n.close(),()=>{}),o):new ioe(`frame bytes could not be decoded: ${wp(o)}`,{cause:o})}}isRunActive(e){return!!(this.running&&!this.stopping&&e===this.runEpoch&&this.runController&&!this.runController.signal.aborted)}validateFrame(e){if(!e||typeof e!="object")throw new Wa("frame must be an object");if(typeof e.tabId!="string"||e.tabId.length===0||e.tabId.length>4096)throw new Wa("frame.tabId must be a non-empty bounded string");if(this.validateProtocolInteger(e.sequence,"frame.sequence",1),this.validateProtocolInteger(e.generation,"frame.generation",1),this.validateProtocolInteger(e.viewportRevision,"frame.viewportRevision",1),this.validateViewport(e.viewport,"frame.viewport"),e.format!=="jpeg"&&e.format!=="png")throw new Wa("frame.format must be jpeg or png");let t=e.format==="jpeg"?"image/jpeg":"image/png";if(e.mimeType!==t)throw new Wa(`frame.mimeType must be ${t} for ${e.format}`);if(this.validateProtocolInteger(e.width,"frame.width",1,12288),this.validateProtocolInteger(e.height,"frame.height",1,12288),e.width*e.height>8294400)throw new Wa("frame pixel area must not exceed 8294400");if(!(e.data instanceof Uint8Array))throw new Wa("frame.data must be a Uint8Array");if(e.data.byteLength===0||e.data.byteLength>34226176)throw new Wa("frame.data byte length must be between 1 and 34226176");let s=e.metadata;if(!s||typeof s!="object")throw new Wa("frame.metadata must be an object");if(this.validateProtocolNumber(s.offsetTop,"frame.metadata.offsetTop"),this.validateProtocolNumber(s.pageScaleFactor,"frame.metadata.pageScaleFactor",!0),this.validateProtocolNumber(s.deviceWidth,"frame.metadata.deviceWidth",!0),this.validateProtocolNumber(s.deviceHeight,"frame.metadata.deviceHeight",!0),s.deviceWidth>12288||s.deviceHeight>12288||s.deviceWidth*s.deviceHeight>8294400)throw new Wa("frame metadata dimensions must fit within 8294400 pixels");this.validateProtocolNumber(s.scrollOffsetX,"frame.metadata.scrollOffsetX"),this.validateProtocolNumber(s.scrollOffsetY,"frame.metadata.scrollOffsetY"),s.timestamp!==void 0&&this.validateProtocolNumber(s.timestamp,"frame.metadata.timestamp")}validateViewport(e,t){if(!e||typeof e!="object")throw new Wa(`${t} must be an object`);if(this.validateProtocolInteger(e.width,`${t}.width`,1,4096),this.validateProtocolInteger(e.height,`${t}.height`,1,4096),this.validateProtocolNumber(e.deviceScaleFactor,`${t}.deviceScaleFactor`,!0),e.deviceScaleFactor>3)throw new Wa(`${t}.deviceScaleFactor must not exceed 3`);if(e.width*e.height*e.deviceScaleFactor*e.deviceScaleFactor>8294400)throw new Wa(`${t} physical pixel area must not exceed 8294400`)}validateProtocolInteger(e,t,s,i=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(e)||e<s||e>i)throw new Wa(`${t} must be an integer between ${s} and ${i}`)}validateProtocolNumber(e,t,s=!1){if(!Number.isFinite(e)||s&&e<=0)throw new Wa(`${t} must be a ${s?"positive ":""}finite number`)}releasePointerCapture(e){this.capturedPointerIds.delete(e);try{this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e)}catch{}}releasePointerCaptures(){let e=[...this.capturedPointerIds];this.capturedPointerIds.clear();for(let t of e)this.releasePointerCapture(t)}};Te();var aoe=xo(D2t(),1),ooe=xo(O2t(),1);var Rqa=22,Dqa=2,Oqa="agl",DDt=48*1024,noe=128*1024,Aqa=20,ODt=200,ADt=512*1024,NDt="[elided: this tool payload exceeds the live transfer budget]",loe=64*1024,WY=8,jY=10*1024*1024,YY=10*1024*1024,Nqa=16*1024,Pqa=["opencode","flex","controller"],Lqa=["opencode","flex"],Ep=a(r=>JSON.stringify([r.harnessId,r.nativeId]),"controllerRuntimeIdKey"),Bqa=["compact","undo","redo","init"],PDt=["sessions.changed","session.changed","session.draft.changed","session.history.changed","session.tool.updated","session.reasoning.updated","session.text.updated","permissions.changed","harness.changed","projects.changed","settings.changed","sessiongroups.changed","resources.changed","terminals.changed","upgrade.changed"];var qer=new Set(PDt),Ver=35e3,Ia=a((r,e)=>{if(!r||typeof r!="object")return!1;let t=r;return Object.keys(t).length===2&&typeof t.harnessId=="string"&&e.has(t.harnessId)&&typeof t.nativeId=="string"&&t.nativeId.length>0&&new TextEncoder().encode(t.nativeId).byteLength<=512},"isQualifiedRuntimeId"),Cp=new Set(["opencode","flex"]),Ger=new Set(["controller"]),Wer=new Set(["sessionId","messageId","partId","callId","toolName","status","input","output","exitCode","errorText","childSessionId","model","startedAt","finishedAt","order","sourceUpdatedAt","revision","streamEpoch"]),jer=new Set(["sessionId","messageId","partId","text","status","order","sourceUpdatedAt","revision","streamEpoch"]),Yer=new Set(["sessionId","messageId","partId","text","status","order","sourceUpdatedAt","revision","streamEpoch"]),BDt=a(r=>r===void 0||typeof r=="number"&&Number.isFinite(r),"isOptionalFiniteNumber"),xGe=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Object.keys(e).length===2&&Number.isSafeInteger(e.messageIndex)&&(e.messageIndex??-1)>=0&&Number.isSafeInteger(e.partIndex)&&(e.partIndex??-1)>=0},"isTranscriptOrder"),FDt=a((r,e)=>{try{return new TextEncoder().encode(JSON.stringify(r)).byteLength<=e}catch{return!1}},"serializedBytesWithin"),Ker=a(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;if(!Object.keys(e).every(t=>["id","name","mediaType","size","kind","dataBase64"].includes(t))||typeof e.id!="string"||e.id.length===0||new TextEncoder().encode(e.id).byteLength>512||typeof e.name!="string"||e.name.length===0||new TextEncoder().encode(e.name).byteLength>255||typeof e.mediaType!="string"||e.mediaType.length===0||new TextEncoder().encode(e.mediaType).byteLength>129||!Number.isSafeInteger(e.size)||(e.size??-1)<0||(e.size??0)>jY||!["image","text","binary"].includes(e.kind??"")||typeof e.dataBase64!="string")return!1;try{let t=globalThis.atob(e.dataBase64);return t.length===e.size&&globalThis.btoa(t)===e.dataBase64}catch{return!1}},"isDraftAttachment"),Qer=a(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return!(!Object.keys(e).every(t=>["revision","text","attachments"].includes(t))||!Number.isSafeInteger(e.revision)||(e.revision??-1)<0||e.text===void 0&&e.attachments===void 0||e.text!==void 0&&(typeof e.text!="string"||new TextEncoder().encode(e.text).byteLength>loe)||e.attachments!==void 0&&(!Array.isArray(e.attachments)||e.attachments.length>WY||!e.attachments.every(Ker)||e.attachments.reduce((t,s)=>t+s.size,0)>YY))},"isSessionDraftUpdate"),Xer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>Wer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&Ia(e.callId,t)&&typeof e.toolName=="string"&&e.toolName.length>0&&new TextEncoder().encode(e.toolName).byteLength<=2048&&["pending","running","completed","error"].includes(e.status??"")&&(e.exitCode===void 0||Number.isSafeInteger(e.exitCode)&&e.exitCode>=0)&&(e.errorText===void 0||typeof e.errorText=="string")&&(e.childSessionId===void 0||Ia(e.childSessionId,t))&&(e.model===void 0||typeof e.model=="string")&&BDt(e.startedAt)&&BDt(e.finishedAt)&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&e.sourceUpdatedAt>=0&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerToolExecution"),Zer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>jer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&typeof e.text=="string"&&new TextEncoder().encode(e.text).byteLength<=noe&&["running","completed","cancelled"].includes(e.status??"")&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerReasoningUpdate"),Jer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>Yer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&typeof e.text=="string"&&new TextEncoder().encode(e.text).byteLength<=noe&&["running","completed"].includes(e.status??"")&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerTextUpdate"),etr=a(r=>{if(!r||typeof r!="object")return!1;let e=r,t=e.sessionStatus!==void 0||e.sessionError!==void 0,s=e.toolExecution!==void 0,i=e.reasoningUpdate!==void 0,o=e.textUpdate!==void 0,n=e.sessionDraftUpdate!==void 0,l=e.upgrade!==void 0;return typeof e.type=="string"&&qer.has(e.type)&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&(e.harnessId===void 0||e.harnessId==="opencode"||e.harnessId==="flex")&&(e.sessionId===void 0||Ia(e.sessionId,Cp))&&(e.projectId===void 0||typeof e.projectId=="string"&&e.projectId.length>0)&&(e.sessionStatus===void 0||["idle","busy","retry","error"].includes(e.sessionStatus))&&(e.sessionError===void 0||e.sessionError===!0)&&(e.toolStreamEpoch===void 0||Number.isSafeInteger(e.toolStreamEpoch)&&e.toolStreamEpoch>=0)&&(e.messageStreamEpoch===void 0||Number.isSafeInteger(e.messageStreamEpoch)&&e.messageStreamEpoch>=0)&&(e.toolExecution===void 0||Xer(e.toolExecution))&&(e.reasoningUpdate===void 0||Zer(e.reasoningUpdate))&&(e.textUpdate===void 0||Jer(e.textUpdate))&&(e.sessionDraftUpdate===void 0||Qer(e.sessionDraftUpdate))&&(!s||FDt(e,DDt))&&(!(i||o)||FDt(e,noe))&&(!t||e.type==="session.changed"&&Ia(e.sessionId,Cp))&&(e.harnessId===void 0||e.sessionId===void 0||e.harnessId===e.sessionId.harnessId)&&!(e.sessionStatus!==void 0&&e.sessionError===!0)&&(!s||e.type==="session.tool.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.sessionId.harnessId&&e.harnessId===e.toolExecution.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.toolExecution.sessionId)&&e.toolStreamEpoch===void 0)&&(s||e.type!=="session.tool.updated")&&(!i||e.type==="session.reasoning.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.reasoningUpdate.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.reasoningUpdate.sessionId))&&(i||e.type!=="session.reasoning.updated")&&(!o||e.type==="session.text.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.textUpdate.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.textUpdate.sessionId))&&(o||e.type!=="session.text.updated")&&(!n||e.type==="session.draft.changed"&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp))&&(n||e.type!=="session.draft.changed")&&(e.toolStreamEpoch===void 0||e.type==="harness.changed"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&!s)&&(e.messageStreamEpoch===void 0||e.type==="harness.changed"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&!i&&!o)&&(e.upgrade===void 0||typeof e.upgrade=="object"&&e.upgrade!==null&&Object.keys(e.upgrade).length===3&&typeof e.upgrade.fromVersion=="string"&&e.upgrade.fromVersion.length>0&&new TextEncoder().encode(e.upgrade.fromVersion).byteLength<=128&&typeof e.upgrade.toVersion=="string"&&e.upgrade.toVersion.length>0&&new TextEncoder().encode(e.upgrade.toVersion).byteLength<=128&&["preparing","pausing","installing","restarting","continuing","completed","failed"].includes(e.upgrade.phase))&&(!l||e.type==="upgrade.changed")&&(l||e.type!=="upgrade.changed")},"isControllerEvent"),ttr=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Ia(e.terminalId,Ger)&&typeof e.dataBase64=="string"&&(e.reset===void 0||typeof e.reset=="boolean")&&(e.ended===void 0||typeof e.ended=="boolean")},"isControllerTerminalOutput"),coe=class{constructor(e){this.options=e;this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.event",async t=>(etr(t)&&await this.options.onControllerEvent(t),{received:!0}))),this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.terminal.output",async t=>(ttr(t)&&await this.options.onTerminalOutput?.(t),{}))),this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.browser.view.event",async t=>(await this.options.onBrowserViewEvent?.(t),{})))}options;static{a(this,"ControllerSocketClient")}typedRouter=new ws.TypedRouter;typedSocket;statusSubscription;diagnosticsSubscription;abortController;startPromise;get status(){return this.typedSocket?.getStatus()??"new"}get isConnected(){return this.status==="connected"}async start(){if(this.typedSocket?.getStatus()==="connected")return;if(this.startPromise)return this.startPromise;let e=this.startInternal();this.startPromise=e;try{await e}finally{this.startPromise===e&&(this.startPromise=void 0)}}async stop(){this.abortController?.abort(),this.abortController=void 0,this.statusSubscription?.unsubscribe(),this.statusSubscription=void 0,this.diagnosticsSubscription?.unsubscribe(),this.diagnosticsSubscription=void 0;let e=this.typedSocket;this.typedSocket=void 0,e&&await e.stop(),this.startPromise&&await this.startPromise.catch(()=>{})}async fire(e,t,s){let i=this.typedSocket;if(!i||i.getStatus()!=="connected")throw new Error("The controller connection is not available.");let o=s?.timeoutMs??Ver,{abortSignal:n,...l}=s??{};return i.createTypedRequest(e,void 0,{timeoutMs:o,abortSignal:n}).fire(t,{...l,timeoutMs:o})}async startInternal(){this.options.onStatus("connecting"),this.abortController=new AbortController;let e=await $1.TypedSocket.createClient(this.typedRouter,$1.TypedSocket.useWindowLocationOriginUrl(),{autoReconnect:!0,maxRetries:100,initialBackoffMs:500,maxBackoffMs:1e4,abortSignal:this.abortController.signal});this.typedSocket=e,this.statusSubscription=e.statusSubject.subscribe(t=>{this.options.onStatus(t)}),this.diagnosticsSubscription=e.diagnosticsSubject.subscribe(t=>{t.kind==="connectionClosed"&&typeof t.closeCode=="number"&&t.closeCode!==1e3&&this.options.onTransportClose?.(t.closeCode,typeof t.reason=="string"?t.reason:"")}),this.options.onStatus(e.getStatus())}};var KY={name:"agl",version:"21.0.0",description:"Agent Gateway Layer for OpenCode and FlexHarness sessions"};var Wqa=150,jqa=4,ff=a(r=>r.map(e=>({...e})),"cloneAttachments"),$Dt=a(r=>({text:r.text,attachments:ff(r.attachments),revision:r.revision}),"cloneDraft"),QY=a((r,e)=>r.length===e.length&&r.every((t,s)=>{let i=e[s];return i!==void 0&&t.id===i.id&&t.name===i.name&&t.mediaType===i.mediaType&&t.size===i.size&&t.kind===i.kind&&t.dataBase64===i.dataBase64}),"attachmentsEqual"),rtr=a((r,e)=>r.harnessId===e.harnessId&&r.nativeId===e.nativeId,"runtimeIdsEqual"),doe=class{constructor(e){this.options=e;this.debounceMs=e.debounceMs??150}options;static{a(this,"SessionDraftSync")}debounceMs;generation=0;active;disposed=!1;get state(){return this.active?this.publicState(this.active):void 0}async activate(e,t){if(this.disposed)return;this.deactivate();let s=++this.generation,i={projectId:e,sessionId:{...t},generation:s,authoritative:{text:"",attachments:[],revision:0},desiredText:"",desiredAttachments:[],dirtyText:!1,dirtyAttachments:!1,drainAfterDeactivate:!1,loading:!0,saving:!1,error:""};return this.active=i,this.emit(i),await this.hydrate(i),this.isCurrent(i)?this.publicState(i):void 0}deactivate(){let e=this.active;if(e?.debounceTimer&&clearTimeout(e.debounceTimer),e&&!e.loading&&(e.dirtyText||e.dirtyAttachments)&&(e.drainAfterDeactivate=!0,!e.writeTask)){let t=this.flushActive(e);e.writeTask=t,t.catch(s=>this.options.onError?.(s)).finally(()=>{e.writeTask===t&&(e.writeTask=void 0)})}this.generation+=1,this.active=void 0,this.options.onState(void 0)}setText(e){let t=this.active;!t||t.loading||(t.desiredText=e,t.dirtyText=t.desiredText!==t.authoritative.text,t.error="",this.emit(t),this.schedule(t))}setAttachments(e){let t=this.active;!t||t.loading||(t.desiredAttachments=ff(e),t.dirtyAttachments=!QY(t.desiredAttachments,t.authoritative.attachments),t.error="",this.emit(t),this.schedule(t))}async flush(){let e=this.active;if(!e)throw new Error("No session draft is active.");if(e.debounceTimer&&(clearTimeout(e.debounceTimer),e.debounceTimer=void 0),e.loading&&await this.hydrate(e),!this.isCurrent(e))throw new Error("The session draft changed during synchronization.");if(e.writeTask)return e.writeTask;let t=this.flushActive(e);e.writeTask=t;try{return await t}finally{e.writeTask===t&&(e.writeTask=void 0)}}async refresh(){let e=this.active;if(e)return await this.hydrate(e),this.isCurrent(e)?this.publicState(e):void 0}applyRemoteUpdate(e,t,s){let i=this.active;return!i||i.projectId!==e||!rtr(i.sessionId,t)||s.revision<=i.authoritative.revision?!1:s.revision!==i.authoritative.revision+1?(this.hydrate(i).catch(o=>this.options.onError?.(o)),!0):(i.authoritative={text:s.text??i.authoritative.text,attachments:s.attachments===void 0?i.authoritative.attachments:ff(s.attachments),revision:s.revision},!i.dirtyText&&s.text!==void 0&&(i.desiredText=s.text),!i.dirtyAttachments&&s.attachments!==void 0&&(i.desiredAttachments=ff(s.attachments)),i.dirtyText=i.desiredText!==i.authoritative.text,i.dirtyAttachments=!QY(i.desiredAttachments,i.authoritative.attachments),this.emit(i),(i.dirtyText||i.dirtyAttachments)&&this.schedule(i),!0)}dispose(){this.disposed||(this.disposed=!0,this.deactivate())}async hydrate(e){if(e.hydrateTask)return e.hydrateTask;let t;t=(async()=>{e.loading=!0,this.emit(e);try{let s=await this.options.transport.getDraft(e.projectId,e.sessionId);if(!this.canSynchronize(e))return;e.authoritative=$Dt(s),e.dirtyText||(e.desiredText=s.text),e.dirtyAttachments||(e.desiredAttachments=ff(s.attachments)),e.dirtyText=e.desiredText!==s.text,e.dirtyAttachments=!QY(e.desiredAttachments,s.attachments),e.error=""}catch(s){throw this.isCurrent(e)&&(e.error=this.errorMessage(s)),s}finally{e.loading=!1,this.emit(e)}})(),e.hydrateTask=t;try{await t}finally{e.hydrateTask===t&&(e.hydrateTask=void 0)}}async flushActive(e){e.saving=!0,this.emit(e);let t=0;try{for(;this.canSynchronize(e)&&(e.dirtyText||e.dirtyAttachments);){let s=e.desiredText,i=ff(e.desiredAttachments),o=e.dirtyText,n=e.dirtyAttachments,l=e.authoritative.revision,c;try{c=await this.options.transport.updateDraft(e.projectId,e.sessionId,l,{...o?{text:s}:{},...n?{attachments:i}:{}})}catch(d){if(this.options.transport.isConflict(d)&&t<4){t+=1,await this.hydrate(e);continue}throw d}if(!this.canSynchronize(e))break;t=0,c.revision>=e.authoritative.revision&&(e.authoritative=$Dt(c),o&&e.desiredText===s&&(e.dirtyText=!1),n&&QY(e.desiredAttachments,i)&&(e.dirtyAttachments=!1)),e.dirtyText=e.desiredText!==e.authoritative.text,e.dirtyAttachments=!QY(e.desiredAttachments,e.authoritative.attachments),e.error="",this.emit(e)}return{text:e.desiredText,attachments:ff(e.desiredAttachments),revision:e.authoritative.revision}}catch(s){throw this.isCurrent(e)&&(e.error=this.errorMessage(s),this.emit(e)),s}finally{e.saving=!1,this.emit(e),e.drainAfterDeactivate=!1}}schedule(e){!this.isCurrent(e)||e.loading||(e.debounceTimer&&clearTimeout(e.debounceTimer),e.debounceTimer=setTimeout(()=>{e.debounceTimer=void 0,this.flush().catch(t=>this.options.onError?.(t))},this.debounceMs))}isCurrent(e){return!this.disposed&&this.active===e&&this.generation===e.generation}canSynchronize(e){return this.isCurrent(e)||e.drainAfterDeactivate}emit(e){this.isCurrent(e)&&this.options.onState(this.publicState(e))}publicState(e){return{projectId:e.projectId,sessionId:{...e.sessionId},text:e.desiredText,attachments:ff(e.desiredAttachments),revision:e.authoritative.revision,loading:e.loading,saving:e.saving,error:e.error}}errorMessage(e){return e instanceof Error?e.message:"Draft synchronization failed."}};var ZDt,JDt,eOt,tOt,rOt,sOt,iOt,aOt,oOt,nOt,lOt,cOt,dOt,uOt,pOt,hOt,fOt,mOt,gOt,vOt,bOt,_Ot,yOt,xOt,SOt,wOt,EOt,COt,TOt,kOt,MOt,IOt,ROt,DOt,OOt,AOt,NOt,POt,LOt,BOt,FOt,$Ot,zOt,UOt,HOt,qOt,VOt,GOt,WOt,jOt,YOt,KOt,QOt,Ze,IGe,RGe,DGe,OGe,AGe,NGe,PGe,LGe,BGe,FGe,$Ge,zGe,UGe,HGe,qGe,VGe,GGe,WGe,jGe,YGe,KGe,QGe,XGe,ZGe,JGe,eWe,tWe,rWe,sWe,iWe,aWe,oWe,nWe,lWe,cWe,dWe,uWe,pWe,hWe,fWe,mWe,gWe,vWe,bWe,_We,yWe,xWe,SWe,wWe,EWe,CWe,uoe=a(()=>({truncated:!1,historyLimited:!1,unavailable:!1}),"emptyDetailHistoryLimits"),zDt=a((r,e)=>r==="backfilling"?"Loading earlier messages...":r!=="partial"?"":e.unavailable?"Earlier history is unavailable":e.truncated&&e.historyLimited?"Earlier messages were removed by the provider and additional history was limited by the controller":e.truncated?"Earlier messages were removed by the provider":e.historyLimited?"Earlier history is limited by the controller":"Earlier history is unavailable","detailHistoryStatusText"),pr=a(r=>typeof r=="string"&&r.trim().length>0,"isNonEmptyString"),UDt=a(r=>{if(!Array.isArray(r))return;let e=[];for(let t of r){if(!t||typeof t!="object"||Array.isArray(t))return;let s=t;if(!pr(s.id)||!pr(s.name)||!pr(s.mediaType)||!Number.isSafeInteger(s.size)||(s.size??-1)<0||!["image","text","binary"].includes(s.kind??"")||typeof s.dataBase64!="string")return;e.push({id:s.id,name:s.name,mediaType:s.mediaType,size:s.size,kind:s.kind,dataBase64:s.dataBase64})}return e},"toControllerDraftAttachments"),XY=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Object.keys(e).length===2&&(e.harnessId==="opencode"||e.harnessId==="flex"||e.harnessId==="controller")&&typeof e.nativeId=="string"&&e.nativeId.length>0&&new TextEncoder().encode(e.nativeId).byteLength<=512},"isControllerRuntimeId"),qt=a(r=>XY(r)&&r.harnessId!=="controller","isSessionRuntimeId"),mf=a(r=>XY(r)&&r.harnessId==="controller","isTerminalRuntimeId"),gf=a(r=>qt(r.id),"hasSessionRuntimeId"),str=a(r=>mf(r.id),"hasTerminalRuntimeId"),ct=a(r=>{if(!XY(r))throw new Error("Invalid qualified runtime ID.");return JSON.stringify([r.harnessId,r.nativeId])},"controllerRuntimeIdToUiKey"),dt=a((r,e)=>r===void 0?e===void 0:e!==void 0&&ct(r)===ct(e),"controllerRuntimeIdsEqual"),SGe=a((r,e)=>{if(Object.is(r,e))return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((n,l)=>SGe(n,e[l]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=r,s=e,i=Object.keys(t).sort(),o=Object.keys(s).sort();return i.length===o.length&&i.every((n,l)=>n===o[l]&&SGe(t[n],s[n]))},"controllerJsonValuesEqual"),itr=a(r=>{let e=r.trim();if(!e)throw new Error("Enter a browser address.");let t=e.match(/^([a-z][a-z\d+.-]*):\/\//i)?.[1]?.toLowerCase();if(t!==void 0&&t!=="http"&&t!=="https")throw new Error("Enter a valid HTTP or HTTPS address.");let s=/^[^/?#\s]+:\d+(?:[/?#]|$)/.test(e);if(/^[a-z][a-z\d+.-]*:/i.test(e)&&t===void 0&&!s)throw new Error("Enter a valid HTTP or HTTPS address.");let i=t===void 0?`https://${e}`:e,o;try{o=new URL(i)}catch{throw new Error("Enter a valid HTTP or HTTPS address.")}if(o.protocol!=="http:"&&o.protocol!=="https:"||!o.hostname)throw new Error("Enter a valid HTTP or HTTPS address.");return o.href},"controllerNormalizeBrowserAddress"),my=a(r=>new Map([...r].map(e=>[ct(e),e])),"runtimeIdsByUiKey"),Ll=a(r=>r==="flex"?"Flex":"OpenCode","sessionHarnessLabel"),ZY=a(r=>`${r.harnessId==="controller"?"Controller":Ll(r.harnessId)}:${r.nativeId}`,"runtimeIdDisplay"),atr=a(r=>{let e=r.harnessId;if(e!=="opencode"&&e!=="flex")throw new Error("Invalid model harness ID.");return e},"modelHarnessId"),poe=a(r=>{let e=r;return[Ll(atr(r)),`${r.providerID}/${r.modelID}`,e.providerConnectionId?`connection ${e.providerConnectionId}`:""].filter(Boolean).join(" \xB7 ")},"modelOptionLabel"),ow=a((r,e)=>r.length===e.length&&r.every((t,s)=>t===e[s]),"sameStringArray"),otr=a((r,e)=>r.length===e.length&&r.every((t,s)=>t.label===e[s]?.label&&t.value===e[s]?.value),"sameComposerOptions"),Xo=a(r=>`draft:${r}`,"draftSessionKey"),HDt=2e3,qDt=50,ntr=1e4,ltr=HDt*2.5,ctr=500,hoe=128,JY=4*1024*1024,dtr=16,utr=40,ptr=4,VDt=400,foe="Live preview is unavailable. Open the subagent chat to view its transcript.",GDt=50,WDt="harnessControllerSidebarWidth",htr=292,wGe=260,EGe=520,jDt=8,CGe=1e4,ftr=900*1e3,mtr=300*1e3,gtr=360*1e3,vtr=12,YDt=500,TGe=a(r=>Math.min(EGe,Math.max(wGe,Math.round(r))),"controllerClampSidebarWidth"),nw=a(r=>{let e=new TextEncoder,t=[],s=2;for(let i=r.length-1;i>=0;i-=1){let o=r[i],n=e.encode(JSON.stringify(o)).byteLength,l=t.length===0?0:1;if(t.length>=ODt||s+l+n>ADt)break;t.unshift(o),s+=l+n}return{bundles:t,limited:t.length!==r.length}},"boundedNewestMessageBundles"),btr=a((r,e,t)=>{let s=new Set(e.flatMap(l=>l.sessionIds.map(ct))),i=r.filter(gf).filter(l=>l.archivedAt===void 0).map((l,c)=>({id:l.id,sortAt:l.updatedAt,sourceIndex:c})).filter(l=>!s.has(ct(l.id))).sort((l,c)=>c.sortAt-l.sortAt||l.sourceIndex-c.sourceIndex),o=new Map(i.map(l=>[ct(l.id),l])),n=[];for(let l of t){let c=ct(l);o.has(c)&&(n.push(l),o.delete(c))}return n.push(...i.filter(l=>o.has(ct(l.id))).map(l=>l.id)),n},"controllerEffectiveUngroupedLayoutItemIds"),kGe=a((r,e,t)=>{let s=new Set(e.flatMap(l=>l.sessionIds.map(ct))),i=new Map(r.filter(gf).map(l=>[ct(l.id),l])),o=[],n=new Set;for(let l of t){let c=ct(l),d=i.get(c);!s.has(c)&&!n.has(c)&&(d===void 0||d.archivedAt===void 0)&&(o.push(l),n.add(c))}for(let l of btr(r,e,t)){let c=ct(l);n.has(c)||(o.push(l),n.add(c))}return o},"controllerMutableUngroupedLayoutItemIds"),eK=a(r=>({groups:r.groups.map(e=>({...e,sessionIds:e.sessionIds.map(t=>({...t}))})),ungroupedSessionIds:r.ungroupedSessionIds.map(e=>({...e})),revision:r.revision}),"cloneSessionLayout"),_tr=[{name:"compact",description:"Summarize the conversation and compact its context"},{name:"undo",description:"Revert the last message and its changes"},{name:"redo",description:"Restore previously reverted messages"},{name:"init",description:"Analyze the project and create AGENTS.md"}],ytr=[{name:"compact",description:"Summarize the conversation and compact its context"},{name:"init",description:"Analyze the project and create AGENTS.md"},{name:"undo",description:"Revert the last message and its changes"},{name:"redo",description:"Restore previously reverted messages"}],xtr=a(r=>r==="flex"?ytr:_tr,"localBuiltinSlashCommands"),Str=a(r=>{let e="";for(let s=0;s<r.length;s+=32768)e+=String.fromCharCode(...r.subarray(s,s+32768));return btoa(e)},"bytesToBase64"),wtr=a(r=>{try{let e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)t[s]=e.charCodeAt(s);return t}catch{return new Uint8Array(0)}},"base64ToBytes"),wr=a(r=>r instanceof Error&&r.message?r.message:String(r||"The operation failed."),"errorMessage"),MGe=a(r=>typeof r=="number"&&Number.isFinite(r)?`${Math.round(r)}%`:"--","formatPercentage"),KDt=a(r=>{if(typeof r!="number"||!Number.isFinite(r)||r<0)return"--";let e=["B","KB","MB","GB","TB"],t=r,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;let i=t>=100||s===0?0:1;return`${t.toFixed(i)} ${e[s]}`},"formatBytes"),QDt=a(r=>{if(typeof r!="number"||!Number.isFinite(r)||r<0)return"--";let e=["B","K","M","G","T"],t=r,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;let i=t>=100||s===0?0:1;return`${t.toFixed(i)}${e[s]}/s`},"formatByteRate"),Etr=a(r=>!Number.isFinite(r)||r<0?"--":r<60?`${Math.ceil(r)}s`:r<3600?`${Math.ceil(r/60)}m`:r<86400?`${Math.ceil(r/3600)}h`:`${Math.ceil(r/86400)}d`,"formatDuration"),Ctr=a((r,e,t)=>e===r?"match":t===`${r}->${e}`?"stale":"reload","controllerBundleReloadDecision");QOt=[tt.customElement("harness-controller-app")];var It=class It extends(KOt=tt.DeesElement,YOt=[tt.state()],jOt=[tt.state()],WOt=[tt.state()],GOt=[tt.state()],VOt=[tt.state()],qOt=[tt.state()],HOt=[tt.state()],UOt=[tt.state()],zOt=[tt.state()],$Ot=[tt.state()],FOt=[tt.state()],BOt=[tt.state()],LOt=[tt.state()],POt=[tt.state()],NOt=[tt.state()],AOt=[tt.state()],OOt=[tt.state()],DOt=[tt.state()],ROt=[tt.state()],IOt=[tt.state()],MOt=[tt.state()],kOt=[tt.state()],TOt=[tt.state()],COt=[tt.state()],EOt=[tt.state()],wOt=[tt.state()],SOt=[tt.state()],xOt=[tt.state()],yOt=[tt.state()],_Ot=[tt.state()],bOt=[tt.state()],vOt=[tt.state()],gOt=[tt.state()],mOt=[tt.state()],fOt=[tt.state()],hOt=[tt.state()],pOt=[tt.state()],uOt=[tt.state()],dOt=[tt.state()],cOt=[tt.state()],lOt=[tt.state()],nOt=[tt.state()],oOt=[tt.state()],aOt=[tt.state()],iOt=[tt.state()],sOt=[tt.state()],rOt=[tt.state()],tOt=[tt.state()],eOt=[tt.state()],JDt=[tt.state()],ZDt=[tt.state()],KOt){constructor(){super();Pe(this,"socketClient");Pe(this,"sessionDraftSync");Pe(this,"componentConnected",!1);Pe(this,"lifecycleGeneration",0);Pe(this,"connectionGeneration",0);Pe(this,"sessionsRequestId",0);Pe(this,"detailRequestId",0);Pe(this,"detailEnrichmentGeneration",0);Pe(this,"detailRequestAbortController");Pe(this,"detailAuxiliaryAbortController");Pe(this,"detailHistoryAbortController");Pe(this,"detailRefreshInFlight");Pe(this,"detailRefreshPending",!1);Pe(this,"detailRefreshRestartEnrichment",!1);Pe(this,"detailHistoryOwnership");Pe(this,"detailHistoryCursor");Pe(this,"detailHistorySeenCursors",new Set);Pe(this,"detailBundles",[]);Pe(this,"detailBundleKeys",new Set);Pe(this,"detailCoreBundleKeys",new Set);Pe(this,"detailProvisionalBundleKeys",new Set);Pe(this,"detailHistoryLimits",uoe());Pe(this,"activeCeremonyId");Pe(this,"activeMutationId");Pe(this,"mutationSequence",0);Pe(this,"refreshTimer");Pe(this,"immediateRefreshTimer");Pe(this,"immediateRefreshPending",!1);Pe(this,"refreshInFlight");Pe(this,"systemMetricsTimer");Pe(this,"legalDisclosureHideTimer");Pe(this,"highCpuStartedAt");Pe(this,"lastCpuSampleAt");Pe(this,"refreshPending",!1);Pe(this,"projectsRequestId",0);Pe(this,"modelCatalogRequestId",0);Pe(this,"layoutRequestId",0);Pe(this,"terminalRequestId",0);Pe(this,"resourceRequestId",0);Pe(this,"browserViewGeneration",0);Pe(this,"browserNavigationRequestId",0);Pe(this,"browserViewOpenAbortController");Pe(this,"browserNavigationAbortController");Pe(this,"browserViewId","");Pe(this,"browserViewConnectionGeneration",-1);Pe(this,"browserViewPendingClose");Pe(this,"browserViewResourceId","");Pe(this,"browserViewAttachmentRevision",-1);Pe(this,"browserViewState");Pe(this,"browserViewListeners",new Set);Pe(this,"browserRenderer");Pe(this,"suggestRequestId",0);Pe(this,"suggestDebounce");Pe(this,"controllerStatus");Pe(this,"providers",[]);Pe(this,"providerConnections",[]);Pe(this,"providerManagementState","loading");Pe(this,"providerManagementRefreshRequested",!1);Pe(this,"providerManagementTask");Pe(this,"activeProviderLogin");Pe(this,"providerLoginBeginTask");Pe(this,"providerLoginPollTimer");Pe(this,"providerLoginPollDeadline");Pe(this,"providerLoginPollTask");Pe(this,"providerLoginPollTaskKey");Pe(this,"providerRefreshPollTimers",new Map);Pe(this,"providerRefreshJobs",new Map);Pe(this,"providerRefreshPollDeadlines",new Map);Pe(this,"providerRefreshStartTokens",new Map);Pe(this,"providerRefreshStatuses",new Map);Pe(this,"providerRateLimits",new Map);Pe(this,"providerRateLimitErrors",new Map);Pe(this,"providerRateLimitTasks",new Map);Pe(this,"providerOpenCodeSwitch");Pe(this,"providerOpenCodeSwitchStatus","");Pe(this,"providerLoginStatusRoot");Pe(this,"providerLoginStatusError","");Pe(this,"settingsModalRef");Pe(this,"settingsModalGeneration",0);Pe(this,"settingsModalOpenTask");Pe(this,"settingsModalContentRenderer");Pe(this,"settingsDraftHarnessId","opencode");Pe(this,"settingsDraftModelString","");Pe(this,"settingsDraftEffortString","");Pe(this,"settingsDraftAutoAccept",!1);Pe(this,"autoAcceptPermissions",!1);Pe(this,"modelChoicesByString",new Map);Pe(this,"modelVariantsByString",new Map);Pe(this,"flexDefaultModelStrings",new Set);Pe(this,"defaultModelStrings",{opencode:"",flex:""});Pe(this,"defaultEffortStrings",{opencode:"",flex:""});Pe(this,"defaultModelChoices",{});Pe(this,"sessionModelOverrides",new Map);Pe(this,"sessionEffortOverrides",new Map);Pe(this,"sessionAccountOverrides",new Map);Pe(this,"sessionModelSaveTokens",new Map);Pe(this,"flexAccountOptionsCache",[]);Pe(this,"modelOptionsCache",new Map);Pe(this,"effortOptionsCache",new Map);Pe(this,"slashCatalogRequestId",0);Pe(this,"slashMenuEpisode",0);Pe(this,"slashMenuEligible",!1);Pe(this,"slashCatalogState");Pe(this,"slashCatalogRequest");Pe(this,"sessionsLoadedForProjectId","");Pe(this,"groupsLoadedForProjectId","");Pe(this,"terminalsLoadedForProjectId","");Pe(this,"resourcesLoadedForProjectId","");Pe(this,"pendingTerminalOutput",[]);Pe(this,"answeredQuestionCards",new Map);Pe(this,"answeredPermissionCards",new Map);Pe(this,"pendingQuestionBatchAnswers",new Map);Pe(this,"authoritativeStatusesByProject",new Map);Pe(this,"finishedSessionIdsByProject",new Map);Pe(this,"errorSessionIdsByProject",new Map);Pe(this,"optimisticWorkingIdsByProject",new Map);Pe(this,"sessionEventRevisionByProject",new Map);Pe(this,"confirmedSessionLayouts",new Map);Pe(this,"pendingSessionLayouts",new Map);Pe(this,"layoutSavePromises",new Map);Pe(this,"pendingLayoutReloadProjectIds",new Set);Pe(this,"staleDraftSessionsToDelete",new Map);Pe(this,"staleDraftSessionCleanupPromises",new Map);Pe(this,"staleDraftSessionCleanupAttempts",new Map);Pe(this,"sidebarResizePointerId");Pe(this,"sidebarResizeStartX",0);Pe(this,"sidebarResizeBaseline");Pe(this,"composerFocusRequestId",0);Pe(this,"composerFocusRequest");Pe(this,"composerFocusInFlight");Pe(this,"draftSessionGeneration",0);Pe(this,"draftSessionDetailReadyId");Pe(this,"scratchpadSaveIdsBySession",new Map);Pe(this,"scratchpadErrorsBySession",new Map);Pe(this,"intelligenceAskIdsBySession",new Map);Pe(this,"intelligenceErrorsBySession",new Map);Pe(this,"liveToolOverlays",new Map);Pe(this,"liveReasoningUpdates",new Map);Pe(this,"liveTextUpdates",new Map);Pe(this,"liveToolHydrationFloors",new Map);Pe(this,"liveMessageHydrationFloors",new Map);Pe(this,"liveHistoryBarriers",new Map);Pe(this,"liveToolOverlayBytes",0);Pe(this,"liveMessageOverlayBytes",0);Pe(this,"liveToolStreamEpochs",new Map);Pe(this,"liveMessageStreamEpochs",new Map);Pe(this,"subtaskPreviewEntries",new Map);Pe(this,"subtaskPreviewGeneration",0);Pe(this,"subtaskPreviewHydrationQueue",[]);Pe(this,"activeSubtaskPreviewHydrations",0);Jt(this,IGe,pt(Ze,8,this,"new")),pt(Ze,11,this);Jt(this,RGe,pt(Ze,12,this,"loading")),pt(Ze,15,this);Jt(this,DGe,pt(Ze,16,this,!1)),pt(Ze,19,this);Jt(this,OGe,pt(Ze,20,this,!1)),pt(Ze,23,this);Jt(this,AGe,pt(Ze,24,this,"")),pt(Ze,27,this);Jt(this,NGe,pt(Ze,28,this,"")),pt(Ze,31,this);Jt(this,PGe,pt(Ze,32,this,!1)),pt(Ze,35,this);Jt(this,LGe,pt(Ze,36,this,"")),pt(Ze,39,this);Jt(this,BGe,pt(Ze,40,this,"")),pt(Ze,43,this);Jt(this,FGe,pt(Ze,44,this,"")),pt(Ze,47,this);Jt(this,$Ge,pt(Ze,48,this,!1)),pt(Ze,51,this);Jt(this,zGe,pt(Ze,52,this,[])),pt(Ze,55,this);Jt(this,UGe,pt(Ze,56,this,"")),pt(Ze,59,this);Jt(this,HGe,pt(Ze,60,this,!1)),pt(Ze,63,this);Jt(this,qGe,pt(Ze,64,this,"")),pt(Ze,67,this);Jt(this,VGe,pt(Ze,68,this,"")),pt(Ze,71,this);Jt(this,GGe,pt(Ze,72,this,[])),pt(Ze,75,this);Jt(this,WGe,pt(Ze,76,this,[])),pt(Ze,79,this);Jt(this,jGe,pt(Ze,80,this)),pt(Ze,83,this);Jt(this,YGe,pt(Ze,84,this,[])),pt(Ze,87,this);Jt(this,KGe,pt(Ze,88,this,"")),pt(Ze,91,this);Jt(this,QGe,pt(Ze,92,this)),pt(Ze,95,this);Jt(this,XGe,pt(Ze,96,this,"")),pt(Ze,99,this);Jt(this,ZGe,pt(Ze,100,this)),pt(Ze,103,this);Jt(this,JGe,pt(Ze,104,this,!1)),pt(Ze,107,this);Jt(this,eWe,pt(Ze,108,this,!1)),pt(Ze,111,this);Jt(this,tWe,pt(Ze,112,this,[])),pt(Ze,115,this);Jt(this,rWe,pt(Ze,116,this)),pt(Ze,119,this);Jt(this,sWe,pt(Ze,120,this)),pt(Ze,123,this);Jt(this,iWe,pt(Ze,124,this,!1)),pt(Ze,127,this);Jt(this,aWe,pt(Ze,128,this,!1)),pt(Ze,131,this);Jt(this,oWe,pt(Ze,132,this,"idle")),pt(Ze,135,this);Jt(this,nWe,pt(Ze,136,this,!1)),pt(Ze,139,this);Jt(this,lWe,pt(Ze,140,this,!1)),pt(Ze,143,this);Jt(this,cWe,pt(Ze,144,this,!1)),pt(Ze,147,this);Jt(this,dWe,pt(Ze,148,this,"opencode")),pt(Ze,151,this);Jt(this,uWe,pt(Ze,152,this)),pt(Ze,155,this);Jt(this,pWe,pt(Ze,156,this,"")),pt(Ze,159,this);Jt(this,hWe,pt(Ze,160,this,[])),pt(Ze,163,this);Jt(this,fWe,pt(Ze,164,this,[])),pt(Ze,167,this);Jt(this,mWe,pt(Ze,168,this,[])),pt(Ze,171,this);Jt(this,gWe,pt(Ze,172,this,0)),pt(Ze,175,this);Jt(this,vWe,pt(Ze,176,this,htr)),pt(Ze,179,this);Jt(this,bWe,pt(Ze,180,this,!1)),pt(Ze,183,this);Jt(this,_We,pt(Ze,184,this,!0)),pt(Ze,187,this);Jt(this,yWe,pt(Ze,188,this,[])),pt(Ze,191,this);Jt(this,xWe,pt(Ze,192,this,[])),pt(Ze,195,this);Jt(this,SWe,pt(Ze,196,this,"")),pt(Ze,199,this);Jt(this,wWe,pt(Ze,200,this,!1)),pt(Ze,203,this);Jt(this,EWe,pt(Ze,204,this)),pt(Ze,207,this);Jt(this,CWe,pt(Ze,208,this,!1)),pt(Ze,211,this);Pe(this,"handleSidebarPointerDown",a(t=>{if(t.button!==0)return;let s=t.currentTarget;s instanceof HTMLElement&&(t.preventDefault(),this.sidebarResizePointerId=t.pointerId,this.sidebarResizeStartX=t.clientX,this.sidebarResizeBaseline=this.sidebarWidth,this.sidebarResizing=!0,s.setPointerCapture(t.pointerId),s.focus())},"handleSidebarPointerDown"));Pe(this,"handleSidebarPointerMove",a(t=>{t.pointerId!==this.sidebarResizePointerId||this.sidebarResizeBaseline===void 0||(this.sidebarWidth=TGe(this.sidebarResizeBaseline+t.clientX-this.sidebarResizeStartX))},"handleSidebarPointerMove"));Pe(this,"handleSidebarPointerEnd",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.finishSidebarResize()},"handleSidebarPointerEnd"));Pe(this,"handleSidebarPointerCancel",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.cancelSidebarResize()},"handleSidebarPointerCancel"));Pe(this,"handleSidebarLostPointerCapture",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.cancelSidebarResize()},"handleSidebarLostPointerCapture"));Pe(this,"handleSidebarKeyDown",a(t=>{if(t.key==="Escape"&&this.sidebarResizeBaseline!==void 0){t.preventDefault(),this.cancelSidebarResize();return}let s;t.key==="ArrowLeft"&&(s=this.sidebarWidth-jDt),t.key==="ArrowRight"&&(s=this.sidebarWidth+jDt),t.key==="Home"&&(s=wGe),t.key==="End"&&(s=EGe),s!==void 0&&(t.preventDefault(),this.sidebarResizeBaseline??=this.sidebarWidth,this.sidebarWidth=TGe(s))},"handleSidebarKeyDown"));Pe(this,"handleSidebarKeyUp",a(t=>{["ArrowLeft","ArrowRight","Home","End"].includes(t.key)&&this.persistSidebarWidth()},"handleSidebarKeyUp"));Pe(this,"handleSidebarBlur",a(()=>{this.sidebarResizePointerId===void 0&&(this.sidebarResizeBaseline=void 0,this.persistSidebarWidth())},"handleSidebarBlur"));Pe(this,"toggleConversationSidebar",a(()=>{this.conversationSidebarVisible&&this.cancelSidebarResize(),this.conversationSidebarVisible=!this.conversationSidebarVisible},"toggleConversationSidebar"));Pe(this,"showLegalDisclosure",a(()=>{this.legalDisclosureHideTimer&&(clearTimeout(this.legalDisclosureHideTimer),this.legalDisclosureHideTimer=void 0),this.legalDisclosureVisible=!0},"showLegalDisclosure"));Pe(this,"scheduleLegalDisclosureHide",a(()=>{this.legalDisclosureHideTimer&&clearTimeout(this.legalDisclosureHideTimer),this.legalDisclosureHideTimer=setTimeout(()=>{this.legalDisclosureHideTimer=void 0,this.legalDisclosureVisible=!1},ctr)},"scheduleLegalDisclosureHide"));Pe(this,"handleSetupSubmit",a(async t=>{let s=t.detail?.data?.setupCode;if(!pr(s)||this.ceremonyBusy){pr(s)||(this.setupError="Enter the setup code printed by the CLI.");return}let i=t.currentTarget;if(!(i instanceof ks.DeesForm)){this.setupError="The setup form could not be read.";return}let o=s.trim(),n=this.connectionGeneration,l=Symbol("setupCeremony");this.activeCeremonyId=l,this.ceremonyBusy=!0,this.setupError="",i.setStatus("pending","Creating passkey\u2026");try{let c=await this.socketClient.fire("controller.auth.setup.begin",{setupCode:o});this.assertActiveCeremony(l,n);let d=await cy.startRegistration({optionsJSON:c.options});this.assertActiveCeremony(l,n);let u=await this.socketClient.fire("controller.auth.setup.finish",{ceremonyId:c.ceremonyId,setupCode:o,response:d});this.assertActiveCeremony(l,n),this.storeResumeToken(u.resumeToken),this.authState="ready",this.authenticated=!0,await this.loadWorkspaceData()}catch(c){this.activeCeremonyId===l&&this.isCurrentConnection(n)&&(this.setupError=wr(c),i.setStatus("normal","Create passkey"))}finally{this.activeCeremonyId===l&&(this.activeCeremonyId=void 0,this.ceremonyBusy=!1)}},"handleSetupSubmit"));Pe(this,"handleTempPasswordSubmit",a(async t=>{let s=t.detail?.data?.tempPassword,i=t.currentTarget;if(!(i instanceof ks.DeesForm))return;if(!pr(s)){this.tempPasswordError="Enter the temporary password printed by the CLI.";return}let o=this.connectionGeneration;this.tempPasswordError="",i.setStatus("pending","Signing in\u2026");try{let n=await this.socketClient.fire("controller.auth.temppassword.login",{password:s.trim()});if(!this.isCurrentConnection(o))return;this.storeResumeToken(n.resumeToken),this.authenticated=!0,this.showTempPasswordForm=!1,await this.loadWorkspaceData()}catch(n){this.isCurrentConnection(o)&&(this.tempPasswordError=wr(n),i.setStatus("normal","Sign in"))}},"handleTempPasswordSubmit"));Pe(this,"passkeyLoginHandler",a(async t=>{if(t.intent!=="authenticate"||t.mediation!=="optional")throw new Error("Only explicit passkey authentication is supported.");if(this.ceremonyBusy)throw new Error("A passkey ceremony is already running.");let s=this.connectionGeneration,i=Symbol("authenticationCeremony");this.activeCeremonyId=i,this.ceremonyBusy=!0;try{this.assertActiveCeremony(i,s,t.signal);let o=await this.socketClient.fire("controller.auth.authentication.begin",{});this.assertActiveCeremony(i,s,t.signal);let n=await cy.startAuthentication({optionsJSON:o.options});this.assertActiveCeremony(i,s,t.signal);let l=await this.socketClient.fire("controller.auth.authentication.finish",{ceremonyId:o.ceremonyId,response:n});this.assertActiveCeremony(i,s,t.signal),this.storeResumeToken(l.resumeToken),this.authenticated=!0,await this.loadWorkspaceData()}finally{this.activeCeremonyId===i&&(this.activeCeremonyId=void 0,this.ceremonyBusy=!1)}},"passkeyLoginHandler"));Pe(this,"handleLoadEarlier",a(()=>{this.loadEarlierSessionHistory()},"handleLoadEarlier"));Pe(this,"handleSessionSelect",a(t=>{let s=t.detail?.session?.id;if(!pr(s))return;let i=my(this.terminals.map(n=>n.id).filter(mf)).get(s);if(i){this.openTerminalById(i);return}let o=my(this.sessions.map(n=>n.id).filter(qt)).get(s);o&&this.openSessionById(o)},"handleSessionSelect"));Pe(this,"handleResourceSelect",a(t=>{let s=t.detail?.resource?.id,i=this.resources.find(o=>o.id===s);if(!(!i||i.lifecycle!=="active")){if(this.invalidateSlashCatalog(),this.selectedResourceId=i.id,i.kind==="browser"){if(this.closeTerminalView(),i.browserRuntimeState!=="available"){this.workspaceError="BrowserRuntime is unavailable on this host.";return}this.openBrowserView(i);return}if(this.closeBrowserView(),i.processState!=="running"){this.closeTerminalView(),this.workspaceError="";return}this.openTerminalById({harnessId:"controller",nativeId:i.id})}},"handleResourceSelect"));Pe(this,"handleBrowserAddressNavigation",a(t=>{t.type==="submit"&&t.preventDefault();let s=t.currentTarget,i=s instanceof HTMLFormElement?s:s instanceof HTMLElement?s.closest("form"):null;i&&this.navigateBrowserAddress(i)},"handleBrowserAddressNavigation"));Pe(this,"handleResourceAssociationRequest",a(t=>{let s=t.detail,i=this.resources.find(n=>n.id===s?.resource?.id);if(!s||!i||this.mutationPending)return;let o=s.toSessionId===null?null:my(this.sessions.map(n=>n.id).filter(qt)).get(s.toSessionId);s.toSessionId!==null&&!o||this.changeResourceAssociation(i,o??null)},"handleResourceAssociationRequest"));Pe(this,"handleResourceContext",a(t=>{let s=t.detail,i=this.resources.find(n=>n.id===s?.resource?.id);if(!i||!s?.originalEvent||this.mutationPending)return;let o=s.originalEvent instanceof MouseEvent?s.originalEvent:new MouseEvent("contextmenu",{clientX:s.clientX,clientY:s.clientY});ks.DeesContextmenu.openContextMenuWithOptions(o,[{name:"Rename",iconName:"lucide:Pencil",action:a(async()=>this.showTextPromptModal({heading:`Rename ${i.kind}`,label:"Title",initialValue:i.title,submitLabel:"Rename",onSubmit:a(async n=>this.renameResource(i.id,n),"onSubmit")}),"action")},...i.kind==="terminal"?[{name:i.processState==="running"?"Stop":"Start",iconName:i.processState==="running"?"lucide:Square":"lucide:Play",action:a(async()=>this.setResourceRunning(i,i.processState!=="running"),"action")}]:[],{divider:!0},{name:"Retire",iconName:"lucide:Trash2",action:a(async()=>this.showResourceRetirementConfirmation(i),"action")}]).then(n=>{if(!n){s.close();return}let l=new MutationObserver(()=>{n.isConnected||(l.disconnect(),s.close())});l.observe(document.body,{childList:!0})}).catch(()=>s.close())},"handleResourceContext"));Pe(this,"showArchivedModal",a(()=>{let t=this.sessions.filter(gf).filter(i=>i.archivedAt!==void 0),s;ks.DeesModal.createAndShow({heading:"Archived conversations",width:"small",content:tt.html`
41192
+ `,e)}a(iGe,"warnOnBrokenImplementation");function aGe(){if(!Sp())return qae.stubThis(new Promise(e=>e(!1)));let r=globalThis.PublicKeyCredential;return r?.isConditionalMediationAvailable===void 0?qae.stubThis(new Promise(e=>e(!1))):qae.stubThis(r.isConditionalMediationAvailable())}a(aGe,"browserSupportsWebAuthnAutofill");var qae={stubThis:a(r=>r,"stubThis")};function I2t({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Ti({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new Ti({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let s=globalThis.location.hostname;if(Uae(s)){if(t.rpId!==s)return new Ti({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new Ti({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new Ti({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}a(I2t,"identifyAuthenticationError");async function mKt(r){!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});let{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!Sp())throw new Error("WebAuthn is not supported in this browser");let i;e.allowCredentials?.length!==0&&(i=e.allowCredentials?.map(zae));let o={...e,challenge:uf(e.challenge),allowCredentials:i},n={};if(t){if(!await aGe())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');n.mediation="conditional",o.allowCredentials=[]}n.publicKey=o,n.signal=zY.createNewAbortSignal();let l;try{l=await navigator.credentials.get(n)}catch(v){throw I2t({error:v,options:n})}if(!l)throw new Error("Authentication was not completed");let{id:c,rawId:d,response:u,type:p}=l,h;return u.userHandle&&(h=Yn(u.userHandle)),{id:c,rawId:Yn(d),response:{authenticatorData:Yn(u.authenticatorData),clientDataJSON:Yn(u.clientDataJSON),signature:Yn(u.signature),userHandle:h},type:p,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:Hae(l.authenticatorAttachment)}}a(mKt,"startAuthentication");function gKt(){return Sp()?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():new Promise(r=>r(!1))}a(gKt,"platformAuthenticatorIsAvailable");var yGe=xo(IDt(),1),soe=yGe.default;var uqa=128,pqa=16,hqa=2,fqa=12288,mqa=8294400,gqa=34226176,vqa=4096,bqa=4096,_qa=3,yqa=.001,xqa=1e4,hy=class extends Error{static{a(this,"LiveBrowserOperationTimeoutError")}},Qo=class extends Error{static{a(this,"LiveBrowserRunAbortedError")}},Wa=class extends Error{static{a(this,"LiveBrowserFrameProtocolError")}},ioe=class extends Error{static{a(this,"LiveBrowserFrameIntegrityError")}},hf=a((r,e)=>r.width===e.width&&r.height===e.height&&r.deviceScaleFactor===e.deviceScaleFactor,"viewportEquals"),GY=a(r=>({alt:r.altKey,control:r.ctrlKey,meta:r.metaKey,shift:r.shiftKey}),"createModifiers"),Her=a(r=>({tabId:r.tabId,sequence:r.sequence,generation:r.generation,viewportRevision:r.viewportRevision}),"createFrameAcknowledgementRequest"),aw=a(r=>({tabId:r.tabId,generation:r.generation,viewportRevision:r.viewportRevision}),"createInputIdentity"),wp=a(r=>r instanceof Error?r.message:String(r),"getErrorMessage"),fy=class{static{a(this,"LiveBrowserCanvasRenderer")}constructor(e){this.lifecycleTail=Promise.resolve(),this.runEpoch=0,this.running=!1,this.suspended=!1,this.stopping=!1,this.interruptionRequested=!1,this.operationControllers=new Set,this.acceptingFrames=!1,this.focusWasAdjusted=!1,this.focusHadTabIndex=!1,this.focusTabIndexValue=null,this.highestFrameSequence=-1,this.acknowledgementPromises=new Set,this.rawDecodeSettlementPromises=new Set,this.inputBlocked=!0,this.inputCommands=[],this.inputProcessing=!1,this.inputIdleResolvers=[],this.inputResetTail=Promise.resolve(),this.inputResetCount=0,this.inputOverflowRecoveryPending=!1,this.pressedKeys=new Map,this.pressedMouseButtons=new Map,this.capturedPointerIds=new Set,this.viewportProcessing=!1,this.canvas=e.canvas,this.client=e.client,this.focusTarget=e.focusTarget??this.canvas,this.resizeTarget=e.resizeTarget,this.getDeviceScaleFactor=e.getDeviceScaleFactor??(()=>window.devicePixelRatio||1),this.operationTimeoutMs=this.validateTimeout(e.operationTimeoutMs??1e4,"operationTimeoutMs"),this.frameDecodeTimeoutMs=this.validateTimeout(e.frameDecodeTimeoutMs??this.operationTimeoutMs,"frameDecodeTimeoutMs"),this.onError=e.onError,this.onFrameRendered=e.onFrameRendered,this.initialCanvasWidth=this.canvas.width,this.initialCanvasHeight=this.canvas.height;let t=this.canvas.getContext("2d");if(!t)throw new Error("LiveBrowserCanvasRenderer requires a 2D canvas context");this.canvasContext=t}get isRunning(){return this.running}get isSuspended(){return this.suspended}start(){return this.enqueueLifecycle(async()=>{if(!this.running){if(this.suspended)throw new Error("Live browser renderer is suspended; call resume() to start a fresh run");await this.startRun(!1)}})}stop(){return this.interruptRun(this.runEpoch),this.enqueueLifecycle(async()=>{let e=this.runEpoch;if(this.interruptRun(e),this.stopping){await this.finishRun(e,!1);return}this.suspended&&(this.suspended=!1,this.restoreCanvasAndFocus())})}suspend(){return this.interruptRun(this.runEpoch),this.enqueueLifecycle(async()=>{let e=this.runEpoch;this.interruptRun(e),this.stopping&&await this.finishRun(e,!0)})}resume(){return this.enqueueLifecycle(async()=>{if(!this.running){if(!this.suspended)throw new Error("Live browser renderer is not suspended");await this.startRun(!0)}})}async insertText(e){let t=this.requireInputFrame(),s=aw(t);await this.enqueueInputCommand({kind:"text",runEpoch:this.runEpoch,execute:a(async i=>{await this.client.insertText({...s,text:e},i)},"execute")})}syncViewport(){if(!this.running||this.stopping||this.interruptionRequested||!this.resizeTarget)return;let e=Math.floor(this.resizeTarget.clientWidth),t=Math.floor(this.resizeTarget.clientHeight);this.queueViewport(e,t,this.runEpoch)}enqueueLifecycle(e){let t=this.lifecycleTail.then(e,e);return this.lifecycleTail=t.then(()=>{},()=>{}),t}async startRun(e){await Promise.all([...this.rawDecodeSettlementPromises]);let t=++this.runEpoch;this.runController=new AbortController,this.running=!0,this.suspended=!1,this.stopping=!1,this.interruptionRequested=!1,this.acceptingFrames=!0,this.inputBlocked=!0,this.state=void 0,this.displayedFrame=void 0,this.highestFrameSequence=-1,this.clearCanvas();try{this.makeFocusTargetFocusable(),this.installDomListeners(t),this.unsubscribe=this.client.onEvent(s=>{this.handleEvent(s,t)}),this.applyState(this.client.getState(),t),this.installResizeObserver(t)}catch(s){throw this.interruptRun(t),await this.finishRun(t,e),s}}interruptRun(e){if(e!==this.runEpoch||!this.running&&!this.stopping)return;this.running=!1,this.stopping=!0,this.interruptionRequested=!0,this.acceptingFrames=!1,this.inputBlocked=!0,this.pendingViewport=void 0,this.queuedFrame=void 0,this.displayedFrame=void 0,this.resizeFence=void 0,this.releasePointerCaptures(),this.clearCanvas();let t=new Qo(`Live browser renderer run ${e} was interrupted`);this.runController?.abort(t);for(let i of this.operationControllers)i.abort(t);let s=this.inputCommands.splice(0);for(let i of s)i.reject(t);this.pressedKeys.clear(),this.pressedMouseButtons.clear(),this.inputOverflowRecoveryPending=!1}async finishRun(e,t){if(e===this.runEpoch)try{this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.listenerController?.abort(),this.listenerController=void 0;let s=this.unsubscribe;if(this.unsubscribe=void 0,s)try{s()}catch(i){this.reportError({code:"renderer_cleanup_failed",message:`Could not unsubscribe the live browser renderer: ${wp(i)}`,cause:i},e)}await Promise.allSettled([this.viewportProcessingPromise,this.inputResetTail,this.waitForInputIdle(),this.frameProcessingPromise,...this.acknowledgementPromises])}finally{for(let o of this.operationControllers)o.abort(new Qo(`Live browser renderer run ${e} finished`));this.operationControllers.clear(),this.runController=void 0,this.running=!1,this.suspended=t,this.acceptingFrames=!1,this.state=void 0,this.displayedFrame=void 0,this.highestFrameSequence=-1,this.queuedFrame=void 0,this.frameProcessingPromise=void 0,this.acknowledgementPromises.clear(),this.resizeFence=void 0,this.pendingViewport=void 0,this.inFlightViewport=void 0,this.viewportProcessing=!1,this.viewportProcessingPromise=void 0,this.inputResetPromise=void 0,this.inputResetTail=Promise.resolve(),this.inputResetCount=0,this.inputBlocked=!0,this.pressedKeys.clear(),this.pressedMouseButtons.clear(),this.releasePointerCaptures();let s=this.inputCommands.splice(0);for(let o of s)o.reject(new Error("Live browser renderer stopped before dispatching input"));let i=this.inputIdleResolvers;this.inputIdleResolvers=[];for(let o of i)o();this.restoreCanvasAndFocus(),this.interruptionRequested=!1,this.stopping=!1}}restoreCanvasAndFocus(){this.canvas.width=this.initialCanvasWidth,this.canvas.height=this.initialCanvasHeight,this.restoreFocusTarget()}installDomListeners(e){let t=new AbortController,s=t.signal;this.listenerController=t,this.canvas.addEventListener("pointerdown",i=>{this.handlePointerDown(i,e)},{signal:s}),this.canvas.addEventListener("pointermove",i=>{this.handlePointerMove(i,e)},{signal:s}),this.canvas.addEventListener("pointerup",i=>{this.handlePointerUp(i,e)},{signal:s}),this.canvas.addEventListener("pointercancel",i=>{this.releasePointerCapture(i.pointerId),this.scheduleInputReset(!1,e)},{signal:s}),this.canvas.addEventListener("lostpointercapture",i=>{this.capturedPointerIds.delete(i.pointerId),this.pressedMouseButtons.size>0&&this.scheduleInputReset(!1,e)},{signal:s}),this.canvas.addEventListener("contextmenu",i=>{i.preventDefault()},{signal:s}),this.canvas.addEventListener("wheel",i=>{this.handleWheel(i,e)},{passive:!1,signal:s}),this.focusTarget.addEventListener("keydown",i=>{this.handleKey(i,"down",e)},{signal:s}),this.focusTarget.addEventListener("keyup",i=>{this.handleKey(i,"up",e)},{signal:s}),this.focusTarget.addEventListener("compositionend",i=>{!this.inputBlocked&&i.data&&this.insertText(i.data).catch(()=>{})},{signal:s}),window.addEventListener("blur",()=>{this.scheduleInputReset(!1,e)},{signal:s}),window.addEventListener("resize",()=>{this.syncViewport()},{signal:s}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.scheduleInputReset(!1,e)},{signal:s})}installResizeObserver(e){this.resizeTarget&&(this.resizeObserver=new ResizeObserver(t=>{let s=t.find(i=>i.target===this.resizeTarget);s&&this.queueViewport(Math.floor(s.contentRect.width),Math.floor(s.contentRect.height),e)}),this.resizeObserver.observe(this.resizeTarget),this.syncViewport())}handleEvent(e,t){if(e.type==="frame"){this.queueFrame(e.frame,t);return}if(!(!this.running||t!==this.runEpoch)){if(e.type==="state"){this.applyState(e.state,t);return}this.reportError({code:"remote_browser_error",message:`${e.error.code}: ${e.error.message}`,cause:e.error},t)}}applyState(e,t){if(!(!this.running||t!==this.runEpoch)){if(this.state=e,this.displayedFrame&&this.isStateAheadOfDisplayedFrame(e,this.displayedFrame)){this.displayedFrame=void 0,this.clearCanvas(),this.scheduleInputReset(!1,t);return}this.updateInputAvailability()}}isStateAheadOfDisplayedFrame(e,t){if(e.status!=="running"||e.activeTabId!==t.tabId)return!0;let s=e.tabs.find(i=>i.id===t.tabId);return!s||s.status!=="open"?!0:e.viewportRevision>t.viewportRevision||s.generation>t.generation}queueFrame(e,t){if(!this.running||!this.acceptingFrames||t!==this.runEpoch)return;try{if(this.validateFrame(e),e.sequence<=this.highestFrameSequence)throw new Wa(`frame.sequence ${e.sequence} must be strictly greater than current run high-water ${this.highestFrameSequence}`)}catch(i){this.requestSuspend(t),this.reportError({code:"frame_render_failed",message:`Rejected invalid live browser frame: ${wp(i)}`,cause:i,frame:e},t);return}this.highestFrameSequence=e.sequence;let s={frame:e,runEpoch:t,acknowledgementAttempted:!1};if(this.queuedFrame){let i=this.queuedFrame;this.queuedFrame=void 0,this.acknowledgeFrame(i)}this.queuedFrame=s,this.ensureFrameProcessor()}ensureFrameProcessor(){if(this.frameProcessingPromise||!this.queuedFrame)return;let e=this.processFrameQueue().finally(()=>{this.frameProcessingPromise===e&&(this.frameProcessingPromise=void 0,this.queuedFrame&&this.ensureFrameProcessor())});this.frameProcessingPromise=e}async processFrameQueue(){for(;this.queuedFrame;){let e=this.queuedFrame;this.queuedFrame=void 0,await this.processFrame(e)}}async processFrame(e){let{frame:t,runEpoch:s}=e,i,o=!1,n;try{if(!this.canRenderFrame(t,s))return;let l=new Uint8Array(t.data.byteLength);if(l.set(t.data),i=await this.decodeFrame(new Blob([l.buffer],{type:t.mimeType}),s),i.width!==t.width||i.height!==t.height)throw new ioe(`decoded frame dimensions ${i.width}x${i.height} do not match ${t.width}x${t.height}`);if(!this.canRenderFrame(t,s)||t.sequence!==this.highestFrameSequence)return;this.canvas.width=t.width,this.canvas.height=t.height,this.canvasContext.clearRect(0,0,t.width,t.height),this.canvasContext.drawImage(i,0,0,t.width,t.height),this.displayedFrame={tabId:t.tabId,sequence:t.sequence,generation:t.generation,viewportRevision:t.viewportRevision,viewport:{...t.viewport}},this.resizeFence&&!this.viewportProcessing&&t.viewportRevision>=this.resizeFence.minimumViewportRevision&&hf(t.viewport,this.resizeFence.target)&&(this.resizeFence=void 0),this.updateInputAvailability(),this.callFrameRendered(t,s)}catch(l){if(l instanceof Qo)return;o=!0,n=l}finally{i?.close(),await this.acknowledgeFrame(e),o&&(this.requestSuspend(s),this.reportError({code:"frame_render_failed",message:`Could not render live browser frame: ${wp(n)}`,cause:n,frame:t},s))}}canRenderFrame(e,t){if(!this.running||!this.acceptingFrames||t!==this.runEpoch||this.viewportProcessing)return!1;let s=this.state;if(!s||s.status!=="running"||s.activeTabId!==e.tabId)return!1;let i=s.tabs.find(o=>o.id===e.tabId);return!i||i.status!=="open"||s.viewportRevision>e.viewportRevision||i.generation>e.generation?!1:this.resizeFence?e.viewportRevision>=this.resizeFence.minimumViewportRevision&&hf(e.viewport,this.resizeFence.target):!0}acknowledgeFrame(e){if(e.acknowledgementAttempted||(e.acknowledgementAttempted=!0,!this.isRunActive(e.runEpoch)))return Promise.resolve();if(this.acknowledgementPromises.size>=16)return this.requestSuspend(e.runEpoch),this.reportError({code:"frame_acknowledgement_failed",message:"Live browser frame acknowledgement capacity of 16 was reached"},e.runEpoch),Promise.resolve();let t=this.runClientOperation(i=>this.client.acknowledgeFrame(Her(e.frame),i),"frame acknowledgement",e.runEpoch).then(()=>{}).catch(i=>{i instanceof Qo||(this.requestSuspend(e.runEpoch),this.reportError({code:"frame_acknowledgement_failed",message:`Could not acknowledge live browser frame: ${wp(i)}`,cause:i,frame:e.frame},e.runEpoch))}),s;return s=t.finally(()=>{this.acknowledgementPromises.delete(s)}),this.acknowledgementPromises.add(s),s}handlePointerDown(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getMouseButton(e.button);if(!s)return;let i=this.getInputFrame();if(!i||t!==this.runEpoch)return;e.preventDefault();let o=this.mapCoordinates(e,i.viewport);if(!o)return;this.focusTarget.focus({preventScroll:!0});try{this.canvas.setPointerCapture(e.pointerId),this.capturedPointerIds.add(e.pointerId)}catch{}let n={...aw(i),type:"down",...o,button:s,buttons:e.buttons,clickCount:Math.min(3,Math.max(1,e.detail||1)),modifiers:GY(e)};this.enqueueInputCommand({kind:"mouse",runEpoch:t,execute:a(async l=>this.client.dispatchMouse(n,l),"execute"),onAttempt:a(()=>this.pressedMouseButtons.set(s,n),"onAttempt")}).catch(()=>{})}handlePointerMove(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getInputFrame();if(!s||t!==this.runEpoch)return;e.preventDefault();let i=this.mapCoordinates(e,s.viewport);if(!i){this.releasePointerCapture(e.pointerId),this.scheduleInputReset(!1,t);return}let o={...aw(s),type:"move",...i,button:"none",buttons:e.buttons,modifiers:GY(e)};this.enqueueInputCommand({kind:"mouseMove",runEpoch:t,execute:a(async n=>this.client.dispatchMouse(o,n),"execute")}).catch(()=>{})}handlePointerUp(e,t){if(e.pointerType&&e.pointerType!=="mouse")return;let s=this.getMouseButton(e.button),i=this.getInputFrame();if(!s||!i||t!==this.runEpoch){this.releasePointerCapture(e.pointerId);return}e.preventDefault();let o=this.mapCoordinates(e,i.viewport);if(!o){this.releasePointerCapture(e.pointerId),this.scheduleInputReset(!1,t);return}let n={...aw(i),type:"up",...o,button:s,buttons:e.buttons,clickCount:Math.min(3,Math.max(1,e.detail||1)),modifiers:GY(e)};this.enqueueInputCommand({kind:"mouse",runEpoch:t,execute:a(async l=>this.client.dispatchMouse(n,l),"execute"),onSuccess:a(()=>this.pressedMouseButtons.delete(s),"onSuccess")}).catch(()=>{}),this.releasePointerCapture(e.pointerId)}handleWheel(e,t){let s=this.getInputFrame();if(!s||t!==this.runEpoch)return;e.preventDefault();let i=this.mapCoordinates(e,s.viewport);if(!i)return;let o=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?s.viewport.height:1,n=a(l=>Math.max(-1e6,Math.min(1e6,l)),"clampDelta");this.enqueueInputCommand({kind:"wheel",runEpoch:t,execute:a(async l=>this.client.dispatchWheel({...aw(s),...i,deltaX:n(e.deltaX*o),deltaY:n(e.deltaY*o),modifiers:GY(e)},l),"execute")}).catch(()=>{})}handleKey(e,t,s){let i=this.getInputFrame();if(!i||s!==this.runEpoch||e.isComposing||e.key==="Process")return;e.preventDefault();let o=t==="down"&&e.key.length===1&&!e.metaKey&&(!e.ctrlKey||e.altKey)?e.key:void 0,n={...aw(i),type:t,key:e.key,code:e.code||void 0,text:o,windowsVirtualKeyCode:e.keyCode||void 0,autoRepeat:e.repeat,isKeypad:e.location===KeyboardEvent.DOM_KEY_LOCATION_NUMPAD,location:e.location,modifiers:GY(e)},l=e.code||e.key;this.enqueueInputCommand({kind:"key",runEpoch:s,execute:a(async c=>this.client.dispatchKey(n,c),"execute"),onAttempt:t==="down"?()=>this.pressedKeys.set(l,n):void 0,onSuccess:a(()=>{t==="up"&&this.pressedKeys.delete(l)},"onSuccess")}).catch(()=>{})}mapCoordinates(e,t){let s=this.canvas.getBoundingClientRect();if(s.width<=0||s.height<=0)return;let i=(e.clientX-s.left)/s.width*t.width,o=(e.clientY-s.top)/s.height*t.height;return{x:Math.max(0,Math.min(t.width-.001,i)),y:Math.max(0,Math.min(t.height-.001,o))}}getMouseButton(e){return e===0?"left":e===1?"middle":e===2?"right":e===3?"back":e===4?"forward":void 0}getInputFrame(){return this.inputBlocked||!this.isDisplayedFrameCurrent()?void 0:this.displayedFrame}requireInputFrame(){let e=this.getInputFrame();if(!e)throw new Error("Live browser input is unavailable until a current frame is displayed");return e}isDisplayedFrameCurrent(){let e=this.state,t=this.displayedFrame;if(!e||!t||e.status!=="running"||e.activeTabId!==t.tabId||e.viewportRevision>t.viewportRevision)return!1;let s=e.tabs.find(i=>i.id===t.tabId);return!!(s&&s.status==="open"&&s.generation<=t.generation)}enqueueInputCommand(e){return!this.running||this.inputBlocked||e.runEpoch!==this.runEpoch?Promise.reject(new Error("Live browser input is currently blocked")):new Promise((t,s)=>{let i={...e,resolve:t,reject:s},o=this.inputCommands.at(-1);if(i.kind==="mouseMove"&&o?.kind==="mouseMove")o.resolve(),this.inputCommands[this.inputCommands.length-1]=i;else if(this.inputCommands.length>=128){if(i.kind==="mouseMove"){t();return}let n=new Error("Live browser input queue reached its capacity");this.reportError({code:"input_queue_capacity_exceeded",message:n.message,cause:n},i.runEpoch),s(n),this.recoverFromInputOverflow(i.runEpoch);return}else this.inputCommands.push(i);this.processInputCommands()})}processInputCommands(){this.inputProcessing||(this.inputProcessing=!0,(async()=>{try{for(;this.inputCommands.length>0;){let e=this.inputCommands.shift();if(!this.isRunActive(e.runEpoch)){e.reject(new Qo(`Live browser input belongs to inactive run ${e.runEpoch}`));continue}try{if(e.onAttempt?.(),await this.runClientOperation(e.execute,"input dispatch",e.runEpoch),!this.isRunActive(e.runEpoch))throw new Qo(`Live browser input belongs to inactive run ${e.runEpoch}`);e.onSuccess?.(),e.resolve()}catch(t){if(e.reject(t),t instanceof Qo)continue;t instanceof hy&&this.requestSuspend(e.runEpoch),this.reportError({code:"input_dispatch_failed",message:`Could not dispatch live browser input: ${wp(t)}`,cause:t},e.runEpoch);let s=this.inputCommands.splice(0);for(let i of s)i.reject(new Error("Live browser input was abandoned after a dispatch failure"));!(t instanceof hy)&&!this.stopping&&this.scheduleInputReset(!1,e.runEpoch)}}}finally{if(this.inputProcessing=!1,this.inputCommands.length>0)this.processInputCommands();else{let e=this.inputIdleResolvers;this.inputIdleResolvers=[];for(let t of e)t()}}})())}waitForInputIdle(){return!this.inputProcessing&&this.inputCommands.length===0?Promise.resolve():new Promise(e=>{this.inputIdleResolvers.push(e)})}scheduleInputReset(e,t){if(t!==this.runEpoch||this.stopping)return Promise.resolve();if(this.inputBlocked=!0,this.releasePointerCaptures(),e&&(this.displayedFrame=void 0,this.clearCanvas()),this.inputResetPromise)return this.inputResetPromise;this.inputResetCount++;let s;return s=this.inputResetTail.then(async()=>{await this.waitForInputIdle(),await this.releasePressedInput(t)}).finally(()=>{this.inputResetCount--,this.inputResetPromise===s&&(this.inputResetPromise=void 0),this.updateInputAvailability()}),this.inputResetPromise=s,this.inputResetTail=s.then(()=>{},()=>{}),s}recoverFromInputOverflow(e){this.inputOverflowRecoveryPending||(this.inputOverflowRecoveryPending=!0,this.inputBlocked=!0,this.scheduleInputReset(!1,e).finally(()=>{this.inputOverflowRecoveryPending=!1}))}async releasePressedInput(e){for(let[t,s]of[...this.pressedKeys.entries()])await this.tryInputRelease(o=>this.client.dispatchKey({...s,type:"up",text:void 0,autoRepeat:!1,modifiers:{}},o),e)&&this.pressedKeys.get(t)===s&&this.pressedKeys.delete(t);for(let[t,s]of[...this.pressedMouseButtons.entries()])await this.tryInputRelease(o=>this.client.dispatchMouse({...s,type:"up",buttons:0,clickCount:1,modifiers:{}},o),e)&&this.pressedMouseButtons.get(t)===s&&this.pressedMouseButtons.delete(t)}async tryInputRelease(e,t){let s;for(let i=0;i<2;i++)try{return await this.runClientOperation(e,"input release",t),!0}catch(o){if(o instanceof Qo)return!1;s=o}return this.requestSuspend(t),this.reportInputReleaseError(s,t),!1}reportInputReleaseError(e,t){this.reportError({code:"input_dispatch_failed",message:`Could not release live browser input: ${wp(e)}`,cause:e},t)}queueViewport(e,t,s){if(!this.running||this.stopping||this.interruptionRequested||s!==this.runEpoch||e<=0||t<=0)return;let i=this.getDeviceScaleFactor();if(!Number.isFinite(i)||i<=0){this.reportError({code:"viewport_update_failed",message:"Live browser device scale factor must be a positive finite number"},s);return}let o={width:e,height:t,deviceScaleFactor:i};if(!(this.pendingViewport&&hf(o,this.pendingViewport))){if(this.inFlightViewport&&hf(o,this.inFlightViewport)){this.pendingViewport=void 0;return}if(!this.inFlightViewport&&this.resizeFence&&hf(o,this.resizeFence.target)){this.pendingViewport=void 0;return}if(!this.inFlightViewport&&!this.resizeFence&&this.state&&hf(o,this.state.viewport)){this.pendingViewport=void 0,this.updateInputAvailability();return}this.pendingViewport=o,this.inputBlocked=!0,this.ensureViewportProcessor(s)}}ensureViewportProcessor(e){if(this.viewportProcessingPromise||!this.pendingViewport)return;let t=this.processViewportQueue(e).finally(()=>{this.viewportProcessingPromise===t&&(this.viewportProcessingPromise=void 0,this.pendingViewport&&this.running&&!this.stopping&&e===this.runEpoch&&this.ensureViewportProcessor(e))});this.viewportProcessingPromise=t}async processViewportQueue(e){this.viewportProcessing=!0;try{for(;this.pendingViewport&&this.running&&!this.stopping&&e===this.runEpoch;){let t=this.pendingViewport;if(this.pendingViewport=void 0,this.inFlightViewport=t,!this.resizeFence&&this.state&&hf(t,this.state.viewport)){this.inFlightViewport=void 0;continue}if(await this.scheduleInputReset(!0,e),!this.running||this.stopping||e!==this.runEpoch)return;let s=this.state?.viewportRevision??0,i=this.resizeFence?.minimumViewportRevision??s;try{if(await this.runClientOperation(o=>this.client.setViewport(t,o),"viewport update",e),!this.running||this.stopping||e!==this.runEpoch)return;this.resizeFence={target:t,minimumViewportRevision:Math.max(s,i)+1}}catch(o){e===this.runEpoch&&!(o instanceof Qo)&&(this.resizeFence=void 0,o instanceof hy&&this.requestSuspend(e),this.reportError({code:"viewport_update_failed",message:`Could not update live browser viewport: ${wp(o)}`,cause:o},e))}finally{this.inFlightViewport&&hf(this.inFlightViewport,t)&&(this.inFlightViewport=void 0)}}}finally{this.viewportProcessing=!1,this.updateInputAvailability()}}updateInputAvailability(){this.inputBlocked=!(this.running&&this.acceptingFrames&&!this.viewportProcessing&&!this.resizeFence&&this.inputResetCount===0&&this.isDisplayedFrameCurrent())}makeFocusTargetFocusable(){this.focusWasAdjusted=!1,!(this.focusTarget.tabIndex>=0)&&(this.focusHadTabIndex=this.focusTarget.hasAttribute("tabindex"),this.focusTabIndexValue=this.focusTarget.getAttribute("tabindex"),this.focusTarget.setAttribute("tabindex","0"),this.focusWasAdjusted=!0)}restoreFocusTarget(){this.focusWasAdjusted&&(this.focusHadTabIndex&&this.focusTabIndexValue!==null?this.focusTarget.setAttribute("tabindex",this.focusTabIndexValue):this.focusTarget.removeAttribute("tabindex"),this.focusWasAdjusted=!1)}clearCanvas(){this.canvasContext.clearRect(0,0,this.canvas.width,this.canvas.height)}callFrameRendered(e,t){if(!(!this.onFrameRendered||t!==this.runEpoch||!this.running))try{this.onFrameRendered(e)}catch(s){this.reportError({code:"renderer_callback_failed",message:`Live browser frame callback failed: ${wp(s)}`,cause:s,frame:e},t)}}reportError(e,t){if(!(!this.onError||t!==this.runEpoch))try{this.onError(e)}catch{}}requestSuspend(e){!this.isRunActive(e)||this.interruptionRequested||(this.interruptRun(e),this.suspend())}validateTimeout(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`${t} must be a positive finite number`);return e}runClientOperation(e,t,s){return this.runAbortableOperation(i=>e({signal:i}),this.operationTimeoutMs,t,s)}runAbortableOperation(e,t,s,i){let o=this.runController;if(!o||!this.isRunActive(i)||o.signal.aborted)return Promise.reject(new Qo(`Cannot start ${s} for inactive run ${i}`));let n=new AbortController;this.operationControllers.add(n);let l=a(()=>{let p=o.signal.reason instanceof Error?o.signal.reason:new Qo(`Live browser renderer run ${i} was interrupted`);n.abort(p)},"abortFromRun");o.signal.addEventListener("abort",l,{once:!0});let c=globalThis.setTimeout(()=>{n.abort(new hy(`${s} timed out after ${t}ms`))},t),d=a(()=>{},"abortOperation");return new Promise((p,h)=>{let v=!1,g=a(m=>{v||(v=!0,m())},"settle");d=a(()=>{let m=n.signal.reason instanceof Error?n.signal.reason:new Qo(`${s} was aborted`);g(()=>h(m))},"abortOperation"),n.signal.addEventListener("abort",d,{once:!0});let f;try{f=e(n.signal)}catch(m){g(()=>h(m));return}f.then(m=>{g(()=>p(m))},m=>{g(()=>h(m))})}).finally(()=>{globalThis.clearTimeout(c),o.signal.removeEventListener("abort",l),n.signal.removeEventListener("abort",d),this.operationControllers.delete(n)})}async decodeFrame(e,t){let s;try{s=createImageBitmap(e)}catch(o){throw o}let i;i=s.then(()=>{},()=>{}).finally(()=>{this.rawDecodeSettlementPromises.delete(i)}),this.rawDecodeSettlementPromises.add(i);try{return await this.runAbortableOperation(async()=>s,this.frameDecodeTimeoutMs,"frame decode",t)}catch(o){throw o instanceof hy||o instanceof Qo?(s.then(n=>n.close(),()=>{}),o):new ioe(`frame bytes could not be decoded: ${wp(o)}`,{cause:o})}}isRunActive(e){return!!(this.running&&!this.stopping&&e===this.runEpoch&&this.runController&&!this.runController.signal.aborted)}validateFrame(e){if(!e||typeof e!="object")throw new Wa("frame must be an object");if(typeof e.tabId!="string"||e.tabId.length===0||e.tabId.length>4096)throw new Wa("frame.tabId must be a non-empty bounded string");if(this.validateProtocolInteger(e.sequence,"frame.sequence",1),this.validateProtocolInteger(e.generation,"frame.generation",1),this.validateProtocolInteger(e.viewportRevision,"frame.viewportRevision",1),this.validateViewport(e.viewport,"frame.viewport"),e.format!=="jpeg"&&e.format!=="png")throw new Wa("frame.format must be jpeg or png");let t=e.format==="jpeg"?"image/jpeg":"image/png";if(e.mimeType!==t)throw new Wa(`frame.mimeType must be ${t} for ${e.format}`);if(this.validateProtocolInteger(e.width,"frame.width",1,12288),this.validateProtocolInteger(e.height,"frame.height",1,12288),e.width*e.height>8294400)throw new Wa("frame pixel area must not exceed 8294400");if(!(e.data instanceof Uint8Array))throw new Wa("frame.data must be a Uint8Array");if(e.data.byteLength===0||e.data.byteLength>34226176)throw new Wa("frame.data byte length must be between 1 and 34226176");let s=e.metadata;if(!s||typeof s!="object")throw new Wa("frame.metadata must be an object");if(this.validateProtocolNumber(s.offsetTop,"frame.metadata.offsetTop"),this.validateProtocolNumber(s.pageScaleFactor,"frame.metadata.pageScaleFactor",!0),this.validateProtocolNumber(s.deviceWidth,"frame.metadata.deviceWidth",!0),this.validateProtocolNumber(s.deviceHeight,"frame.metadata.deviceHeight",!0),s.deviceWidth>12288||s.deviceHeight>12288||s.deviceWidth*s.deviceHeight>8294400)throw new Wa("frame metadata dimensions must fit within 8294400 pixels");this.validateProtocolNumber(s.scrollOffsetX,"frame.metadata.scrollOffsetX"),this.validateProtocolNumber(s.scrollOffsetY,"frame.metadata.scrollOffsetY"),s.timestamp!==void 0&&this.validateProtocolNumber(s.timestamp,"frame.metadata.timestamp")}validateViewport(e,t){if(!e||typeof e!="object")throw new Wa(`${t} must be an object`);if(this.validateProtocolInteger(e.width,`${t}.width`,1,4096),this.validateProtocolInteger(e.height,`${t}.height`,1,4096),this.validateProtocolNumber(e.deviceScaleFactor,`${t}.deviceScaleFactor`,!0),e.deviceScaleFactor>3)throw new Wa(`${t}.deviceScaleFactor must not exceed 3`);if(e.width*e.height*e.deviceScaleFactor*e.deviceScaleFactor>8294400)throw new Wa(`${t} physical pixel area must not exceed 8294400`)}validateProtocolInteger(e,t,s,i=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(e)||e<s||e>i)throw new Wa(`${t} must be an integer between ${s} and ${i}`)}validateProtocolNumber(e,t,s=!1){if(!Number.isFinite(e)||s&&e<=0)throw new Wa(`${t} must be a ${s?"positive ":""}finite number`)}releasePointerCapture(e){this.capturedPointerIds.delete(e);try{this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e)}catch{}}releasePointerCaptures(){let e=[...this.capturedPointerIds];this.capturedPointerIds.clear();for(let t of e)this.releasePointerCapture(t)}};Te();var aoe=xo(D2t(),1),ooe=xo(O2t(),1);var Rqa=22,Dqa=2,Oqa="agl",DDt=48*1024,noe=128*1024,Aqa=20,ODt=200,ADt=512*1024,NDt="[elided: this tool payload exceeds the live transfer budget]",loe=64*1024,WY=8,jY=10*1024*1024,YY=10*1024*1024,Nqa=16*1024,Pqa=["opencode","flex","controller"],Lqa=["opencode","flex"],Ep=a(r=>JSON.stringify([r.harnessId,r.nativeId]),"controllerRuntimeIdKey"),Bqa=["compact","undo","redo","init"],PDt=["sessions.changed","session.changed","session.draft.changed","session.history.changed","session.tool.updated","session.reasoning.updated","session.text.updated","permissions.changed","harness.changed","projects.changed","settings.changed","sessiongroups.changed","resources.changed","terminals.changed","upgrade.changed"];var qer=new Set(PDt),Ver=35e3,Ia=a((r,e)=>{if(!r||typeof r!="object")return!1;let t=r;return Object.keys(t).length===2&&typeof t.harnessId=="string"&&e.has(t.harnessId)&&typeof t.nativeId=="string"&&t.nativeId.length>0&&new TextEncoder().encode(t.nativeId).byteLength<=512},"isQualifiedRuntimeId"),Cp=new Set(["opencode","flex"]),Ger=new Set(["controller"]),Wer=new Set(["sessionId","messageId","partId","callId","toolName","status","input","output","exitCode","errorText","childSessionId","model","startedAt","finishedAt","order","sourceUpdatedAt","revision","streamEpoch"]),jer=new Set(["sessionId","messageId","partId","text","status","order","sourceUpdatedAt","revision","streamEpoch"]),Yer=new Set(["sessionId","messageId","partId","text","status","order","sourceUpdatedAt","revision","streamEpoch"]),BDt=a(r=>r===void 0||typeof r=="number"&&Number.isFinite(r),"isOptionalFiniteNumber"),xGe=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Object.keys(e).length===2&&Number.isSafeInteger(e.messageIndex)&&(e.messageIndex??-1)>=0&&Number.isSafeInteger(e.partIndex)&&(e.partIndex??-1)>=0},"isTranscriptOrder"),FDt=a((r,e)=>{try{return new TextEncoder().encode(JSON.stringify(r)).byteLength<=e}catch{return!1}},"serializedBytesWithin"),Ker=a(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;if(!Object.keys(e).every(t=>["id","name","mediaType","size","kind","dataBase64"].includes(t))||typeof e.id!="string"||e.id.length===0||new TextEncoder().encode(e.id).byteLength>512||typeof e.name!="string"||e.name.length===0||new TextEncoder().encode(e.name).byteLength>255||typeof e.mediaType!="string"||e.mediaType.length===0||new TextEncoder().encode(e.mediaType).byteLength>129||!Number.isSafeInteger(e.size)||(e.size??-1)<0||(e.size??0)>jY||!["image","text","binary"].includes(e.kind??"")||typeof e.dataBase64!="string")return!1;try{let t=globalThis.atob(e.dataBase64);return t.length===e.size&&globalThis.btoa(t)===e.dataBase64}catch{return!1}},"isDraftAttachment"),Qer=a(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return!(!Object.keys(e).every(t=>["revision","text","attachments"].includes(t))||!Number.isSafeInteger(e.revision)||(e.revision??-1)<0||e.text===void 0&&e.attachments===void 0||e.text!==void 0&&(typeof e.text!="string"||new TextEncoder().encode(e.text).byteLength>loe)||e.attachments!==void 0&&(!Array.isArray(e.attachments)||e.attachments.length>WY||!e.attachments.every(Ker)||e.attachments.reduce((t,s)=>t+s.size,0)>YY))},"isSessionDraftUpdate"),Xer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>Wer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&Ia(e.callId,t)&&typeof e.toolName=="string"&&e.toolName.length>0&&new TextEncoder().encode(e.toolName).byteLength<=2048&&["pending","running","completed","error"].includes(e.status??"")&&(e.exitCode===void 0||Number.isSafeInteger(e.exitCode)&&e.exitCode>=0)&&(e.errorText===void 0||typeof e.errorText=="string")&&(e.childSessionId===void 0||Ia(e.childSessionId,t))&&(e.model===void 0||typeof e.model=="string")&&BDt(e.startedAt)&&BDt(e.finishedAt)&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&e.sourceUpdatedAt>=0&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerToolExecution"),Zer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>jer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&typeof e.text=="string"&&new TextEncoder().encode(e.text).byteLength<=noe&&["running","completed","cancelled"].includes(e.status??"")&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerReasoningUpdate"),Jer=a(r=>{if(!r||typeof r!="object")return!1;let e=r;if(!Ia(e.sessionId,Cp))return!1;let t=new Set([e.sessionId.harnessId]);return Object.keys(e).every(s=>Yer.has(s))&&Ia(e.messageId,t)&&Ia(e.partId,t)&&typeof e.text=="string"&&new TextEncoder().encode(e.text).byteLength<=noe&&["running","completed"].includes(e.status??"")&&(e.order===void 0||xGe(e.order))&&(e.sessionId.harnessId!=="flex"||e.order!==void 0)&&(e.sessionId.harnessId!=="opencode"||e.order===void 0)&&typeof e.sourceUpdatedAt=="number"&&Number.isFinite(e.sourceUpdatedAt)&&Number.isSafeInteger(e.revision)&&(e.revision??-1)>=0&&Number.isSafeInteger(e.streamEpoch)&&(e.streamEpoch??-1)>=0},"isControllerTextUpdate"),etr=a(r=>{if(!r||typeof r!="object")return!1;let e=r,t=e.sessionStatus!==void 0||e.sessionError!==void 0,s=e.toolExecution!==void 0,i=e.reasoningUpdate!==void 0,o=e.textUpdate!==void 0,n=e.sessionDraftUpdate!==void 0,l=e.upgrade!==void 0;return typeof e.type=="string"&&qer.has(e.type)&&typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)&&(e.harnessId===void 0||e.harnessId==="opencode"||e.harnessId==="flex")&&(e.sessionId===void 0||Ia(e.sessionId,Cp))&&(e.projectId===void 0||typeof e.projectId=="string"&&e.projectId.length>0)&&(e.sessionStatus===void 0||["idle","busy","retry","error"].includes(e.sessionStatus))&&(e.sessionError===void 0||e.sessionError===!0)&&(e.toolStreamEpoch===void 0||Number.isSafeInteger(e.toolStreamEpoch)&&e.toolStreamEpoch>=0)&&(e.messageStreamEpoch===void 0||Number.isSafeInteger(e.messageStreamEpoch)&&e.messageStreamEpoch>=0)&&(e.toolExecution===void 0||Xer(e.toolExecution))&&(e.reasoningUpdate===void 0||Zer(e.reasoningUpdate))&&(e.textUpdate===void 0||Jer(e.textUpdate))&&(e.sessionDraftUpdate===void 0||Qer(e.sessionDraftUpdate))&&(!s||FDt(e,DDt))&&(!(i||o)||FDt(e,noe))&&(!t||e.type==="session.changed"&&Ia(e.sessionId,Cp))&&(e.harnessId===void 0||e.sessionId===void 0||e.harnessId===e.sessionId.harnessId)&&!(e.sessionStatus!==void 0&&e.sessionError===!0)&&(!s||e.type==="session.tool.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.sessionId.harnessId&&e.harnessId===e.toolExecution.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.toolExecution.sessionId)&&e.toolStreamEpoch===void 0)&&(s||e.type!=="session.tool.updated")&&(!i||e.type==="session.reasoning.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.reasoningUpdate.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.reasoningUpdate.sessionId))&&(i||e.type!=="session.reasoning.updated")&&(!o||e.type==="session.text.updated"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp)&&e.harnessId===e.textUpdate.sessionId.harnessId&&Ep(e.sessionId)===Ep(e.textUpdate.sessionId))&&(o||e.type!=="session.text.updated")&&(!n||e.type==="session.draft.changed"&&typeof e.projectId=="string"&&Ia(e.sessionId,Cp))&&(n||e.type!=="session.draft.changed")&&(e.toolStreamEpoch===void 0||e.type==="harness.changed"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&!s)&&(e.messageStreamEpoch===void 0||e.type==="harness.changed"&&(e.harnessId==="opencode"||e.harnessId==="flex")&&!i&&!o)&&(e.upgrade===void 0||typeof e.upgrade=="object"&&e.upgrade!==null&&Object.keys(e.upgrade).length===3&&typeof e.upgrade.fromVersion=="string"&&e.upgrade.fromVersion.length>0&&new TextEncoder().encode(e.upgrade.fromVersion).byteLength<=128&&typeof e.upgrade.toVersion=="string"&&e.upgrade.toVersion.length>0&&new TextEncoder().encode(e.upgrade.toVersion).byteLength<=128&&["preparing","pausing","installing","restarting","continuing","completed","failed"].includes(e.upgrade.phase))&&(!l||e.type==="upgrade.changed")&&(l||e.type!=="upgrade.changed")},"isControllerEvent"),ttr=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Ia(e.terminalId,Ger)&&typeof e.dataBase64=="string"&&(e.reset===void 0||typeof e.reset=="boolean")&&(e.ended===void 0||typeof e.ended=="boolean")},"isControllerTerminalOutput"),coe=class{constructor(e){this.options=e;this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.event",async t=>(etr(t)&&await this.options.onControllerEvent(t),{received:!0}))),this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.terminal.output",async t=>(ttr(t)&&await this.options.onTerminalOutput?.(t),{}))),this.typedRouter.addTypedHandler(new ws.TypedHandler("controller.browser.view.event",async t=>(await this.options.onBrowserViewEvent?.(t),{})))}options;static{a(this,"ControllerSocketClient")}typedRouter=new ws.TypedRouter;typedSocket;statusSubscription;diagnosticsSubscription;abortController;startPromise;get status(){return this.typedSocket?.getStatus()??"new"}get isConnected(){return this.status==="connected"}async start(){if(this.typedSocket?.getStatus()==="connected")return;if(this.startPromise)return this.startPromise;let e=this.startInternal();this.startPromise=e;try{await e}finally{this.startPromise===e&&(this.startPromise=void 0)}}async stop(){this.abortController?.abort(),this.abortController=void 0,this.statusSubscription?.unsubscribe(),this.statusSubscription=void 0,this.diagnosticsSubscription?.unsubscribe(),this.diagnosticsSubscription=void 0;let e=this.typedSocket;this.typedSocket=void 0,e&&await e.stop(),this.startPromise&&await this.startPromise.catch(()=>{})}async fire(e,t,s){let i=this.typedSocket;if(!i||i.getStatus()!=="connected")throw new Error("The controller connection is not available.");let o=s?.timeoutMs??Ver,{abortSignal:n,...l}=s??{};return i.createTypedRequest(e,void 0,{timeoutMs:o,abortSignal:n}).fire(t,{...l,timeoutMs:o})}async startInternal(){this.options.onStatus("connecting"),this.abortController=new AbortController;let e=await $1.TypedSocket.createClient(this.typedRouter,$1.TypedSocket.useWindowLocationOriginUrl(),{autoReconnect:!0,maxRetries:100,initialBackoffMs:500,maxBackoffMs:1e4,abortSignal:this.abortController.signal});this.typedSocket=e,this.statusSubscription=e.statusSubject.subscribe(t=>{this.options.onStatus(t)}),this.diagnosticsSubscription=e.diagnosticsSubject.subscribe(t=>{t.kind==="connectionClosed"&&typeof t.closeCode=="number"&&t.closeCode!==1e3&&this.options.onTransportClose?.(t.closeCode,typeof t.reason=="string"?t.reason:"")}),this.options.onStatus(e.getStatus())}};var KY={name:"agl",version:"21.0.2",description:"Agent Gateway Layer for OpenCode and FlexHarness sessions"};var Wqa=150,jqa=4,ff=a(r=>r.map(e=>({...e})),"cloneAttachments"),$Dt=a(r=>({text:r.text,attachments:ff(r.attachments),revision:r.revision}),"cloneDraft"),QY=a((r,e)=>r.length===e.length&&r.every((t,s)=>{let i=e[s];return i!==void 0&&t.id===i.id&&t.name===i.name&&t.mediaType===i.mediaType&&t.size===i.size&&t.kind===i.kind&&t.dataBase64===i.dataBase64}),"attachmentsEqual"),rtr=a((r,e)=>r.harnessId===e.harnessId&&r.nativeId===e.nativeId,"runtimeIdsEqual"),doe=class{constructor(e){this.options=e;this.debounceMs=e.debounceMs??150}options;static{a(this,"SessionDraftSync")}debounceMs;generation=0;active;disposed=!1;get state(){return this.active?this.publicState(this.active):void 0}async activate(e,t){if(this.disposed)return;this.deactivate();let s=++this.generation,i={projectId:e,sessionId:{...t},generation:s,authoritative:{text:"",attachments:[],revision:0},desiredText:"",desiredAttachments:[],dirtyText:!1,dirtyAttachments:!1,drainAfterDeactivate:!1,loading:!0,saving:!1,error:""};return this.active=i,this.emit(i),await this.hydrate(i),this.isCurrent(i)?this.publicState(i):void 0}deactivate(){let e=this.active;if(e?.debounceTimer&&clearTimeout(e.debounceTimer),e&&!e.loading&&(e.dirtyText||e.dirtyAttachments)&&(e.drainAfterDeactivate=!0,!e.writeTask)){let t=this.flushActive(e);e.writeTask=t,t.catch(s=>this.options.onError?.(s)).finally(()=>{e.writeTask===t&&(e.writeTask=void 0)})}this.generation+=1,this.active=void 0,this.options.onState(void 0)}setText(e){let t=this.active;!t||t.loading||(t.desiredText=e,t.dirtyText=t.desiredText!==t.authoritative.text,t.error="",this.emit(t),this.schedule(t))}setAttachments(e){let t=this.active;!t||t.loading||(t.desiredAttachments=ff(e),t.dirtyAttachments=!QY(t.desiredAttachments,t.authoritative.attachments),t.error="",this.emit(t),this.schedule(t))}async flush(){let e=this.active;if(!e)throw new Error("No session draft is active.");if(e.debounceTimer&&(clearTimeout(e.debounceTimer),e.debounceTimer=void 0),e.loading&&await this.hydrate(e),!this.isCurrent(e))throw new Error("The session draft changed during synchronization.");if(e.writeTask)return e.writeTask;let t=this.flushActive(e);e.writeTask=t;try{return await t}finally{e.writeTask===t&&(e.writeTask=void 0)}}async refresh(){let e=this.active;if(e)return await this.hydrate(e),this.isCurrent(e)?this.publicState(e):void 0}applyRemoteUpdate(e,t,s){let i=this.active;return!i||i.projectId!==e||!rtr(i.sessionId,t)||s.revision<=i.authoritative.revision?!1:s.revision!==i.authoritative.revision+1?(this.hydrate(i).catch(o=>this.options.onError?.(o)),!0):(i.authoritative={text:s.text??i.authoritative.text,attachments:s.attachments===void 0?i.authoritative.attachments:ff(s.attachments),revision:s.revision},!i.dirtyText&&s.text!==void 0&&(i.desiredText=s.text),!i.dirtyAttachments&&s.attachments!==void 0&&(i.desiredAttachments=ff(s.attachments)),i.dirtyText=i.desiredText!==i.authoritative.text,i.dirtyAttachments=!QY(i.desiredAttachments,i.authoritative.attachments),this.emit(i),(i.dirtyText||i.dirtyAttachments)&&this.schedule(i),!0)}dispose(){this.disposed||(this.disposed=!0,this.deactivate())}async hydrate(e){if(e.hydrateTask)return e.hydrateTask;let t;t=(async()=>{e.loading=!0,this.emit(e);try{let s=await this.options.transport.getDraft(e.projectId,e.sessionId);if(!this.canSynchronize(e))return;e.authoritative=$Dt(s),e.dirtyText||(e.desiredText=s.text),e.dirtyAttachments||(e.desiredAttachments=ff(s.attachments)),e.dirtyText=e.desiredText!==s.text,e.dirtyAttachments=!QY(e.desiredAttachments,s.attachments),e.error=""}catch(s){throw this.isCurrent(e)&&(e.error=this.errorMessage(s)),s}finally{e.loading=!1,this.emit(e)}})(),e.hydrateTask=t;try{await t}finally{e.hydrateTask===t&&(e.hydrateTask=void 0)}}async flushActive(e){e.saving=!0,this.emit(e);let t=0;try{for(;this.canSynchronize(e)&&(e.dirtyText||e.dirtyAttachments);){let s=e.desiredText,i=ff(e.desiredAttachments),o=e.dirtyText,n=e.dirtyAttachments,l=e.authoritative.revision,c;try{c=await this.options.transport.updateDraft(e.projectId,e.sessionId,l,{...o?{text:s}:{},...n?{attachments:i}:{}})}catch(d){if(this.options.transport.isConflict(d)&&t<4){t+=1,await this.hydrate(e);continue}throw d}if(!this.canSynchronize(e))break;t=0,c.revision>=e.authoritative.revision&&(e.authoritative=$Dt(c),o&&e.desiredText===s&&(e.dirtyText=!1),n&&QY(e.desiredAttachments,i)&&(e.dirtyAttachments=!1)),e.dirtyText=e.desiredText!==e.authoritative.text,e.dirtyAttachments=!QY(e.desiredAttachments,e.authoritative.attachments),e.error="",this.emit(e)}return{text:e.desiredText,attachments:ff(e.desiredAttachments),revision:e.authoritative.revision}}catch(s){throw this.isCurrent(e)&&(e.error=this.errorMessage(s),this.emit(e)),s}finally{e.saving=!1,this.emit(e),e.drainAfterDeactivate=!1}}schedule(e){!this.isCurrent(e)||e.loading||(e.debounceTimer&&clearTimeout(e.debounceTimer),e.debounceTimer=setTimeout(()=>{e.debounceTimer=void 0,this.flush().catch(t=>this.options.onError?.(t))},this.debounceMs))}isCurrent(e){return!this.disposed&&this.active===e&&this.generation===e.generation}canSynchronize(e){return this.isCurrent(e)||e.drainAfterDeactivate}emit(e){this.isCurrent(e)&&this.options.onState(this.publicState(e))}publicState(e){return{projectId:e.projectId,sessionId:{...e.sessionId},text:e.desiredText,attachments:ff(e.desiredAttachments),revision:e.authoritative.revision,loading:e.loading,saving:e.saving,error:e.error}}errorMessage(e){return e instanceof Error?e.message:"Draft synchronization failed."}};var ZDt,JDt,eOt,tOt,rOt,sOt,iOt,aOt,oOt,nOt,lOt,cOt,dOt,uOt,pOt,hOt,fOt,mOt,gOt,vOt,bOt,_Ot,yOt,xOt,SOt,wOt,EOt,COt,TOt,kOt,MOt,IOt,ROt,DOt,OOt,AOt,NOt,POt,LOt,BOt,FOt,$Ot,zOt,UOt,HOt,qOt,VOt,GOt,WOt,jOt,YOt,KOt,QOt,Ze,IGe,RGe,DGe,OGe,AGe,NGe,PGe,LGe,BGe,FGe,$Ge,zGe,UGe,HGe,qGe,VGe,GGe,WGe,jGe,YGe,KGe,QGe,XGe,ZGe,JGe,eWe,tWe,rWe,sWe,iWe,aWe,oWe,nWe,lWe,cWe,dWe,uWe,pWe,hWe,fWe,mWe,gWe,vWe,bWe,_We,yWe,xWe,SWe,wWe,EWe,CWe,uoe=a(()=>({truncated:!1,historyLimited:!1,unavailable:!1}),"emptyDetailHistoryLimits"),zDt=a((r,e)=>r==="backfilling"?"Loading earlier messages...":r!=="partial"?"":e.unavailable?"Earlier history is unavailable":e.truncated&&e.historyLimited?"Earlier messages were removed by the provider and additional history was limited by the controller":e.truncated?"Earlier messages were removed by the provider":e.historyLimited?"Earlier history is limited by the controller":"Earlier history is unavailable","detailHistoryStatusText"),pr=a(r=>typeof r=="string"&&r.trim().length>0,"isNonEmptyString"),UDt=a(r=>{if(!Array.isArray(r))return;let e=[];for(let t of r){if(!t||typeof t!="object"||Array.isArray(t))return;let s=t;if(!pr(s.id)||!pr(s.name)||!pr(s.mediaType)||!Number.isSafeInteger(s.size)||(s.size??-1)<0||!["image","text","binary"].includes(s.kind??"")||typeof s.dataBase64!="string")return;e.push({id:s.id,name:s.name,mediaType:s.mediaType,size:s.size,kind:s.kind,dataBase64:s.dataBase64})}return e},"toControllerDraftAttachments"),XY=a(r=>{if(!r||typeof r!="object")return!1;let e=r;return Object.keys(e).length===2&&(e.harnessId==="opencode"||e.harnessId==="flex"||e.harnessId==="controller")&&typeof e.nativeId=="string"&&e.nativeId.length>0&&new TextEncoder().encode(e.nativeId).byteLength<=512},"isControllerRuntimeId"),qt=a(r=>XY(r)&&r.harnessId!=="controller","isSessionRuntimeId"),mf=a(r=>XY(r)&&r.harnessId==="controller","isTerminalRuntimeId"),gf=a(r=>qt(r.id),"hasSessionRuntimeId"),str=a(r=>mf(r.id),"hasTerminalRuntimeId"),ct=a(r=>{if(!XY(r))throw new Error("Invalid qualified runtime ID.");return JSON.stringify([r.harnessId,r.nativeId])},"controllerRuntimeIdToUiKey"),dt=a((r,e)=>r===void 0?e===void 0:e!==void 0&&ct(r)===ct(e),"controllerRuntimeIdsEqual"),SGe=a((r,e)=>{if(Object.is(r,e))return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((n,l)=>SGe(n,e[l]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=r,s=e,i=Object.keys(t).sort(),o=Object.keys(s).sort();return i.length===o.length&&i.every((n,l)=>n===o[l]&&SGe(t[n],s[n]))},"controllerJsonValuesEqual"),itr=a(r=>{let e=r.trim();if(!e)throw new Error("Enter a browser address.");let t=e.match(/^([a-z][a-z\d+.-]*):\/\//i)?.[1]?.toLowerCase();if(t!==void 0&&t!=="http"&&t!=="https")throw new Error("Enter a valid HTTP or HTTPS address.");let s=/^[^/?#\s]+:\d+(?:[/?#]|$)/.test(e);if(/^[a-z][a-z\d+.-]*:/i.test(e)&&t===void 0&&!s)throw new Error("Enter a valid HTTP or HTTPS address.");let i=t===void 0?`https://${e}`:e,o;try{o=new URL(i)}catch{throw new Error("Enter a valid HTTP or HTTPS address.")}if(o.protocol!=="http:"&&o.protocol!=="https:"||!o.hostname)throw new Error("Enter a valid HTTP or HTTPS address.");return o.href},"controllerNormalizeBrowserAddress"),my=a(r=>new Map([...r].map(e=>[ct(e),e])),"runtimeIdsByUiKey"),Ll=a(r=>r==="flex"?"Flex":"OpenCode","sessionHarnessLabel"),ZY=a(r=>`${r.harnessId==="controller"?"Controller":Ll(r.harnessId)}:${r.nativeId}`,"runtimeIdDisplay"),atr=a(r=>{let e=r.harnessId;if(e!=="opencode"&&e!=="flex")throw new Error("Invalid model harness ID.");return e},"modelHarnessId"),poe=a(r=>{let e=r;return[Ll(atr(r)),`${r.providerID}/${r.modelID}`,e.providerConnectionId?`connection ${e.providerConnectionId}`:""].filter(Boolean).join(" \xB7 ")},"modelOptionLabel"),ow=a((r,e)=>r.length===e.length&&r.every((t,s)=>t===e[s]),"sameStringArray"),otr=a((r,e)=>r.length===e.length&&r.every((t,s)=>t.label===e[s]?.label&&t.value===e[s]?.value),"sameComposerOptions"),Xo=a(r=>`draft:${r}`,"draftSessionKey"),HDt=2e3,qDt=50,ntr=1e4,ltr=HDt*2.5,ctr=500,hoe=128,JY=4*1024*1024,dtr=16,utr=40,ptr=4,VDt=400,foe="Live preview is unavailable. Open the subagent chat to view its transcript.",GDt=50,WDt="harnessControllerSidebarWidth",htr=292,wGe=260,EGe=520,jDt=8,CGe=1e4,ftr=900*1e3,mtr=300*1e3,gtr=360*1e3,vtr=12,YDt=500,TGe=a(r=>Math.min(EGe,Math.max(wGe,Math.round(r))),"controllerClampSidebarWidth"),nw=a(r=>{let e=new TextEncoder,t=[],s=2;for(let i=r.length-1;i>=0;i-=1){let o=r[i],n=e.encode(JSON.stringify(o)).byteLength,l=t.length===0?0:1;if(t.length>=ODt||s+l+n>ADt)break;t.unshift(o),s+=l+n}return{bundles:t,limited:t.length!==r.length}},"boundedNewestMessageBundles"),btr=a((r,e,t)=>{let s=new Set(e.flatMap(l=>l.sessionIds.map(ct))),i=r.filter(gf).filter(l=>l.archivedAt===void 0).map((l,c)=>({id:l.id,sortAt:l.updatedAt,sourceIndex:c})).filter(l=>!s.has(ct(l.id))).sort((l,c)=>c.sortAt-l.sortAt||l.sourceIndex-c.sourceIndex),o=new Map(i.map(l=>[ct(l.id),l])),n=[];for(let l of t){let c=ct(l);o.has(c)&&(n.push(l),o.delete(c))}return n.push(...i.filter(l=>o.has(ct(l.id))).map(l=>l.id)),n},"controllerEffectiveUngroupedLayoutItemIds"),kGe=a((r,e,t)=>{let s=new Set(e.flatMap(l=>l.sessionIds.map(ct))),i=new Map(r.filter(gf).map(l=>[ct(l.id),l])),o=[],n=new Set;for(let l of t){let c=ct(l),d=i.get(c);!s.has(c)&&!n.has(c)&&(d===void 0||d.archivedAt===void 0)&&(o.push(l),n.add(c))}for(let l of btr(r,e,t)){let c=ct(l);n.has(c)||(o.push(l),n.add(c))}return o},"controllerMutableUngroupedLayoutItemIds"),eK=a(r=>({groups:r.groups.map(e=>({...e,sessionIds:e.sessionIds.map(t=>({...t}))})),ungroupedSessionIds:r.ungroupedSessionIds.map(e=>({...e})),revision:r.revision}),"cloneSessionLayout"),_tr=[{name:"compact",description:"Summarize the conversation and compact its context"},{name:"undo",description:"Revert the last message and its changes"},{name:"redo",description:"Restore previously reverted messages"},{name:"init",description:"Analyze the project and create AGENTS.md"}],ytr=[{name:"compact",description:"Summarize the conversation and compact its context"},{name:"init",description:"Analyze the project and create AGENTS.md"},{name:"undo",description:"Revert the last message and its changes"},{name:"redo",description:"Restore previously reverted messages"}],xtr=a(r=>r==="flex"?ytr:_tr,"localBuiltinSlashCommands"),Str=a(r=>{let e="";for(let s=0;s<r.length;s+=32768)e+=String.fromCharCode(...r.subarray(s,s+32768));return btoa(e)},"bytesToBase64"),wtr=a(r=>{try{let e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)t[s]=e.charCodeAt(s);return t}catch{return new Uint8Array(0)}},"base64ToBytes"),wr=a(r=>r instanceof Error&&r.message?r.message:String(r||"The operation failed."),"errorMessage"),MGe=a(r=>typeof r=="number"&&Number.isFinite(r)?`${Math.round(r)}%`:"--","formatPercentage"),KDt=a(r=>{if(typeof r!="number"||!Number.isFinite(r)||r<0)return"--";let e=["B","KB","MB","GB","TB"],t=r,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;let i=t>=100||s===0?0:1;return`${t.toFixed(i)} ${e[s]}`},"formatBytes"),QDt=a(r=>{if(typeof r!="number"||!Number.isFinite(r)||r<0)return"--";let e=["B","K","M","G","T"],t=r,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;let i=t>=100||s===0?0:1;return`${t.toFixed(i)}${e[s]}/s`},"formatByteRate"),Etr=a(r=>!Number.isFinite(r)||r<0?"--":r<60?`${Math.ceil(r)}s`:r<3600?`${Math.ceil(r/60)}m`:r<86400?`${Math.ceil(r/3600)}h`:`${Math.ceil(r/86400)}d`,"formatDuration"),Ctr=a((r,e,t)=>e===r?"match":t===`${r}->${e}`?"stale":"reload","controllerBundleReloadDecision");QOt=[tt.customElement("harness-controller-app")];var It=class It extends(KOt=tt.DeesElement,YOt=[tt.state()],jOt=[tt.state()],WOt=[tt.state()],GOt=[tt.state()],VOt=[tt.state()],qOt=[tt.state()],HOt=[tt.state()],UOt=[tt.state()],zOt=[tt.state()],$Ot=[tt.state()],FOt=[tt.state()],BOt=[tt.state()],LOt=[tt.state()],POt=[tt.state()],NOt=[tt.state()],AOt=[tt.state()],OOt=[tt.state()],DOt=[tt.state()],ROt=[tt.state()],IOt=[tt.state()],MOt=[tt.state()],kOt=[tt.state()],TOt=[tt.state()],COt=[tt.state()],EOt=[tt.state()],wOt=[tt.state()],SOt=[tt.state()],xOt=[tt.state()],yOt=[tt.state()],_Ot=[tt.state()],bOt=[tt.state()],vOt=[tt.state()],gOt=[tt.state()],mOt=[tt.state()],fOt=[tt.state()],hOt=[tt.state()],pOt=[tt.state()],uOt=[tt.state()],dOt=[tt.state()],cOt=[tt.state()],lOt=[tt.state()],nOt=[tt.state()],oOt=[tt.state()],aOt=[tt.state()],iOt=[tt.state()],sOt=[tt.state()],rOt=[tt.state()],tOt=[tt.state()],eOt=[tt.state()],JDt=[tt.state()],ZDt=[tt.state()],KOt){constructor(){super();Pe(this,"socketClient");Pe(this,"sessionDraftSync");Pe(this,"componentConnected",!1);Pe(this,"lifecycleGeneration",0);Pe(this,"connectionGeneration",0);Pe(this,"sessionsRequestId",0);Pe(this,"detailRequestId",0);Pe(this,"detailEnrichmentGeneration",0);Pe(this,"detailRequestAbortController");Pe(this,"detailAuxiliaryAbortController");Pe(this,"detailHistoryAbortController");Pe(this,"detailRefreshInFlight");Pe(this,"detailRefreshPending",!1);Pe(this,"detailRefreshRestartEnrichment",!1);Pe(this,"detailHistoryOwnership");Pe(this,"detailHistoryCursor");Pe(this,"detailHistorySeenCursors",new Set);Pe(this,"detailBundles",[]);Pe(this,"detailBundleKeys",new Set);Pe(this,"detailCoreBundleKeys",new Set);Pe(this,"detailProvisionalBundleKeys",new Set);Pe(this,"detailHistoryLimits",uoe());Pe(this,"activeCeremonyId");Pe(this,"activeMutationId");Pe(this,"mutationSequence",0);Pe(this,"refreshTimer");Pe(this,"immediateRefreshTimer");Pe(this,"immediateRefreshPending",!1);Pe(this,"refreshInFlight");Pe(this,"systemMetricsTimer");Pe(this,"legalDisclosureHideTimer");Pe(this,"highCpuStartedAt");Pe(this,"lastCpuSampleAt");Pe(this,"refreshPending",!1);Pe(this,"projectsRequestId",0);Pe(this,"modelCatalogRequestId",0);Pe(this,"layoutRequestId",0);Pe(this,"terminalRequestId",0);Pe(this,"resourceRequestId",0);Pe(this,"browserViewGeneration",0);Pe(this,"browserNavigationRequestId",0);Pe(this,"browserViewOpenAbortController");Pe(this,"browserNavigationAbortController");Pe(this,"browserViewId","");Pe(this,"browserViewConnectionGeneration",-1);Pe(this,"browserViewPendingClose");Pe(this,"browserViewResourceId","");Pe(this,"browserViewAttachmentRevision",-1);Pe(this,"browserViewState");Pe(this,"browserViewListeners",new Set);Pe(this,"browserRenderer");Pe(this,"suggestRequestId",0);Pe(this,"suggestDebounce");Pe(this,"controllerStatus");Pe(this,"providers",[]);Pe(this,"providerConnections",[]);Pe(this,"providerManagementState","loading");Pe(this,"providerManagementRefreshRequested",!1);Pe(this,"providerManagementTask");Pe(this,"activeProviderLogin");Pe(this,"providerLoginBeginTask");Pe(this,"providerLoginPollTimer");Pe(this,"providerLoginPollDeadline");Pe(this,"providerLoginPollTask");Pe(this,"providerLoginPollTaskKey");Pe(this,"providerRefreshPollTimers",new Map);Pe(this,"providerRefreshJobs",new Map);Pe(this,"providerRefreshPollDeadlines",new Map);Pe(this,"providerRefreshStartTokens",new Map);Pe(this,"providerRefreshStatuses",new Map);Pe(this,"providerRateLimits",new Map);Pe(this,"providerRateLimitErrors",new Map);Pe(this,"providerRateLimitTasks",new Map);Pe(this,"providerOpenCodeSwitch");Pe(this,"providerOpenCodeSwitchStatus","");Pe(this,"providerLoginStatusRoot");Pe(this,"providerLoginStatusError","");Pe(this,"settingsModalRef");Pe(this,"settingsModalGeneration",0);Pe(this,"settingsModalOpenTask");Pe(this,"settingsModalContentRenderer");Pe(this,"settingsDraftHarnessId","opencode");Pe(this,"settingsDraftModelString","");Pe(this,"settingsDraftEffortString","");Pe(this,"settingsDraftAutoAccept",!1);Pe(this,"autoAcceptPermissions",!1);Pe(this,"modelChoicesByString",new Map);Pe(this,"modelVariantsByString",new Map);Pe(this,"flexDefaultModelStrings",new Set);Pe(this,"defaultModelStrings",{opencode:"",flex:""});Pe(this,"defaultEffortStrings",{opencode:"",flex:""});Pe(this,"defaultModelChoices",{});Pe(this,"sessionModelOverrides",new Map);Pe(this,"sessionEffortOverrides",new Map);Pe(this,"sessionAccountOverrides",new Map);Pe(this,"sessionModelSaveTokens",new Map);Pe(this,"flexAccountOptionsCache",[]);Pe(this,"modelOptionsCache",new Map);Pe(this,"effortOptionsCache",new Map);Pe(this,"slashCatalogRequestId",0);Pe(this,"slashMenuEpisode",0);Pe(this,"slashMenuEligible",!1);Pe(this,"slashCatalogState");Pe(this,"slashCatalogRequest");Pe(this,"sessionsLoadedForProjectId","");Pe(this,"groupsLoadedForProjectId","");Pe(this,"terminalsLoadedForProjectId","");Pe(this,"resourcesLoadedForProjectId","");Pe(this,"pendingTerminalOutput",[]);Pe(this,"answeredQuestionCards",new Map);Pe(this,"answeredPermissionCards",new Map);Pe(this,"pendingQuestionBatchAnswers",new Map);Pe(this,"authoritativeStatusesByProject",new Map);Pe(this,"finishedSessionIdsByProject",new Map);Pe(this,"errorSessionIdsByProject",new Map);Pe(this,"optimisticWorkingIdsByProject",new Map);Pe(this,"sessionEventRevisionByProject",new Map);Pe(this,"confirmedSessionLayouts",new Map);Pe(this,"pendingSessionLayouts",new Map);Pe(this,"layoutSavePromises",new Map);Pe(this,"pendingLayoutReloadProjectIds",new Set);Pe(this,"staleDraftSessionsToDelete",new Map);Pe(this,"staleDraftSessionCleanupPromises",new Map);Pe(this,"staleDraftSessionCleanupAttempts",new Map);Pe(this,"sidebarResizePointerId");Pe(this,"sidebarResizeStartX",0);Pe(this,"sidebarResizeBaseline");Pe(this,"composerFocusRequestId",0);Pe(this,"composerFocusRequest");Pe(this,"composerFocusInFlight");Pe(this,"draftSessionGeneration",0);Pe(this,"draftSessionDetailReadyId");Pe(this,"scratchpadSaveIdsBySession",new Map);Pe(this,"scratchpadErrorsBySession",new Map);Pe(this,"intelligenceAskIdsBySession",new Map);Pe(this,"intelligenceErrorsBySession",new Map);Pe(this,"liveToolOverlays",new Map);Pe(this,"liveReasoningUpdates",new Map);Pe(this,"liveTextUpdates",new Map);Pe(this,"liveToolHydrationFloors",new Map);Pe(this,"liveMessageHydrationFloors",new Map);Pe(this,"liveHistoryBarriers",new Map);Pe(this,"liveToolOverlayBytes",0);Pe(this,"liveMessageOverlayBytes",0);Pe(this,"liveToolStreamEpochs",new Map);Pe(this,"liveMessageStreamEpochs",new Map);Pe(this,"subtaskPreviewEntries",new Map);Pe(this,"subtaskPreviewGeneration",0);Pe(this,"subtaskPreviewHydrationQueue",[]);Pe(this,"activeSubtaskPreviewHydrations",0);Jt(this,IGe,pt(Ze,8,this,"new")),pt(Ze,11,this);Jt(this,RGe,pt(Ze,12,this,"loading")),pt(Ze,15,this);Jt(this,DGe,pt(Ze,16,this,!1)),pt(Ze,19,this);Jt(this,OGe,pt(Ze,20,this,!1)),pt(Ze,23,this);Jt(this,AGe,pt(Ze,24,this,"")),pt(Ze,27,this);Jt(this,NGe,pt(Ze,28,this,"")),pt(Ze,31,this);Jt(this,PGe,pt(Ze,32,this,!1)),pt(Ze,35,this);Jt(this,LGe,pt(Ze,36,this,"")),pt(Ze,39,this);Jt(this,BGe,pt(Ze,40,this,"")),pt(Ze,43,this);Jt(this,FGe,pt(Ze,44,this,"")),pt(Ze,47,this);Jt(this,$Ge,pt(Ze,48,this,!1)),pt(Ze,51,this);Jt(this,zGe,pt(Ze,52,this,[])),pt(Ze,55,this);Jt(this,UGe,pt(Ze,56,this,"")),pt(Ze,59,this);Jt(this,HGe,pt(Ze,60,this,!1)),pt(Ze,63,this);Jt(this,qGe,pt(Ze,64,this,"")),pt(Ze,67,this);Jt(this,VGe,pt(Ze,68,this,"")),pt(Ze,71,this);Jt(this,GGe,pt(Ze,72,this,[])),pt(Ze,75,this);Jt(this,WGe,pt(Ze,76,this,[])),pt(Ze,79,this);Jt(this,jGe,pt(Ze,80,this)),pt(Ze,83,this);Jt(this,YGe,pt(Ze,84,this,[])),pt(Ze,87,this);Jt(this,KGe,pt(Ze,88,this,"")),pt(Ze,91,this);Jt(this,QGe,pt(Ze,92,this)),pt(Ze,95,this);Jt(this,XGe,pt(Ze,96,this,"")),pt(Ze,99,this);Jt(this,ZGe,pt(Ze,100,this)),pt(Ze,103,this);Jt(this,JGe,pt(Ze,104,this,!1)),pt(Ze,107,this);Jt(this,eWe,pt(Ze,108,this,!1)),pt(Ze,111,this);Jt(this,tWe,pt(Ze,112,this,[])),pt(Ze,115,this);Jt(this,rWe,pt(Ze,116,this)),pt(Ze,119,this);Jt(this,sWe,pt(Ze,120,this)),pt(Ze,123,this);Jt(this,iWe,pt(Ze,124,this,!1)),pt(Ze,127,this);Jt(this,aWe,pt(Ze,128,this,!1)),pt(Ze,131,this);Jt(this,oWe,pt(Ze,132,this,"idle")),pt(Ze,135,this);Jt(this,nWe,pt(Ze,136,this,!1)),pt(Ze,139,this);Jt(this,lWe,pt(Ze,140,this,!1)),pt(Ze,143,this);Jt(this,cWe,pt(Ze,144,this,!1)),pt(Ze,147,this);Jt(this,dWe,pt(Ze,148,this,"opencode")),pt(Ze,151,this);Jt(this,uWe,pt(Ze,152,this)),pt(Ze,155,this);Jt(this,pWe,pt(Ze,156,this,"")),pt(Ze,159,this);Jt(this,hWe,pt(Ze,160,this,[])),pt(Ze,163,this);Jt(this,fWe,pt(Ze,164,this,[])),pt(Ze,167,this);Jt(this,mWe,pt(Ze,168,this,[])),pt(Ze,171,this);Jt(this,gWe,pt(Ze,172,this,0)),pt(Ze,175,this);Jt(this,vWe,pt(Ze,176,this,htr)),pt(Ze,179,this);Jt(this,bWe,pt(Ze,180,this,!1)),pt(Ze,183,this);Jt(this,_We,pt(Ze,184,this,!0)),pt(Ze,187,this);Jt(this,yWe,pt(Ze,188,this,[])),pt(Ze,191,this);Jt(this,xWe,pt(Ze,192,this,[])),pt(Ze,195,this);Jt(this,SWe,pt(Ze,196,this,"")),pt(Ze,199,this);Jt(this,wWe,pt(Ze,200,this,!1)),pt(Ze,203,this);Jt(this,EWe,pt(Ze,204,this)),pt(Ze,207,this);Jt(this,CWe,pt(Ze,208,this,!1)),pt(Ze,211,this);Pe(this,"handleSidebarPointerDown",a(t=>{if(t.button!==0)return;let s=t.currentTarget;s instanceof HTMLElement&&(t.preventDefault(),this.sidebarResizePointerId=t.pointerId,this.sidebarResizeStartX=t.clientX,this.sidebarResizeBaseline=this.sidebarWidth,this.sidebarResizing=!0,s.setPointerCapture(t.pointerId),s.focus())},"handleSidebarPointerDown"));Pe(this,"handleSidebarPointerMove",a(t=>{t.pointerId!==this.sidebarResizePointerId||this.sidebarResizeBaseline===void 0||(this.sidebarWidth=TGe(this.sidebarResizeBaseline+t.clientX-this.sidebarResizeStartX))},"handleSidebarPointerMove"));Pe(this,"handleSidebarPointerEnd",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.finishSidebarResize()},"handleSidebarPointerEnd"));Pe(this,"handleSidebarPointerCancel",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.cancelSidebarResize()},"handleSidebarPointerCancel"));Pe(this,"handleSidebarLostPointerCapture",a(t=>{t.pointerId===this.sidebarResizePointerId&&this.cancelSidebarResize()},"handleSidebarLostPointerCapture"));Pe(this,"handleSidebarKeyDown",a(t=>{if(t.key==="Escape"&&this.sidebarResizeBaseline!==void 0){t.preventDefault(),this.cancelSidebarResize();return}let s;t.key==="ArrowLeft"&&(s=this.sidebarWidth-jDt),t.key==="ArrowRight"&&(s=this.sidebarWidth+jDt),t.key==="Home"&&(s=wGe),t.key==="End"&&(s=EGe),s!==void 0&&(t.preventDefault(),this.sidebarResizeBaseline??=this.sidebarWidth,this.sidebarWidth=TGe(s))},"handleSidebarKeyDown"));Pe(this,"handleSidebarKeyUp",a(t=>{["ArrowLeft","ArrowRight","Home","End"].includes(t.key)&&this.persistSidebarWidth()},"handleSidebarKeyUp"));Pe(this,"handleSidebarBlur",a(()=>{this.sidebarResizePointerId===void 0&&(this.sidebarResizeBaseline=void 0,this.persistSidebarWidth())},"handleSidebarBlur"));Pe(this,"toggleConversationSidebar",a(()=>{this.conversationSidebarVisible&&this.cancelSidebarResize(),this.conversationSidebarVisible=!this.conversationSidebarVisible},"toggleConversationSidebar"));Pe(this,"showLegalDisclosure",a(()=>{this.legalDisclosureHideTimer&&(clearTimeout(this.legalDisclosureHideTimer),this.legalDisclosureHideTimer=void 0),this.legalDisclosureVisible=!0},"showLegalDisclosure"));Pe(this,"scheduleLegalDisclosureHide",a(()=>{this.legalDisclosureHideTimer&&clearTimeout(this.legalDisclosureHideTimer),this.legalDisclosureHideTimer=setTimeout(()=>{this.legalDisclosureHideTimer=void 0,this.legalDisclosureVisible=!1},ctr)},"scheduleLegalDisclosureHide"));Pe(this,"handleSetupSubmit",a(async t=>{let s=t.detail?.data?.setupCode;if(!pr(s)||this.ceremonyBusy){pr(s)||(this.setupError="Enter the setup code printed by the CLI.");return}let i=t.currentTarget;if(!(i instanceof ks.DeesForm)){this.setupError="The setup form could not be read.";return}let o=s.trim(),n=this.connectionGeneration,l=Symbol("setupCeremony");this.activeCeremonyId=l,this.ceremonyBusy=!0,this.setupError="",i.setStatus("pending","Creating passkey\u2026");try{let c=await this.socketClient.fire("controller.auth.setup.begin",{setupCode:o});this.assertActiveCeremony(l,n);let d=await cy.startRegistration({optionsJSON:c.options});this.assertActiveCeremony(l,n);let u=await this.socketClient.fire("controller.auth.setup.finish",{ceremonyId:c.ceremonyId,setupCode:o,response:d});this.assertActiveCeremony(l,n),this.storeResumeToken(u.resumeToken),this.authState="ready",this.authenticated=!0,await this.loadWorkspaceData()}catch(c){this.activeCeremonyId===l&&this.isCurrentConnection(n)&&(this.setupError=wr(c),i.setStatus("normal","Create passkey"))}finally{this.activeCeremonyId===l&&(this.activeCeremonyId=void 0,this.ceremonyBusy=!1)}},"handleSetupSubmit"));Pe(this,"handleTempPasswordSubmit",a(async t=>{let s=t.detail?.data?.tempPassword,i=t.currentTarget;if(!(i instanceof ks.DeesForm))return;if(!pr(s)){this.tempPasswordError="Enter the temporary password printed by the CLI.";return}let o=this.connectionGeneration;this.tempPasswordError="",i.setStatus("pending","Signing in\u2026");try{let n=await this.socketClient.fire("controller.auth.temppassword.login",{password:s.trim()});if(!this.isCurrentConnection(o))return;this.storeResumeToken(n.resumeToken),this.authenticated=!0,this.showTempPasswordForm=!1,await this.loadWorkspaceData()}catch(n){this.isCurrentConnection(o)&&(this.tempPasswordError=wr(n),i.setStatus("normal","Sign in"))}},"handleTempPasswordSubmit"));Pe(this,"passkeyLoginHandler",a(async t=>{if(t.intent!=="authenticate"||t.mediation!=="optional")throw new Error("Only explicit passkey authentication is supported.");if(this.ceremonyBusy)throw new Error("A passkey ceremony is already running.");let s=this.connectionGeneration,i=Symbol("authenticationCeremony");this.activeCeremonyId=i,this.ceremonyBusy=!0;try{this.assertActiveCeremony(i,s,t.signal);let o=await this.socketClient.fire("controller.auth.authentication.begin",{});this.assertActiveCeremony(i,s,t.signal);let n=await cy.startAuthentication({optionsJSON:o.options});this.assertActiveCeremony(i,s,t.signal);let l=await this.socketClient.fire("controller.auth.authentication.finish",{ceremonyId:o.ceremonyId,response:n});this.assertActiveCeremony(i,s,t.signal),this.storeResumeToken(l.resumeToken),this.authenticated=!0,await this.loadWorkspaceData()}finally{this.activeCeremonyId===i&&(this.activeCeremonyId=void 0,this.ceremonyBusy=!1)}},"passkeyLoginHandler"));Pe(this,"handleLoadEarlier",a(()=>{this.loadEarlierSessionHistory()},"handleLoadEarlier"));Pe(this,"handleSessionSelect",a(t=>{let s=t.detail?.session?.id;if(!pr(s))return;let i=my(this.terminals.map(n=>n.id).filter(mf)).get(s);if(i){this.openTerminalById(i);return}let o=my(this.sessions.map(n=>n.id).filter(qt)).get(s);o&&this.openSessionById(o)},"handleSessionSelect"));Pe(this,"handleResourceSelect",a(t=>{let s=t.detail?.resource?.id,i=this.resources.find(o=>o.id===s);if(!(!i||i.lifecycle!=="active")){if(this.invalidateSlashCatalog(),this.selectedResourceId=i.id,i.kind==="browser"){if(this.closeTerminalView(),i.browserRuntimeState!=="available"){this.workspaceError="BrowserRuntime is unavailable on this host.";return}this.openBrowserView(i);return}if(this.closeBrowserView(),i.processState!=="running"){this.closeTerminalView(),this.workspaceError="";return}this.openTerminalById({harnessId:"controller",nativeId:i.id})}},"handleResourceSelect"));Pe(this,"handleBrowserAddressNavigation",a(t=>{t.type==="submit"&&t.preventDefault();let s=t.currentTarget,i=s instanceof HTMLFormElement?s:s instanceof HTMLElement?s.closest("form"):null;i&&this.navigateBrowserAddress(i)},"handleBrowserAddressNavigation"));Pe(this,"handleResourceAssociationRequest",a(t=>{let s=t.detail,i=this.resources.find(n=>n.id===s?.resource?.id);if(!s||!i||this.mutationPending)return;let o=s.toSessionId===null?null:my(this.sessions.map(n=>n.id).filter(qt)).get(s.toSessionId);s.toSessionId!==null&&!o||this.changeResourceAssociation(i,o??null)},"handleResourceAssociationRequest"));Pe(this,"handleResourceContext",a(t=>{let s=t.detail,i=this.resources.find(n=>n.id===s?.resource?.id);if(!i||!s?.originalEvent||this.mutationPending)return;let o=s.originalEvent instanceof MouseEvent?s.originalEvent:new MouseEvent("contextmenu",{clientX:s.clientX,clientY:s.clientY});ks.DeesContextmenu.openContextMenuWithOptions(o,[{name:"Rename",iconName:"lucide:Pencil",action:a(async()=>this.showTextPromptModal({heading:`Rename ${i.kind}`,label:"Title",initialValue:i.title,submitLabel:"Rename",onSubmit:a(async n=>this.renameResource(i.id,n),"onSubmit")}),"action")},...i.kind==="terminal"?[{name:i.processState==="running"?"Stop":"Start",iconName:i.processState==="running"?"lucide:Square":"lucide:Play",action:a(async()=>this.setResourceRunning(i,i.processState!=="running"),"action")}]:[],{divider:!0},{name:"Retire",iconName:"lucide:Trash2",action:a(async()=>this.showResourceRetirementConfirmation(i),"action")}]).then(n=>{if(!n){s.close();return}let l=new MutationObserver(()=>{n.isConnected||(l.disconnect(),s.close())});l.observe(document.body,{childList:!0})}).catch(()=>s.close())},"handleResourceContext"));Pe(this,"showArchivedModal",a(()=>{let t=this.sessions.filter(gf).filter(i=>i.archivedAt!==void 0),s;ks.DeesModal.createAndShow({heading:"Archived conversations",width:"small",content:tt.html`
41193
41193
  <div style="display: grid; gap: 4px; padding: 4px 0; max-height: 50vh; overflow-y: auto;">
41194
41194
  ${t.length===0?tt.html`
41195
41195
  <div style="opacity: 0.7; font-size: 13px;">No archived conversations.</div>
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '21.0.0',
6
+ version: '21.0.2',
7
7
  description: 'Agent Gateway Layer for OpenCode and FlexHarness sessions'
8
8
  };
9
9
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMDBfY29tbWl0aW5mb19kYXRhLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vdHMvMDBfY29tbWl0aW5mb19kYXRhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHO0lBQ3hCLElBQUksRUFBRSxLQUFLO0lBQ1gsT0FBTyxFQUFFLFFBQVE7SUFDakIsV0FBVyxFQUFFLDJEQUEyRDtDQUN6RSxDQUFBIn0=