@bivy/bivy 0.20.1-staging.8 → 0.20.1
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/bin/access-view.mjs +43 -0
- package/bin/bivy.mjs +111 -14
- package/bin/cli-commands.mjs +1 -0
- package/bin/tailscale.mjs +10 -3
- package/dist/access.js +72 -0
- package/dist/apps/listeners.js +31 -3
- package/dist/apps/service.js +8 -1
- package/dist/apps/styles.css +4 -0
- package/dist/auth.js +18 -4
- package/dist/controllers/app-commands.js +7 -2
- package/dist/protocol/client-command-routes.js +2 -0
- package/dist/protocol/client-command-schemas.js +3 -1
- package/dist/remote/direct.js +2 -1
- package/dist/remote/index.js +1 -0
- package/dist/remote/tailnet.js +44 -0
- package/dist/server.js +40 -2
- package/dist/session/run-terminal.js +6 -2
- package/package.json +1 -1
- package/web/assets/AutomationsView-fnzmthnq.js +51 -0
- package/web/assets/{ChangesCard-sGQlkM2d.js → ChangesCard-BWUgQ40Y.js} +1 -1
- package/web/assets/{LibraryView-DYUo2624.js → LibraryView-JlSOji08.js} +1 -1
- package/web/assets/{ProviderConnect-DB-gwOwe.js → ProviderConnect-BFFZWHsW.js} +1 -1
- package/web/assets/Settings-BAHWxYDH.js +10 -0
- package/web/assets/{Sheet-BmAB1Fu_.js → Sheet-cVfLQVwf.js} +1 -1
- package/web/assets/{Terminal-Dkr504wc.js → Terminal-C3QFXkbI.js} +1 -1
- package/web/assets/{VoiceSettings-DaR6ba3A.js → VoiceSettings-CWOtAlAV.js} +1 -1
- package/web/assets/{abnfDiagram-VCTEODGH-CZTMfHPQ.js → abnfDiagram-VCTEODGH-7cQ-bgry.js} +1 -1
- package/web/assets/architecture-7GRP2DOG-DVlvlW8H.js +1 -0
- package/web/assets/{architectureDiagram-5GKGNRK7-BBR7u-Nc.js → architectureDiagram-5GKGNRK7-BWOpNQNn.js} +1 -1
- package/web/assets/{blockDiagram-I7D4REHJ-DU1iTe41.js → blockDiagram-I7D4REHJ-8eE7JD9I.js} +1 -1
- package/web/assets/{c4Diagram-7LVT6UL2-DoY25VIT.js → c4Diagram-7LVT6UL2-DgiPr6K1.js} +1 -1
- package/web/assets/channel-Coq89lsO.js +1 -0
- package/web/assets/{chunk-4HAMMTFA-CwLS5ngk.js → chunk-4HAMMTFA-C8GTT_rj.js} +1 -1
- package/web/assets/{chunk-75Z2AOVW-FHeNbdLy.js → chunk-75Z2AOVW-BRMKvs-_.js} +1 -1
- package/web/assets/{chunk-DU6HZSFF-CUNfwm6b.js → chunk-DU6HZSFF-A-GuRJzV.js} +1 -1
- package/web/assets/{chunk-F27PBJKO-BT9LzzRz.js → chunk-F27PBJKO-D34kNJfE.js} +1 -1
- package/web/assets/{chunk-GMAD6QVW-BUr3PoNi.js → chunk-GMAD6QVW-CzLW6Gbl.js} +1 -1
- package/web/assets/{chunk-GVQU2GXP-Dwa-Ue8e.js → chunk-GVQU2GXP-CqTFATNd.js} +1 -1
- package/web/assets/{chunk-IMKFNOWR-CBemkwVh.js → chunk-IMKFNOWR-BLo_6uPl.js} +1 -1
- package/web/assets/{chunk-L3NEJ4N5-AGhZr4q5.js → chunk-L3NEJ4N5-CFSYYra2.js} +1 -1
- package/web/assets/{chunk-OSK3NFVY-CxTtDDij.js → chunk-OSK3NFVY-DJ3F-6TB.js} +1 -1
- package/web/assets/{chunk-P2QGCYS3-DGmss7hg.js → chunk-P2QGCYS3-B3qbBF6d.js} +1 -1
- package/web/assets/{chunk-POPQ4Y6H-nsxQTUJd.js → chunk-POPQ4Y6H-DbN8xQ-f.js} +1 -1
- package/web/assets/{chunk-PWAF6VOD-CFEkzIZ2.js → chunk-PWAF6VOD-C7BBYtAa.js} +1 -1
- package/web/assets/{chunk-SHT3W25Y-BArb8KoG.js → chunk-SHT3W25Y-B3wT37BE.js} +1 -1
- package/web/assets/{chunk-SVP7TREG-CEFJfpYl.js → chunk-SVP7TREG-OXvICZat.js} +1 -1
- package/web/assets/{chunk-TICWLB2K-ByqSjpyA.js → chunk-TICWLB2K-CrmJ4sWX.js} +1 -1
- package/web/assets/classDiagram-ZZMXUADV-rFDDoTN3.js +1 -0
- package/web/assets/classDiagram-v2-VYDZK3BY-rFDDoTN3.js +1 -0
- package/web/assets/{cynefin-OW5HDTMX-BPd4eJmp.js → cynefin-OW5HDTMX-BFhdG87z.js} +1 -1
- package/web/assets/{cynefinDiagram-5FMLGOSQ-rm271vYO.js → cynefinDiagram-5FMLGOSQ-BlBRhJR5.js} +1 -1
- package/web/assets/{dagre-GXQ25YYZ-a4DVMh7o.js → dagre-GXQ25YYZ-COxHf3g-.js} +1 -1
- package/web/assets/{diagram-S7CK7UJ4-CR4kj8JQ.js → diagram-S7CK7UJ4-mWtNPBS9.js} +1 -1
- package/web/assets/{diagram-UQ7AKVKN-BVAidz_h.js → diagram-UQ7AKVKN-CAvoNcsc.js} +1 -1
- package/web/assets/{diagram-VSXAHHWV-P_KshIhr.js → diagram-VSXAHHWV-DA9LJqgE.js} +1 -1
- package/web/assets/{diagram-VX7I27RA-CfR4HucM.js → diagram-VX7I27RA-7RswVDku.js} +1 -1
- package/web/assets/{diagram-Z3DM3KII-CnxFHDS4.js → diagram-Z3DM3KII-DknRBMRd.js} +1 -1
- package/web/assets/{ebnfDiagram-PWID7BFC-0lvDIevQ.js → ebnfDiagram-PWID7BFC-hAmbemf1.js} +1 -1
- package/web/assets/{erDiagram-RLTQ6QDP-B5onTaVV.js → erDiagram-RLTQ6QDP-DxXSxQWj.js} +1 -1
- package/web/assets/eventmodeling-NTZA5JFV-CMDfKRrP.js +1 -0
- package/web/assets/flowDiagram-HODETNUW-BQ27YGHa.js +1 -0
- package/web/assets/{ganttDiagram-EL5Y4UJY-DcP58ot2.js → ganttDiagram-EL5Y4UJY-BV-zpuyt.js} +1 -1
- package/web/assets/{gitGraph-4MIJSDKK-DMgkg1Fa.js → gitGraph-4MIJSDKK-BfZe7_3E.js} +1 -1
- package/web/assets/{gitGraphDiagram-WWUBYQGX-ChZQlU2S.js → gitGraphDiagram-WWUBYQGX-3_hHUbBU.js} +1 -1
- package/web/assets/index-D36pVYmX.css +1 -0
- package/web/assets/{index-emCm7_bF.js → index-x_iImoSf.js} +2 -2
- package/web/assets/{info-A6RAGUB7-Bwm7-KTz.js → info-A6RAGUB7-DUWO2H1L.js} +1 -1
- package/web/assets/{infoDiagram-27XIBGKW-PpNSZSrV.js → infoDiagram-27XIBGKW-BKxWRZYw.js} +1 -1
- package/web/assets/{ishikawaDiagram-5VMMS53U-DXh6yXna.js → ishikawaDiagram-5VMMS53U-CxQdy8l3.js} +1 -1
- package/web/assets/{journeyDiagram-3NMN7TZE-DFEj5jkB.js → journeyDiagram-3NMN7TZE-DplhU31X.js} +1 -1
- package/web/assets/{kanban-definition-UXKFOSKX-C5Mvo17h.js → kanban-definition-UXKFOSKX-Cmls5FZv.js} +1 -1
- package/web/assets/{line-CqUbcJrv.js → line-NoU3PhOc.js} +1 -1
- package/web/assets/{mermaid-parser.core-BzUSMP_7.js → mermaid-parser.core-CyOqjoOF.js} +3 -3
- package/web/assets/{mermaid.core-CooqV3Py.js → mermaid.core-BbpKlZWj.js} +4 -4
- package/web/assets/{mindmap-definition-YA3MSWOX-CvsfS7bG.js → mindmap-definition-YA3MSWOX-CfDDhyG9.js} +1 -1
- package/web/assets/mount-GHVLdZcl.js +27 -0
- package/web/assets/{packet-AYTQ26CC-BzXGhTo4.js → packet-AYTQ26CC-CEyZqXlC.js} +1 -1
- package/web/assets/{pegDiagram-XKGWAZYB-BvdN2RIR.js → pegDiagram-XKGWAZYB-BsQ551jM.js} +1 -1
- package/web/assets/{pie-WAS4IAKB-CNH8JQby.js → pie-WAS4IAKB-Cy_8_ris.js} +1 -1
- package/web/assets/{pieDiagram-E7YTZNPT-C6LABPqT.js → pieDiagram-E7YTZNPT-DQHtyFkg.js} +1 -1
- package/web/assets/{quadrantDiagram-AXDQQJYC-D2ebcGIP.js → quadrantDiagram-AXDQQJYC-iSVEwT1y.js} +1 -1
- package/web/assets/{radar-RG4KPBEZ-B7uFPzC9.js → radar-RG4KPBEZ-BO-qdlYd.js} +1 -1
- package/web/assets/{railroad-74A4TZTK-CE9pdZ9o.js → railroad-74A4TZTK-BEuDeDCt.js} +1 -1
- package/web/assets/railroad-abnf-HS5TGJTU-BbGdsa6v.js +1 -0
- package/web/assets/railroad-ebnf-LZEXJU2U-qaRxJkxs.js +1 -0
- package/web/assets/railroad-peg-WCYAUIDC-C6hTOfSB.js +1 -0
- package/web/assets/{railroadDiagram-O6MQD6OU-vJc9tRJP.js → railroadDiagram-O6MQD6OU-Bmp5czol.js} +1 -1
- package/web/assets/{requirementDiagram-BXWQKSXE-CVLUnEfL.js → requirementDiagram-BXWQKSXE-CflpYj7d.js} +1 -1
- package/web/assets/{sankeyDiagram-P5KCCOFB-DkHI3ZIh.js → sankeyDiagram-P5KCCOFB-D3xDfaLR.js} +1 -1
- package/web/assets/{sequenceDiagram-WJ2MYXX4-BgosmpaZ.js → sequenceDiagram-WJ2MYXX4-C6ZWIJwX.js} +1 -1
- package/web/assets/settingsRoute-COWp-9BH.js +1 -0
- package/web/assets/{stateDiagram-D77RDMKH-BZ5Zqme7.js → stateDiagram-D77RDMKH-BXjL8DPv.js} +1 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-BCGm337k.js +1 -0
- package/web/assets/{swimlanes-42K2YHIH-rkMg8KEw.js → swimlanes-42K2YHIH-CkyaLI3E.js} +1 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-RZPHF_4s.js +8 -0
- package/web/assets/{timeline-definition-24CTP7MA-_z_HJLWC.js → timeline-definition-24CTP7MA-BdMWCl3_.js} +1 -1
- package/web/assets/{treeView-Q6P3EWNA-jR5Z1Fmf.js → treeView-Q6P3EWNA-C4MMyFq1.js} +1 -1
- package/web/assets/{treemap-WGGIJYW6-OtJhfdUS.js → treemap-WGGIJYW6-BUER7WW0.js} +1 -1
- package/web/assets/{useStore-CaPvUEwc.js → useStore-B5xeFBSp.js} +3 -3
- package/web/assets/{vennDiagram-4TSXK5OY-BFTbjE-l.js → vennDiagram-4TSXK5OY-CmcfuybF.js} +1 -1
- package/web/assets/{wardley-WFR3VGLG-BV0ly0l7.js → wardley-WFR3VGLG-CbuHqcZs.js} +1 -1
- package/web/assets/{wardleyDiagram-VM6X3IG4-DYvCqNRg.js → wardleyDiagram-VM6X3IG4-B-dD7NPY.js} +1 -1
- package/web/assets/{xychartDiagram-S5SC5T6Z-CaYy8yTC.js → xychartDiagram-S5SC5T6Z-DkJf1OlB.js} +1 -1
- package/web/index.html +2 -2
- package/web/sw.js +1 -1
- package/web/assets/AutomationsView-BnHdmp7P.js +0 -51
- package/web/assets/Settings-VYk0Et0A.js +0 -10
- package/web/assets/architecture-7GRP2DOG-MiVMMOHz.js +0 -1
- package/web/assets/channel-m_2Ky5Co.js +0 -1
- package/web/assets/classDiagram-ZZMXUADV-BM6g8SUg.js +0 -1
- package/web/assets/classDiagram-v2-VYDZK3BY-BM6g8SUg.js +0 -1
- package/web/assets/eventmodeling-NTZA5JFV-DviokIMu.js +0 -1
- package/web/assets/flowDiagram-HODETNUW-BtFCDXEP.js +0 -1
- package/web/assets/index-CsC63U16.css +0 -1
- package/web/assets/mount-BD-g3eYn.js +0 -26
- package/web/assets/railroad-abnf-HS5TGJTU-C_bKzcjL.js +0 -1
- package/web/assets/railroad-ebnf-LZEXJU2U-BzPEt-Wn.js +0 -1
- package/web/assets/railroad-peg-WCYAUIDC-CeL6qyBT.js +0 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-DtyGmcgM.js +0 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-CbnaKO-d.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,C as r,D as i,I as a,O as o,P as s,S as c,T as l,V as u,b as d,k as f,v as p,w as m,x as h}from"./index-emCm7_bF.js";import{t as g}from"./jsx-runtime-NZYk81nU.js";var _=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function x(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var S=x.prototype=new b;S.constructor=x,_(S,y.prototype),S.isPureReactComponent=!0;var C=Array.isArray;function w(){}var T={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function D(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function O(e,t){return D(e.type,t,e.props)}function ee(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function te(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ne=/\/+/g;function k(e,t){return typeof e==`object`&&e&&e.key!=null?te(``+e.key):t.toString(36)}function re(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(w,w):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function A(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+k(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(ne,`$&/`)+`/`),A(o,r,i,``,function(e){return e})):o!=null&&(ee(o)&&(o=O(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(ne,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(C(e))for(var u=0;u<e.length;u++)a=e[u],s=l+k(a,u),c+=A(a,r,i,s,o);else if(u=h(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+k(a,u++),c+=A(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return A(re(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function ie(e,t,n){if(e==null)return e;var r=[],i=0;return A(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ae(e){if(e._status===-1){var t=e._result,n=t();n.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t,n.status===void 0&&(n.status=`fulfilled`,n.value=t))},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t,n.status===void 0&&(n.status=`rejected`,n.reason=t))}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var oe=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)};function se(e){var t=T.T,n={};n.types=t===null?null:t.types,T.T=n;try{var r=e(),i=T.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(w,oe)}catch(e){oe(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function ce(e){var t=T.T;if(t!==null){var n=t.types;n===null?t.types=[e]:n.indexOf(e)===-1&&n.push(e)}else se(ce.bind(null,e))}var le={map:ie,forEach:function(e,t,n){ie(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return ie(e,function(){t++}),t},toArray:function(e){return ie(e,function(e){return e})||[]},only:function(e){if(!ee(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=le,e.Component=y,e.Fragment=r,e.Profiler=a,e.PureComponent=x,e.StrictMode=i,e.Suspense=l,e.ViewTransition=p,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return T.H.useMemoCache(e)}},e.addTransitionType=ce,e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=_({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!E.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return D(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)E.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return D(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=ee,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ae}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=se,e.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},e.use=function(e){return T.H.use(e)},e.useActionState=function(e,t,n){return T.H.useActionState(e,t,n)},e.useCallback=function(e,t){return T.H.useCallback(e,t)},e.useContext=function(e){return T.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return T.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return T.H.useEffect(e,t)},e.useEffectEvent=function(e){return T.H.useEffectEvent(e)},e.useId=function(){return T.H.useId()},e.useImperativeHandle=function(e,t,n){return T.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return T.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return T.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return T.H.useMemo(e,t)},e.useOptimistic=function(e,t){return T.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return T.H.useReducer(e,t,n)},e.useRef=function(e){return T.H.useRef(e)},e.useState=function(e){return T.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return T.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return T.H.useTransition()},e.version=`19.3.0`})),v=e(((e,t)=>{t.exports=_()})),y=v();function b(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function x(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function S(e){return b(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function C(e){let t=String(e||``).replace(/-/g,`+`).replace(/_/g,`/`),n=t+`=`.repeat((4-t.length%4)%4);return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}var w={pair:`bivy-pair-v1`,rotate:`bivy-rotate-v1`,modelAuthVault:`bivy-model-auth-vault-v1`,githubAppVault:`bivy-github-app-vault-v1`,deviceVault:`bivy-device-vault-v1`},T=196608;async function E(e){return crypto.subtle.importKey(`raw`,e,`AES-GCM`,!1,[`encrypt`,`decrypt`])}async function D(e,t){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,tagLength:128},e,new TextEncoder().encode(t))),i=r.slice(0,r.length-16),a=r.slice(r.length-16),o=new Uint8Array(28+i.length);return o.set(n,0),o.set(a,12),o.set(i,28),b(o)}async function O(e,t){let n=x(t),r=n.slice(0,12),i=n.slice(12,28),a=n.slice(28),o=new Uint8Array(a.length+16);return o.set(a,0),o.set(i,a.length),new TextDecoder().decode(await crypto.subtle.decrypt({name:`AES-GCM`,iv:r},e,o))}function ee(e){let t=e?.replayWindowMs||3e5,n=e?.maxNonces||5e3,r=new Map;return function(e){let i=e;if(!i||typeof i.ts!=`number`||typeof i.nonce!=`string`)return!1;let a=Date.now();if(Math.abs(a-i.ts)>t||r.has(i.nonce))return!1;if(r.set(i.nonce,a+t),r.size>n)for(let[e,t]of r)t<=a&&r.delete(e);return!0}}var te=T;function ne(e,t){let n=String(e||``);if(n.length>33554432)throw Error(`Relay payload exceeds the receiver limit; use a bounded transfer.`);if(n.length<=te)return[JSON.stringify({t:`frame`,p:n})];let r=t?t():`${Date.now()}-${Math.random()}`,i=Math.ceil(n.length/te),a=[];for(let e=0;e<i;e++)a.push(JSON.stringify({t:`frame`,p:n.slice(e*te,(e+1)*te),fc:r,fi:e,fn:i}));return a}function k(e={}){let t=new Map,n=new Map,r=e.maxGroups??16,i=e.maxBytes??33554432,a=e.timeoutMs??3e4,o=0,s=e=>{let n=t.get(e);n&&(clearTimeout(n.timer),o-=n.bytes,t.delete(e))},c=(t,r)=>(s(t),n.size>=256&&n.delete(n.keys().next().value),n.set(t,Date.now()+a),e.onReject?.(r),null);return Object.assign(e=>{for(let[e,t]of n)t<=Date.now()&&n.delete(e);if(!e||typeof e.p!=`string`)return null;if(e.fc===void 0)return e.p.length<=i?e.p:c(`unchunked`,`Relay response exceeds the receive limit.`);let l=String(e.fc);if(n.has(l))return null;let u=Number(e.fi),d=Number(e.fn);if(!Number.isInteger(u)||!Number.isInteger(d)||d<=0||d>4096||u<0||u>=d)return c(l,`Invalid relay chunk metadata.`);let f=t.get(l);if(f&&f.total!==d)return c(l,`Inconsistent relay chunk count.`);if(!f){if(t.size>=r)return c(l,`Too many incomplete relay responses.`);let e=setTimeout(()=>c(l,`Relay response timed out before all chunks arrived.`),a);e.unref?.(),f={total:d,parts:Array(d),have:0,bytes:0,timer:e},t.set(l,f)}if(f.parts[u]!==void 0)return null;if(o+e.p.length>i)return c(l,`Relay responses exceed the receive memory limit.`);if(f.parts[u]=e.p,f.have++,f.bytes+=e.p.length,o+=e.p.length,f.have<f.total)return null;let p=f.parts.join(``);return s(l),n.size>=256&&n.delete(n.keys().next().value),n.set(l,Date.now()+a),p},{reset(){for(let e of t.keys())s(e);n.clear()}})}function re(e){return String(e||``).replace(/[&<>]/g,e=>({"&":`&`,"<":`<`,">":`>`})[e])}function A(e){return re(e).replace(/"/g,`"`)}function ie(e,t){return`<a href="${A(t)}" target="_blank" rel="noopener">${e}</a>`}function ae(e,t){return`<img class="md-image" data-remote-src="${A(t)}" alt="${A(e)}" loading="lazy">`}function oe(e){let t=[],n=new Set;for(let r of String(e||``).matchAll(/!\[[^\]]*\]\((https:\/\/[^)\s]+)\)/g)){let e=r[1];e&&!n.has(e)&&(n.add(e),t.push(e))}return t}function se(e){let t=String(e||``),n=``;for(;/[.,;:!?*_]$/.test(t);)n=t.slice(-1)+n,t=t.slice(0,-1);for(;t.endsWith(`)`)&&(t.match(/\)/g)||[]).length>(t.match(/\(/g)||[]).length;)n=`)`+n,t=t.slice(0,-1);return{href:t,suffix:n}}function ce(e){let t=[],n=[];return re(e).replace(/```([a-zA-Z0-9_+-]*)\n?([\s\S]*?)```/g,(e,n,r)=>{let i=`CODE${t.length}`;return t.push(`<pre><code${n?` class="language-${n}"`:``}>${r}</code></pre>`),i}).replace(/`([^`]+)`/g,(e,n)=>{let r=`CODE${t.length}`;return t.push(`<code>${n}</code>`),r}).replace(/!\[([^\]]*)\]\((https:\/\/[^)\s]+)\)/g,(e,t,r)=>{let i=`LINK${n.length}`;return n.push(ae(t,r)),i}).replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g,(e,t,r)=>{let i=`LINK${n.length}`;return n.push(ie(t,r)),i}).replace(/https?:\/\/[^\s<>"]+/g,e=>{let{href:t,suffix:r}=se(e);if(!t)return e;let i=`LINK${n.length}`;return n.push(ie(t,t)),i+r}).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/__([^_]+)__/g,`<strong>$1</strong>`).replace(/\*([^*]+)\*/g,`<em>$1</em>`).replace(/\b_([^_]+)_\b/g,`<em>$1</em>`).replace(/LINK(\d+)/g,(e,t)=>n[Number(t)]||``).replace(/CODE(\d+)/g,(e,n)=>t[Number(n)]||``)}function le(e){let t=String(e||``).trim();if(!t.includes(`|`))return[];let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>=2?n:[]}function ue(e){let t=le(e);if(t.length<2)return null;let n=[];for(let e of t){if(!/^:?-+:?$/.test(e))return null;n.push(e.startsWith(`:`)&&e.endsWith(`:`)?`center`:e.endsWith(`:`)?`right`:`left`)}return n}function de(e,t,n){let r=e=>t[e]&&t[e]!==`left`?` style="text-align:${t[e]}"`:``;return`<div class="markdown-table-wrap"><table><thead><tr>${e.map((e,t)=>`<th${r(t)}>${ce(e)}</th>`).join(``)}</tr></thead><tbody>${n.map(e=>`<tr>${e.map((e,t)=>`<td${r(t)}>${ce(e)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div>`}function fe(e){let t=String(e||``).match(/^[ \t]*/);return(t?t[0]:``).replace(/\t/g,` `).length}function pe(e){let t=String(e||``).match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(!t)return null;let n=/\d/.test(t[2][0]);return{indent:fe(t[1]),marker:t[2],type:n?`ol`:`ul`,start:n?Number(t[2].match(/\d+/)?.[0]||1):null,text:t[3]}}function me(e,t,n){return`<${e}${e===`ol`&&n&&n!==1?` start="${n}"`:``}>${t.join(``)}</${e}>`}function he(e,t,n){let r=pe(e[t]);if(!r||r.indent<n)return null;let i=r.type,a=r.indent,o=a+2,s=[],c=r.start;for(;t<e.length;){let n=pe(e[t]);if(!n||n.indent!==a||n.type!==i)break;let r=n.text,c=r.match(/^\[([ xX])\]\s+(.*)$/);c&&(r=c[2]);let l=[`${` `.repeat(o)}${r}`];for(t++;t<e.length;){let n=e[t],r=pe(n);if(r&&r.indent===a||n.trim()&&fe(n)<=a&&!r)break;l.push(n),t++}let u=ge(l,0,o),d=u.html;u.blocks.length===1&&u.blocks[0].startsWith(`<p>`)&&u.blocks[0].endsWith(`</p>`)&&(d=u.blocks[0].slice(3,-4));let f=c?`<input type="checkbox" disabled${/[xX]/.test(c[1])?` checked`:``}> `:``;s.push(`<li${c?` class="task-list-item"`:``}>${f}${d}</li>`)}return{html:me(i,s,c),next:t}}function ge(e,t=0,n=0){let r=[],i=t;for(;i<e.length;){let t=e[i];if(!t.trim()){i++;continue}if(fe(t)<n)break;if(t.trim().startsWith("```")){let n=t.trim().slice(3).trim().split(/\s+/)[0]||``,a=[];for(i++;i<e.length&&!e[i].trim().startsWith("```");)a.push(e[i]),i++;i<e.length&&i++,r.push(`<pre><code${n?` class="language-${A(n)}"`:``}>${re(a.join(`
|
|
1
|
+
import{t as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,C as r,D as i,I as a,O as o,P as s,S as c,T as l,V as u,b as d,k as f,v as p,w as m,x as h}from"./index-x_iImoSf.js";import{t as g}from"./jsx-runtime-NZYk81nU.js";var _=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function x(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var S=x.prototype=new b;S.constructor=x,_(S,y.prototype),S.isPureReactComponent=!0;var C=Array.isArray;function w(){}var T={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function D(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function O(e,t){return D(e.type,t,e.props)}function ee(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function te(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ne=/\/+/g;function k(e,t){return typeof e==`object`&&e&&e.key!=null?te(``+e.key):t.toString(36)}function re(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(w,w):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function A(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,A(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+k(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(ne,`$&/`)+`/`),A(o,r,i,``,function(e){return e})):o!=null&&(ee(o)&&(o=O(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(ne,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(C(e))for(var u=0;u<e.length;u++)a=e[u],s=l+k(a,u),c+=A(a,r,i,s,o);else if(u=h(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+k(a,u++),c+=A(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return A(re(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function ie(e,t,n){if(e==null)return e;var r=[],i=0;return A(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ae(e){if(e._status===-1){var t=e._result,n=t();n.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t,n.status===void 0&&(n.status=`fulfilled`,n.value=t))},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t,n.status===void 0&&(n.status=`rejected`,n.reason=t))}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var oe=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)};function se(e){var t=T.T,n={};n.types=t===null?null:t.types,T.T=n;try{var r=e(),i=T.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(w,oe)}catch(e){oe(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function ce(e){var t=T.T;if(t!==null){var n=t.types;n===null?t.types=[e]:n.indexOf(e)===-1&&n.push(e)}else se(ce.bind(null,e))}var le={map:ie,forEach:function(e,t,n){ie(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return ie(e,function(){t++}),t},toArray:function(e){return ie(e,function(e){return e})||[]},only:function(e){if(!ee(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=le,e.Component=y,e.Fragment=r,e.Profiler=a,e.PureComponent=x,e.StrictMode=i,e.Suspense=l,e.ViewTransition=p,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return T.H.useMemoCache(e)}},e.addTransitionType=ce,e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=_({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!E.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return D(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)E.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return D(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=ee,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ae}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=se,e.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},e.use=function(e){return T.H.use(e)},e.useActionState=function(e,t,n){return T.H.useActionState(e,t,n)},e.useCallback=function(e,t){return T.H.useCallback(e,t)},e.useContext=function(e){return T.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return T.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return T.H.useEffect(e,t)},e.useEffectEvent=function(e){return T.H.useEffectEvent(e)},e.useId=function(){return T.H.useId()},e.useImperativeHandle=function(e,t,n){return T.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return T.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return T.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return T.H.useMemo(e,t)},e.useOptimistic=function(e,t){return T.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return T.H.useReducer(e,t,n)},e.useRef=function(e){return T.H.useRef(e)},e.useState=function(e){return T.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return T.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return T.H.useTransition()},e.version=`19.3.0`})),v=e(((e,t)=>{t.exports=_()})),y=v();function b(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function x(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function S(e){return b(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function C(e){let t=String(e||``).replace(/-/g,`+`).replace(/_/g,`/`),n=t+`=`.repeat((4-t.length%4)%4);return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}var w={pair:`bivy-pair-v1`,rotate:`bivy-rotate-v1`,modelAuthVault:`bivy-model-auth-vault-v1`,githubAppVault:`bivy-github-app-vault-v1`,deviceVault:`bivy-device-vault-v1`},T=196608;async function E(e){return crypto.subtle.importKey(`raw`,e,`AES-GCM`,!1,[`encrypt`,`decrypt`])}async function D(e,t){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,tagLength:128},e,new TextEncoder().encode(t))),i=r.slice(0,r.length-16),a=r.slice(r.length-16),o=new Uint8Array(28+i.length);return o.set(n,0),o.set(a,12),o.set(i,28),b(o)}async function O(e,t){let n=x(t),r=n.slice(0,12),i=n.slice(12,28),a=n.slice(28),o=new Uint8Array(a.length+16);return o.set(a,0),o.set(i,a.length),new TextDecoder().decode(await crypto.subtle.decrypt({name:`AES-GCM`,iv:r},e,o))}function ee(e){let t=e?.replayWindowMs||3e5,n=e?.maxNonces||5e3,r=new Map;return function(e){let i=e;if(!i||typeof i.ts!=`number`||typeof i.nonce!=`string`)return!1;let a=Date.now();if(Math.abs(a-i.ts)>t||r.has(i.nonce))return!1;if(r.set(i.nonce,a+t),r.size>n)for(let[e,t]of r)t<=a&&r.delete(e);return!0}}var te=T;function ne(e,t){let n=String(e||``);if(n.length>33554432)throw Error(`Relay payload exceeds the receiver limit; use a bounded transfer.`);if(n.length<=te)return[JSON.stringify({t:`frame`,p:n})];let r=t?t():`${Date.now()}-${Math.random()}`,i=Math.ceil(n.length/te),a=[];for(let e=0;e<i;e++)a.push(JSON.stringify({t:`frame`,p:n.slice(e*te,(e+1)*te),fc:r,fi:e,fn:i}));return a}function k(e={}){let t=new Map,n=new Map,r=e.maxGroups??16,i=e.maxBytes??33554432,a=e.timeoutMs??3e4,o=0,s=e=>{let n=t.get(e);n&&(clearTimeout(n.timer),o-=n.bytes,t.delete(e))},c=(t,r)=>(s(t),n.size>=256&&n.delete(n.keys().next().value),n.set(t,Date.now()+a),e.onReject?.(r),null);return Object.assign(e=>{for(let[e,t]of n)t<=Date.now()&&n.delete(e);if(!e||typeof e.p!=`string`)return null;if(e.fc===void 0)return e.p.length<=i?e.p:c(`unchunked`,`Relay response exceeds the receive limit.`);let l=String(e.fc);if(n.has(l))return null;let u=Number(e.fi),d=Number(e.fn);if(!Number.isInteger(u)||!Number.isInteger(d)||d<=0||d>4096||u<0||u>=d)return c(l,`Invalid relay chunk metadata.`);let f=t.get(l);if(f&&f.total!==d)return c(l,`Inconsistent relay chunk count.`);if(!f){if(t.size>=r)return c(l,`Too many incomplete relay responses.`);let e=setTimeout(()=>c(l,`Relay response timed out before all chunks arrived.`),a);e.unref?.(),f={total:d,parts:Array(d),have:0,bytes:0,timer:e},t.set(l,f)}if(f.parts[u]!==void 0)return null;if(o+e.p.length>i)return c(l,`Relay responses exceed the receive memory limit.`);if(f.parts[u]=e.p,f.have++,f.bytes+=e.p.length,o+=e.p.length,f.have<f.total)return null;let p=f.parts.join(``);return s(l),n.size>=256&&n.delete(n.keys().next().value),n.set(l,Date.now()+a),p},{reset(){for(let e of t.keys())s(e);n.clear()}})}function re(e){return String(e||``).replace(/[&<>]/g,e=>({"&":`&`,"<":`<`,">":`>`})[e])}function A(e){return re(e).replace(/"/g,`"`)}function ie(e,t){return`<a href="${A(t)}" target="_blank" rel="noopener">${e}</a>`}function ae(e,t){return`<img class="md-image" data-remote-src="${A(t)}" alt="${A(e)}" loading="lazy">`}function oe(e){let t=[],n=new Set;for(let r of String(e||``).matchAll(/!\[[^\]]*\]\((https:\/\/[^)\s]+)\)/g)){let e=r[1];e&&!n.has(e)&&(n.add(e),t.push(e))}return t}function se(e){let t=String(e||``),n=``;for(;/[.,;:!?*_]$/.test(t);)n=t.slice(-1)+n,t=t.slice(0,-1);for(;t.endsWith(`)`)&&(t.match(/\)/g)||[]).length>(t.match(/\(/g)||[]).length;)n=`)`+n,t=t.slice(0,-1);return{href:t,suffix:n}}function ce(e){let t=[],n=[];return re(e).replace(/```([a-zA-Z0-9_+-]*)\n?([\s\S]*?)```/g,(e,n,r)=>{let i=`CODE${t.length}`;return t.push(`<pre><code${n?` class="language-${n}"`:``}>${r}</code></pre>`),i}).replace(/`([^`]+)`/g,(e,n)=>{let r=`CODE${t.length}`;return t.push(`<code>${n}</code>`),r}).replace(/!\[([^\]]*)\]\((https:\/\/[^)\s]+)\)/g,(e,t,r)=>{let i=`LINK${n.length}`;return n.push(ae(t,r)),i}).replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g,(e,t,r)=>{let i=`LINK${n.length}`;return n.push(ie(t,r)),i}).replace(/https?:\/\/[^\s<>"]+/g,e=>{let{href:t,suffix:r}=se(e);if(!t)return e;let i=`LINK${n.length}`;return n.push(ie(t,t)),i+r}).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/__([^_]+)__/g,`<strong>$1</strong>`).replace(/\*([^*]+)\*/g,`<em>$1</em>`).replace(/\b_([^_]+)_\b/g,`<em>$1</em>`).replace(/LINK(\d+)/g,(e,t)=>n[Number(t)]||``).replace(/CODE(\d+)/g,(e,n)=>t[Number(n)]||``)}function le(e){let t=String(e||``).trim();if(!t.includes(`|`))return[];let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>=2?n:[]}function ue(e){let t=le(e);if(t.length<2)return null;let n=[];for(let e of t){if(!/^:?-+:?$/.test(e))return null;n.push(e.startsWith(`:`)&&e.endsWith(`:`)?`center`:e.endsWith(`:`)?`right`:`left`)}return n}function de(e,t,n){let r=e=>t[e]&&t[e]!==`left`?` style="text-align:${t[e]}"`:``;return`<div class="markdown-table-wrap"><table><thead><tr>${e.map((e,t)=>`<th${r(t)}>${ce(e)}</th>`).join(``)}</tr></thead><tbody>${n.map(e=>`<tr>${e.map((e,t)=>`<td${r(t)}>${ce(e)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div>`}function fe(e){let t=String(e||``).match(/^[ \t]*/);return(t?t[0]:``).replace(/\t/g,` `).length}function pe(e){let t=String(e||``).match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(!t)return null;let n=/\d/.test(t[2][0]);return{indent:fe(t[1]),marker:t[2],type:n?`ol`:`ul`,start:n?Number(t[2].match(/\d+/)?.[0]||1):null,text:t[3]}}function me(e,t,n){return`<${e}${e===`ol`&&n&&n!==1?` start="${n}"`:``}>${t.join(``)}</${e}>`}function he(e,t,n){let r=pe(e[t]);if(!r||r.indent<n)return null;let i=r.type,a=r.indent,o=a+2,s=[],c=r.start;for(;t<e.length;){let n=pe(e[t]);if(!n||n.indent!==a||n.type!==i)break;let r=n.text,c=r.match(/^\[([ xX])\]\s+(.*)$/);c&&(r=c[2]);let l=[`${` `.repeat(o)}${r}`];for(t++;t<e.length;){let n=e[t],r=pe(n);if(r&&r.indent===a||n.trim()&&fe(n)<=a&&!r)break;l.push(n),t++}let u=ge(l,0,o),d=u.html;u.blocks.length===1&&u.blocks[0].startsWith(`<p>`)&&u.blocks[0].endsWith(`</p>`)&&(d=u.blocks[0].slice(3,-4));let f=c?`<input type="checkbox" disabled${/[xX]/.test(c[1])?` checked`:``}> `:``;s.push(`<li${c?` class="task-list-item"`:``}>${f}${d}</li>`)}return{html:me(i,s,c),next:t}}function ge(e,t=0,n=0){let r=[],i=t;for(;i<e.length;){let t=e[i];if(!t.trim()){i++;continue}if(fe(t)<n)break;if(t.trim().startsWith("```")){let n=t.trim().slice(3).trim().split(/\s+/)[0]||``,a=[];for(i++;i<e.length&&!e[i].trim().startsWith("```");)a.push(e[i]),i++;i<e.length&&i++,r.push(`<pre><code${n?` class="language-${A(n)}"`:``}>${re(a.join(`
|
|
2
2
|
`))}</code></pre>`);continue}if(/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(t)){r.push(`<hr>`),i++;continue}let a=le(t),o=ue(e[i+1]||``);if(fe(t)<=3&&a.length>=2&&o&&o.length===a.length){let t=[],n=i+2;for(;n<e.length;){let r=le(e[n]);if(r.length!==a.length)break;t.push(r),n++}r.push(de(a,o,t)),i=n;continue}let s=t.match(/^\s{0,3}(#{1,6})\s+(.+)$/);if(s){let e=s[1].length;r.push(`<h${e}>${ce(s[2].trim())}</h${e}>`),i++;continue}if(/^\s*>\s?/.test(t)){let t=[];for(;i<e.length&&/^\s*>\s?/.test(e[i]);)t.push(e[i].replace(/^\s*>\s?/,``)),i++;r.push(`<blockquote>${ye(t.join(`
|
|
3
3
|
`))}</blockquote>`);continue}let c=he(e,i,n);if(c){r.push(c.html),i=c.next;continue}let l=[];for(;i<e.length;){let t=e[i];if(!t.trim()||fe(t)<n)break;if(l.length){let n=le(t),r=ue(e[i+1]||``);if(t.trim().startsWith("```")||/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(t)||/^\s{0,3}#{1,6}\s+/.test(t)||/^\s*>\s?/.test(t)||pe(t)||fe(t)<=3&&n.length>=2&&r&&r.length===n.length)break}l.push(t.trim()),i++}r.push(`<p>${ce(l.join(` `))}</p>`)}return{html:r.join(``),next:i,blocks:r}}var _e=new Map,ve=400;function ye(e){let t=String(e),n=_e.get(t);if(n!==void 0)return _e.delete(t),_e.set(t,n),n;let r=ge(t.replace(/\r\n/g,`
|
|
4
4
|
`).split(`
|
|
@@ -16,7 +16,7 @@ if [ -d "$BIVY_PACKAGE_DIR/node_modules/.bin" ]; then export PATH="$BIVY_PACKAGE
|
|
|
16
16
|
`),l=`${n}/${e.region}/${e.service}/aws4_request`,u=[`AWS4-HMAC-SHA256`,t,l,await vr(c)].join(`
|
|
17
17
|
`),d=_r(await yr(await yr(await yr(await yr(await yr(ar.encode(`AWS4${e.creds.secretAccessKey}`),n),e.region),e.service),`aws4_request`),u));return{...r,authorization:`AWS4-HMAC-SHA256 Credential=${e.creds.accessKeyId}/${l}, SignedHeaders=${o}, Signature=${d}`}}var Cr={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`};function wr(e){return e.replace(/&(#x?[0-9a-fA-F]+|[a-z]+);/gi,(e,t)=>{if(t[0]===`#`){let n=t[1]===`x`||t[1]===`X`?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isFinite(n)?String.fromCodePoint(n):e}return Cr[t.toLowerCase()]??e})}function Tr(e){let t=0,n=e.length,r=e=>e===` `||e===` `||e===`
|
|
18
18
|
`||e===`\r`;function i(){for(;t<n&&r(e.charAt(t));)t++}function a(){for(;;){if(i(),e.startsWith(`<?`,t)){let r=e.indexOf(`?>`,t);t=r<0?n:r+2;continue}if(e.startsWith(`<!--`,t)){let r=e.indexOf(`-->`,t);t=r<0?n:r+3;continue}if(e.startsWith(`<!`,t)){let r=e.indexOf(`>`,t);t=r<0?n:r+1;continue}break}}function o(){let i=t;for(;t<n&&!r(e.charAt(t))&&e.charAt(t)!==`>`&&e.charAt(t)!==`/`&&e.charAt(t)!==`=`;)t++;return e.slice(i,t)}function s(){for(;;){if(i(),t>=n||e.charAt(t)===`>`||e.charAt(t)===`/`)return;if(o(),i(),e.charAt(t)===`=`){t++,i();let a=e.charAt(t);if(a===`"`||a===`'`){t++;let r=e.indexOf(a,t);t=r<0?n:r+1}else for(;t<n&&!r(e.charAt(t))&&e.charAt(t)!==`>`;)t++}}}function c(){t++;let r=o();s(),i();let a={tag:r,children:[],text:``};if(e.charAt(t)===`/`)return t+=2,a;t++;let l=``;for(;t<n;){if(e.startsWith(`</`,t)){let r=e.indexOf(`>`,t);t=r<0?n:r+1;break}if(e.startsWith(`<!--`,t)){let r=e.indexOf(`-->`,t);t=r<0?n:r+3;continue}if(e.charAt(t)===`<`){a.children.push(c());continue}let r=t;for(;t<n&&e.charAt(t)!==`<`;)t++;l+=e.slice(r,t)}return a.text=wr(l).trim(),a}return a(),t>=n||e.charAt(t)!==`<`?{tag:``,children:[],text:``}:c()}function U(e,t){return e?.children.find(e=>e.tag===t)}function Er(e,t){return e?e.children.filter(e=>e.tag===t):[]}function Dr(e,t){if(e){if(e.tag===t)return e;for(let n of e.children){let e=Dr(n,t);if(e)return e}}}function Or(e){return Object.entries(e).filter(e=>e[1]!==void 0).map(([e,t])=>`${br(e)}=${br(t)}`).join(`&`)}function kr(e){return`ec2.${e}.amazonaws.com`}function Ar(e){return`ssm.${e}.amazonaws.com`}async function jr(e,t,n,r,i,a){let o=kr(n),s=Or({Action:r,Version:`2016-11-15`,...i}),c=await Sr({method:`POST`,host:o,path:`/`,region:n,service:`ec2`,headers:{"content-type":`application/x-www-form-urlencoded; charset=UTF-8`},body:s,creds:t}),l=await z(e,{method:`POST`,url:`https://${o}/`,headers:c,body:s}),u=typeof l.body==`string`&&l.body.trim()?Tr(l.body):{tag:``,children:[],text:``};if(l.status>=300){let e=Dr(u,`Code`)?.text,t=Dr(u,`Message`)?.text;throw Error(`AWS failed to ${a} (HTTP ${l.status}${e?`: ${e}`:``}${t?` — ${t}`:``})`)}return u}async function Mr(e,t,n,r){let i=Ar(n),a=JSON.stringify({Name:r}),o=await Sr({method:`POST`,host:i,path:`/`,region:n,service:`ssm`,headers:{"content-type":`application/x-amz-json-1.1`,"x-amz-target":`AmazonSSM.GetParameter`},body:a,creds:t}),s=await z(e,{method:`POST`,url:`https://${i}/`,headers:o,body:a});if(s.status>=300){let e=cr(s.body)||(s.body&&typeof s.body==`object`?String(s.body.__type??``):``);throw Error(`AWS failed to resolve the Ubuntu AMI (HTTP ${s.status}${e?`: ${e}`:``})`)}let c=s.body&&typeof s.body==`object`?s.body?.Parameter?.Value:void 0;if(!c)throw Error(`AWS SSM did not return an AMI id`);return String(c)}var Nr=`/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id`,Pr=new Map;function Fr(e,t,n){return lr(Pr,n,()=>Mr(e,t,n,Nr))}function Ir(e){switch(e){case`running`:return`running`;case`pending`:return`starting`;case`stopping`:case`stopped`:case`shutting-down`:return`stopped`;case`terminated`:return`gone`;default:return`starting`}}var Lr=[{id:`us-east-1`,label:`US East (N. Virginia)`},{id:`us-west-2`,label:`US West (Oregon)`},{id:`eu-west-1`,label:`Europe (Ireland)`},{id:`eu-central-1`,label:`Europe (Frankfurt)`},{id:`ap-southeast-1`,label:`Asia Pacific (Singapore)`},{id:`ap-northeast-1`,label:`Asia Pacific (Tokyo)`}],Rr=40,W=(e,t,n,r,i)=>({id:e,label:t,vcpus:n,memoryMiB:r*1024,diskGiB:Rr,architecture:`x86_64`,pricePerHour:i,priceSource:`indicative`}),zr=[W(`t3.micro`,`t3.micro · 2 vCPU · 1 GB`,2,1,.0104),W(`t3.small`,`t3.small · 2 vCPU · 2 GB`,2,2,.0208),W(`t3.medium`,`t3.medium · 2 vCPU · 4 GB`,2,4,.0416),W(`t3.large`,`t3.large · 2 vCPU · 8 GB`,2,8,.0832),W(`t3.xlarge`,`t3.xlarge · 4 vCPU · 16 GB`,4,16,.1664),W(`t3.2xlarge`,`t3.2xlarge · 8 vCPU · 32 GB`,8,32,.3328),W(`m7i.xlarge`,`m7i.xlarge · 4 vCPU · 16 GB`,4,16,.2016),W(`m7i.2xlarge`,`m7i.2xlarge · 8 vCPU · 32 GB`,8,32,.4032),W(`r7i.2xlarge`,`r7i.2xlarge · 8 vCPU · 64 GB`,8,64,.5292),W(`r7i.4xlarge`,`r7i.4xlarge · 16 vCPU · 128 GB`,16,128,1.0584)],Br={id:`aws`,name:`AWS EC2`,currency:`USD`,regions:Lr,defaultRegion:`us-east-1`,sizes:zr,defaultSize:`m7i.xlarge`,async validateToken({exec:e,token:t,region:n}){await jr(e,gr(t),n||Br.defaultRegion,`DescribeInstances`,{MaxResults:`5`},`validate credential`)},async listSizes({exec:e,token:t,region:n}){let r=gr(t),i=n||Br.defaultRegion,a={};zr.forEach((e,t)=>{a[`InstanceType.${t+1}`]=e.id});let o;try{o=await jr(e,r,i,`DescribeInstanceTypes`,a,`list instance types`)}catch{return zr}let s;try{let t={LocationType:`region`};zr.forEach((e,n)=>{t[`Filter.1.Value.${n+1}`]=e.id}),t[`Filter.1.Name`]=`instance-type`;let n=await jr(e,r,i,`DescribeInstanceTypeOfferings`,t,`list instance offerings`);s=new Set(Er(U(n,`instanceTypeOfferingSet`),`item`).map(e=>U(e,`instanceType`)?.text||``).filter(Boolean))}catch{}let c=Er(U(o,`instanceTypeSet`),`item`).map(e=>{let t=U(e,`instanceType`)?.text||``,n=U(U(e,`vCpuInfo`),`defaultVCpus`)?.text,r=U(U(e,`memoryInfo`),`sizeInMiB`)?.text,i=r?Math.round(Number(r)/1024):void 0,a=zr.find(e=>e.id===t);return!t||s&&!s.has(t)?null:{...a,id:t,label:`${t} · ${n??`?`} vCPU · ${i??`?`} GB`,vcpus:n?Number(n):a?.vcpus,memoryMiB:r?Number(r):a?.memoryMiB}}).filter(e=>!!e);return c.length?c:zr},async provision({exec:e,token:t,config:n,userData:r}){let i=gr(t),a=n.region||Br.defaultRegion,o=`bivy-${n.slug}`,s=U(U(await jr(e,i,a,`RunInstances`,{ImageId:n.image?String(n.image):await Fr(e,i,a),InstanceType:n.size||Br.defaultSize,MinCount:`1`,MaxCount:`1`,UserData:b(ar.encode(r)),InstanceInitiatedShutdownBehavior:`terminate`,"BlockDeviceMapping.1.DeviceName":`/dev/sda1`,"BlockDeviceMapping.1.Ebs.VolumeSize":String(Rr),"BlockDeviceMapping.1.Ebs.VolumeType":`gp3`,"BlockDeviceMapping.1.Ebs.DeleteOnTermination":`true`,...n.attemptId?{ClientToken:String(n.attemptId)}:{},"TagSpecification.1.ResourceType":`instance`,"TagSpecification.1.Tag.1.Key":`Name`,"TagSpecification.1.Tag.1.Value":o,"TagSpecification.1.Tag.2.Key":`bivy`,"TagSpecification.1.Tag.2.Value":`ephemeral`,...n.attemptId?{"TagSpecification.1.Tag.3.Key":`bivy-attempt`,"TagSpecification.1.Tag.3.Value":String(n.attemptId)}:{},...n.ownershipTag?{"TagSpecification.1.Tag.4.Key":`bivy-account`,"TagSpecification.1.Tag.4.Value":String(n.ownershipTag)}:{}},`launch instance`),`instancesSet`),`item`),c=U(s,`instanceId`)?.text;if(!c)throw Error(`AWS did not return an instance id`);let l=U(U(s,`instanceState`),`name`)?.text,u=U(s,`ipAddress`)?.text||Dr(U(s,`networkInterfaceSet`),`publicIp`)?.text||null;return{id:c,provider:`aws`,name:o,region:a,status:Ir(l),ip:u||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=gr(t),i;try{i=await jr(e,r,n.region,`DescribeInstances`,{"InstanceId.1":n.id},`get instance`)}catch(e){if(String(e.message||``).includes(`InvalidInstanceID.NotFound`))return`gone`;throw e}let a=U(Dr(i,`instancesSet`),`item`);return a?Ir(U(U(a,`instanceState`),`name`)?.text):`gone`},async destroy({exec:e,token:t,machine:n}){let r=gr(t);try{await jr(e,r,n.region,`TerminateInstances`,{"InstanceId.1":n.id},`terminate instance`)}catch(e){if(!String(e.message||``).includes(`InvalidInstanceID.NotFound`))throw e}},async discover({exec:e,token:t,ownershipTag:n}){let r=gr(t),i=[];for(let t of Lr.map(e=>e.id)){let a;try{a=await jr(e,r,t,`DescribeInstances`,{"Filter.1.Name":`tag:bivy-account`,"Filter.1.Value.1":n,"Filter.2.Name":`instance-state-name`,"Filter.2.Value.1":`pending`,"Filter.2.Value.2":`running`,"Filter.2.Value.3":`stopping`,"Filter.2.Value.4":`stopped`},`list instances`)}catch{continue}for(let e of Er(U(a,`reservationSet`),`item`))for(let n of Er(U(e,`instancesSet`),`item`)){let e=U(n,`instanceId`)?.text;if(!e)continue;let r=U(U(n,`instanceState`),`name`)?.text,a=Er(U(n,`tagSet`),`item`).find(e=>U(e,`key`)?.text===`bivy-attempt`);i.push({id:e,provider:`aws`,name:e,region:t,status:Ir(r),ip:U(n,`ipAddress`)?.text||null,createdAt:U(n,`launchTime`)?.text||``,attemptId:a?U(a,`value`)?.text:void 0})}}return i}};function Vr(e){return e===`started`?`running`:e===`destroyed`?`gone`:e===`stopped`?`stopped`:`starting`}var Hr=`personal`;async function Ur(e,t,n){let r=String(n||``).trim();if(r)return r;let i=await z(e,{method:`POST`,url:`https://api.fly.io/graphql`,headers:{...B(t),"content-type":`application/json`},body:{query:`query { organizations { nodes { slug type } } }`}});if(i.status>=300)throw Error(H(i,`list organizations`));let a=Array.isArray(i.body?.data?.organizations?.nodes)?i.body.data.organizations.nodes:[];if(!a.length){let e=cr(i.body);throw Error(`Fly token has no accessible organizations${e?`: ${e}`:``}`)}let o=a.find(e=>String(e?.type||``).toUpperCase()===`PERSONAL`&&e?.slug)||a.find(e=>e?.slug)||a[0];return String(o?.slug||Hr)}var Wr={"shared-1x-1gb":{cpus:1,memoryMb:1024,cpuKind:`shared`},"shared-1x-2gb":{cpus:1,memoryMb:2048,cpuKind:`shared`},"shared-2x-4gb":{cpus:2,memoryMb:4096,cpuKind:`shared`},"shared-4x-8gb":{cpus:4,memoryMb:8192,cpuKind:`shared`},"shared-8x-16gb":{cpus:8,memoryMb:16384,cpuKind:`shared`}};function Gr(e){let t=e.installUrl||`https://bivy.sh/install.sh`,n=Qn(e.ttlMinutes)*60,r=e=>b(ar.encode(e)),i=[`set -euo pipefail`,`export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$HOME/.local/bin:$PATH"`,`export DEBIAN_FRONTEND=noninteractive`,`mkdir -p /etc/bivy /workspace`,`chmod 700 /etc/bivy`,`chmod 600 /etc/bivy/relay.json /etc/bivy/start.sh`,`export BIVY_DATA_DIR=/etc/bivy`,`export BIVY_WORKSPACE=/workspace`,`trap ${V(mr(e,`failed`))} ERR`,mr(e,`booting`),`if ! command -v bivy >/dev/null 2>&1; then\n${mr(e,`installing`)}\napt-get update -qq\napt-get install -y -qq curl ca-certificates\ncurl --connect-timeout 10 --max-time 120 -fsSL ${V(t)} | bash\nfi`,mr(e,`starting`),`exec bash /etc/bivy/start.sh`].join(`
|
|
19
|
-
`);return{files:[{guest_path:`/etc/bivy/relay.json`,raw_value:r(dr(e))},{guest_path:`/etc/bivy/start.sh`,raw_value:r(pr(e))}],init:{exec:[`/usr/bin/timeout`,`--kill-after=10s`,String(n),`/bin/bash`,`-c`,i]}}}async function Kr(e,t,n){if(!/^bivy-[a-z0-9-]+$/.test(n))return;let r=`https://api.machines.dev/v1/apps/${encodeURIComponent(n)}`,i=await z(e,{method:`GET`,url:`${r}/machines`,headers:B(t)});if(i.status===404)return;if(i.status>=300)throw Error(H(i,`check empty app`));if(!Array.isArray(i.body))throw Error(`Fly returned an invalid app inventory; keeping the app for cleanup retry`);if(i.body.length)return;let a=await z(e,{method:`DELETE`,url:r,headers:B(t)});if(a.status>=300&&a.status!==404)throw Error(H(a,`delete empty app`))}var qr={id:`fly`,name:`Fly.io`,currency:`USD`,regions:[{id:`iad`,label:`Ashburn, VA`},{id:`sjc`,label:`San Jose`},{id:`lhr`,label:`London`},{id:`fra`,label:`Frankfurt`},{id:`syd`,label:`Sydney`},{id:`nrt`,label:`Tokyo`}],defaultRegion:`iad`,sizes:[{id:`shared-1x-1gb`,label:`shared · 1 vCPU · 1 GB`,vcpus:1,memoryMiB:1024,architecture:`x86_64`,pricePerHour:.009,priceSource:`indicative`},{id:`shared-1x-2gb`,label:`shared · 1 vCPU · 2 GB`,vcpus:1,memoryMiB:2048,architecture:`x86_64`,pricePerHour:.0136,priceSource:`indicative`},{id:`shared-2x-4gb`,label:`shared · 2 vCPU · 4 GB`,vcpus:2,memoryMiB:4096,architecture:`x86_64`,pricePerHour:.0273,priceSource:`indicative`},{id:`shared-4x-8gb`,label:`shared · 4 vCPU · 8 GB`,vcpus:4,memoryMiB:8192,architecture:`x86_64`,pricePerHour:.0546,priceSource:`indicative`},{id:`shared-8x-16gb`,label:`shared · 8 vCPU · 16 GB`,vcpus:8,memoryMiB:16384,architecture:`x86_64`,pricePerHour:.1234,priceSource:`indicative`}],defaultSize:`shared-4x-8gb`,async validateToken({exec:e,token:t}){let n=await Ur(e,t),r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(n)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`validate credential`))},async provision({exec:e,token:t,config:n,bootstrap:r}){if(!r)throw Error(`Fly requires a structured Bivy bootstrap; cloud-init is not supported by Fly Machines.`);let i=`bivy-${n.slug}`,a=await Ur(e,t,n.org),o=Wr[n.size]||Wr[qr.defaultSize]||{cpus:1,memoryMb:2048,cpuKind:`shared`},s=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps`,headers:{...B(t),"content-type":`application/json`},body:{app_name:i,org_slug:a}}),c=s.status===422&&/name has already been taken/i.test(cr(s.body));if(s.status>=300&&s.status!==409&&!c)throw Error(H(s,`create app`));if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(r.status>=300)throw Error(H(r,`check existing launch`));if(!Array.isArray(r.body))throw Error(`Fly returned an invalid machine inventory; refusing to risk a duplicate launch`);let a=r.body.find(e=>e?.config?.metadata?.[`bivy-attempt`]===String(n.attemptId));if(r.status<300&&a?.id)return{id:String(a.id),provider:`fly`,app:i,name:i,region:a.region||n.region||`iad`,status:Vr(a.state),ip:null,createdAt:a.created_at||sr(),ttlMinutes:n.ttlMinutes};if(r.body.length)throw Error(`This Fly app already contains a machine from another launch. Reconnect or destroy it before rebuilding.`)}let l=Gr(r),u=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:{...B(t),"content-type":`application/json`},body:{region:n.region||`iad`,config:{image:n.image||`ghcr.io/bivysh/bivy-ephemeral-runner@sha256:30705bdda88425646b0c5dc19fc0e95cc4a026ca9c09a4f904c15b3a21e246ac`,auto_destroy:!r?.debugKeepMachine,restart:{policy:`no`},guest:{cpu_kind:o.cpuKind,cpus:Number(n.cpus)||o.cpus,memory_mb:Number(n.memoryMb)||o.memoryMb},metadata:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}},...l}}});if(u.status>=300)throw s.status<300&&u.status>=400&&u.status<500&&![408,409,429].includes(u.status)&&await Kr(e,t,i),Error(H(u,`create machine`));let d=u.body;if(!d||!d.id)throw Error(`Fly did not return a machine`);return{id:String(d.id),provider:`fly`,app:i,name:i,region:n.region||`iad`,status:Vr(d.state),ip:null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get machine`));return Vr(r.body?.state)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete machine`));await Kr(e,t,n.app||``)},async cleanupAttempt({exec:e,token:t,nodeId:n,attemptId:r,ownershipTag:i}){if(!/^eph-(?:[a-f0-9]{16}|[a-f0-9]{32})$/.test(n))return!1;let a=`bivy-${n.replace(/^eph-/,``)}`,o=`https://api.machines.dev/v1/apps/${encodeURIComponent(a)}`,s=await z(e,{method:`GET`,url:`${o}/machines`,headers:B(t)});if(s.status!==404){if(s.status>=300||!Array.isArray(s.body))throw Error(`Cannot verify canceled Fly launch inventory`);if(s.body.some(e=>e?.config?.metadata?.[`bivy-attempt`]!==r||e?.config?.metadata?.[`bivy-account`]!==i))return!1;for(let n of s.body){if(!n?.id)return!1;let r=await z(e,{method:`DELETE`,url:`${o}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)return!1}let n=await z(e,{method:`DELETE`,url:o,headers:B(t)});if(n.status>=300&&n.status!==404)return!1}return(await z(e,{method:`GET`,url:o,headers:B(t)})).status===404},async discover({exec:e,token:t,ownershipTag:n}){let r=await Ur(e,t),i=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(r)}`,headers:B(t)});if(i.status>=300)throw Error(H(i,`list apps`));let a=Array.isArray(i.body?.apps)?i.body.apps:Array.isArray(i.body)?i.body:[],o=[];for(let r of a){let i=String(r?.name||``);if(!i.startsWith(`bivy-`))continue;let a=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(a.status>=300)continue;let s=Array.isArray(a.body)?a.body:[];for(let e of s){let t=e?.config?.metadata||{};t.bivy===`ephemeral`&&t[`bivy-account`]===n&&o.push({id:String(e.id),provider:`fly`,app:i,name:i,region:e.region||``,status:Vr(e.state),ip:null,createdAt:typeof e.created_at==`string`?e.created_at:``,attemptId:typeof t[`bivy-attempt`]==`string`?t[`bivy-attempt`]:void 0})}}return o}};function Jr(e){return e===`running`?`running`:e===`off`||e===`stopping`?`stopped`:`starting`}function Yr(e){let t=Array.isArray(e?.prices)?e.prices:[];for(let e of t){let t=Number(e?.price_hourly?.gross);if(Number.isFinite(t)&&t>0)return t}}var Xr=new Map,Zr=new Map;function Qr(e,t){return lr(Xr,t,async()=>{let n=[],r=`https://api.hetzner.cloud/v1/server_types?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list server types`));let a=Array.isArray(i.body?.server_types)?i.body.server_types:[];for(let e of a){if(e.deprecation)continue;let t=e.architecture===`arm`?`Arm64`:`x86`;n.push({typeId:Number(e.id),id:String(e.name),label:`${e.name} · ${e.cores} vCPU · ${e.memory} GB · ${e.disk} GB (${t})`,cores:Number(e.cores)||0,memory:Number(e.memory)||0,disk:Number(e.disk)||0,architecture:e.architecture===`arm`?`arm64`:`x86_64`,pricePerHour:Yr(e)})}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/server_types?per_page=50&page=${o}`:null}return n})}function $r(e,t){return lr(Zr,t,async()=>{let n=new Map,r=`https://api.hetzner.cloud/v1/datacenters?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list datacenters`));let a=Array.isArray(i.body?.datacenters)?i.body.datacenters:[];for(let e of a){let t=e?.location?.name;if(!t)continue;let r=n.get(t)??new Set,i=Array.isArray(e?.server_types?.available)?e.server_types.available:[];for(let e of i)r.add(Number(e));n.set(t,r)}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/datacenters?per_page=50&page=${o}`:null}return n})}var ei={id:`hetzner`,name:`Hetzner Cloud`,currency:`EUR`,regions:[{id:`nbg1`,label:`Nuremberg`},{id:`fsn1`,label:`Falkenstein`},{id:`hel1`,label:`Helsinki`},{id:`ash`,label:`Ashburn, VA`},{id:`hil`,label:`Hillsboro, OR`}],defaultRegion:`nbg1`,sizes:[{id:`cpx11`,label:`cpx11 · 2 vCPU · 2 GB · 40 GB (AMD x86)`,vcpus:2,memoryMiB:2048,diskGiB:40,architecture:`x86_64`,pricePerHour:.007,priceSource:`indicative`},{id:`cpx21`,label:`cpx21 · 3 vCPU · 4 GB · 80 GB (AMD x86)`,vcpus:3,memoryMiB:4096,diskGiB:80,architecture:`x86_64`,pricePerHour:.013,priceSource:`indicative`},{id:`cpx31`,label:`cpx31 · 4 vCPU · 8 GB · 160 GB (AMD x86)`,vcpus:4,memoryMiB:8192,diskGiB:160,architecture:`x86_64`,pricePerHour:.026,priceSource:`indicative`},{id:`cpx41`,label:`cpx41 · 8 vCPU · 16 GB · 240 GB (AMD x86)`,vcpus:8,memoryMiB:16384,diskGiB:240,architecture:`x86_64`,pricePerHour:.049,priceSource:`indicative`},{id:`cpx51`,label:`cpx51 · 16 vCPU · 32 GB · 360 GB (AMD x86)`,vcpus:16,memoryMiB:32768,diskGiB:360,architecture:`x86_64`,pricePerHour:.099,priceSource:`indicative`},{id:`cax11`,label:`cax11 · 2 vCPU · 4 GB · 40 GB (Arm64)`,vcpus:2,memoryMiB:4096,diskGiB:40,architecture:`arm64`,pricePerHour:.006,priceSource:`indicative`},{id:`cax21`,label:`cax21 · 4 vCPU · 8 GB · 80 GB (Arm64)`,vcpus:4,memoryMiB:8192,diskGiB:80,architecture:`arm64`,pricePerHour:.012,priceSource:`indicative`},{id:`cax31`,label:`cax31 · 8 vCPU · 16 GB · 160 GB (Arm64)`,vcpus:8,memoryMiB:16384,diskGiB:160,architecture:`arm64`,pricePerHour:.024,priceSource:`indicative`},{id:`cax41`,label:`cax41 · 16 vCPU · 32 GB · 320 GB (Arm64)`,vcpus:16,memoryMiB:32768,diskGiB:320,architecture:`arm64`,pricePerHour:.048,priceSource:`indicative`}],defaultSize:`cpx31`,guestCanEnsureDeletion:!1,async validateToken({exec:e,token:t}){let n=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?per_page=1`,headers:B(t)});if(n.status>=300)throw Error(H(n,`validate credential`))},async listSizes({exec:e,token:t,region:n}){let r=await Qr(e,t),i=r;if(n)try{let a=(await $r(e,t)).get(n),o=a?r.filter(e=>a.has(e.typeId)):r;o.length&&(i=o)}catch{}return[...i].sort((e,t)=>e.cores-t.cores||e.memory-t.memory||e.id.localeCompare(t.id)).map(({id:e,label:t,cores:n,memory:r,disk:i,architecture:a,pricePerHour:o})=>({id:e,label:t,vcpus:n,memoryMiB:r*1024,diskGiB:i,architecture:a,pricePerHour:o,priceSource:o?`live`:void 0}))},async provision({exec:e,token:t,config:n,userData:r}){let i=`bivy-${n.slug}`;if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-attempt=${n.attemptId}`)}`,headers:B(t)});if(r.status<300&&Array.isArray(r.body?.servers)&&r.body.servers[0]){let e=r.body.servers[0];return{id:String(e.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}}}let a=await z(e,{method:`POST`,url:`https://api.hetzner.cloud/v1/servers`,headers:{...B(t),"content-type":`application/json`},body:{name:i,server_type:n.size||ei.defaultSize,image:n.image||`ubuntu-24.04`,location:n.region||`nbg1`,user_data:r,start_after_create:!0,labels:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}}}});if(a.status>=300)throw Error(H(a,`create server`));let o=a.body&&a.body.server;if(!o)throw Error(`Hetzner did not return a server`);return{id:String(o.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(o.status),ip:o.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get server`));return Jr(r.body?.server?.status)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete server`))},async discover({exec:e,token:t,ownershipTag:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-account=${n}`)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`list servers`));return(Array.isArray(r.body?.servers)?r.body.servers:[]).map(e=>({id:String(e.id),provider:`hetzner`,name:String(e.name||``),region:e.datacenter?.location?.name||``,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:typeof e.created==`string`?e.created:``,attemptId:typeof e.labels?.[`bivy-attempt`]==`string`?e.labels[`bivy-attempt`]:void 0}))}},ti=new Map([ei,qr,Br].map(e=>[e.id,e]));function ni(e){return ti.get(String(e||``).trim().toLowerCase())||null}async function ri(e,t,n,r){let i=ni(e);if(!i)throw Error(`Unknown provider: ${e}`);let a=String(t||``).trim();if(!a)throw Error(`${i.name} token is required`);if(!i.validateToken)throw Error(`${i.name} credential validation is not available`);await i.validateToken({exec:n,token:a,region:r||i.defaultRegion})}function ii(e,t,n,r=Date.now()){return rr(e,t,n,r)}function ai(e){return e.replace(/^eph-/,``)}function oi(e){let t=e.region||e.defaultRegion,n=e.size||e.defaultSize,r=ai(e.nodeId),i=String(e.name||``).trim();return{attemptId:e.attemptId,nodeId:e.nodeId,requestedAt:e.requestedAt,provider:e.provider,region:t,size:n,providerConfig:{slug:r,region:t,size:n,image:e.image,ttlMinutes:e.ttlMinutes,attemptId:e.attemptId,ownershipTag:e.ownershipTag},machineFacts:{...i?{name:i}:{},...e.setupId?{setupId:e.setupId}:{},...e.repo?{repo:e.repo}:{},...e.teardownOnAgentFinish?{teardownOnAgentFinish:!0}:{},...e.workItemId?{workItemId:e.workItemId}:{},...e.purpose?{purpose:e.purpose}:{}}}}function si(e,t,n){return{...e,...t.machineFacts,attemptId:t.attemptId,nodeId:t.nodeId,size:t.size,milestones:{...e.milestones??{},requestedAt:t.requestedAt,providerAcceptedAt:n}}}function ci(e){let t=e.nodeId.replace(/^eph-/,``);return{bootstrap:{relayUrl:e.relayUrl,controlPlaneUrl:e.controlPlaneUrl,enrollmentToken:e.enrollmentToken,e2eKeyB64:e.roomKeyB64,ttlMinutes:e.ttlMinutes,repo:e.repo,hostedTasks:e.hostedTasks,hostedCredentialCustody:e.hostedCredentialCustody,hostedCredentialPublisher:e.hostedCredentialPublisher,nodeLabel:e.hostedTasks?t:void 0,githubToken:e.githubToken,hostedMint:e.hostedMint,provider:e.provider,teardownOnAgentFinish:e.teardownOnAgentFinish,debugKeepMachine:e.debugKeepMachine,restoreSessionId:e.restoreSessionId}}}var li=[{id:`fly`,name:`Fly.io`,computeClass:`byo-cloud`,tokenLabel:`Fly.io access token`,blurb:`Bivy creates a temporary Fly Machine, runs the session, then destroys it.`,steps:[`Open your Fly.io access tokens and sign in.`,`Click Create token — use a short-lived/deploy token if your account offers one.`,`Copy the token and paste it below. Revoke it after the session if you like.`],links:[{label:`Create a Fly.io token`,url:`https://fly.io/user/personal_access_tokens`},{label:`Fly Machines docs`,url:`https://fly.io/docs/machines/`}]},{id:`hetzner`,name:`Hetzner Cloud`,computeClass:`byo-cloud`,tokenLabel:`Hetzner Cloud API token`,blurb:`Bivy manages Hetzner servers from start to deletion so billing always stops, even when your devices are offline.`,steps:[`Open the Hetzner Cloud Console and select or create a project for Bivy's runners.`,`Go to Security → API Tokens and click Generate API token.`,`Choose Read & Write, then copy the token and paste it below.`],links:[{label:`Hetzner Cloud Console`,url:`https://console.hetzner.cloud/projects`},{label:`API token docs`,url:`https://docs.hetzner.com/cloud/api/getting-started/generating-api-token/`}],hostedOnly:!0},{id:`aws`,name:`AWS EC2`,computeClass:`byo-cloud`,tokenLabel:`Access key — paste as accessKeyId:secretAccessKey`,blurb:`Bivy launches a temporary EC2 instance, runs the session, then terminates it.`,steps:[`Create (or reuse) an IAM user scoped to a minimal EC2 policy — see the Bivy docs link below for a copy-pasteable policy.`,`On that user, open Security credentials → Access keys → Create access key.`,`Paste both values below as accessKeyId:secretAccessKey (append :sessionToken if you're using temporary STS credentials).`],links:[{label:`IAM access keys`,url:`https://console.aws.amazon.com/iam/home#/security_credentials`},{label:`EC2 console`,url:`https://console.aws.amazon.com/ec2/home`},{label:`Minimal IAM policy (Bivy docs)`,url:`https://github.com/bivysh/bivy/blob/main/docs/ephemeral-sessions.md#aws-ec2`}]}];function G(e){let t=String(e||``).trim().toLowerCase();return li.find(e=>e.id===t)||null}function ui(e){return{id:e.machineId||e.nodeId,provider:e.provider,name:e.nodeId,region:e.region||``,status:`gone`,ip:null,createdAt:``,ttlMinutes:e.ttlMinutes,app:e.app,nodeId:e.nodeId,setupId:e.setupId,repo:e.repo,computeSource:e.computeSource}}function di(e){let t=e.ephemeral;return!t?.provider||!t.machineId?null:{id:t.machineId,provider:t.provider,name:e.name||t.machineId,region:t.region||``,status:`stopped`,ip:null,createdAt:``,app:t.app,nodeId:e.id}}function fi(){try{return new Date().toISOString()}catch{return``}}function pi(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function mi(){let e=new Map;return{async getAll(){return[...e.values()].map(e=>({...e}))},async put(t,n){e.set(t,{...n})},async delete(t){e.delete(t)}}}function hi(e,t,n,r){function i(){return new Promise((i,a)=>{let o=e.open(t,1);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(n)||o.result.createObjectStore(n,{keyPath:r})},o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)})}function a(e,t){return e.transaction(n,t).objectStore(n)}function o(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}return{async getAll(){let e=await i();try{return await o(a(e,`readonly`).getAll())||[]}finally{e.close()}},async put(e,t){let n=await i();try{await o(a(n,`readwrite`).put(t))}finally{n.close()}},async delete(e){let t=await i();try{await o(a(t,`readwrite`).delete(e))}finally{t.close()}}}}function K(e,t){try{let n=globalThis.indexedDB;if(n)return hi(n,e===`provider-keys`?`bivy-ephemeral`:`bivy-ephemeral-${e}`,e,t)}catch{}return mi()}function gi(e=K(`provider-keys`,`provider`)){return{async list(){let t;try{t=await e.getAll()}catch{t=[]}let n=new Map(t.map(e=>[e.provider,e]));return li.map(e=>{let t=n.get(e.id);return{id:e.id,name:e.name,configured:!!(t&&t.token),updatedAt:t?t.updatedAt:null}})},async getToken(t){let n=G(t);if(!n)return``;let r;try{r=await e.getAll()}catch{return``}let i=r.find(e=>e.provider===n.id);return i&&i.token?i.token:``},async setToken(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n||``).trim();if(!i)throw Error(`API token cannot be empty`);await e.put(r.id,{provider:r.id,token:i,updatedAt:fi()})},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function _i(e=K(`model-oauth`,`id`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>t(e||`default`)||`default`,r=(e,t)=>`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async entries(){return(await i()).filter(e=>e?.provider&&e?.refresh).map(e=>({provider:t(e.provider),label:n(e.label),access:String(e.access||``),refresh:String(e.refresh),expires:Number(e.expires)||0,...Number.isFinite(Number(e.refreshedAt))?{refreshedAt:Number(e.refreshedAt)}:{},...Number.isFinite(Number(e.updatedAt))?{updatedAt:Number(e.updatedAt)}:{}}))},async set(i){let a=t(i.provider),o=n(i.label);if(!a||!String(i.refresh||``).trim())throw Error(`A provider and refresh token are required`);await e.put(r(a,o),{...i,id:r(a,o),provider:a,label:o})},async remove(i,a=`default`){await e.delete(r(t(i),n(a)))}}}function vi(e=K(`model-keys`,`provider`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>String(e||`default`).trim().toLowerCase()||`default`,r=(e,t)=>t==="default"?e:`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async list(){return(await i()).filter(e=>e&&e.provider).map(e=>({provider:String(e.provider),label:n(e.label),configured:!!e.key,updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`})).sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async entries(){return(await i()).filter(e=>e&&e.provider&&e.key).map(e=>({provider:String(e.provider),label:n(e.label),key:String(e.key),updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`}))},async get(e,r=`default`){let a=t(e),o=n(r);if(!a)return``;let s=(await i()).find(e=>e.provider===a&&n(e.label)===o);return s&&s.key?s.key:``},async set(i,a,o=`account`,s=`default`){let c=t(i),l=n(s);if(!c)throw Error(`Provider is required`);let u=String(a||``).trim();if(!u)throw Error(`API key cannot be empty`);if(o!==`account`&&o!==`device`)throw Error(`Credential scope must be account or device`);await e.put(r(c,l),{provider:c,label:l,key:u,scope:o,updatedAt:fi()})},async remove(i,a=`default`){let o=t(i);o&&await e.delete(r(o,n(a)))}}}var yi=`github-task-token`;function bi(e=K(`github-task-token`,`id`)){return{async get(){let t;try{t=await e.getAll()}catch{return``}let n=t.find(e=>e.id===yi);return n&&n.token?n.token:``},async set(t){let n=String(t||``).trim();if(!n)throw Error(`GitHub token cannot be empty`);await e.put(yi,{id:yi,token:n,updatedAt:fi()})},async remove(){await e.delete(yi)}}}var xi={region:null,size:null,ttlMinutes:null,repo:null,teardownOnAgentFinish:!1};function Si(e=K(`provider-prefs`,`provider`)){let t=async t=>{let n=G(t);if(!n)return{...xi};let r;try{r=await e.getAll()}catch{return{...xi}}let i=r.find(e=>e.provider===n.id);return i?{region:i.region??null,size:i.size??null,ttlMinutes:typeof i.ttlMinutes==`number`?i.ttlMinutes:null,repo:i.repo??null,teardownOnAgentFinish:i.teardownOnAgentFinish===!0}:{...xi}};return{get:t,async set(n,r){let i=G(n);if(!i)throw Error(`Unknown ephemeral provider: ${n}`);let a={...await t(i.id),...r};return await e.put(i.id,{provider:i.id,...a,updatedAt:fi()}),a},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function Ci(){try{return`setup-`+pi(8)}catch{return`setup-${Math.random().toString(16).slice(2)}`}}function wi(e=K(`setups`,`id`)){let t=async()=>{try{return(await e.getAll()).filter(e=>e&&e.id&&G(e.provider)).sort((e,t)=>String(e.name).localeCompare(String(t.name)))}catch{return[]}};return{async list(e){let n=await t();if(!e)return n;let r=G(e);return r?n.filter(e=>e.provider===r.id):[]},async get(e){return(await t()).find(t=>t.id===e)??null},async create(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n.name||``).trim();if(!i)throw Error(`Setup name is required`);let a=fi(),o={id:Ci(),provider:r.id,name:i,...xi,region:n.region??null,size:n.size??null,ttlMinutes:n.ttlMinutes??null,repo:n.repo??null,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,createdAt:a,updatedAt:a};return await e.put(o.id,o),o},async update(n,r){let i=(await t()).find(e=>e.id===n);if(!i)throw Error(`Ephemeral setup not found`);let a={...i,...r,id:i.id,provider:i.provider,updatedAt:fi()};if(a.name=String(a.name||``).trim(),!a.name)throw Error(`Setup name is required`);return await e.put(n,a),a},async remove(t){await e.delete(t)}}}function Ti(e=K(`pending-launches`,`id`)){return{async list(){try{return(await e.getAll()).filter(e=>e&&e.id&&e.config&&e.prompt).sort((e,t)=>String(e.createdAt).localeCompare(String(t.createdAt)))}catch{return[]}},async put(t){let{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u}=t;await e.put(n,{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u})},async remove(t){await e.delete(t)}}}function Ei(e=K(`machines`,`id`)){return{async list(){try{return(await e.getAll()).sort((e,t)=>String(t.createdAt).localeCompare(String(e.createdAt)))}catch{return[]}},async add(t){if(!t||!t.id)throw Error(`Machine record needs an id`);return await e.put(t.id,t),t},async update(t,n){let r=(await e.getAll().catch(()=>[])).find(e=>e.id===t);if(!r)return null;let i={...r,...n};return await e.put(t,i),i},async remove(t){await e.delete(t)}}}function Di(){try{return new Date().toISOString()}catch{return``}}function Oi(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}function ki(e,t=fetch){return async n=>{let r=await t(`${Oi(e)}/api/ephemeral/exec`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.s}`},body:JSON.stringify(n)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`exec relay failed (${r.status})`);return{status:i.status??r.status,body:i.body}}}function Ai(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function ji(e,t,n){let r=ni(e);if(!r)return[];if(!r.listSizes)return r.sizes;let i=await t.keys.getToken(e).catch(()=>``);if(!i)return r.sizes;try{let e=await r.listSizes({exec:t.exec,token:i,region:n});return e.length?e:r.sizes}catch{return r.sizes}}async function Mi(e,t){if(e.computeSource===`managed`&&!e.externalTeardownGuaranteed)throw Error(`Bivy hosted machines must be launched by the control plane, not with a device-held cloud token.`);if(t.enrollment?.token&&!e.reuseNodeId)throw Error(`Saved enrollment requires the original node identity`);let n=Di(),r=t.fetchImpl??fetch,i=ni(e.provider);if(!i)throw Error(`Unknown provider: ${e.provider}`);let a=t=>{try{e.onProgress?.(t)}catch{}};a(`Preparing ${i.name} launch…`);let o=await t.keys.getToken(e.provider);if(!o)throw Error(`Add a ${i.name} token first.`);if(i.guestCanEnsureDeletion===!1&&!e.externalTeardownGuaranteed)throw Error(`${i.name} requires hosted provisioning: powering off its guest does not delete the billable server, so a device-only launch is unsafe.`);let s=e.attemptId||Ai(16),c=e.reuseNodeId||`eph-`+Ai(8);await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`requested`});let l=JSON.stringify({nodeId:c,name:e.name||`Ephemeral ${i.name}`});a(`Enrolling a secure Bivy node…`);let u=async()=>{let e=await r(`${Oi(t.store)}/nodes/enroll`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${t.store.s}`},body:l});return{res:e,data:await e.json().catch(()=>({}))}},d=t.enrollment?.token;if(!d){let{res:t,data:n}=await u();if(!t.ok||typeof n?.enrollmentToken!=`string`||!n.enrollmentToken){let t=n?.error||`Could not enroll the machine`;throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:t}),Error(t)}d=n.enrollmentToken}await t.enrollment?.persist(c,d),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`enrolled`}),a(`Node enrolled. Building its secure bootstrap…`);let f=e.reuseRoomKeyB64?C(e.reuseRoomKeyB64):crypto.getRandomValues(new Uint8Array(32));t.store.addKey(c,S(f)),await t.persistRoomKey?.(c,S(f));let p=oi({...e,attemptId:s,nodeId:c,requestedAt:n,defaultRegion:i.defaultRegion,defaultSize:i.defaultSize}),m=ci({...e,provider:p.provider,nodeId:p.nodeId,enrollmentToken:d,roomKeyB64:b(f),relayUrl:t.store.relay,controlPlaneUrl:Oi(t.store)}),h=hr(m.bootstrap);a(`Creating the machine in ${p.region} (${p.size})…`);let g;try{g=await i.provision({exec:t.exec,token:o,userData:h,bootstrap:m.bootstrap,config:p.providerConfig})}catch(t){throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:String(t?.message||t).slice(0,500)}),t}let _={...g,...p.machineFacts,attemptId:s};return await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`provider-accepted`,machine:_}),a(`Machine created. Starting Bivy and connecting securely…`),g=si(_,p,Di()),await t.machines.add(g),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`tracked`,machine:g}),g}async function Ni(e,t){let n=t.fetchImpl??fetch,r=ni(e.provider);if(r){let n=await t.keys.getToken(e.provider);if(!n)throw Error(`Add the ${r.name} token on this device to destroy this machine.`);try{await r.destroy({exec:t.exec,token:n,machine:e})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Couldn't destroy this machine at ${r.name}: ${t}. It's still listed — try again in a moment.`)}}t.providerOnly||(await t.machines.remove(e.id),e.nodeId&&await n(`${Oi(t.store)}/nodes/${encodeURIComponent(e.nodeId)}`,{method:`DELETE`,headers:{authorization:`Bearer ${t.store.s}`}}).catch(()=>{}))}var Pi=`bivy`,q=`device-key`,Fi=`x25519`;function Ii(){try{return typeof globalThis<`u`&&!!globalThis.indexedDB}catch{return!1}}var Li=4e3;function Ri(){return new Promise((e,t)=>{let n=!1,r=e=>{n||(n=!0,e())},i=setTimeout(()=>r(()=>t(Error(`indexedDB.open timed out`))),Li),a=indexedDB.open(Pi,1);a.onupgradeneeded=()=>{a.result.objectStoreNames.contains(q)||a.result.createObjectStore(q)},a.onsuccess=()=>r(()=>{clearTimeout(i),e(a.result)}),a.onerror=()=>r(()=>{clearTimeout(i),t(a.error)}),a.onblocked=()=>r(()=>{clearTimeout(i),t(Error(`indexedDB.open blocked`))})})}function zi(e,t){return new Promise((n,r)=>{let i;try{i=t(e)}catch(e){r(e);return}i.onsuccess=()=>n(i.result),i.onerror=e=>{e.preventDefault(),r(i.error)}})}async function Bi(){if(!Ii())return;let e=await Ri();try{await zi(e.transaction(q,`readwrite`).objectStore(q),e=>e.delete(Fi))}finally{e.close()}}function Vi(){return Ii()?{async load(){let e=await Ri();try{let t=await zi(e.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));return t&&t.priv instanceof CryptoKey&&typeof t.pub==`string`?{priv:t.priv,pub:t.pub}:null}finally{e.close()}},async save(e,t){try{let n=globalThis.structuredClone;n&&n({priv:e,pub:t})}catch{throw Error(`IndexedDB cannot clone this device key`)}let n=await Ri();try{let r=n.transaction(q,`readwrite`);r.onerror=e=>e.preventDefault(),await zi(r.objectStore(q),n=>n.put({priv:e,pub:t},Fi)),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)});let i=await zi(n.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));if(!i||!(i.priv instanceof CryptoKey)||i.priv.extractable||i.pub!==t)throw Error(`IndexedDB did not preserve the non-extractable device key`)}finally{n.close()}}}:null}var Hi=new WeakMap;function Ui(e,t){if(t)return Wi(e,t);let n=Hi.get(e);if(n)return n;let r=Wi(e,Vi()??void 0);return Hi.set(e,r),r.catch(()=>{Hi.get(e)===r&&Hi.delete(e)}),r}async function Wi(e,t){let n=t??Vi();if(n)try{let t=await n.load();if(t)return t;let r=e.device();if(r){let t=await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!1,[`deriveBits`]);return await n.save(t,r.pub),e.clearDevice(),{priv:t,pub:r.pub}}let i=await crypto.subtle.generateKey({name:`X25519`},!1,[`deriveBits`]),a=S(new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)));return await n.save(i.privateKey,a),{priv:i.privateKey,pub:a}}catch{}let r=e.device();if(r)return{priv:await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!0,[`deriveBits`]),pub:r.pub};let i=await crypto.subtle.generateKey({name:`X25519`},!0,[`deriveBits`]),a=new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)),o=new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,i.privateKey)),s=S(a),c=S(o);return e.setDevice({pub:s,priv:c}),{priv:i.privateKey,pub:s}}async function Gi(e,t){let n=await crypto.subtle.importKey(`raw`,C(t),{name:`X25519`},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:`X25519`,public:n},e,256))}async function Ki(e,t,n){let r=await Gi(e,t),i=await crypto.subtle.importKey(`raw`,r,`HKDF`,!1,[`deriveBits`]),a=n===`rotate`?w.rotate:n===`device-vault`?w.deviceVault:w.pair,o=new TextEncoder().encode(a),s=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array,info:o},i,256)),c=n===`device-vault`?[`encrypt`,`decrypt`]:[`decrypt`];return crypto.subtle.importKey(`raw`,s,`AES-GCM`,!1,c)}async function qi(e,t){let n=await crypto.subtle.importKey(`raw`,C(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return S(new Uint8Array(await crypto.subtle.sign(`HMAC`,n,C(t))))}var Ji=class extends Error{constructor(){super(`Device vault changed concurrently`),this.name=`DeviceVaultConflictError`}},Yi=()=>({v:3,providerTokens:{},modelKeys:{},oauthCredentials:{}}),Xi=()=>({phase:`idle`,attemptedAt:null,succeededAt:null,pending:!1,failure:null}),Zi=e=>{let t=e?Date.parse(e):NaN;return Number.isFinite(t)?t:0};function Qi(e){if(e&&typeof e==`object`&&e.v===3){let t=e,n={};for(let[e,r]of Object.entries(t.modelKeys&&typeof t.modelKeys==`object`?t.modelKeys:{})){if(!r||typeof r!=`object`)continue;let t=r;n[e]=t.value?{...t,value:{provider:t.value.provider||e.split(`:`)[0]||e,label:t.value.label||e.split(`:`).slice(1).join(`:`)||`default`,key:t.value.key}}:t}return{v:3,providerTokens:t.providerTokens&&typeof t.providerTokens==`object`?t.providerTokens:{},modelKeys:n,oauthCredentials:t.oauthCredentials&&typeof t.oauthCredentials==`object`?t.oauthCredentials:{}}}let t=Yi(),n=Date.now();if(e&&typeof e==`object`&&e.v===2){let r=e;for(let[e,i]of Object.entries(r.providerTokens??{}))typeof i==`string`&&(t.providerTokens[e]={value:i,updatedAt:n});for(let[e,i]of Object.entries(r.modelKeys??{}))i&&typeof i.key==`string`&&(t.modelKeys[e]={value:{provider:e,label:`default`,key:i.key},updatedAt:Zi(i.updatedAt)||n})}else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e))typeof i==`string`&&(t.providerTokens[r]={value:i,updatedAt:n});return t}function $i(e,t){return e?t?e.updatedAt===t.updatedAt?!!e.tombstone==!!t.tombstone?JSON.stringify(e.value)>=JSON.stringify(t.value)?e:t:e.tombstone?e:t:e.updatedAt>t.updatedAt?e:t:e:t}function ea(e,t){let n=Yi();for(let r of new Set([...Object.keys(e.providerTokens),...Object.keys(t.providerTokens)]))n.providerTokens[r]=$i(e.providerTokens[r],t.providerTokens[r]);for(let r of new Set([...Object.keys(e.modelKeys),...Object.keys(t.modelKeys)]))n.modelKeys[r]=$i(e.modelKeys[r],t.modelKeys[r]);for(let r of new Set([...Object.keys(e.oauthCredentials),...Object.keys(t.oauthCredentials)]))n.oauthCredentials[r]=$i(e.oauthCredentials[r],t.oauthCredentials[r]);return n}function J(e,t=`default`){let n=String(e||``).trim().toLowerCase(),r=String(t||`default`).trim().toLowerCase()||`default`;return r==="default"?n:`${n}:${r}`}function ta(e){let t=e.indexOf(`:`);return t<0?{provider:e,label:`default`}:{provider:e.slice(0,t),label:e.slice(t+1)||`default`}}function na(){return crypto.getRandomValues(new Uint8Array(32))}function ra(e){let t=e.randomKey??na,n=e.now??Date.now,r=null,i=0,a=0,o=Yi(),s=null,c=0,l={},u={},d={},f={},p={},m={},h=Xi(),g=null,_=async()=>e.state?.save({clock:c,tokenVersions:l,modelVersions:u,oauthVersions:d,tokenTombstones:f,modelTombstones:p,oauthTombstones:m,sync:h}),v=()=>s??=(async()=>{let t=await e.state?.load();c=Math.max(t?.clock??0,n()),l={...t?.tokenVersions??{}},u={...t?.modelVersions??{}},d={...t?.oauthVersions??{}},f={...t?.tokenTombstones??{}},p={...t?.modelTombstones??{}},m={...t?.oauthTombstones??{}},h=t?.sync??Xi()})(),y=()=>c=Math.max(c+1,n()),S=async(e,t)=>D(await E(t),JSON.stringify(e)),C=async(e,t)=>Qi(JSON.parse(await O(await E(t),e))),w=async(e,t,n)=>D(await Ki(e.priv,t,`device-vault`),b(n)),T=async(e,t,n)=>x(await O(await Ki(e.priv,t,`device-vault`),n));async function ee(){let t=Yi();if(e.providerTokenSyncEnabled?.()!==!1)for(let n of await e.local.list()){let r=await e.local.getToken(n.id);r&&(t.providerTokens[n.id]={value:r,updatedAt:Math.max(Zi(n.updatedAt),l[n.id]??1)})}for(let[e,n]of Object.entries(f))t.providerTokens[e]=$i(t.providerTokens[e],{value:null,updatedAt:n,tombstone:!0});if(e.modelKeys){for(let n of await e.modelKeys.entries())if(n.scope===`account`){let e=J(n.provider,n.label);t.modelKeys[e]={value:{provider:n.provider,label:n.label,key:n.key},updatedAt:Math.max(Zi(n.updatedAt),u[e]??1)}}}for(let[e,n]of Object.entries(p))t.modelKeys[e]=$i(t.modelKeys[e],{value:null,updatedAt:n,tombstone:!0});if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let n of await e.oauthCredentials.entries()){let e=J(n.provider,n.label),r=Math.max(Number(n.refreshedAt)||0,Number(n.updatedAt)||0,d[e]??1);t.oauthCredentials[e]={value:n,updatedAt:r}}for(let[e,n]of Object.entries(m))t.oauthCredentials[e]=$i(t.oauthCredentials[e],{value:null,updatedAt:n,tombstone:!0});return t}async function te(t){for(let[n,r]of Object.entries(t.providerTokens)){let t=(await e.local.list()).find(e=>e.id===n),i=Zi(t?.updatedAt);r.tombstone?(f[n]=Math.max(f[n]??0,r.updatedAt),i<=r.updatedAt&&await e.local.remove(n)):r.value&&(!t?.configured||i<r.updatedAt)&&(await e.local.setToken(n,r.value),l[n]=r.updatedAt,delete f[n])}if(e.modelKeys)for(let[n,r]of Object.entries(t.modelKeys)){let t=r.value?.provider??n,i=r.value?.label??`default`,a=(await e.modelKeys.list()).find(e=>e.provider===t&&e.label===i),o=Zi(a?.updatedAt);r.tombstone?(p[n]=Math.max(p[n]??0,r.updatedAt),o<=r.updatedAt&&await e.modelKeys.remove(t,i)):r.value&&(!a?.configured||o<r.updatedAt)&&(await e.modelKeys.set(t,r.value.key,`account`,i),u[n]=r.updatedAt,delete p[n])}if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let[n,r]of Object.entries(t.oauthCredentials)){let t=(await e.oauthCredentials.entries()).find(e=>J(e.provider,e.label)===n),i=Math.max(Number(t?.refreshedAt)||0,Number(t?.updatedAt)||0,d[n]??0);if(r.tombstone){if(m[n]=Math.max(m[n]??0,r.updatedAt),i<=r.updatedAt){let r=t??ta(n);await e.oauthCredentials.remove(r.provider,r.label)}}else r.value&&i<r.updatedAt&&(await e.oauthCredentials.set(r.value),d[n]=r.updatedAt,delete m[n])}}async function ne(){if(!e.enabled())return;await v();let s=await e.device(),c=await e.remote.get();a=c.generation??0;let l=c.keyGeneration??0;(!r||(c.wrappedKey?.generation??0)>i)&&c.wrappedKey&&(r=await T(s,c.wrappedKey.wrappedByPublicKeyB64,c.wrappedKey.wrappedKey),i=c.wrappedKey.generation??l),r&&c.vault&&(o=await C(c.vault,r)),r&&l>i&&(r=t(),i=l);let u=await ee(),d=ea(o,u),f=Object.keys(d.providerTokens).length+Object.keys(d.modelKeys).length+Object.keys(d.oauthCredentials).length>0;if(!r){if(!c.vault&&f)r=t(),i=l;else{await e.remote.requestKey(),h={...h,phase:`pending`,pending:!0,failure:null},await _();return}}let p=JSON.stringify(d)!==JSON.stringify(o)||!c.vault||l>(c.wrappedKey?.generation??l);o=d,p&&(a=(await e.remote.putVault(await S(o,r),a,i))?.generation??a+1);let m=new Set([s.pub,...c.recipients??[],...c.requests]);for(let t of m)await e.remote.putWrapped(t,await w(s,t,r),s.pub,i);await te(o),h={phase:`synced`,attemptedAt:h.attemptedAt,succeededAt:new Date(n()).toISOString(),pending:!1,failure:null},await _()}async function k(){return g||(g=(async()=>{await v(),h={...h,phase:`pending`,attemptedAt:new Date(n()).toISOString(),pending:!0,failure:null},await _();try{for(let e=0;e<3;e++)try{await ne();return}catch(t){if(!(t instanceof Ji)||e===2)throw t}}catch(e){throw h={...h,phase:`failed`,pending:!0,failure:e instanceof Error?e.message:String(e)},await _(),e}})().finally(()=>{g=null}),g)}return{sync:k,getSyncState:()=>({...h}),async getToken(t){let n=await e.local.getToken(t);if(n)return n;e.enabled()&&!o.providerTokens[t]&&await k();let r=o.providerTokens[t];return r&&!r.tombstone?r.value??``:``},async setToken(t,n){await v(),await e.local.setToken(t,n),l[t]=y(),delete f[t],await _(),e.enabled()&&e.providerTokenSyncEnabled?.()!==!1&&await k()},async remove(t){await v(),await e.local.remove(t),f[t]=y(),await _(),e.enabled()&&await k()},async list(){let t=await e.local.list(),n=new Set(t.filter(e=>e.configured).map(e=>e.id)),r=[...t];if(e.providerTokenSyncEnabled?.()!==!1)for(let[e,t]of Object.entries(o.providerTokens))!t.tombstone&&t.value&&!n.has(e)&&r.push({id:e,name:e,configured:!0,updatedAt:new Date(t.updatedAt).toISOString()});return r},async listModelKeys(){let t=await e.modelKeys?.list()??[],n=new Set(t.filter(e=>e.configured).map(e=>J(e.provider,e.label)));for(let[e,r]of Object.entries(o.modelKeys))!r.tombstone&&r.value&&!n.has(e)&&t.push({provider:r.value.provider,label:r.value.label,configured:!0,updatedAt:new Date(r.updatedAt).toISOString(),scope:`account`});return t.sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async modelKeyEntries(){let t=await e.modelKeys?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.modelKeys))!t.tombstone&&t.value&&!n.has(e)&&n.set(e,{provider:t.value.provider,label:t.value.label,key:t.value.key,updatedAt:new Date(t.updatedAt).toISOString(),scope:`account`});return[...n.values()]},async getModelKey(t){let n=J(t),r=await e.modelKeys?.get(t)??``;if(r)return r;e.enabled()&&!o.modelKeys[n]&&await k();let i=o.modelKeys[n];return i&&!i.tombstone?i.value?.key??``:``},async setModelKey(t,n,r=`account`,i=`default`){if(!e.modelKeys)throw Error(`Device model-key storage is unavailable`);await v();let a=J(t,i);await e.modelKeys.set(t,n,r,i),r===`device`?p[a]=y():(u[a]=y(),delete p[a]),await _(),e.enabled()&&await k()},async removeModelKey(t,n=`default`){await v();let r=J(t,n);await e.modelKeys?.remove(t,n),p[r]=y(),await _(),e.enabled()&&await k()},async importModelKeys(t){if(e.modelKeys){await v();for(let n of t){let t=n.label??`default`,r=J(n.provider,t);await e.modelKeys.set(n.provider,n.key,`account`,t),u[r]=y(),delete p[r]}await _(),e.enabled()&&await k()}},async oauthCredentialEntries(){if(e.oauthRecoveryEnabled?.()!==!0)return[];let t=await e.oauthCredentials?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.oauthCredentials))if(!t.tombstone&&t.value){let r=n.get(e),i=Math.max(Number(r?.refreshedAt)||0,Number(r?.updatedAt)||0);(!r||i<t.updatedAt)&&n.set(e,t.value)}return[...n.values()]},async importOAuthCredentials(t){if(!e.oauthCredentials||e.oauthRecoveryEnabled?.()!==!0)return;await v();let n=await e.oauthCredentials.entries();for(let r of t){let t=J(r.provider,r.label),i=Math.max(Number(r.refreshedAt)||0,Number(r.updatedAt)||0),a=n.find(e=>J(e.provider,e.label)===t),o=Math.max(Number(a?.refreshedAt)||0,Number(a?.updatedAt)||0,d[t]??0);a&&i<=o||(await e.oauthCredentials.set(r),d[t]=i||y(),delete m[t])}await _(),e.enabled()&&await k()},async removeOAuthCredential(t,n=`default`,r){await v();let i=J(t,n),a=Number(r)||y();a<=(d[i]??0)||(await e.oauthCredentials?.remove(t,n),m[i]=Math.max(m[i]??0,a),await _(),e.enabled()&&await k())}}}var ia=`bivy_local_token`,aa=15e3,oa=`This device isn't paired with this machine. Run 'bivy tailscale pair' there and open the link on this device.`,sa=class{origin;tokenStore;fetchImpl;WS;bootstrap;pairCode;deviceName;requireToken;handlers;authPending=Promise.resolve();ws=null;connected=!1;backoff=1e3;closedByUs=!1;reconnectTimer=null;constructor(e){this.origin=e.origin??``,this.tokenStore=e.tokenStore??(typeof globalThis<`u`?globalThis.sessionStorage:void 0),this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.bootstrap=e.bootstrap??``,this.pairCode=e.pairCode??``,this.deviceName=e.deviceName??`Paired device`,this.requireToken=e.requireToken??!1,this.handlers=e.handlers}token(){return this.tokenStore?.getItem(ia)||``}directHeaders(e){let t=this.token();return{"content-type":`application/json`,...t?{authorization:`Bearer ${t}`}:{},...e||{}}}async directApi(e,t={}){if(!e.startsWith(`/api/auth/`)&&(await this.authPending,this.requireToken&&!this.token()))throw Error(oa);let n=await this.fetchImpl(`${this.origin}${e}`,{...t,headers:{...this.directHeaders(),...t.headers||{}}}),r=await n.json().catch(()=>({}));if(!n.ok){let e=Error(r?.error||`Local request failed (${n.status})`);throw r&&typeof r==`object`&&Object.assign(e,r),e}return r}async bootstrapAuth(){if(this.pairCode){let e=this.pairCode;this.pairCode=``;try{let t=await this.directApi(`/api/auth/pair`,{method:`POST`,body:JSON.stringify({code:e,name:this.deviceName})});if(t?.token){this.tokenStore?.setItem(ia,t.token);return}}catch(e){this.handlers.onError?.(e instanceof Error?e.message:String(e))}}if(!(this.token()||this.requireToken))try{let e=await this.directApi(`/api/auth/bootstrap`,{method:`POST`,body:JSON.stringify({name:`Local Remote UI`,bootstrap:this.bootstrap})});e?.token&&this.tokenStore?.setItem(ia,e.token)}catch(e){console.warn(`local bootstrap failed`,e)}}notPaired(){this.connected=!1,this.setStatus(`offline`),this.handlers.onError?.(oa)}setStatus(e){this.handlers.onStatus(e)}emit(e){this.handlers.onEvent(e)}emitMerged(e,t,n){this.emit({...n||{},...t||{},type:e})}async connect(){if(this.closedByUs=!1,this.setStatus(`connecting`),this.authPending=this.bootstrapAuth(),await this.authPending,this.requireToken&&!this.token()){this.notPaired();return}let e=typeof location<`u`&&location.protocol===`https:`?`wss:`:`ws:`,t=typeof location<`u`?location.host:this.origin.replace(/^https?:\/\//,``),n=this.token(),r=`${e}//${t}/ws${n?`?access_token=${encodeURIComponent(n)}`:``}`,i=new this.WS(r);this.ws=i;let a=()=>i===this.ws;i.onopen=()=>{a()&&(this.connected=!0,this.backoff=1e3,this.setStatus(`online`),this.send({kind:`sessions.list`}),this.send({kind:`models.list`}),this.send({kind:`runtimes.list`}),this.send({kind:`terminal.list`}),this.send({kind:`terminal.multiplexers`}))},i.onmessage=e=>{if(a())try{this.emit(JSON.parse(String(e.data)))}catch{}},i.onclose=e=>{if(a()&&!this.closedByUs){if(this.requireToken&&e?.code===1008&&e.reason===`Unauthorized`){this.tokenStore?.setItem(ia,``),this.notPaired();return}this.connected=!1,this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.closedByUs||this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,aa)}},i.onerror=()=>{}}close(){if(this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){let e=this.ws;this.ws=null,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}async send(e){try{switch(e.kind){case`ping`:this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e));break;case`history`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.have==null?{}:{have:String(e.have)},...e.haveToken?{haveToken:String(e.haveToken)}:{}});this.emit(await this.directApi(`/api/session/history?${t}`));break}case`session.replay`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},afterSeq:String(e.afterSeq??0)});this.emit(await this.directApi(`/api/session/replay?${t}`));break}case`sessions.list`:this.emit({type:`sessions.list`,sessions:await this.directApi(`/api/sessions`)});break;case`session.open`:{let t=await this.directApi(`/api/sessions/open`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,path:e.path,agent:e.agent,runtimeId:e.runtimeId})});this.emit({type:`session.history`,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:t.messages||[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.new`:{let t=await this.directApi(`/api/session`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`session.history`,requestId:e.requestId,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/sessions/discover`);this.emit({type:`session.discover.result`,requestId:t,sessions:e?.sessions??[]})}catch(e){this.emit({type:`session.discover.error`,requestId:t,error:e?.message||String(e)})}break}case`apps.list`:case`apps.publish`:case`apps.offers`:case`apps.adopt`:case`apps.open`:case`apps.logs`:case`apps.showMe`:case`apps.mute`:case`apps.reviewMode`:case`apps.annotate`:case`apps.clearNotes`:case`apps.agentNotes`:case`apps.share`:case`apps.unshare`:case`apps.revoke`:case`apps.remove`:case`artifacts.list`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/${e.kind.replace(`.`,`/`)}`,{method:`POST`,body:JSON.stringify(e)});if(typeof n.error==`string`)throw Error(n.error);this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`session.presence.get`:case`session.presence.draft`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/session/presence/${e.kind.slice(17)}`,{method:`POST`,body:JSON.stringify(e)});this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`attachment.fetch`:{let t=String(e.requestId??``),n=String(e.hash??``);try{let e=await this.fetchImpl(`${this.origin}/api/attachment/${encodeURIComponent(n)}`,{headers:this.directHeaders()});if(!e.ok)throw Error(`Attachment fetch failed (${e.status})`);let r=e.headers.get(`content-type`)||`application/octet-stream`,i=new Uint8Array(await e.arrayBuffer()),a=``,o=32768;for(let e=0;e<i.length;e+=o)a+=String.fromCharCode(...i.subarray(e,e+o));this.emit({type:`attachment.data`,requestId:t,hash:n,mimeType:r,data:btoa(a)})}catch(e){this.emit({type:`attachment.error`,requestId:t,hash:n,error:e?.message||String(e)})}break}case`session.import`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/sessions/import`,{method:`POST`,body:JSON.stringify({runtimeId:e.runtimeId,ref:e.ref,acceptDisclosure:e.acceptDisclosure})});this.emit({type:`session.import.result`,requestId:t,sessionId:n.sessionId,runtimeId:n.runtimeId,mode:n.mode,seedPrompt:n.seedPrompt})}catch(e){let n=e;this.emit({type:`session.import.error`,requestId:t,error:String(n?.message??e),needsDisclosure:n?.needsDisclosure,disclosure:n?.disclosure})}break}case`session.delete`:await this.directApi(`/api/sessions/delete`,{method:`POST`,body:JSON.stringify({id:e.sessionId,path:e.path})});break;case`session.rename`:await this.directApi(`/api/sessions/rename`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name})});break;case`session.pr.refresh`:this.emitMerged(`session.pr_result`,await this.directApi(`/api/session/pr/refresh`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),{sessionId:String(e.sessionId??``)});break;case`sessions.pr.refresh_all`:this.emitMerged(`sessions.pr_refresh_result`,await this.directApi(`/api/sessions/pr/refresh`,{method:`POST`}));break;case`prompt`:await this.directApi(`/api/session/prompt`,{method:`POST`,body:JSON.stringify(e)});break;case`abort`:await this.directApi(`/api/session/abort`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});break;case`session.turn_attention.resolve`:await this.directApi(`/api/session/turn-attention`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,action:e.action})});break;case`session.limit_retry`:await this.directApi(`/api/session/limit-retry`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,enabled:e.enabled})});break;case`session.command.invoke`:await this.directApi(`/api/session/command`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name,args:e.args})});break;case`session.pause`:await this.directApi(`/api/session/pause`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.paused`,sessionId:String(e.sessionId??``)});break;case`session.resume`:await this.directApi(`/api/session/resume`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.resumed`,sessionId:String(e.sessionId??``)});break;case`session.checkpoints`:{let t=await this.directApi(`/api/session/checkpoints`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});this.emit({type:`session.checkpoints`,sessionId:String(e.sessionId??``),checkpoints:t?.checkpoints??[]});break}case`session.rewind`:await this.directApi(`/api/session/rewind`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,checkpointId:e.checkpointId})}),this.emit({type:`session.rewound`,sessionId:String(e.sessionId??``),checkpointId:String(e.checkpointId??``)});break;case`session.question.answer`:await this.directApi(`/api/session/question/answer`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,requestId:e.requestId,answers:e.answers,cancelled:e.cancelled})});break;case`models.list`:this.emitMerged(`models.list`,await this.directApi(`/api/models?${new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.runtimeId?{runtimeId:String(e.runtimeId)}:{}})}`));break;case`models.prefetch`:await this.directApi(`/api/models/prefetch`,{method:`POST`,body:JSON.stringify({runtimeIds:e.runtimeIds})});break;case`model.select`:await this.directApi(`/api/models/select`,{method:`POST`,body:JSON.stringify(e)});break;case`thinking.set_level`:await this.directApi(`/api/thinking/set-level`,{method:`POST`,body:JSON.stringify(e)});break;case`node.stats`:{let t=new URLSearchParams(e.sessionId?{sessionId:String(e.sessionId)}:{});this.emit({type:`node.stats`,stats:await this.directApi(`/api/node/stats?${t}`)});break}case`capabilities.get`:this.emit({type:`capabilities`,capabilities:await this.directApi(`/api/capabilities`)});break;case`runtimes.list`:this.emitMerged(`runtimes.list`,await this.directApi(`/api/runtimes`));break;case`runtime.select`:this.emitMerged(`runtime.updated`,await this.directApi(`/api/runtimes/select`,{method:`POST`,body:JSON.stringify({id:e.id})}));break;case`runtime.install`:this.emitMerged(`runtime.install.done`,await this.directApi(`/api/runtimes/install`,{method:`POST`,body:JSON.stringify({id:e.id})}),{id:String(e.id??``)});break;case`providers.list`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers`));break;case`provider.auth.get`:this.emitMerged(`provider.auth`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`));break;case`provider.apiKey`:{let t=String(e.requestId??``);try{this.emitMerged(`providers.list`,await this.directApi(`/api/auth/api-key`,{method:`POST`,body:JSON.stringify({provider:e.provider,key:e.key})})),this.emit({type:`provider.apiKey.ok`,requestId:t})}catch(e){this.emit({type:`provider.apiKey.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.remove`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}));break;case`credentials.list`:this.emitMerged(`credentials.records`,await this.directApi(`/api/auth/credentials`));break;case`credentials.native.preview`:case`credentials.native.import`:{let t=String(e.requestId??``),n=e.kind===`credentials.native.preview`?`native-preview`:`native-import`;try{let r=await this.directApi(`/api/auth/credentials/${n}`,{method:`POST`,body:JSON.stringify(e)});if(typeof r.error==`string`)throw Error(r.error);this.emit({...r,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`credentials.account.export`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials/account-export`,{method:`POST`,body:JSON.stringify({includeOAuth:e.includeOAuth===!0})});this.emit({type:`credentials.account.export`,requestId:t,...n})}catch(e){this.emit({type:`credentials.account.export.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.account.import`:{let t=String(e.requestId??``);try{await this.directApi(`/api/auth/credentials/account-import`,{method:`POST`,body:JSON.stringify({oauthEntries:e.oauthEntries})}),this.emit({type:`credentials.account.import.ok`,requestId:t})}catch(e){this.emit({type:`credentials.account.import.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials`,{method:`POST`,body:JSON.stringify(e)});this.emitMerged(`credentials.records`,n),this.emitMerged(`providers.list`,n),this.emit({type:`credential.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.remove`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}`,{method:`DELETE`});this.emitMerged(`credentials.records`,i),this.emitMerged(`providers.list`,i),this.emit({type:`credential.remove.ok`,requestId:t})}catch(e){this.emit({type:`credential.remove.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.sync.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/availability`,{method:`POST`,body:JSON.stringify({sync:e.sync})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.sync.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.sync.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.unattended.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/unattended`,{method:`POST`,body:JSON.stringify({unattended:e.unattended===!0})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.unattended.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.unattended.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.test`:{let t=String(e.requestId??``),n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`));try{let e=await this.directApi(`/api/auth/credentials/${n}/${r}/test`,{method:`POST`,body:`{}`});this.emitMerged(`credentials.records`,e),this.emit({type:`credential.test.result`,requestId:t,...e})}catch(n){this.emit({type:`credential.test.result`,requestId:t,provider:e.provider,label:e.label,ok:!1,at:Date.now(),reason:`network_error`,error:n instanceof Error?n.message:String(n)})}break}case`credentials.presets.get`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`));break;case`credentials.presets.setMapping`:{let t=String(e.requestId??``);try{this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`,{method:`POST`,body:JSON.stringify({preset:e.preset,provider:e.provider,label:e.label})})),this.emit({type:`credentials.presets.setMapping.ok`,requestId:t})}catch(e){this.emit({type:`credentials.presets.setMapping.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.presets.setActive`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments/active`,{method:`POST`,body:JSON.stringify({active:e.active})}));break;case`models.custom.list`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom`));break;case`models.custom.presets`:this.emitMerged(`models.custom.presets`,await this.directApi(`/api/models/catalog`));break;case`models.custom.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/models/discover`,{method:`POST`,body:`{}`});this.emit({type:`models.custom.discover.ok`,requestId:t,...e})}catch(e){this.emit({type:`models.custom.discover.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.verify`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/verify`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`models.custom.verify.ok`,requestId:t,...n})}catch(e){this.emit({type:`models.custom.verify.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.save`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/custom`,{method:`POST`,body:JSON.stringify(e.spec??e)});this.emitMerged(`models.custom.list`,n),this.emit({type:`models.custom.save.ok`,requestId:t,provider:n.provider})}catch(e){this.emit({type:`models.custom.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.remove`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom/${encodeURIComponent(String(e.id??e.provider??``))}`,{method:`DELETE`}));break;case`rulesets.list`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`));break;case`rulesets.save`:{let t=String(e.requestId??``);try{this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`,{method:`POST`,body:JSON.stringify(e)})),this.emit({type:`rulesets.save.ok`,requestId:t})}catch(e){this.emit({type:`rulesets.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`rulesets.remove`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets/${encodeURIComponent(String(e.name??``))}`,{method:`DELETE`}));break;case`activation.readiness`:this.emitMerged(`activation.readiness`,await this.directApi(`/api/activation/readiness`));break;case`repos.list`:this.emitMerged(`repos.list`,await this.directApi(`/api/repos`));break;case`branches.list`:this.emitMerged(`branches.list`,await this.directApi(`/api/repos/branches?repo=${encodeURIComponent(String(e.repo||``))}`));break;case`workspaces.list`:this.emitMerged(`workspaces.list`,await this.directApi(`/api/workspaces`));break;case`node.settings.get`:this.emit({type:`node.settings`,requestId:String(e.requestId??``),settings:await this.directApi(`/api/node/settings`)});break;case`node.settings.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/node/settings`,{method:`POST`,body:JSON.stringify(e.settings??e)});this.emit({type:`node.settings`,requestId:t,settings:n?.settings??n})}catch(e){this.emit({type:`node.settings.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.reset`:this.emitMerged(`provider.oauth.reset`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}),{provider:String(e.provider??``)});break;case`provider.oauth.start`:this.emitMerged(`provider.oauth.started`,await this.directApi(`/api/auth/oauth/start`,{method:`POST`,body:JSON.stringify({provider:e.provider,label:e.label})}),{provider:String(e.provider??``)});break;case`provider.oauth.open_on_node`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/open-on-node`,{method:`POST`,body:`{}`});this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,...n})}catch(e){this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,opened:!1,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.code`:await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/manual-code`,{method:`POST`,body:JSON.stringify({code:e.code})});break;case`github.app.manifest.start`:try{this.emitMerged(`github.app.manifest.ready`,await this.directApi(`/api/github/app/manifest/start`,{method:`POST`,body:JSON.stringify({origin:e.origin,org:e.org})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.manifest.code`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/manifest/complete`,{method:`POST`,body:JSON.stringify({code:e.code,state:e.state})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.connect-existing`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/connect-existing`,{method:`POST`,body:JSON.stringify({appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.disconnect`:await this.directApi(`/api/github/app/disconnect`,{method:`POST`,body:JSON.stringify({appId:e.appId})}),this.emit({type:`github.app.disconnected`,requestId:String(e.requestId??``),ok:!0});break;case`github.connect.start`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/start`,{method:`POST`}));break;case`github.connect.poll`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/poll`));break;case`approval`:await this.directApi(`/api/approvals/${encodeURIComponent(String(e.id))}/${e.approved?`approve`:`reject`}`,{method:`POST`,body:`{}`});break;case`stt.config.get`:this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`));break;case`stt.config.set`:{let t=String(e.requestId??``);try{this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`,{method:`POST`,body:JSON.stringify({provider:e.provider,setKey:e.setKey,removeKey:e.removeKey})})),this.emit({type:`stt.config.set.ok`,requestId:t})}catch(e){this.emit({type:`stt.config.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`transcribe`:this.emitMerged(`transcription`,await this.directApi(`/api/transcribe`,{method:`POST`,body:JSON.stringify({audio:e.audio,mimeType:e.mimeType,provider:e.provider,language:e.language})}),{requestId:String(e.requestId??``)});break;case`synthesize`:this.emitMerged(`speech.audio`,await this.directApi(`/api/speech`,{method:`POST`,body:JSON.stringify({text:e.text,voice:e.voice,instructions:e.instructions})}),{requestId:String(e.requestId??``)});break;case`node.update`:try{await this.directApi(`/api/node/update`,{method:`POST`,body:`{}`}),this.emit({type:`node.update.result`,ok:!0})}catch(e){this.emit({type:`node.update.result`,ok:!1,error:e?.message||String(e)})}break;default:/^(terminal|session\.fork)\./.test(String(e.kind||``))&&this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e))}}catch(e){this.handlers.onError?.(e?.message||String(e))}}},ca=8388608,la=class{deps;queue=[];queuedBytes=0;pending;timer;generation=0;constructor(e){this.deps=e}accept(e){if(e.type===`transfer.part`){this.part(e);return}if(this.pending||this.queue.length){if(this.queuedBytes+=new TextEncoder().encode(JSON.stringify(e)).length,this.queuedBytes>ca||this.queue.length>=4096){this.reset(),this.deps.fault(`Transcript delivery fell behind. Reconnecting to synchronize again.`);return}this.queue.push(e);return}this.deliver(e)}deliver(e){if(e.code!==`transfer_required`){this.deps.emit(e);return}let t=e.transfer;if(!t||!/^[a-f0-9]{48}$/.test(t.id)||!/^[a-f0-9]{64}$/.test(t.key)||!/^[a-f0-9]{24}$/.test(t.iv)||!Number.isSafeInteger(t.bytes)||t.bytes<=0||t.bytes>67108864||t.pageBytes!==393216){this.deps.emit({type:`session.error`,code:`delivery_invalid`,sessionId:e.sessionId,requestId:e.requestId,error:`Invalid large-response transfer. Update the app and retry.`});return}this.pending={offer:t,envelope:e,bytes:new Uint8Array(t.bytes),offset:0,requestId:``,retries:0},this.request()}request(){let e=this.pending;e&&(e.requestId=`transfer-${crypto.randomUUID()}`,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.pending===e&&(++e.retries<=2?this.request():this.fail(`Large-response delivery timed out. Retry to synchronize.`))},this.deps.timeoutMs??1e4),this.deps.send({kind:`transfer.read`,transferId:e.offer.id,offset:e.offset,requestId:e.requestId}).catch(()=>{this.pending===e&&this.fail(`Could not request the next response page. Retry to synchronize.`)}))}async part(e){let t=this.pending;if(t&&e.requestId===t.requestId&&e.transferId===t.offer.id&&e.offset===t.offset){if(clearTimeout(this.timer),typeof e.error==`string`){this.fail(e.error);return}try{if(typeof e.data!=`string`||e.data.length>524288)throw Error(`Invalid response page.`);let n=x(e.data);if(n.length!==Math.min(393216,t.offer.bytes-t.offset))throw Error(`Incomplete response page.`);if(t.bytes.set(n,t.offset),t.offset+=n.length,t.retries=0,t.offset<t.offer.bytes){this.request();return}t.requestId=``;let r=this.generation,i=e=>Uint8Array.from(e.match(/../g),e=>parseInt(e,16)),a=await crypto.subtle.importKey(`raw`,i(t.offer.key),`AES-GCM`,!1,[`decrypt`]),o;try{o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i(t.offer.iv)},a,t.bytes)}catch{throw Error(`Response integrity check failed.`)}if(r!==this.generation||this.pending!==t)return;let s=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(o));if(!s||typeof s.type!=`string`||s.code===`transfer_required`||s.type===`transfer.part`)throw Error(`Invalid response envelope.`);this.pending=void 0,this.deps.emit(s),this.drain()}catch(e){this.pending===t&&this.fail(`${e.message} Retry to synchronize.`)}}}fail(e){let t=this.pending?.envelope;this.reset(),this.deps.emit({type:`session.error`,code:`delivery_failed`,sessionId:t?.sessionId,requestId:t?.requestId,error:e}),this.deps.fault(e)}drain(){for(;!this.pending&&this.queue.length;){let e=this.queue.shift();this.queuedBytes-=new TextEncoder().encode(JSON.stringify(e)).length,this.deliver(e)}}reset(){clearTimeout(this.timer),this.pending=void 0,this.queue=[],this.queuedBytes=0,this.generation++}},ua=15e3,da=15e3,fa=4,pa=3;function ma(){return b(crypto.getRandomValues(new Uint8Array(12)))}function ha(e){return/device limit|another account|isn't authorized|not authorized|forbidden/i.test(e)}var ga=class{store;handlers;fetchImpl;WS;pairingOnly;ws=null;connected=!1;initialBackoff;backoff;closedByUs=!1;reconnectTimer=null;pairSent=!1;pairAttempts=0;connectFailures=0;hasReachedNode=!1;curKey=null;devicePromise=null;sendQueue=[];reassemble=k({onReject:e=>{this.handlers.onError?.(e),/limit/.test(e)?this.close():this.ws?.close()}});acceptFrame=ee();transfers;receiveChain=Promise.resolve();decryptBytes=0;constructor(e){this.store=e.store,this.pairingOnly=e.pairingOnly??!1,this.handlers=e.handlers,this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.initialBackoff=e.initialBackoffMs??1e3,this.backoff=this.initialBackoff,this.transfers=new la({send:e=>this.send(e),emit:e=>this.handlers.onEvent(e),fault:e=>{this.handlers.onError?.(e),this.ws?.close()}})}cpBase(){return(this.store.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}reportRemoteReconnect(){if(!this.store.s)return;let e=typeof navigator<`u`&&/Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);this.fetchImpl(`${this.cpBase()}/account/product-events`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({event:`remote_reconnect`,client:e?`mobile`:`desktop`})}).catch(()=>{})}setStatus(e){this.handlers.onStatus(e)}device(){return this.devicePromise||=Ui(this.store).catch(e=>{throw this.devicePromise=null,e}),this.devicePromise}async keyFor(e){let t=this.store.keys()[e];return t?E(C(t)):null}canConnect(){let e=this.store.cur;return e?!!(this.curKey||this.store.keys()[e]||this.store.s||this.store.nodePubs()[e]&&this.store.pairSecrets()[e]):!1}soloCreds(){let e=this.store.solo()[this.store.cur];return e&&e.room&&e.roomToken?e:null}async mintClientTicket(){let e=await this.fetchImpl(`${this.cpBase()}/client/relay-ticket`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})});if(!e.ok)throw Error(`ticket request failed: ${e.status}`);let t=await e.json();if(!t?.ticket)throw Error(`no ticket`);return{ticket:t.ticket,relayUrl:typeof t.relayUrl==`string`?t.relayUrl:null}}async connect(){if(this.closedByUs=!1,this.setStatus(`connecting`),this.curKey=await this.keyFor(this.store.cur),this.closedByUs)return;let e=this.soloCreds(),t=``,n=null;if(!e)try{({ticket:t,relayUrl:n}=await this.mintClientTicket())}catch(e){this.connectFailures+=1,this.connectFailures>=fa&&this.handlers.onError?.(e?.message||`ticket mint failed`),this.scheduleReconnect();return}if(this.closedByUs)return;this.pairSent=!1;let r=this.store.cur,i=(n||this.store.relay).replace(/\/$/,``),a=e?`${i}/client?room=${encodeURIComponent(e.room)}&roomToken=${encodeURIComponent(e.roomToken)}`:`${i}/client?ticket=${encodeURIComponent(t)}&nodeId=${encodeURIComponent(r)}`,o=new this.WS(a);this.ws=o;let s=()=>o===this.ws&&r===this.store.cur;o.onmessage=async e=>{if(!s())return;let t;try{t=JSON.parse(String(e.data))}catch{return}if(t.t===`ready`||t.t===`peer.online`){let e=o;this.hasReachedNode&&!e._productReconnectReported&&(e._productReconnectReported=!0,this.reportRemoteReconnect()),this.hasReachedNode=!0,this.connected=!0,this.backoff=this.initialBackoff,this.connectFailures=0,this.setStatus(this.curKey?`online`:`pairing`),await this.onLinkReady()}else if(t.t===`peer.offline`)this.setStatus(`reconnecting`);else if(t.t===`pair`&&typeof t.p==`string`)await this.handlePairFrame(t.p);else if(t.t===`error`)this.handlers.onError?.(t.error||`relay error`);else if(t.t===`run.updated`&&typeof t.id==`string`)this.handlers.onEvent({type:`run.updated`,runId:t.id,revision:typeof t.revision==`string`?t.revision:void 0});else if(t.t===`frame`&&typeof t.p==`string`){if(!this.curKey)return;let e=this.reassemble(t);if(e===null)return;if(this.decryptBytes+e.length>33554432){this.handlers.onError?.(`Response decoding fell behind. Reconnecting to synchronize.`),o.close();return}this.decryptBytes+=e.length;let n=this.curKey;this.receiveChain=this.receiveChain.then(async()=>{if(!s()||o.readyState!==1)return;let t=JSON.parse(await O(n,e));s()&&o.readyState===1&&this.acceptFrame(t)&&this.transfers.accept(t.data)}).catch(()=>{s()&&o.readyState===1&&(this.handlers.onError?.(`Could not decode the machine response. Reconnecting to synchronize.`),o.close())}).finally(()=>{this.decryptBytes-=e.length})}},o.onclose=()=>{s()&&!this.closedByUs&&(this.connected=!1,this.transfers.reset(),this.reassemble.reset(),this.scheduleReconnect())},o.onerror=()=>{}}scheduleReconnect(){this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.canConnect()&&!this.closedByUs&&this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,ua)}shouldResync(){let e=this.ws;if(!e)return!1;let t=Date.now();return e._resyncAt!==void 0&&t-e._resyncAt<da?!1:(e._resyncAt=t,!0)}async onLinkReady(){if(this.curKey){if(this.pairingOnly||(this.flush(),!this.shouldResync()))return;this.store.sessions(),await this.send({kind:`sessions.list`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}else{this.setStatus(`linking`);let e=this.store.cur;this.store.nodePubs()[e]&&this.store.pairSecrets()[e]?await this.sendPairHello():await this.sendAccountPair()}}async sendPairHello(){if(this.pairSent)return;let e=this.store.cur,t=this.store.nodePubs()[e],n=this.store.pairSecrets()[e];if(!t||!n)return;let r=await this.device(),i=await qi(n,r.pub);this.pairSent=!0,this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.hello`,devicePublicKeyB64:r.pub,proofB64:i,label:_a()})}))}async sendAccountPair(){if(this.pairSent||!this.store.s)return;let e=await this.device();this.pairSent=!0;try{let t=await this.fetchImpl(`${this.cpBase()}/client/pair-grant`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})}),n=await t.json().catch(()=>({}));if(!t.ok||!n?.grant)throw Error(`Could not create pairing grant`);this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.account`,sessionToken:n.grant,devicePublicKeyB64:e.pub,label:_a()})}))}catch(e){this.pairSent=!1,this.handlers.onError?.(e?.message||`Could not pair this device`),this.setStatus(`reconnecting`)}}async handlePairFrame(e){let t;try{t=JSON.parse(e)}catch{return}let n=this.store.cur,r=this.store.nodePubs()[n];!r&&typeof t.nodePublicKeyB64==`string`&&(this.store.addNodePub(n,t.nodePublicKeyB64),r=t.nodePublicKeyB64);let i=await this.device();if(t.k===`pair.welcome`&&typeof t.wrapped==`string`&&r&&!this.curKey)try{let e=x(await O(await Ki(i.priv,r,`pair`),t.wrapped));if(this.storeRoomKey(n,e),this.store.clearPairSecret(n),this.curKey=await this.keyFor(n),this.pairAttempts=0,this.setStatus(`online`),this.pairingOnly)return;this.flush(),await this.send({kind:`sessions.list`}),await this.send({kind:`history`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}catch{this.setStatus(`reconnecting`)}else if(t.k===`key.rotate`&&Array.isArray(t.deliveries)&&r){let e=await Ki(i.priv,r,`rotate`);for(let r of t.deliveries)try{this.storeRoomKey(n,x(await O(e,r.wrapped))),this.curKey=await this.keyFor(n);break}catch{}}else t.k===`pair.error`&&this.onPairRejected(typeof t.error==`string`?t.error:``)}onPairRejected(e){if(ha(e)){this.handlers.onError?.(e),this.close();return}if(this.pairAttempts+=1,this.pairAttempts>=pa){this.handlers.onError?.(e||`Couldn't link this device — the node rejected it. Make sure the node is online and you're signed in to the right account, then try again.`),this.close();return}this.handlers.onError?.(e?`${e} — retrying…`:`Device link was rejected — retrying…`),this.pairSent=!1;let t=this.ws;this.ws=null,this.connected=!1;try{t?.close()}catch{}this.scheduleReconnect()}storeRoomKey(e,t){this.store.addKey(e,S(t))}rawSend(e){this.connected&&this.ws?.readyState===1?this.ws.send(e):this.sendQueue.push(e)}flush(){for(;this.sendQueue.length&&this.ws?.readyState===1;){let e=this.sendQueue.shift();e!==void 0&&this.ws.send(e)}}async send(e){if(!this.curKey)return;let t={v:1,ts:Date.now(),nonce:ma(),data:e},n=await D(this.curKey,JSON.stringify(t));if(n.length>33554432){let t=`This request is too large to send. Reduce the attachments and retry.`;this.handlers.onError?.(t),this.handlers.onEvent({type:`session.error`,code:`delivery_too_large`,sessionId:typeof e.sessionId==`string`?e.sessionId:void 0,requestId:e.requestId,error:t});return}for(let e of ne(n,ma))this.rawSend(e)}close(){if(this.transfers.reset(),this.reassemble.reset(),this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){this.transfers.reset(),this.reassemble.reset();let e=this.ws;this.ws=null,this.connected=!1,this.pairSent=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}};function _a(){return globalThis.navigator?.platform||`Device`}var va=Object.freeze({repo:null,branch:null,sandbox:null,acknowledgeReducedProtections:!1,ephemeralConfig:null});function ya(e,t){switch(t.type){case`select-repository`:return e.repo===t.repo?{...e}:{...e,repo:t.repo,branch:null};case`select-branch`:return{...e,branch:t.branch};case`select-sandbox`:return{...e,sandbox:t.sandbox};case`acknowledge-reduced-protections`:return{...e,acknowledgeReducedProtections:t.acknowledged};case`select-ephemeral-config`:return{...e,ephemeralConfig:t.config};case`reset`:return{...va}}}var ba=512,xa=class{nextSeq=0;held=new Map;maxHeld;constructor(e={}){this.maxHeld=Math.max(1,e.maxHeld??ba)}baseline(e){let t=(Number.isFinite(e)?Math.max(0,Math.floor(e)):0)+1;t>this.nextSeq&&(this.nextSeq=t);for(let e of[...this.held.keys()])e<this.nextSeq&&this.held.delete(e)}accept(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{ready:[t]};let n=Math.floor(e);if(this.nextSeq===0)return this.nextSeq=n+1,{ready:[t]};if(n<this.nextSeq)return{ready:[]};if(n>this.nextSeq)return this.held.set(n,t),this.held.size>this.maxHeld?{ready:[],overflow:!0}:{ready:[],gapFrom:this.nextSeq-1};let r=[t];for(this.nextSeq+=1;this.held.has(this.nextSeq);)r.push(this.held.get(this.nextSeq)),this.held.delete(this.nextSeq),this.nextSeq+=1;return{ready:r}}reset(){this.nextSeq=0,this.held.clear()}get expected(){return this.nextSeq}get heldCount(){return this.held.size}};function Sa(e,t){if(t.type===`node.updated`)return typeof t.name!=`string`||!t.name||!e.currentNodeId?{handled:!0,value:e}:{handled:!0,value:{...e,nodes:e.nodes.map(n=>n.id===e.currentNodeId?{...n,name:t.name}:n)}};if(t.type===`node.update`){let n=typeof t.current==`string`?t.current:``,r=typeof t.latest==`string`?t.latest:``;return{handled:!0,value:n&&r?{...e,nodeUpdate:{current:n,latest:r}}:{...e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1}}}return t.type===`node.update.result`?t.ok===!1?{handled:!0,value:{...e,nodeUpdating:!1,nodeUpdateAcknowledged:!1},error:typeof t.error==`string`?t.error:`Couldn't start the update on this node.`}:{handled:!0,value:{...e,nodeUpdateAcknowledged:!0}}:{handled:!1,value:e}}function Ca(e,t){let n=String(t.sessionId||``);return t.type===`session.paused`?!n||e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:[...e.pausedSessionIds,n]}}:t.type===`session.resumed`?!n||!e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:e.pausedSessionIds.filter(e=>e!==n)}}:{handled:!1,value:e}}function wa(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.termId==`string`?t:void 0}function Ta(e,t,n){if(t.type===`terminal.list`){let n=Array.isArray(t.terminals)?t.terminals.map(wa).filter(e=>!!e):[];return{handled:!0,value:{...e,runTerminals:n}}}if(t.type===`terminal.created`){let n=wa(t.terminal);return n?{handled:!0,value:{...e,runTerminals:[n,...e.runTerminals.filter(e=>e.termId!==n.termId)]}}:{handled:!0,value:e}}if(t.type===`terminal.activity`){let r=String(t.termId||``);if(!r)return{handled:!0,value:e};let i=Number(t.at)||n;return{handled:!0,value:{...e,runTerminals:e.runTerminals.map(e=>e.termId===r?{...e,lastActivityAt:i}:e)}}}if(t.type===`terminal.closed`||t.type===`terminal.exit`){let n=String(t.termId||``);return n?{handled:!0,value:{...e,runTerminals:e.runTerminals.filter(e=>e.termId!==n)}}:{handled:!0,value:e}}if(t.type===`terminal.tui`){let n=String(t.sessionId||``);if(!n)return{handled:!0,value:e};let r=!!t.active;return r===e.tuiSessions.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,tuiSessions:r?[...e.tuiSessions,n]:e.tuiSessions.filter(e=>e!==n)}}}return{handled:!1,value:e}}function Ea(e){switch(e.type){case`repos.list`:return{handled:!0,catalogs:{repos:Array.isArray(e.repos)?e.repos:[],reposAuthed:e.authed!==!1,reposError:e.error||null,reposReason:e.reason===`gh-unauthed`||e.reason===`no-token`?e.reason:null,reposLoading:!1}};case`branches.list`:return{handled:!0,catalogs:{branches:Array.isArray(e.branches)?e.branches:[],branchesRepo:typeof e.repo==`string`&&e.repo?e.repo:null,branchesDefault:typeof e.defaultBranch==`string`?e.defaultBranch:null,branchesError:e.error||null,branchesLoading:!1}};case`credentials.records`:return{handled:!0,settings:{credentialRecords:Array.isArray(e.records)?e.records:[]}};case`credentials.presets`:return{handled:!0,settings:{credentialPresets:e.presets??{}}};case`models.custom.list`:return Array.isArray(e.providers)?{handled:!0,settings:{localModels:e.providers}}:{handled:!0};case`models.custom.presets`:return Array.isArray(e.presets)?{handled:!0,settings:{localModelPresets:e.presets}}:{handled:!0};case`rulesets.list`:return Array.isArray(e.rulesets)?{handled:!0,settings:{rulesets:e.rulesets}}:{handled:!0};case`stt.config`:return Array.isArray(e.providers)&&typeof e.provider==`string`?{handled:!0,settings:{sttConfig:{provider:e.provider,providers:e.providers}}}:{handled:!0};case`node.settings`:return e.settings&&typeof e.settings==`object`?{handled:!0,settings:{nodeSettings:e.settings}}:{handled:!0};default:return{handled:!1}}}function Da(e,t){if(t.type===`sessions.pr_refresh_result`)return{handled:!0,value:{...e,prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}}};let n=e.githubApp||{phase:`idle`};return t.type===`github.app.manifest.ready`?{handled:!0,value:{...e,githubApp:{...n,phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}}}:t.type===`github.app.manifest.done`?{handled:!0,value:{...e,githubApp:{...n,phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}}}:t.type===`github.app.manifest.error`?{handled:!0,value:{...e,githubApp:{...n,phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}}}:{handled:!1,value:e}}function Oa(e){return/^\/[a-zA-Z]/.test(e.trimStart())}function ka(e){return!!(e&&typeof e==`object`&&typeof e.name==`string`&&e.name.startsWith(`/`)&&e.name.length>=2)}function Aa(e){let t=e.trim();if(!Oa(t))return null;let n=/^\/(\S+)\s*([\s\S]*)$/.exec(t);if(!n||!n[1])return null;let r=(n[2]??``).trim();return{name:`/${n[1].toLowerCase()}`,args:r}}function ja(e,t=[]){let n=t.filter(ka),r=n.length>0,i=n.find(t=>t.name.toLowerCase()===e.name.toLowerCase());return i?{kind:`agent`,command:i,args:e.args}:{kind:`unknown`,name:e.name,hasCatalog:r}}function Ma(e,t=[]){let n=e.trimStart().toLowerCase();if(!n.startsWith(`/`)||/\s/.test(n))return[];let r=t.filter(ka);return n===`/`?r:r.filter(e=>e.name.toLowerCase().startsWith(n)||e.aliases?.some(e=>e.toLowerCase().startsWith(n)))}function Na(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!ka(r)||n.has(r.name))continue;n.add(r.name);let e={name:r.name};typeof r.description==`string`&&r.description&&(e.description=r.description),(r.mode===`protocol`||r.mode===`prompt`)&&(e.mode=r.mode),t.push(e)}return t}function Pa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].name!==t[n].name||e[n].description!==t[n].description||e[n].mode!==t[n].mode)return!1;return!0}function Fa(e,t){let n=[];if(Array.isArray(e))for(let t of e){let e=typeof t?.url==`string`?t.url:``;if(!e)continue;let r=t?.state===`merged`||t?.state===`closed`?t.state:`open`;n.push({url:e,state:r,number:typeof t?.number==`number`?t.number:void 0,title:typeof t?.title==`string`?t.title:void 0})}return n.length===0&&typeof t==`string`&&t&&n.push({url:t,state:`open`}),n}function Ia(e){if(e&&e.length!==0)return e.find(e=>e.state===`open`)??e[0]}var La=[`read-only`,`workspace-write`,`danger-full-access`];function Ra(e){let t=String(e??``).trim().toLowerCase().replace(/_/g,`-`);return La.includes(t)?t:void 0}function za(e){let t=String(e??``).trim().toLowerCase();return[`never`,`risky`,`always`,`autonomous`].includes(t)?t:void 0}function Ba(e){let t=String(e??``).trim().toLowerCase();return[`trusted_workstation`,`isolated_customer_cloud`,`restricted`].includes(t)?t:void 0}var Va=[`guaranteed`,`degraded`,`unavailable`];function Ha(e){return!!e&&typeof e==`object`&&Va.includes(e.state)}function Ua(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion===`session-contract.v1`&&typeof t.resolvedAt==`string`&&typeof t.preview==`boolean`&&t.agent&&typeof t.agent==`object`&&typeof t.agent.id==`string`&&Ha(t.executionMode)&&Ha(t.auth)&&Ha(t.resume)&&Ha(t.toolInterception)&&Ha(t.sandbox)&&Array.isArray(t.degradedReasons)&&typeof t.requiresAcknowledgement==`boolean`)return t}function Wa(e){return typeof e==`string`&&e.startsWith(`repo:`)?e.slice(5):null}function Ga(e){return typeof e==`string`&&(e.startsWith(`issue:`)||e.startsWith(`queue:`))}function Ka(e){if(typeof e!=`string`||!e.startsWith(`issue:`))return null;let t=e.slice(6),n=t.lastIndexOf(`#`);if(n===-1)return null;let r=t.slice(0,n),i=Number(t.slice(n+1));return!r||!Number.isFinite(i)?null:{repo:r,issueNumber:i}}function qa(e){let t=e?.source,n=Wa(t),r=e?.githubIssueUrl||null;!r&&typeof t==`string`&&t.startsWith(`github:issue`)&&(r=t.split(`:`).slice(1).join(`:`)||null);let i=Fa(e?.prs,e?.prUrl);return{issueUrl:r,prUrl:(Ia(i)?.state===`open`?Ia(i)?.url:null)??e?.prUrl??null,branch:e?.branch||null,repo:n,prs:i}}function Ja(e){return qa({source:e.source,branch:e.branch,prUrl:e.prUrl,prs:e.prs})}function Ya(e){if(!e||typeof e!=`object`)return null;let t=typeof e.costUsd==`number`,n=e.tokens&&typeof e.tokens.total==`number`,r=e.plan&&Array.isArray(e.plan.windows)&&e.plan.windows.length;return!t&&!n&&!r?null:e}function Xa(e){if(!e||typeof e!=`object`)return null;let t=e.memory?.node&&typeof e.memory.node.total==`number`,n=e.cpu?.node&&typeof e.cpu.node.usedPct==`number`,r=e.storage?.node&&typeof e.storage.node.total==`number`;return!t&&!n&&!r?null:e}function Za(e){return!e||typeof e!=`object`||!e.os||typeof e.os.platform!=`string`||typeof e.generatedAt!=`string`?null:e}function Qa(e){if(!Array.isArray(e)||!e.length)return null;for(let t of e){if(typeof t?.question!=`string`||typeof t?.header!=`string`||!Array.isArray(t.options)||t.options.length===1)return null;for(let e of t.options)if(typeof e?.label!=`string`)return null}return e}function $a(e,t=[]){if(!Array.isArray(e))return[];let n=new Map(t.map(e=>[e.sessionId,e])),r=new Map;for(let t of e){let e=String(t?.sessionId||t?.id||``);if(!e||r.has(e))continue;let i=n.get(e),a=eo(t?.sessionState);r.set(e,{sessionId:e,path:t?.path||t?.sessionFile||void 0,workspace:t?.workspace||t?.bivySession?.workspace||void 0,worktree:t?.worktree||t?.bivySession?.worktree||t?.bivySession?.workspaceContext?.worktree||void 0,name:String(t?.name||`Untitled session`),source:t?.source,bivyCreated:t?.bivyCreated===!0,forkedFrom:t?.forkedFrom||void 0,delegatedFrom:t?.delegatedFrom&&typeof t.delegatedFrom.sessionId==`string`?t.delegatedFrom:void 0,nodeId:t?.nodeId||void 0,runtimeId:t?.runtimeId,agentName:t?.agentName,updatedAt:t?.updatedAt||t?.modified,needsAction:a?.agent===`awaiting-input`||!!t?.needsAction,status:no(t?.status,!!t?.needsAction,!!t?.isStreaming,a),sessionState:a,branch:t?.branch||void 0,rebuildable:t?.rebuildable?!0:void 0,sandbox:Ra(t?.sandbox??t?.bivySession?.sandbox),approvalMode:za(t?.approvalMode??t?.bivySession?.approvalMode),ephemeral:(t?.ephemeral??t?.bivySession?.ephemeral)===!0||void 0,executionProfile:Ba(t?.executionProfile??t?.bivySession?.executionProfile),contract:Ua(t?.contract??t?.bivySession?.contract),auditHealth:t?.auditHealth??t?.bivySession?.auditHealth,eventLogHealth:t?.eventLogHealth??t?.bivySession?.eventLogHealth,prUrl:t?.prUrl||void 0,prs:Fa(t?.prs,t?.prUrl),attention:Array.isArray(t?.attention)?t.attention:i?.attention,lastSeenAt:i?.lastSeenAt,finishedAt:i?.finishedAt,failedAt:i?.failedAt,launchProgress:i?.launchProgress})}return[...r.values()]}function eo(e){if(!e||typeof e!=`object`)return;let t=e;if((t.transport===`reachable`||t.transport===`unreachable`)&&(t.process===`alive`||t.process===`exited`||t.process===`none`)&&(t.agent===`idle`||t.agent===`working`||t.agent===`waiting`||t.agent===`awaiting-input`)&&(t.workspace===`clean`||t.workspace===`dirty`||t.workspace===`checkpointing`)&&(t.displayStatus===`idle`||t.displayStatus===`working`||t.displayStatus===`needs_attention`||t.displayStatus===`failed`))return t}function to(e){return e?.displayStatus===`needs_attention`?`needs_action`:e?.displayStatus}function no(e,t,n,r){return e===`saved`?`saved`:to(r)||(t||e===`needs_action`?`needs_action`:e===`working`||n?`working`:e===`failed`?`failed`:`idle`)}function ro(e){return Array.isArray(e)?e.map(e=>({id:String(e?.id||e?.model||``),label:e?.label||e?.name,...e})):[]}function io(e){let t=Array.isArray(e?.availableThinkingLevels)&&e.availableThinkingLevels.length?e.availableThinkingLevels.map(String):[`off`];return{supportsThinking:!!e?.supportsThinking,thinkingLevel:String(e?.thinkingLevel||`off`),availableThinkingLevels:t}}function ao(e,t){return!e||!t?!1:e.id===t.id&&e.provider===t.provider}function oo(e){return e?String(e.displayName||e.name||e.id||``):``}function so(e){return Qa(e)??void 0}function co(e,t){return e.approvals.some(e=>e.sessionId===t)||e.questions.some(e=>e.sessionId===t)||e.turnAttentions.some(e=>e.sessionId===t)}function lo(e,t,n){let r=t;switch(t.type){case`approval.created`:{let i=r.approval||t;return i?.id?{handled:!0,value:{...e,approvals:[...e.approvals.filter(e=>e.id!==i.id),i]},...i.sessionId?{row:{sessionId:i.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}:{handled:!0,value:e}}case`approval.resolved`:case`approval.removed`:{let t=String(r.id||r.approvalId||``),n=e.approvals.find(e=>e.id===t),i={...e,approvals:e.approvals.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.question`:{let t=String(r.requestId||``),i=so(r.questions);if(!t||!i)return{handled:!0,value:e};let a={id:t,...r.sessionId?{sessionId:String(r.sessionId)}:{},questions:i,createdAt:Number(r.createdAt)||n};return{handled:!0,value:{...e,questions:[...e.questions.filter(e=>e.id!==t),a]},...a.sessionId?{row:{sessionId:a.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}}case`session.question.resolved`:{let t=String(r.requestId||r.id||``),n=e.questions.find(e=>e.id===t),i={...e,questions:e.questions.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.turn_attention`:{let t=String(r.sessionId||``),i=r.trigger===`wedged`||r.trigger===`stalled`?r.trigger:void 0;if(!t||!i)return{handled:!0,value:e};let a={sessionId:t,trigger:i,idleMs:Math.max(0,Number(r.idleMs)||0),at:Number(r.at)||n,message:String(r.message||`This turn may be stuck. Stop it or keep waiting?`)};return{handled:!0,value:{...e,turnAttentions:[...e.turnAttentions.filter(e=>e.sessionId!==t),a]},row:{sessionId:t,status:`needs_action`,needsAction:!0,updatedAt:n}}}case`session.turn_attention.resolved`:{let t=String(r.sessionId||``);if(!t)return{handled:!0,value:e};let n={...e,turnAttentions:e.turnAttentions.filter(e=>e.sessionId!==t)};return{handled:!0,value:n,...co(n,t)?{}:{row:{sessionId:t,status:`working`,needsAction:!1}}}}default:return{handled:!1,value:e}}}function uo(e,t){return!!t&&t!==e}function fo(e){return(Array.isArray(e.actions)?e.actions:[e.action]).filter(e=>typeof e==`string`&&e.length>0)}function po(e,t,n){let r=t,i=String(r.sessionId||``);switch(t.type){case`session.state`:{let t=eo(r.state??r.sessionState);return!i||!t?{handled:!0,commands:[]}:{handled:!0,patch:i===e.activeSessionId?{working:t.agent===`working`,...t.agent===`working`?{}:{workingLabel:``}}:void 0,commands:[{kind:`row`,sessionId:i,patch:{sessionState:t,status:to(t),needsAction:t.displayStatus===`needs_attention`}}]}}case`session.renamed`:{let t=[];return r.name&&i&&t.push({kind:`rename`,sessionId:i,name:String(r.name)}),r.branch&&i&&t.push({kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}),{handled:!0,patch:!i||i===e.activeSessionId?{...r.name?{activeTitle:String(r.name)}:{},...r.branch?{github:{...e.github,branch:String(r.branch)}}:{}}:void 0,commands:t}}case`session.branch_renamed`:return{handled:!0,patch:(!i||i===e.activeSessionId)&&r.branch?{github:{...e.github,branch:String(r.branch)}}:void 0,commands:r.branch&&i?[{kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}]:[]};case`session.error`:case`session.errored`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=r.error&&typeof r.error==`object`?r.error:null,n=t?.kind===`model_auth`&&typeof t.provider==`string`,i=n?`No credentials for ${t.provider}`:je(String(r.error||r.errorMessage||`error`)),a={kind:`entry`,role:`error`,text:i,...n?{actions:[`connect-provider:${t.provider}`]}:{}};return{handled:!0,patch:{...String(r.code||``).startsWith(`delivery_`)?{}:{working:!1},opening:!1},commands:r.sessionId?[a]:[{kind:`global-error`,message:i}]}}case`session.closed`:return{handled:!0,patch:i===e.activeSessionId?{working:!1,workingLabel:``,opening:!1}:void 0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`saved`,needsAction:!1}}]:[]};case`session.failed`:return{handled:!0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`failed`,needsAction:!1,failedAt:Number(r.failedAt)||n,updatedAt:n}}]:[]};case`session.notice`:{if(!r.message||i&&i!==e.activeSessionId)return{handled:!0,commands:[]};let t=fo(r);return{handled:!0,commands:[{kind:`entry`,role:`system`,text:String(r.message),...t.length?{actions:t}:{}}]}}case`session.cloning`:return{handled:!0,patch:!i||i===e.activeSessionId?{working:!0,workingLabel:`Cloning ${r.repo||`repo`}…`}:void 0,commands:[]};case`session.auth_required`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.provider?[{kind:`model-auth`,provider:String(r.provider),reason:String(r.reason||``)}]:[]};case`session.usage`:return{handled:!0,patch:uo(e.activeSessionId,r.sessionId)?void 0:{usage:Ya(r.usage)},commands:[]};case`session.warning`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.warning?[{kind:`entry`,role:`system`,text:String(r.warning)}]:[]};case`session.changes`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=Array.isArray(r.changes)?r.changes:[];if(!t.length)return{handled:!0,patch:{changes:null},commands:[]};let i={before:r.before?String(r.before):void 0,after:String(r.after??``),files:t};return{handled:!0,patch:{changes:i,changesHistory:[...e.changesHistory,{...i,id:e.newChangeId??`change-${e.changesHistory.length+1}`,at:n}]},commands:[]}}case`session.rewound`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{changes:null},commands:[{kind:`entry`,role:`system`,text:`Rewound the workspace to an earlier checkpoint.`}]};case`session.checkpoints`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{checkpoints:Array.isArray(r.checkpoints)?r.checkpoints.map(e=>({id:String(e.id??``),label:String(e.label??`checkpoint`),createdAt:Number(e.createdAt??0)})).filter(e=>e.id):[]},commands:[]};default:return{handled:!1,commands:[]}}}var mo=e=>{let t=e;return!!t&&typeof t.hash==`string`&&/^[0-9a-f]{64}$/.test(t.hash)&&[t.size,t.width,t.height].every(e=>typeof e==`number`&&e>=0)};function ho(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&(t.trigger===`present`||t.trigger===`run`||t.trigger===`asked`||t.trigger===`notes`)&&typeof t.at==`number`&&(t.shot===void 0||mo(t.shot))&&(t.before===void 0||mo(t.before))&&(t.note===void 0||typeof t.note==`string`)&&(t.notes===void 0||Number.isInteger(t.notes)&&t.notes>=0)}var go=[`open`,`changed`,`gone`,`done`];function _o(e){if(!e||typeof e!=`object`)return!1;let t=e,n=(e,t)=>!!e&&typeof e==`object`&&t.every(t=>typeof e[t]==`number`);return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&typeof t.words==`string`&&typeof t.at==`number`&&(t.number===void 0||Number.isInteger(t.number)&&t.number>=1)&&Array.isArray(t.selectors)&&t.selectors.every(e=>typeof e==`string`)&&n(t.region,[`x`,`y`,`width`,`height`])&&n(t.viewport,[`width`,`height`])&&go.includes(t.state)&&(t.shot===void 0||mo(t.shot))}function vo(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.sessionId==`string`&&t.sessionId.length>0&&typeof t.name==`string`&&t.name.length<=100}var yo=[{id:`1h`,label:`1 hour`,ms:36e5},{id:`1d`,label:`1 day`,ms:864e5},{id:`7d`,label:`7 days`,ms:6048e5}],bo=[`here`,`subagents`,`new`],xo=e=>e===void 0||bo.includes(e);function So(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.title===void 0||typeof t.title==`string`)&&xo(t.run)}function Co(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.urgent===void 0||typeof t.urgent==`boolean`)}function wo(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.status==`string`&&typeof t.task==`string`&&[t.agent,t.machine,t.nodeId,t.group,t.childSessionId,t.answer,t.branch,t.prUrl,t.failure].every(e=>e===void 0||typeof e==`string`)}function To(e){return!!e&&e.type===`bivy_attachment`&&!!e.ref&&typeof e.ref.hash==`string`&&(e.ref.kind===`image`||e.ref.kind===`file`)}function Eo(e,t){return{kind:e.kind,name:e.name,size:e.size,mimeType:e.mimeType,hash:e.hash,...t?.createdAt===void 0?{}:{createdAt:t.createdAt},...t?.artifact?{artifact:!0}:{}}}var Do=0,Y=()=>`e${Date.now().toString(36)}-${(Do++).toString(36)}`;function Oo(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`text`||t===`output_text`||!t&&typeof e?.text==`string`}function ko(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`thinking`||t===`reasoning`}var Ao=/^\s*(?:\[Request interrupted by user|<(?:task-notification|system-reminder)[\s>/])/;function jo(e){return Ao.test(e)}function Mo(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.filter(Oo).map(e=>String(e?.text??e?.content??``)).join(`
|
|
19
|
+
`);return{files:[{guest_path:`/etc/bivy/relay.json`,raw_value:r(dr(e))},{guest_path:`/etc/bivy/start.sh`,raw_value:r(pr(e))}],init:{exec:[`/usr/bin/timeout`,`--kill-after=10s`,String(n),`/bin/bash`,`-c`,i]}}}async function Kr(e,t,n){if(!/^bivy-[a-z0-9-]+$/.test(n))return;let r=`https://api.machines.dev/v1/apps/${encodeURIComponent(n)}`,i=await z(e,{method:`GET`,url:`${r}/machines`,headers:B(t)});if(i.status===404)return;if(i.status>=300)throw Error(H(i,`check empty app`));if(!Array.isArray(i.body))throw Error(`Fly returned an invalid app inventory; keeping the app for cleanup retry`);if(i.body.length)return;let a=await z(e,{method:`DELETE`,url:r,headers:B(t)});if(a.status>=300&&a.status!==404)throw Error(H(a,`delete empty app`))}var qr={id:`fly`,name:`Fly.io`,currency:`USD`,regions:[{id:`iad`,label:`Ashburn, VA`},{id:`sjc`,label:`San Jose`},{id:`lhr`,label:`London`},{id:`fra`,label:`Frankfurt`},{id:`syd`,label:`Sydney`},{id:`nrt`,label:`Tokyo`}],defaultRegion:`iad`,sizes:[{id:`shared-1x-1gb`,label:`shared · 1 vCPU · 1 GB`,vcpus:1,memoryMiB:1024,architecture:`x86_64`,pricePerHour:.009,priceSource:`indicative`},{id:`shared-1x-2gb`,label:`shared · 1 vCPU · 2 GB`,vcpus:1,memoryMiB:2048,architecture:`x86_64`,pricePerHour:.0136,priceSource:`indicative`},{id:`shared-2x-4gb`,label:`shared · 2 vCPU · 4 GB`,vcpus:2,memoryMiB:4096,architecture:`x86_64`,pricePerHour:.0273,priceSource:`indicative`},{id:`shared-4x-8gb`,label:`shared · 4 vCPU · 8 GB`,vcpus:4,memoryMiB:8192,architecture:`x86_64`,pricePerHour:.0546,priceSource:`indicative`},{id:`shared-8x-16gb`,label:`shared · 8 vCPU · 16 GB`,vcpus:8,memoryMiB:16384,architecture:`x86_64`,pricePerHour:.1234,priceSource:`indicative`}],defaultSize:`shared-4x-8gb`,async validateToken({exec:e,token:t}){let n=await Ur(e,t),r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(n)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`validate credential`))},async provision({exec:e,token:t,config:n,bootstrap:r}){if(!r)throw Error(`Fly requires a structured Bivy bootstrap; cloud-init is not supported by Fly Machines.`);let i=`bivy-${n.slug}`,a=await Ur(e,t,n.org),o=Wr[n.size]||Wr[qr.defaultSize]||{cpus:1,memoryMb:2048,cpuKind:`shared`},s=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps`,headers:{...B(t),"content-type":`application/json`},body:{app_name:i,org_slug:a}}),c=s.status===422&&/name has already been taken/i.test(cr(s.body));if(s.status>=300&&s.status!==409&&!c)throw Error(H(s,`create app`));if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(r.status>=300)throw Error(H(r,`check existing launch`));if(!Array.isArray(r.body))throw Error(`Fly returned an invalid machine inventory; refusing to risk a duplicate launch`);let a=r.body.find(e=>e?.config?.metadata?.[`bivy-attempt`]===String(n.attemptId));if(r.status<300&&a?.id)return{id:String(a.id),provider:`fly`,app:i,name:i,region:a.region||n.region||`iad`,status:Vr(a.state),ip:null,createdAt:a.created_at||sr(),ttlMinutes:n.ttlMinutes};if(r.body.length)throw Error(`This Fly app already contains a machine from another launch. Reconnect or destroy it before rebuilding.`)}let l=Gr(r),u=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:{...B(t),"content-type":`application/json`},body:{region:n.region||`iad`,config:{image:n.image||`ghcr.io/bivysh/bivy-ephemeral-runner@sha256:30705bdda88425646b0c5dc19fc0e95cc4a026ca9c09a4f904c15b3a21e246ac`,auto_destroy:!r?.debugKeepMachine,restart:{policy:`no`},guest:{cpu_kind:o.cpuKind,cpus:Number(n.cpus)||o.cpus,memory_mb:Number(n.memoryMb)||o.memoryMb},metadata:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}},...l}}});if(u.status>=300)throw s.status<300&&u.status>=400&&u.status<500&&![408,409,429].includes(u.status)&&await Kr(e,t,i),Error(H(u,`create machine`));let d=u.body;if(!d||!d.id)throw Error(`Fly did not return a machine`);return{id:String(d.id),provider:`fly`,app:i,name:i,region:n.region||`iad`,status:Vr(d.state),ip:null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get machine`));return Vr(r.body?.state)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete machine`));await Kr(e,t,n.app||``)},async cleanupAttempt({exec:e,token:t,nodeId:n,attemptId:r,ownershipTag:i}){if(!/^eph-(?:[a-f0-9]{16}|[a-f0-9]{32})$/.test(n))return!1;let a=`bivy-${n.replace(/^eph-/,``)}`,o=`https://api.machines.dev/v1/apps/${encodeURIComponent(a)}`,s=await z(e,{method:`GET`,url:`${o}/machines`,headers:B(t)});if(s.status!==404){if(s.status>=300||!Array.isArray(s.body))throw Error(`Cannot verify canceled Fly launch inventory`);if(s.body.some(e=>e?.config?.metadata?.[`bivy-attempt`]!==r||e?.config?.metadata?.[`bivy-account`]!==i))return!1;for(let n of s.body){if(!n?.id)return!1;let r=await z(e,{method:`DELETE`,url:`${o}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)return!1}let n=await z(e,{method:`DELETE`,url:o,headers:B(t)});if(n.status>=300&&n.status!==404)return!1}return(await z(e,{method:`GET`,url:o,headers:B(t)})).status===404},async discover({exec:e,token:t,ownershipTag:n}){let r=await Ur(e,t),i=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(r)}`,headers:B(t)});if(i.status>=300)throw Error(H(i,`list apps`));let a=Array.isArray(i.body?.apps)?i.body.apps:Array.isArray(i.body)?i.body:[],o=[];for(let r of a){let i=String(r?.name||``);if(!i.startsWith(`bivy-`))continue;let a=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(a.status>=300)continue;let s=Array.isArray(a.body)?a.body:[];for(let e of s){let t=e?.config?.metadata||{};t.bivy===`ephemeral`&&t[`bivy-account`]===n&&o.push({id:String(e.id),provider:`fly`,app:i,name:i,region:e.region||``,status:Vr(e.state),ip:null,createdAt:typeof e.created_at==`string`?e.created_at:``,attemptId:typeof t[`bivy-attempt`]==`string`?t[`bivy-attempt`]:void 0})}}return o}};function Jr(e){return e===`running`?`running`:e===`off`||e===`stopping`?`stopped`:`starting`}function Yr(e){let t=Array.isArray(e?.prices)?e.prices:[];for(let e of t){let t=Number(e?.price_hourly?.gross);if(Number.isFinite(t)&&t>0)return t}}var Xr=new Map,Zr=new Map;function Qr(e,t){return lr(Xr,t,async()=>{let n=[],r=`https://api.hetzner.cloud/v1/server_types?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list server types`));let a=Array.isArray(i.body?.server_types)?i.body.server_types:[];for(let e of a){if(e.deprecation)continue;let t=e.architecture===`arm`?`Arm64`:`x86`;n.push({typeId:Number(e.id),id:String(e.name),label:`${e.name} · ${e.cores} vCPU · ${e.memory} GB · ${e.disk} GB (${t})`,cores:Number(e.cores)||0,memory:Number(e.memory)||0,disk:Number(e.disk)||0,architecture:e.architecture===`arm`?`arm64`:`x86_64`,pricePerHour:Yr(e)})}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/server_types?per_page=50&page=${o}`:null}return n})}function $r(e,t){return lr(Zr,t,async()=>{let n=new Map,r=`https://api.hetzner.cloud/v1/datacenters?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list datacenters`));let a=Array.isArray(i.body?.datacenters)?i.body.datacenters:[];for(let e of a){let t=e?.location?.name;if(!t)continue;let r=n.get(t)??new Set,i=Array.isArray(e?.server_types?.available)?e.server_types.available:[];for(let e of i)r.add(Number(e));n.set(t,r)}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/datacenters?per_page=50&page=${o}`:null}return n})}var ei={id:`hetzner`,name:`Hetzner Cloud`,currency:`EUR`,regions:[{id:`nbg1`,label:`Nuremberg`},{id:`fsn1`,label:`Falkenstein`},{id:`hel1`,label:`Helsinki`},{id:`ash`,label:`Ashburn, VA`},{id:`hil`,label:`Hillsboro, OR`}],defaultRegion:`nbg1`,sizes:[{id:`cpx11`,label:`cpx11 · 2 vCPU · 2 GB · 40 GB (AMD x86)`,vcpus:2,memoryMiB:2048,diskGiB:40,architecture:`x86_64`,pricePerHour:.007,priceSource:`indicative`},{id:`cpx21`,label:`cpx21 · 3 vCPU · 4 GB · 80 GB (AMD x86)`,vcpus:3,memoryMiB:4096,diskGiB:80,architecture:`x86_64`,pricePerHour:.013,priceSource:`indicative`},{id:`cpx31`,label:`cpx31 · 4 vCPU · 8 GB · 160 GB (AMD x86)`,vcpus:4,memoryMiB:8192,diskGiB:160,architecture:`x86_64`,pricePerHour:.026,priceSource:`indicative`},{id:`cpx41`,label:`cpx41 · 8 vCPU · 16 GB · 240 GB (AMD x86)`,vcpus:8,memoryMiB:16384,diskGiB:240,architecture:`x86_64`,pricePerHour:.049,priceSource:`indicative`},{id:`cpx51`,label:`cpx51 · 16 vCPU · 32 GB · 360 GB (AMD x86)`,vcpus:16,memoryMiB:32768,diskGiB:360,architecture:`x86_64`,pricePerHour:.099,priceSource:`indicative`},{id:`cax11`,label:`cax11 · 2 vCPU · 4 GB · 40 GB (Arm64)`,vcpus:2,memoryMiB:4096,diskGiB:40,architecture:`arm64`,pricePerHour:.006,priceSource:`indicative`},{id:`cax21`,label:`cax21 · 4 vCPU · 8 GB · 80 GB (Arm64)`,vcpus:4,memoryMiB:8192,diskGiB:80,architecture:`arm64`,pricePerHour:.012,priceSource:`indicative`},{id:`cax31`,label:`cax31 · 8 vCPU · 16 GB · 160 GB (Arm64)`,vcpus:8,memoryMiB:16384,diskGiB:160,architecture:`arm64`,pricePerHour:.024,priceSource:`indicative`},{id:`cax41`,label:`cax41 · 16 vCPU · 32 GB · 320 GB (Arm64)`,vcpus:16,memoryMiB:32768,diskGiB:320,architecture:`arm64`,pricePerHour:.048,priceSource:`indicative`}],defaultSize:`cpx31`,guestCanEnsureDeletion:!1,async validateToken({exec:e,token:t}){let n=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?per_page=1`,headers:B(t)});if(n.status>=300)throw Error(H(n,`validate credential`))},async listSizes({exec:e,token:t,region:n}){let r=await Qr(e,t),i=r;if(n)try{let a=(await $r(e,t)).get(n),o=a?r.filter(e=>a.has(e.typeId)):r;o.length&&(i=o)}catch{}return[...i].sort((e,t)=>e.cores-t.cores||e.memory-t.memory||e.id.localeCompare(t.id)).map(({id:e,label:t,cores:n,memory:r,disk:i,architecture:a,pricePerHour:o})=>({id:e,label:t,vcpus:n,memoryMiB:r*1024,diskGiB:i,architecture:a,pricePerHour:o,priceSource:o?`live`:void 0}))},async provision({exec:e,token:t,config:n,userData:r}){let i=`bivy-${n.slug}`;if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-attempt=${n.attemptId}`)}`,headers:B(t)});if(r.status<300&&Array.isArray(r.body?.servers)&&r.body.servers[0]){let e=r.body.servers[0];return{id:String(e.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}}}let a=await z(e,{method:`POST`,url:`https://api.hetzner.cloud/v1/servers`,headers:{...B(t),"content-type":`application/json`},body:{name:i,server_type:n.size||ei.defaultSize,image:n.image||`ubuntu-24.04`,location:n.region||`nbg1`,user_data:r,start_after_create:!0,labels:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}}}});if(a.status>=300)throw Error(H(a,`create server`));let o=a.body&&a.body.server;if(!o)throw Error(`Hetzner did not return a server`);return{id:String(o.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(o.status),ip:o.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get server`));return Jr(r.body?.server?.status)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete server`))},async discover({exec:e,token:t,ownershipTag:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-account=${n}`)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`list servers`));return(Array.isArray(r.body?.servers)?r.body.servers:[]).map(e=>({id:String(e.id),provider:`hetzner`,name:String(e.name||``),region:e.datacenter?.location?.name||``,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:typeof e.created==`string`?e.created:``,attemptId:typeof e.labels?.[`bivy-attempt`]==`string`?e.labels[`bivy-attempt`]:void 0}))}},ti=new Map([ei,qr,Br].map(e=>[e.id,e]));function ni(e){return ti.get(String(e||``).trim().toLowerCase())||null}async function ri(e,t,n,r){let i=ni(e);if(!i)throw Error(`Unknown provider: ${e}`);let a=String(t||``).trim();if(!a)throw Error(`${i.name} token is required`);if(!i.validateToken)throw Error(`${i.name} credential validation is not available`);await i.validateToken({exec:n,token:a,region:r||i.defaultRegion})}function ii(e,t,n,r=Date.now()){return rr(e,t,n,r)}function ai(e){return e.replace(/^eph-/,``)}function oi(e){let t=e.region||e.defaultRegion,n=e.size||e.defaultSize,r=ai(e.nodeId),i=String(e.name||``).trim();return{attemptId:e.attemptId,nodeId:e.nodeId,requestedAt:e.requestedAt,provider:e.provider,region:t,size:n,providerConfig:{slug:r,region:t,size:n,image:e.image,ttlMinutes:e.ttlMinutes,attemptId:e.attemptId,ownershipTag:e.ownershipTag},machineFacts:{...i?{name:i}:{},...e.setupId?{setupId:e.setupId}:{},...e.repo?{repo:e.repo}:{},...e.teardownOnAgentFinish?{teardownOnAgentFinish:!0}:{},...e.workItemId?{workItemId:e.workItemId}:{},...e.purpose?{purpose:e.purpose}:{}}}}function si(e,t,n){return{...e,...t.machineFacts,attemptId:t.attemptId,nodeId:t.nodeId,size:t.size,milestones:{...e.milestones??{},requestedAt:t.requestedAt,providerAcceptedAt:n}}}function ci(e){let t=e.nodeId.replace(/^eph-/,``);return{bootstrap:{relayUrl:e.relayUrl,controlPlaneUrl:e.controlPlaneUrl,enrollmentToken:e.enrollmentToken,e2eKeyB64:e.roomKeyB64,ttlMinutes:e.ttlMinutes,repo:e.repo,hostedTasks:e.hostedTasks,hostedCredentialCustody:e.hostedCredentialCustody,hostedCredentialPublisher:e.hostedCredentialPublisher,nodeLabel:e.hostedTasks?t:void 0,githubToken:e.githubToken,hostedMint:e.hostedMint,provider:e.provider,teardownOnAgentFinish:e.teardownOnAgentFinish,debugKeepMachine:e.debugKeepMachine,restoreSessionId:e.restoreSessionId}}}var li=[{id:`fly`,name:`Fly.io`,computeClass:`byo-cloud`,tokenLabel:`Fly.io access token`,blurb:`Bivy creates a temporary Fly Machine, runs the session, then destroys it.`,steps:[`Open your Fly.io access tokens and sign in.`,`Click Create token — use a short-lived/deploy token if your account offers one.`,`Copy the token and paste it below. Revoke it after the session if you like.`],links:[{label:`Create a Fly.io token`,url:`https://fly.io/user/personal_access_tokens`},{label:`Fly Machines docs`,url:`https://fly.io/docs/machines/`}]},{id:`hetzner`,name:`Hetzner Cloud`,computeClass:`byo-cloud`,tokenLabel:`Hetzner Cloud API token`,blurb:`Bivy manages Hetzner servers from start to deletion so billing always stops, even when your devices are offline.`,steps:[`Open the Hetzner Cloud Console and select or create a project for Bivy's runners.`,`Go to Security → API Tokens and click Generate API token.`,`Choose Read & Write, then copy the token and paste it below.`],links:[{label:`Hetzner Cloud Console`,url:`https://console.hetzner.cloud/projects`},{label:`API token docs`,url:`https://docs.hetzner.com/cloud/api/getting-started/generating-api-token/`}],hostedOnly:!0},{id:`aws`,name:`AWS EC2`,computeClass:`byo-cloud`,tokenLabel:`Access key — paste as accessKeyId:secretAccessKey`,blurb:`Bivy launches a temporary EC2 instance, runs the session, then terminates it.`,steps:[`Create (or reuse) an IAM user scoped to a minimal EC2 policy — see the Bivy docs link below for a copy-pasteable policy.`,`On that user, open Security credentials → Access keys → Create access key.`,`Paste both values below as accessKeyId:secretAccessKey (append :sessionToken if you're using temporary STS credentials).`],links:[{label:`IAM access keys`,url:`https://console.aws.amazon.com/iam/home#/security_credentials`},{label:`EC2 console`,url:`https://console.aws.amazon.com/ec2/home`},{label:`Minimal IAM policy (Bivy docs)`,url:`https://github.com/bivysh/bivy/blob/main/docs/ephemeral-sessions.md#aws-ec2`}]}];function G(e){let t=String(e||``).trim().toLowerCase();return li.find(e=>e.id===t)||null}function ui(e){return{id:e.machineId||e.nodeId,provider:e.provider,name:e.nodeId,region:e.region||``,status:`gone`,ip:null,createdAt:``,ttlMinutes:e.ttlMinutes,app:e.app,nodeId:e.nodeId,setupId:e.setupId,repo:e.repo,computeSource:e.computeSource}}function di(e){let t=e.ephemeral;return!t?.provider||!t.machineId?null:{id:t.machineId,provider:t.provider,name:e.name||t.machineId,region:t.region||``,status:`stopped`,ip:null,createdAt:``,app:t.app,nodeId:e.id}}function fi(){try{return new Date().toISOString()}catch{return``}}function pi(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function mi(){let e=new Map;return{async getAll(){return[...e.values()].map(e=>({...e}))},async put(t,n){e.set(t,{...n})},async delete(t){e.delete(t)}}}function hi(e,t,n,r){function i(){return new Promise((i,a)=>{let o=e.open(t,1);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(n)||o.result.createObjectStore(n,{keyPath:r})},o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)})}function a(e,t){return e.transaction(n,t).objectStore(n)}function o(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}return{async getAll(){let e=await i();try{return await o(a(e,`readonly`).getAll())||[]}finally{e.close()}},async put(e,t){let n=await i();try{await o(a(n,`readwrite`).put(t))}finally{n.close()}},async delete(e){let t=await i();try{await o(a(t,`readwrite`).delete(e))}finally{t.close()}}}}function K(e,t){try{let n=globalThis.indexedDB;if(n)return hi(n,e===`provider-keys`?`bivy-ephemeral`:`bivy-ephemeral-${e}`,e,t)}catch{}return mi()}function gi(e=K(`provider-keys`,`provider`)){return{async list(){let t;try{t=await e.getAll()}catch{t=[]}let n=new Map(t.map(e=>[e.provider,e]));return li.map(e=>{let t=n.get(e.id);return{id:e.id,name:e.name,configured:!!(t&&t.token),updatedAt:t?t.updatedAt:null}})},async getToken(t){let n=G(t);if(!n)return``;let r;try{r=await e.getAll()}catch{return``}let i=r.find(e=>e.provider===n.id);return i&&i.token?i.token:``},async setToken(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n||``).trim();if(!i)throw Error(`API token cannot be empty`);await e.put(r.id,{provider:r.id,token:i,updatedAt:fi()})},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function _i(e=K(`model-oauth`,`id`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>t(e||`default`)||`default`,r=(e,t)=>`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async entries(){return(await i()).filter(e=>e?.provider&&e?.refresh).map(e=>({provider:t(e.provider),label:n(e.label),access:String(e.access||``),refresh:String(e.refresh),expires:Number(e.expires)||0,...Number.isFinite(Number(e.refreshedAt))?{refreshedAt:Number(e.refreshedAt)}:{},...Number.isFinite(Number(e.updatedAt))?{updatedAt:Number(e.updatedAt)}:{}}))},async set(i){let a=t(i.provider),o=n(i.label);if(!a||!String(i.refresh||``).trim())throw Error(`A provider and refresh token are required`);await e.put(r(a,o),{...i,id:r(a,o),provider:a,label:o})},async remove(i,a=`default`){await e.delete(r(t(i),n(a)))}}}function vi(e=K(`model-keys`,`provider`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>String(e||`default`).trim().toLowerCase()||`default`,r=(e,t)=>t==="default"?e:`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async list(){return(await i()).filter(e=>e&&e.provider).map(e=>({provider:String(e.provider),label:n(e.label),configured:!!e.key,updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`})).sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async entries(){return(await i()).filter(e=>e&&e.provider&&e.key).map(e=>({provider:String(e.provider),label:n(e.label),key:String(e.key),updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`}))},async get(e,r=`default`){let a=t(e),o=n(r);if(!a)return``;let s=(await i()).find(e=>e.provider===a&&n(e.label)===o);return s&&s.key?s.key:``},async set(i,a,o=`account`,s=`default`){let c=t(i),l=n(s);if(!c)throw Error(`Provider is required`);let u=String(a||``).trim();if(!u)throw Error(`API key cannot be empty`);if(o!==`account`&&o!==`device`)throw Error(`Credential scope must be account or device`);await e.put(r(c,l),{provider:c,label:l,key:u,scope:o,updatedAt:fi()})},async remove(i,a=`default`){let o=t(i);o&&await e.delete(r(o,n(a)))}}}var yi=`github-task-token`;function bi(e=K(`github-task-token`,`id`)){return{async get(){let t;try{t=await e.getAll()}catch{return``}let n=t.find(e=>e.id===yi);return n&&n.token?n.token:``},async set(t){let n=String(t||``).trim();if(!n)throw Error(`GitHub token cannot be empty`);await e.put(yi,{id:yi,token:n,updatedAt:fi()})},async remove(){await e.delete(yi)}}}var xi={region:null,size:null,ttlMinutes:null,repo:null,teardownOnAgentFinish:!1};function Si(e=K(`provider-prefs`,`provider`)){let t=async t=>{let n=G(t);if(!n)return{...xi};let r;try{r=await e.getAll()}catch{return{...xi}}let i=r.find(e=>e.provider===n.id);return i?{region:i.region??null,size:i.size??null,ttlMinutes:typeof i.ttlMinutes==`number`?i.ttlMinutes:null,repo:i.repo??null,teardownOnAgentFinish:i.teardownOnAgentFinish===!0}:{...xi}};return{get:t,async set(n,r){let i=G(n);if(!i)throw Error(`Unknown ephemeral provider: ${n}`);let a={...await t(i.id),...r};return await e.put(i.id,{provider:i.id,...a,updatedAt:fi()}),a},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function Ci(){try{return`setup-`+pi(8)}catch{return`setup-${Math.random().toString(16).slice(2)}`}}function wi(e=K(`setups`,`id`)){let t=async()=>{try{return(await e.getAll()).filter(e=>e&&e.id&&G(e.provider)).sort((e,t)=>String(e.name).localeCompare(String(t.name)))}catch{return[]}};return{async list(e){let n=await t();if(!e)return n;let r=G(e);return r?n.filter(e=>e.provider===r.id):[]},async get(e){return(await t()).find(t=>t.id===e)??null},async create(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n.name||``).trim();if(!i)throw Error(`Setup name is required`);let a=fi(),o={id:Ci(),provider:r.id,name:i,...xi,region:n.region??null,size:n.size??null,ttlMinutes:n.ttlMinutes??null,repo:n.repo??null,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,createdAt:a,updatedAt:a};return await e.put(o.id,o),o},async update(n,r){let i=(await t()).find(e=>e.id===n);if(!i)throw Error(`Ephemeral setup not found`);let a={...i,...r,id:i.id,provider:i.provider,updatedAt:fi()};if(a.name=String(a.name||``).trim(),!a.name)throw Error(`Setup name is required`);return await e.put(n,a),a},async remove(t){await e.delete(t)}}}function Ti(e=K(`pending-launches`,`id`)){return{async list(){try{return(await e.getAll()).filter(e=>e&&e.id&&e.config&&e.prompt).sort((e,t)=>String(e.createdAt).localeCompare(String(t.createdAt)))}catch{return[]}},async put(t){let{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u}=t;await e.put(n,{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u})},async remove(t){await e.delete(t)}}}function Ei(e=K(`machines`,`id`)){return{async list(){try{return(await e.getAll()).sort((e,t)=>String(t.createdAt).localeCompare(String(e.createdAt)))}catch{return[]}},async add(t){if(!t||!t.id)throw Error(`Machine record needs an id`);return await e.put(t.id,t),t},async update(t,n){let r=(await e.getAll().catch(()=>[])).find(e=>e.id===t);if(!r)return null;let i={...r,...n};return await e.put(t,i),i},async remove(t){await e.delete(t)}}}function Di(){try{return new Date().toISOString()}catch{return``}}function Oi(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}function ki(e,t=fetch){return async n=>{let r=await t(`${Oi(e)}/api/ephemeral/exec`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.s}`},body:JSON.stringify(n)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`exec relay failed (${r.status})`);return{status:i.status??r.status,body:i.body}}}function Ai(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function ji(e,t,n){let r=ni(e);if(!r)return[];if(!r.listSizes)return r.sizes;let i=await t.keys.getToken(e).catch(()=>``);if(!i)return r.sizes;try{let e=await r.listSizes({exec:t.exec,token:i,region:n});return e.length?e:r.sizes}catch{return r.sizes}}async function Mi(e,t){if(e.computeSource===`managed`&&!e.externalTeardownGuaranteed)throw Error(`Bivy hosted machines must be launched by the control plane, not with a device-held cloud token.`);if(t.enrollment?.token&&!e.reuseNodeId)throw Error(`Saved enrollment requires the original node identity`);let n=Di(),r=t.fetchImpl??fetch,i=ni(e.provider);if(!i)throw Error(`Unknown provider: ${e.provider}`);let a=t=>{try{e.onProgress?.(t)}catch{}};a(`Preparing ${i.name} launch…`);let o=await t.keys.getToken(e.provider);if(!o)throw Error(`Add a ${i.name} token first.`);if(i.guestCanEnsureDeletion===!1&&!e.externalTeardownGuaranteed)throw Error(`${i.name} requires hosted provisioning: powering off its guest does not delete the billable server, so a device-only launch is unsafe.`);let s=e.attemptId||Ai(16),c=e.reuseNodeId||`eph-`+Ai(8);await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`requested`});let l=JSON.stringify({nodeId:c,name:e.name||`Ephemeral ${i.name}`});a(`Enrolling a secure Bivy node…`);let u=async()=>{let e=await r(`${Oi(t.store)}/nodes/enroll`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${t.store.s}`},body:l});return{res:e,data:await e.json().catch(()=>({}))}},d=t.enrollment?.token;if(!d){let{res:t,data:n}=await u();if(!t.ok||typeof n?.enrollmentToken!=`string`||!n.enrollmentToken){let t=n?.error||`Could not enroll the machine`;throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:t}),Error(t)}d=n.enrollmentToken}await t.enrollment?.persist(c,d),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`enrolled`}),a(`Node enrolled. Building its secure bootstrap…`);let f=e.reuseRoomKeyB64?C(e.reuseRoomKeyB64):crypto.getRandomValues(new Uint8Array(32));t.store.addKey(c,S(f)),await t.persistRoomKey?.(c,S(f));let p=oi({...e,attemptId:s,nodeId:c,requestedAt:n,defaultRegion:i.defaultRegion,defaultSize:i.defaultSize}),m=ci({...e,provider:p.provider,nodeId:p.nodeId,enrollmentToken:d,roomKeyB64:b(f),relayUrl:t.store.relay,controlPlaneUrl:Oi(t.store)}),h=hr(m.bootstrap);a(`Creating the machine in ${p.region} (${p.size})…`);let g;try{g=await i.provision({exec:t.exec,token:o,userData:h,bootstrap:m.bootstrap,config:p.providerConfig})}catch(t){throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:String(t?.message||t).slice(0,500)}),t}let _={...g,...p.machineFacts,attemptId:s};return await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`provider-accepted`,machine:_}),a(`Machine created. Starting Bivy and connecting securely…`),g=si(_,p,Di()),await t.machines.add(g),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`tracked`,machine:g}),g}async function Ni(e,t){let n=t.fetchImpl??fetch,r=ni(e.provider);if(r){let n=await t.keys.getToken(e.provider);if(!n)throw Error(`Add the ${r.name} token on this device to destroy this machine.`);try{await r.destroy({exec:t.exec,token:n,machine:e})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Couldn't destroy this machine at ${r.name}: ${t}. It's still listed — try again in a moment.`)}}t.providerOnly||(await t.machines.remove(e.id),e.nodeId&&await n(`${Oi(t.store)}/nodes/${encodeURIComponent(e.nodeId)}`,{method:`DELETE`,headers:{authorization:`Bearer ${t.store.s}`}}).catch(()=>{}))}var Pi=`bivy`,q=`device-key`,Fi=`x25519`;function Ii(){try{return typeof globalThis<`u`&&!!globalThis.indexedDB}catch{return!1}}var Li=4e3;function Ri(){return new Promise((e,t)=>{let n=!1,r=e=>{n||(n=!0,e())},i=setTimeout(()=>r(()=>t(Error(`indexedDB.open timed out`))),Li),a=indexedDB.open(Pi,1);a.onupgradeneeded=()=>{a.result.objectStoreNames.contains(q)||a.result.createObjectStore(q)},a.onsuccess=()=>r(()=>{clearTimeout(i),e(a.result)}),a.onerror=()=>r(()=>{clearTimeout(i),t(a.error)}),a.onblocked=()=>r(()=>{clearTimeout(i),t(Error(`indexedDB.open blocked`))})})}function zi(e,t){return new Promise((n,r)=>{let i;try{i=t(e)}catch(e){r(e);return}i.onsuccess=()=>n(i.result),i.onerror=e=>{e.preventDefault(),r(i.error)}})}async function Bi(){if(!Ii())return;let e=await Ri();try{await zi(e.transaction(q,`readwrite`).objectStore(q),e=>e.delete(Fi))}finally{e.close()}}function Vi(){return Ii()?{async load(){let e=await Ri();try{let t=await zi(e.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));return t&&t.priv instanceof CryptoKey&&typeof t.pub==`string`?{priv:t.priv,pub:t.pub}:null}finally{e.close()}},async save(e,t){try{let n=globalThis.structuredClone;n&&n({priv:e,pub:t})}catch{throw Error(`IndexedDB cannot clone this device key`)}let n=await Ri();try{let r=n.transaction(q,`readwrite`);r.onerror=e=>e.preventDefault(),await zi(r.objectStore(q),n=>n.put({priv:e,pub:t},Fi)),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)});let i=await zi(n.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));if(!i||!(i.priv instanceof CryptoKey)||i.priv.extractable||i.pub!==t)throw Error(`IndexedDB did not preserve the non-extractable device key`)}finally{n.close()}}}:null}var Hi=new WeakMap;function Ui(e,t){if(t)return Wi(e,t);let n=Hi.get(e);if(n)return n;let r=Wi(e,Vi()??void 0);return Hi.set(e,r),r.catch(()=>{Hi.get(e)===r&&Hi.delete(e)}),r}async function Wi(e,t){let n=t??Vi();if(n)try{let t=await n.load();if(t)return t;let r=e.device();if(r){let t=await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!1,[`deriveBits`]);return await n.save(t,r.pub),e.clearDevice(),{priv:t,pub:r.pub}}let i=await crypto.subtle.generateKey({name:`X25519`},!1,[`deriveBits`]),a=S(new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)));return await n.save(i.privateKey,a),{priv:i.privateKey,pub:a}}catch{}let r=e.device();if(r)return{priv:await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!0,[`deriveBits`]),pub:r.pub};let i=await crypto.subtle.generateKey({name:`X25519`},!0,[`deriveBits`]),a=new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)),o=new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,i.privateKey)),s=S(a),c=S(o);return e.setDevice({pub:s,priv:c}),{priv:i.privateKey,pub:s}}async function Gi(e,t){let n=await crypto.subtle.importKey(`raw`,C(t),{name:`X25519`},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:`X25519`,public:n},e,256))}async function Ki(e,t,n){let r=await Gi(e,t),i=await crypto.subtle.importKey(`raw`,r,`HKDF`,!1,[`deriveBits`]),a=n===`rotate`?w.rotate:n===`device-vault`?w.deviceVault:w.pair,o=new TextEncoder().encode(a),s=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array,info:o},i,256)),c=n===`device-vault`?[`encrypt`,`decrypt`]:[`decrypt`];return crypto.subtle.importKey(`raw`,s,`AES-GCM`,!1,c)}async function qi(e,t){let n=await crypto.subtle.importKey(`raw`,C(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return S(new Uint8Array(await crypto.subtle.sign(`HMAC`,n,C(t))))}var Ji=class extends Error{constructor(){super(`Device vault changed concurrently`),this.name=`DeviceVaultConflictError`}},Yi=()=>({v:3,providerTokens:{},modelKeys:{},oauthCredentials:{}}),Xi=()=>({phase:`idle`,attemptedAt:null,succeededAt:null,pending:!1,failure:null}),Zi=e=>{let t=e?Date.parse(e):NaN;return Number.isFinite(t)?t:0};function Qi(e){if(e&&typeof e==`object`&&e.v===3){let t=e,n={};for(let[e,r]of Object.entries(t.modelKeys&&typeof t.modelKeys==`object`?t.modelKeys:{})){if(!r||typeof r!=`object`)continue;let t=r;n[e]=t.value?{...t,value:{provider:t.value.provider||e.split(`:`)[0]||e,label:t.value.label||e.split(`:`).slice(1).join(`:`)||`default`,key:t.value.key}}:t}return{v:3,providerTokens:t.providerTokens&&typeof t.providerTokens==`object`?t.providerTokens:{},modelKeys:n,oauthCredentials:t.oauthCredentials&&typeof t.oauthCredentials==`object`?t.oauthCredentials:{}}}let t=Yi(),n=Date.now();if(e&&typeof e==`object`&&e.v===2){let r=e;for(let[e,i]of Object.entries(r.providerTokens??{}))typeof i==`string`&&(t.providerTokens[e]={value:i,updatedAt:n});for(let[e,i]of Object.entries(r.modelKeys??{}))i&&typeof i.key==`string`&&(t.modelKeys[e]={value:{provider:e,label:`default`,key:i.key},updatedAt:Zi(i.updatedAt)||n})}else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e))typeof i==`string`&&(t.providerTokens[r]={value:i,updatedAt:n});return t}function $i(e,t){return e?t?e.updatedAt===t.updatedAt?!!e.tombstone==!!t.tombstone?JSON.stringify(e.value)>=JSON.stringify(t.value)?e:t:e.tombstone?e:t:e.updatedAt>t.updatedAt?e:t:e:t}function ea(e,t){let n=Yi();for(let r of new Set([...Object.keys(e.providerTokens),...Object.keys(t.providerTokens)]))n.providerTokens[r]=$i(e.providerTokens[r],t.providerTokens[r]);for(let r of new Set([...Object.keys(e.modelKeys),...Object.keys(t.modelKeys)]))n.modelKeys[r]=$i(e.modelKeys[r],t.modelKeys[r]);for(let r of new Set([...Object.keys(e.oauthCredentials),...Object.keys(t.oauthCredentials)]))n.oauthCredentials[r]=$i(e.oauthCredentials[r],t.oauthCredentials[r]);return n}function J(e,t=`default`){let n=String(e||``).trim().toLowerCase(),r=String(t||`default`).trim().toLowerCase()||`default`;return r==="default"?n:`${n}:${r}`}function ta(e){let t=e.indexOf(`:`);return t<0?{provider:e,label:`default`}:{provider:e.slice(0,t),label:e.slice(t+1)||`default`}}function na(){return crypto.getRandomValues(new Uint8Array(32))}function ra(e){let t=e.randomKey??na,n=e.now??Date.now,r=null,i=0,a=0,o=Yi(),s=null,c=0,l={},u={},d={},f={},p={},m={},h=Xi(),g=null,_=async()=>e.state?.save({clock:c,tokenVersions:l,modelVersions:u,oauthVersions:d,tokenTombstones:f,modelTombstones:p,oauthTombstones:m,sync:h}),v=()=>s??=(async()=>{let t=await e.state?.load();c=Math.max(t?.clock??0,n()),l={...t?.tokenVersions??{}},u={...t?.modelVersions??{}},d={...t?.oauthVersions??{}},f={...t?.tokenTombstones??{}},p={...t?.modelTombstones??{}},m={...t?.oauthTombstones??{}},h=t?.sync??Xi()})(),y=()=>c=Math.max(c+1,n()),S=async(e,t)=>D(await E(t),JSON.stringify(e)),C=async(e,t)=>Qi(JSON.parse(await O(await E(t),e))),w=async(e,t,n)=>D(await Ki(e.priv,t,`device-vault`),b(n)),T=async(e,t,n)=>x(await O(await Ki(e.priv,t,`device-vault`),n));async function ee(){let t=Yi();if(e.providerTokenSyncEnabled?.()!==!1)for(let n of await e.local.list()){let r=await e.local.getToken(n.id);r&&(t.providerTokens[n.id]={value:r,updatedAt:Math.max(Zi(n.updatedAt),l[n.id]??1)})}for(let[e,n]of Object.entries(f))t.providerTokens[e]=$i(t.providerTokens[e],{value:null,updatedAt:n,tombstone:!0});if(e.modelKeys){for(let n of await e.modelKeys.entries())if(n.scope===`account`){let e=J(n.provider,n.label);t.modelKeys[e]={value:{provider:n.provider,label:n.label,key:n.key},updatedAt:Math.max(Zi(n.updatedAt),u[e]??1)}}}for(let[e,n]of Object.entries(p))t.modelKeys[e]=$i(t.modelKeys[e],{value:null,updatedAt:n,tombstone:!0});if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let n of await e.oauthCredentials.entries()){let e=J(n.provider,n.label),r=Math.max(Number(n.refreshedAt)||0,Number(n.updatedAt)||0,d[e]??1);t.oauthCredentials[e]={value:n,updatedAt:r}}for(let[e,n]of Object.entries(m))t.oauthCredentials[e]=$i(t.oauthCredentials[e],{value:null,updatedAt:n,tombstone:!0});return t}async function te(t){for(let[n,r]of Object.entries(t.providerTokens)){let t=(await e.local.list()).find(e=>e.id===n),i=Zi(t?.updatedAt);r.tombstone?(f[n]=Math.max(f[n]??0,r.updatedAt),i<=r.updatedAt&&await e.local.remove(n)):r.value&&(!t?.configured||i<r.updatedAt)&&(await e.local.setToken(n,r.value),l[n]=r.updatedAt,delete f[n])}if(e.modelKeys)for(let[n,r]of Object.entries(t.modelKeys)){let t=r.value?.provider??n,i=r.value?.label??`default`,a=(await e.modelKeys.list()).find(e=>e.provider===t&&e.label===i),o=Zi(a?.updatedAt);r.tombstone?(p[n]=Math.max(p[n]??0,r.updatedAt),o<=r.updatedAt&&await e.modelKeys.remove(t,i)):r.value&&(!a?.configured||o<r.updatedAt)&&(await e.modelKeys.set(t,r.value.key,`account`,i),u[n]=r.updatedAt,delete p[n])}if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let[n,r]of Object.entries(t.oauthCredentials)){let t=(await e.oauthCredentials.entries()).find(e=>J(e.provider,e.label)===n),i=Math.max(Number(t?.refreshedAt)||0,Number(t?.updatedAt)||0,d[n]??0);if(r.tombstone){if(m[n]=Math.max(m[n]??0,r.updatedAt),i<=r.updatedAt){let r=t??ta(n);await e.oauthCredentials.remove(r.provider,r.label)}}else r.value&&i<r.updatedAt&&(await e.oauthCredentials.set(r.value),d[n]=r.updatedAt,delete m[n])}}async function ne(){if(!e.enabled())return;await v();let s=await e.device(),c=await e.remote.get();a=c.generation??0;let l=c.keyGeneration??0;(!r||(c.wrappedKey?.generation??0)>i)&&c.wrappedKey&&(r=await T(s,c.wrappedKey.wrappedByPublicKeyB64,c.wrappedKey.wrappedKey),i=c.wrappedKey.generation??l),r&&c.vault&&(o=await C(c.vault,r)),r&&l>i&&(r=t(),i=l);let u=await ee(),d=ea(o,u),f=Object.keys(d.providerTokens).length+Object.keys(d.modelKeys).length+Object.keys(d.oauthCredentials).length>0;if(!r){if(!c.vault&&f)r=t(),i=l;else{await e.remote.requestKey(),h={...h,phase:`pending`,pending:!0,failure:null},await _();return}}let p=JSON.stringify(d)!==JSON.stringify(o)||!c.vault||l>(c.wrappedKey?.generation??l);o=d,p&&(a=(await e.remote.putVault(await S(o,r),a,i))?.generation??a+1);let m=new Set([s.pub,...c.recipients??[],...c.requests]);for(let t of m)await e.remote.putWrapped(t,await w(s,t,r),s.pub,i);await te(o),h={phase:`synced`,attemptedAt:h.attemptedAt,succeededAt:new Date(n()).toISOString(),pending:!1,failure:null},await _()}async function k(){return g||(g=(async()=>{await v(),h={...h,phase:`pending`,attemptedAt:new Date(n()).toISOString(),pending:!0,failure:null},await _();try{for(let e=0;e<3;e++)try{await ne();return}catch(t){if(!(t instanceof Ji)||e===2)throw t}}catch(e){throw h={...h,phase:`failed`,pending:!0,failure:e instanceof Error?e.message:String(e)},await _(),e}})().finally(()=>{g=null}),g)}return{sync:k,getSyncState:()=>({...h}),async getToken(t){let n=await e.local.getToken(t);if(n)return n;e.enabled()&&!o.providerTokens[t]&&await k();let r=o.providerTokens[t];return r&&!r.tombstone?r.value??``:``},async setToken(t,n){await v(),await e.local.setToken(t,n),l[t]=y(),delete f[t],await _(),e.enabled()&&e.providerTokenSyncEnabled?.()!==!1&&await k()},async remove(t){await v(),await e.local.remove(t),f[t]=y(),await _(),e.enabled()&&await k()},async list(){let t=await e.local.list(),n=new Set(t.filter(e=>e.configured).map(e=>e.id)),r=[...t];if(e.providerTokenSyncEnabled?.()!==!1)for(let[e,t]of Object.entries(o.providerTokens))!t.tombstone&&t.value&&!n.has(e)&&r.push({id:e,name:e,configured:!0,updatedAt:new Date(t.updatedAt).toISOString()});return r},async listModelKeys(){let t=await e.modelKeys?.list()??[],n=new Set(t.filter(e=>e.configured).map(e=>J(e.provider,e.label)));for(let[e,r]of Object.entries(o.modelKeys))!r.tombstone&&r.value&&!n.has(e)&&t.push({provider:r.value.provider,label:r.value.label,configured:!0,updatedAt:new Date(r.updatedAt).toISOString(),scope:`account`});return t.sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async modelKeyEntries(){let t=await e.modelKeys?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.modelKeys))!t.tombstone&&t.value&&!n.has(e)&&n.set(e,{provider:t.value.provider,label:t.value.label,key:t.value.key,updatedAt:new Date(t.updatedAt).toISOString(),scope:`account`});return[...n.values()]},async getModelKey(t){let n=J(t),r=await e.modelKeys?.get(t)??``;if(r)return r;e.enabled()&&!o.modelKeys[n]&&await k();let i=o.modelKeys[n];return i&&!i.tombstone?i.value?.key??``:``},async setModelKey(t,n,r=`account`,i=`default`){if(!e.modelKeys)throw Error(`Device model-key storage is unavailable`);await v();let a=J(t,i);await e.modelKeys.set(t,n,r,i),r===`device`?p[a]=y():(u[a]=y(),delete p[a]),await _(),e.enabled()&&await k()},async removeModelKey(t,n=`default`){await v();let r=J(t,n);await e.modelKeys?.remove(t,n),p[r]=y(),await _(),e.enabled()&&await k()},async importModelKeys(t){if(e.modelKeys){await v();for(let n of t){let t=n.label??`default`,r=J(n.provider,t);await e.modelKeys.set(n.provider,n.key,`account`,t),u[r]=y(),delete p[r]}await _(),e.enabled()&&await k()}},async oauthCredentialEntries(){if(e.oauthRecoveryEnabled?.()!==!0)return[];let t=await e.oauthCredentials?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.oauthCredentials))if(!t.tombstone&&t.value){let r=n.get(e),i=Math.max(Number(r?.refreshedAt)||0,Number(r?.updatedAt)||0);(!r||i<t.updatedAt)&&n.set(e,t.value)}return[...n.values()]},async importOAuthCredentials(t){if(!e.oauthCredentials||e.oauthRecoveryEnabled?.()!==!0)return;await v();let n=await e.oauthCredentials.entries();for(let r of t){let t=J(r.provider,r.label),i=Math.max(Number(r.refreshedAt)||0,Number(r.updatedAt)||0),a=n.find(e=>J(e.provider,e.label)===t),o=Math.max(Number(a?.refreshedAt)||0,Number(a?.updatedAt)||0,d[t]??0);a&&i<=o||(await e.oauthCredentials.set(r),d[t]=i||y(),delete m[t])}await _(),e.enabled()&&await k()},async removeOAuthCredential(t,n=`default`,r){await v();let i=J(t,n),a=Number(r)||y();a<=(d[i]??0)||(await e.oauthCredentials?.remove(t,n),m[i]=Math.max(m[i]??0,a),await _(),e.enabled()&&await k())}}}var ia=`bivy_local_token`,aa=15e3,oa=`This device isn't paired with this machine. Run 'bivy tailscale pair' there and open the link on this device.`,sa=class{origin;tokenStore;fetchImpl;WS;bootstrap;pairCode;deviceName;requireToken;unpaired=!1;handlers;authPending=Promise.resolve();ws=null;connected=!1;backoff=1e3;closedByUs=!1;reconnectTimer=null;constructor(e){this.origin=e.origin??``,this.tokenStore=e.tokenStore??(typeof globalThis<`u`?globalThis.sessionStorage:void 0),this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.bootstrap=e.bootstrap??``,this.pairCode=e.pairCode??``,this.deviceName=e.deviceName??`Paired device`,this.requireToken=e.requireToken??!1,this.handlers=e.handlers}token(){return this.tokenStore?.getItem(ia)||``}directHeaders(e){let t=this.token();return{"content-type":`application/json`,...t?{authorization:`Bearer ${t}`}:{},...e||{}}}async directApi(e,t={}){if(!e.startsWith(`/api/auth/`)&&(await this.authPending,this.unpaired))throw Error(oa);let n=await this.fetchImpl(`${this.origin}${e}`,{...t,headers:{...this.directHeaders(),...t.headers||{}}}),r=await n.json().catch(()=>({}));if(!n.ok){let e=Error(r?.error||`Local request failed (${n.status})`);throw r&&typeof r==`object`&&Object.assign(e,r),e}return r}async bootstrapAuth(){if(this.pairCode){let e=this.pairCode;this.pairCode=``;try{let t=await this.directApi(`/api/auth/pair`,{method:`POST`,body:JSON.stringify({code:e,name:this.deviceName})});if(t?.token){this.tokenStore?.setItem(ia,t.token);return}}catch(e){this.handlers.onError?.(e instanceof Error?e.message:String(e))}}if(!(this.token()||this.requireToken))try{let e=await this.directApi(`/api/auth/bootstrap`,{method:`POST`,body:JSON.stringify({name:`Local Remote UI`,bootstrap:this.bootstrap})});e?.token&&this.tokenStore?.setItem(ia,e.token)}catch(e){console.warn(`local bootstrap failed`,e)}}notPaired(){this.unpaired=!0,this.connected=!1,this.setStatus(`offline`),this.handlers.onError?.(oa)}setStatus(e){this.handlers.onStatus(e)}emit(e){this.handlers.onEvent(e)}emitMerged(e,t,n){this.emit({...n||{},...t||{},type:e})}async connect(){this.closedByUs=!1,this.setStatus(`connecting`),this.authPending=this.bootstrapAuth(),await this.authPending;let e=typeof location<`u`&&location.protocol===`https:`?`wss:`:`ws:`,t=typeof location<`u`?location.host:this.origin.replace(/^https?:\/\//,``),n=this.token(),r=`${e}//${t}/ws${n?`?access_token=${encodeURIComponent(n)}`:``}`,i=new this.WS(r);this.ws=i;let a=()=>i===this.ws;i.onopen=()=>{a()&&(this.connected=!0,this.backoff=1e3,this.setStatus(`online`),this.send({kind:`sessions.list`}),this.send({kind:`models.list`}),this.send({kind:`runtimes.list`}),this.send({kind:`terminal.list`}),this.send({kind:`terminal.multiplexers`}))},i.onmessage=e=>{if(a())try{this.emit(JSON.parse(String(e.data)))}catch{}},i.onclose=e=>{if(a()&&!this.closedByUs){if(this.requireToken&&e?.code===1008&&e.reason===`Unauthorized`){this.tokenStore?.setItem(ia,``),this.notPaired();return}this.connected=!1,this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.closedByUs||this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,aa)}},i.onerror=()=>{}}close(){if(this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){let e=this.ws;this.ws=null,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}async send(e){try{switch(e.kind){case`ping`:this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e));break;case`history`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.have==null?{}:{have:String(e.have)},...e.haveToken?{haveToken:String(e.haveToken)}:{}});this.emit(await this.directApi(`/api/session/history?${t}`));break}case`session.replay`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},afterSeq:String(e.afterSeq??0)});this.emit(await this.directApi(`/api/session/replay?${t}`));break}case`sessions.list`:this.emit({type:`sessions.list`,sessions:await this.directApi(`/api/sessions`)});break;case`session.open`:{let t=await this.directApi(`/api/sessions/open`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,path:e.path,agent:e.agent,runtimeId:e.runtimeId})});this.emit({type:`session.history`,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:t.messages||[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.new`:{let t=await this.directApi(`/api/session`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`session.history`,requestId:e.requestId,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/sessions/discover`);this.emit({type:`session.discover.result`,requestId:t,sessions:e?.sessions??[]})}catch(e){this.emit({type:`session.discover.error`,requestId:t,error:e?.message||String(e)})}break}case`apps.list`:case`apps.publish`:case`apps.offers`:case`apps.adopt`:case`apps.open`:case`apps.logs`:case`apps.showMe`:case`apps.mute`:case`apps.reviewMode`:case`apps.annotate`:case`apps.clearNotes`:case`apps.agentNotes`:case`apps.share`:case`apps.unshare`:case`apps.revoke`:case`apps.remove`:case`artifacts.list`:case`access.get`:case`tailnet.machines`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/${e.kind.replace(`.`,`/`)}`,{method:`POST`,body:JSON.stringify(e)});if(typeof n.error==`string`)throw Error(n.error);this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`session.presence.get`:case`session.presence.draft`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/session/presence/${e.kind.slice(17)}`,{method:`POST`,body:JSON.stringify(e)});this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`attachment.fetch`:{let t=String(e.requestId??``),n=String(e.hash??``);try{let e=await this.fetchImpl(`${this.origin}/api/attachment/${encodeURIComponent(n)}`,{headers:this.directHeaders()});if(!e.ok)throw Error(`Attachment fetch failed (${e.status})`);let r=e.headers.get(`content-type`)||`application/octet-stream`,i=new Uint8Array(await e.arrayBuffer()),a=``,o=32768;for(let e=0;e<i.length;e+=o)a+=String.fromCharCode(...i.subarray(e,e+o));this.emit({type:`attachment.data`,requestId:t,hash:n,mimeType:r,data:btoa(a)})}catch(e){this.emit({type:`attachment.error`,requestId:t,hash:n,error:e?.message||String(e)})}break}case`session.import`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/sessions/import`,{method:`POST`,body:JSON.stringify({runtimeId:e.runtimeId,ref:e.ref,acceptDisclosure:e.acceptDisclosure})});this.emit({type:`session.import.result`,requestId:t,sessionId:n.sessionId,runtimeId:n.runtimeId,mode:n.mode,seedPrompt:n.seedPrompt})}catch(e){let n=e;this.emit({type:`session.import.error`,requestId:t,error:String(n?.message??e),needsDisclosure:n?.needsDisclosure,disclosure:n?.disclosure})}break}case`session.delete`:await this.directApi(`/api/sessions/delete`,{method:`POST`,body:JSON.stringify({id:e.sessionId,path:e.path})});break;case`session.rename`:await this.directApi(`/api/sessions/rename`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name})});break;case`session.pr.refresh`:this.emitMerged(`session.pr_result`,await this.directApi(`/api/session/pr/refresh`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),{sessionId:String(e.sessionId??``)});break;case`sessions.pr.refresh_all`:this.emitMerged(`sessions.pr_refresh_result`,await this.directApi(`/api/sessions/pr/refresh`,{method:`POST`}));break;case`prompt`:await this.directApi(`/api/session/prompt`,{method:`POST`,body:JSON.stringify(e)});break;case`abort`:await this.directApi(`/api/session/abort`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});break;case`session.turn_attention.resolve`:await this.directApi(`/api/session/turn-attention`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,action:e.action})});break;case`session.limit_retry`:await this.directApi(`/api/session/limit-retry`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,enabled:e.enabled})});break;case`session.command.invoke`:await this.directApi(`/api/session/command`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name,args:e.args})});break;case`session.pause`:await this.directApi(`/api/session/pause`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.paused`,sessionId:String(e.sessionId??``)});break;case`session.resume`:await this.directApi(`/api/session/resume`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.resumed`,sessionId:String(e.sessionId??``)});break;case`session.checkpoints`:{let t=await this.directApi(`/api/session/checkpoints`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});this.emit({type:`session.checkpoints`,sessionId:String(e.sessionId??``),checkpoints:t?.checkpoints??[]});break}case`session.rewind`:await this.directApi(`/api/session/rewind`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,checkpointId:e.checkpointId})}),this.emit({type:`session.rewound`,sessionId:String(e.sessionId??``),checkpointId:String(e.checkpointId??``)});break;case`session.question.answer`:await this.directApi(`/api/session/question/answer`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,requestId:e.requestId,answers:e.answers,cancelled:e.cancelled})});break;case`models.list`:this.emitMerged(`models.list`,await this.directApi(`/api/models?${new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.runtimeId?{runtimeId:String(e.runtimeId)}:{}})}`));break;case`models.prefetch`:await this.directApi(`/api/models/prefetch`,{method:`POST`,body:JSON.stringify({runtimeIds:e.runtimeIds})});break;case`model.select`:await this.directApi(`/api/models/select`,{method:`POST`,body:JSON.stringify(e)});break;case`thinking.set_level`:await this.directApi(`/api/thinking/set-level`,{method:`POST`,body:JSON.stringify(e)});break;case`node.stats`:{let t=new URLSearchParams(e.sessionId?{sessionId:String(e.sessionId)}:{});this.emit({type:`node.stats`,stats:await this.directApi(`/api/node/stats?${t}`)});break}case`capabilities.get`:this.emit({type:`capabilities`,capabilities:await this.directApi(`/api/capabilities`)});break;case`runtimes.list`:this.emitMerged(`runtimes.list`,await this.directApi(`/api/runtimes`));break;case`runtime.select`:this.emitMerged(`runtime.updated`,await this.directApi(`/api/runtimes/select`,{method:`POST`,body:JSON.stringify({id:e.id})}));break;case`runtime.install`:this.emitMerged(`runtime.install.done`,await this.directApi(`/api/runtimes/install`,{method:`POST`,body:JSON.stringify({id:e.id})}),{id:String(e.id??``)});break;case`providers.list`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers`));break;case`provider.auth.get`:this.emitMerged(`provider.auth`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`));break;case`provider.apiKey`:{let t=String(e.requestId??``);try{this.emitMerged(`providers.list`,await this.directApi(`/api/auth/api-key`,{method:`POST`,body:JSON.stringify({provider:e.provider,key:e.key})})),this.emit({type:`provider.apiKey.ok`,requestId:t})}catch(e){this.emit({type:`provider.apiKey.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.remove`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}));break;case`credentials.list`:this.emitMerged(`credentials.records`,await this.directApi(`/api/auth/credentials`));break;case`credentials.native.preview`:case`credentials.native.import`:{let t=String(e.requestId??``),n=e.kind===`credentials.native.preview`?`native-preview`:`native-import`;try{let r=await this.directApi(`/api/auth/credentials/${n}`,{method:`POST`,body:JSON.stringify(e)});if(typeof r.error==`string`)throw Error(r.error);this.emit({...r,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`credentials.account.export`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials/account-export`,{method:`POST`,body:JSON.stringify({includeOAuth:e.includeOAuth===!0})});this.emit({type:`credentials.account.export`,requestId:t,...n})}catch(e){this.emit({type:`credentials.account.export.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.account.import`:{let t=String(e.requestId??``);try{await this.directApi(`/api/auth/credentials/account-import`,{method:`POST`,body:JSON.stringify({oauthEntries:e.oauthEntries})}),this.emit({type:`credentials.account.import.ok`,requestId:t})}catch(e){this.emit({type:`credentials.account.import.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials`,{method:`POST`,body:JSON.stringify(e)});this.emitMerged(`credentials.records`,n),this.emitMerged(`providers.list`,n),this.emit({type:`credential.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.remove`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}`,{method:`DELETE`});this.emitMerged(`credentials.records`,i),this.emitMerged(`providers.list`,i),this.emit({type:`credential.remove.ok`,requestId:t})}catch(e){this.emit({type:`credential.remove.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.sync.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/availability`,{method:`POST`,body:JSON.stringify({sync:e.sync})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.sync.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.sync.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.unattended.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/unattended`,{method:`POST`,body:JSON.stringify({unattended:e.unattended===!0})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.unattended.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.unattended.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.test`:{let t=String(e.requestId??``),n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`));try{let e=await this.directApi(`/api/auth/credentials/${n}/${r}/test`,{method:`POST`,body:`{}`});this.emitMerged(`credentials.records`,e),this.emit({type:`credential.test.result`,requestId:t,...e})}catch(n){this.emit({type:`credential.test.result`,requestId:t,provider:e.provider,label:e.label,ok:!1,at:Date.now(),reason:`network_error`,error:n instanceof Error?n.message:String(n)})}break}case`credentials.presets.get`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`));break;case`credentials.presets.setMapping`:{let t=String(e.requestId??``);try{this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`,{method:`POST`,body:JSON.stringify({preset:e.preset,provider:e.provider,label:e.label})})),this.emit({type:`credentials.presets.setMapping.ok`,requestId:t})}catch(e){this.emit({type:`credentials.presets.setMapping.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.presets.setActive`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments/active`,{method:`POST`,body:JSON.stringify({active:e.active})}));break;case`models.custom.list`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom`));break;case`models.custom.presets`:this.emitMerged(`models.custom.presets`,await this.directApi(`/api/models/catalog`));break;case`models.custom.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/models/discover`,{method:`POST`,body:`{}`});this.emit({type:`models.custom.discover.ok`,requestId:t,...e})}catch(e){this.emit({type:`models.custom.discover.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.verify`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/verify`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`models.custom.verify.ok`,requestId:t,...n})}catch(e){this.emit({type:`models.custom.verify.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.save`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/custom`,{method:`POST`,body:JSON.stringify(e.spec??e)});this.emitMerged(`models.custom.list`,n),this.emit({type:`models.custom.save.ok`,requestId:t,provider:n.provider})}catch(e){this.emit({type:`models.custom.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.remove`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom/${encodeURIComponent(String(e.id??e.provider??``))}`,{method:`DELETE`}));break;case`rulesets.list`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`));break;case`rulesets.save`:{let t=String(e.requestId??``);try{this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`,{method:`POST`,body:JSON.stringify(e)})),this.emit({type:`rulesets.save.ok`,requestId:t})}catch(e){this.emit({type:`rulesets.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`rulesets.remove`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets/${encodeURIComponent(String(e.name??``))}`,{method:`DELETE`}));break;case`activation.readiness`:this.emitMerged(`activation.readiness`,await this.directApi(`/api/activation/readiness`));break;case`repos.list`:this.emitMerged(`repos.list`,await this.directApi(`/api/repos`));break;case`branches.list`:this.emitMerged(`branches.list`,await this.directApi(`/api/repos/branches?repo=${encodeURIComponent(String(e.repo||``))}`));break;case`workspaces.list`:this.emitMerged(`workspaces.list`,await this.directApi(`/api/workspaces`));break;case`node.settings.get`:this.emit({type:`node.settings`,requestId:String(e.requestId??``),settings:await this.directApi(`/api/node/settings`)});break;case`node.settings.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/node/settings`,{method:`POST`,body:JSON.stringify(e.settings??e)});this.emit({type:`node.settings`,requestId:t,settings:n?.settings??n})}catch(e){this.emit({type:`node.settings.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.reset`:this.emitMerged(`provider.oauth.reset`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}),{provider:String(e.provider??``)});break;case`provider.oauth.start`:this.emitMerged(`provider.oauth.started`,await this.directApi(`/api/auth/oauth/start`,{method:`POST`,body:JSON.stringify({provider:e.provider,label:e.label})}),{provider:String(e.provider??``)});break;case`provider.oauth.open_on_node`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/open-on-node`,{method:`POST`,body:`{}`});this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,...n})}catch(e){this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,opened:!1,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.code`:await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/manual-code`,{method:`POST`,body:JSON.stringify({code:e.code})});break;case`github.app.manifest.start`:try{this.emitMerged(`github.app.manifest.ready`,await this.directApi(`/api/github/app/manifest/start`,{method:`POST`,body:JSON.stringify({origin:e.origin,org:e.org})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.manifest.code`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/manifest/complete`,{method:`POST`,body:JSON.stringify({code:e.code,state:e.state})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.connect-existing`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/connect-existing`,{method:`POST`,body:JSON.stringify({appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.disconnect`:await this.directApi(`/api/github/app/disconnect`,{method:`POST`,body:JSON.stringify({appId:e.appId})}),this.emit({type:`github.app.disconnected`,requestId:String(e.requestId??``),ok:!0});break;case`github.connect.start`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/start`,{method:`POST`}));break;case`github.connect.poll`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/poll`));break;case`approval`:await this.directApi(`/api/approvals/${encodeURIComponent(String(e.id))}/${e.approved?`approve`:`reject`}`,{method:`POST`,body:`{}`});break;case`stt.config.get`:this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`));break;case`stt.config.set`:{let t=String(e.requestId??``);try{this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`,{method:`POST`,body:JSON.stringify({provider:e.provider,setKey:e.setKey,removeKey:e.removeKey})})),this.emit({type:`stt.config.set.ok`,requestId:t})}catch(e){this.emit({type:`stt.config.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`transcribe`:this.emitMerged(`transcription`,await this.directApi(`/api/transcribe`,{method:`POST`,body:JSON.stringify({audio:e.audio,mimeType:e.mimeType,provider:e.provider,language:e.language})}),{requestId:String(e.requestId??``)});break;case`synthesize`:this.emitMerged(`speech.audio`,await this.directApi(`/api/speech`,{method:`POST`,body:JSON.stringify({text:e.text,voice:e.voice,instructions:e.instructions})}),{requestId:String(e.requestId??``)});break;case`node.update`:try{await this.directApi(`/api/node/update`,{method:`POST`,body:`{}`}),this.emit({type:`node.update.result`,ok:!0})}catch(e){this.emit({type:`node.update.result`,ok:!1,error:e?.message||String(e)})}break;default:/^(terminal|session\.fork)\./.test(String(e.kind||``))&&this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e))}}catch(e){this.handlers.onError?.(e?.message||String(e))}}},ca=8388608,la=class{deps;queue=[];queuedBytes=0;pending;timer;generation=0;constructor(e){this.deps=e}accept(e){if(e.type===`transfer.part`){this.part(e);return}if(this.pending||this.queue.length){if(this.queuedBytes+=new TextEncoder().encode(JSON.stringify(e)).length,this.queuedBytes>ca||this.queue.length>=4096){this.reset(),this.deps.fault(`Transcript delivery fell behind. Reconnecting to synchronize again.`);return}this.queue.push(e);return}this.deliver(e)}deliver(e){if(e.code!==`transfer_required`){this.deps.emit(e);return}let t=e.transfer;if(!t||!/^[a-f0-9]{48}$/.test(t.id)||!/^[a-f0-9]{64}$/.test(t.key)||!/^[a-f0-9]{24}$/.test(t.iv)||!Number.isSafeInteger(t.bytes)||t.bytes<=0||t.bytes>67108864||t.pageBytes!==393216){this.deps.emit({type:`session.error`,code:`delivery_invalid`,sessionId:e.sessionId,requestId:e.requestId,error:`Invalid large-response transfer. Update the app and retry.`});return}this.pending={offer:t,envelope:e,bytes:new Uint8Array(t.bytes),offset:0,requestId:``,retries:0},this.request()}request(){let e=this.pending;e&&(e.requestId=`transfer-${crypto.randomUUID()}`,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.pending===e&&(++e.retries<=2?this.request():this.fail(`Large-response delivery timed out. Retry to synchronize.`))},this.deps.timeoutMs??1e4),this.deps.send({kind:`transfer.read`,transferId:e.offer.id,offset:e.offset,requestId:e.requestId}).catch(()=>{this.pending===e&&this.fail(`Could not request the next response page. Retry to synchronize.`)}))}async part(e){let t=this.pending;if(t&&e.requestId===t.requestId&&e.transferId===t.offer.id&&e.offset===t.offset){if(clearTimeout(this.timer),typeof e.error==`string`){this.fail(e.error);return}try{if(typeof e.data!=`string`||e.data.length>524288)throw Error(`Invalid response page.`);let n=x(e.data);if(n.length!==Math.min(393216,t.offer.bytes-t.offset))throw Error(`Incomplete response page.`);if(t.bytes.set(n,t.offset),t.offset+=n.length,t.retries=0,t.offset<t.offer.bytes){this.request();return}t.requestId=``;let r=this.generation,i=e=>Uint8Array.from(e.match(/../g),e=>parseInt(e,16)),a=await crypto.subtle.importKey(`raw`,i(t.offer.key),`AES-GCM`,!1,[`decrypt`]),o;try{o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i(t.offer.iv)},a,t.bytes)}catch{throw Error(`Response integrity check failed.`)}if(r!==this.generation||this.pending!==t)return;let s=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(o));if(!s||typeof s.type!=`string`||s.code===`transfer_required`||s.type===`transfer.part`)throw Error(`Invalid response envelope.`);this.pending=void 0,this.deps.emit(s),this.drain()}catch(e){this.pending===t&&this.fail(`${e.message} Retry to synchronize.`)}}}fail(e){let t=this.pending?.envelope;this.reset(),this.deps.emit({type:`session.error`,code:`delivery_failed`,sessionId:t?.sessionId,requestId:t?.requestId,error:e}),this.deps.fault(e)}drain(){for(;!this.pending&&this.queue.length;){let e=this.queue.shift();this.queuedBytes-=new TextEncoder().encode(JSON.stringify(e)).length,this.deliver(e)}}reset(){clearTimeout(this.timer),this.pending=void 0,this.queue=[],this.queuedBytes=0,this.generation++}},ua=15e3,da=15e3,fa=4,pa=3;function ma(){return b(crypto.getRandomValues(new Uint8Array(12)))}function ha(e){return/device limit|another account|isn't authorized|not authorized|forbidden/i.test(e)}var ga=class{store;handlers;fetchImpl;WS;pairingOnly;ws=null;connected=!1;initialBackoff;backoff;closedByUs=!1;reconnectTimer=null;pairSent=!1;pairAttempts=0;connectFailures=0;hasReachedNode=!1;curKey=null;devicePromise=null;sendQueue=[];reassemble=k({onReject:e=>{this.handlers.onError?.(e),/limit/.test(e)?this.close():this.ws?.close()}});acceptFrame=ee();transfers;receiveChain=Promise.resolve();decryptBytes=0;constructor(e){this.store=e.store,this.pairingOnly=e.pairingOnly??!1,this.handlers=e.handlers,this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.initialBackoff=e.initialBackoffMs??1e3,this.backoff=this.initialBackoff,this.transfers=new la({send:e=>this.send(e),emit:e=>this.handlers.onEvent(e),fault:e=>{this.handlers.onError?.(e),this.ws?.close()}})}cpBase(){return(this.store.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}reportRemoteReconnect(){if(!this.store.s)return;let e=typeof navigator<`u`&&/Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);this.fetchImpl(`${this.cpBase()}/account/product-events`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({event:`remote_reconnect`,client:e?`mobile`:`desktop`})}).catch(()=>{})}setStatus(e){this.handlers.onStatus(e)}device(){return this.devicePromise||=Ui(this.store).catch(e=>{throw this.devicePromise=null,e}),this.devicePromise}async keyFor(e){let t=this.store.keys()[e];return t?E(C(t)):null}canConnect(){let e=this.store.cur;return e?!!(this.curKey||this.store.keys()[e]||this.store.s||this.store.nodePubs()[e]&&this.store.pairSecrets()[e]):!1}soloCreds(){let e=this.store.solo()[this.store.cur];return e&&e.room&&e.roomToken?e:null}async mintClientTicket(){let e=await this.fetchImpl(`${this.cpBase()}/client/relay-ticket`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})});if(!e.ok)throw Error(`ticket request failed: ${e.status}`);let t=await e.json();if(!t?.ticket)throw Error(`no ticket`);return{ticket:t.ticket,relayUrl:typeof t.relayUrl==`string`?t.relayUrl:null}}async connect(){if(this.closedByUs=!1,this.setStatus(`connecting`),this.curKey=await this.keyFor(this.store.cur),this.closedByUs)return;let e=this.soloCreds(),t=``,n=null;if(!e)try{({ticket:t,relayUrl:n}=await this.mintClientTicket())}catch(e){this.connectFailures+=1,this.connectFailures>=fa&&this.handlers.onError?.(e?.message||`ticket mint failed`),this.scheduleReconnect();return}if(this.closedByUs)return;this.pairSent=!1;let r=this.store.cur,i=(n||this.store.relay).replace(/\/$/,``),a=e?`${i}/client?room=${encodeURIComponent(e.room)}&roomToken=${encodeURIComponent(e.roomToken)}`:`${i}/client?ticket=${encodeURIComponent(t)}&nodeId=${encodeURIComponent(r)}`,o=new this.WS(a);this.ws=o;let s=()=>o===this.ws&&r===this.store.cur;o.onmessage=async e=>{if(!s())return;let t;try{t=JSON.parse(String(e.data))}catch{return}if(t.t===`ready`||t.t===`peer.online`){let e=o;this.hasReachedNode&&!e._productReconnectReported&&(e._productReconnectReported=!0,this.reportRemoteReconnect()),this.hasReachedNode=!0,this.connected=!0,this.backoff=this.initialBackoff,this.connectFailures=0,this.setStatus(this.curKey?`online`:`pairing`),await this.onLinkReady()}else if(t.t===`peer.offline`)this.setStatus(`reconnecting`);else if(t.t===`pair`&&typeof t.p==`string`)await this.handlePairFrame(t.p);else if(t.t===`error`)this.handlers.onError?.(t.error||`relay error`);else if(t.t===`run.updated`&&typeof t.id==`string`)this.handlers.onEvent({type:`run.updated`,runId:t.id,revision:typeof t.revision==`string`?t.revision:void 0});else if(t.t===`frame`&&typeof t.p==`string`){if(!this.curKey)return;let e=this.reassemble(t);if(e===null)return;if(this.decryptBytes+e.length>33554432){this.handlers.onError?.(`Response decoding fell behind. Reconnecting to synchronize.`),o.close();return}this.decryptBytes+=e.length;let n=this.curKey;this.receiveChain=this.receiveChain.then(async()=>{if(!s()||o.readyState!==1)return;let t=JSON.parse(await O(n,e));s()&&o.readyState===1&&this.acceptFrame(t)&&this.transfers.accept(t.data)}).catch(()=>{s()&&o.readyState===1&&(this.handlers.onError?.(`Could not decode the machine response. Reconnecting to synchronize.`),o.close())}).finally(()=>{this.decryptBytes-=e.length})}},o.onclose=()=>{s()&&!this.closedByUs&&(this.connected=!1,this.transfers.reset(),this.reassemble.reset(),this.scheduleReconnect())},o.onerror=()=>{}}scheduleReconnect(){this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.canConnect()&&!this.closedByUs&&this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,ua)}shouldResync(){let e=this.ws;if(!e)return!1;let t=Date.now();return e._resyncAt!==void 0&&t-e._resyncAt<da?!1:(e._resyncAt=t,!0)}async onLinkReady(){if(this.curKey){if(this.pairingOnly||(this.flush(),!this.shouldResync()))return;this.store.sessions(),await this.send({kind:`sessions.list`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}else{this.setStatus(`linking`);let e=this.store.cur;this.store.nodePubs()[e]&&this.store.pairSecrets()[e]?await this.sendPairHello():await this.sendAccountPair()}}async sendPairHello(){if(this.pairSent)return;let e=this.store.cur,t=this.store.nodePubs()[e],n=this.store.pairSecrets()[e];if(!t||!n)return;let r=await this.device(),i=await qi(n,r.pub);this.pairSent=!0,this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.hello`,devicePublicKeyB64:r.pub,proofB64:i,label:_a()})}))}async sendAccountPair(){if(this.pairSent||!this.store.s)return;let e=await this.device();this.pairSent=!0;try{let t=await this.fetchImpl(`${this.cpBase()}/client/pair-grant`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})}),n=await t.json().catch(()=>({}));if(!t.ok||!n?.grant)throw Error(`Could not create pairing grant`);this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.account`,sessionToken:n.grant,devicePublicKeyB64:e.pub,label:_a()})}))}catch(e){this.pairSent=!1,this.handlers.onError?.(e?.message||`Could not pair this device`),this.setStatus(`reconnecting`)}}async handlePairFrame(e){let t;try{t=JSON.parse(e)}catch{return}let n=this.store.cur,r=this.store.nodePubs()[n];!r&&typeof t.nodePublicKeyB64==`string`&&(this.store.addNodePub(n,t.nodePublicKeyB64),r=t.nodePublicKeyB64);let i=await this.device();if(t.k===`pair.welcome`&&typeof t.wrapped==`string`&&r&&!this.curKey)try{let e=x(await O(await Ki(i.priv,r,`pair`),t.wrapped));if(this.storeRoomKey(n,e),this.store.clearPairSecret(n),this.curKey=await this.keyFor(n),this.pairAttempts=0,this.setStatus(`online`),this.pairingOnly)return;this.flush(),await this.send({kind:`sessions.list`}),await this.send({kind:`history`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}catch{this.setStatus(`reconnecting`)}else if(t.k===`key.rotate`&&Array.isArray(t.deliveries)&&r){let e=await Ki(i.priv,r,`rotate`);for(let r of t.deliveries)try{this.storeRoomKey(n,x(await O(e,r.wrapped))),this.curKey=await this.keyFor(n);break}catch{}}else t.k===`pair.error`&&this.onPairRejected(typeof t.error==`string`?t.error:``)}onPairRejected(e){if(ha(e)){this.handlers.onError?.(e),this.close();return}if(this.pairAttempts+=1,this.pairAttempts>=pa){this.handlers.onError?.(e||`Couldn't link this device — the node rejected it. Make sure the node is online and you're signed in to the right account, then try again.`),this.close();return}this.handlers.onError?.(e?`${e} — retrying…`:`Device link was rejected — retrying…`),this.pairSent=!1;let t=this.ws;this.ws=null,this.connected=!1;try{t?.close()}catch{}this.scheduleReconnect()}storeRoomKey(e,t){this.store.addKey(e,S(t))}rawSend(e){this.connected&&this.ws?.readyState===1?this.ws.send(e):this.sendQueue.push(e)}flush(){for(;this.sendQueue.length&&this.ws?.readyState===1;){let e=this.sendQueue.shift();e!==void 0&&this.ws.send(e)}}async send(e){if(!this.curKey)return;let t={v:1,ts:Date.now(),nonce:ma(),data:e},n=await D(this.curKey,JSON.stringify(t));if(n.length>33554432){let t=`This request is too large to send. Reduce the attachments and retry.`;this.handlers.onError?.(t),this.handlers.onEvent({type:`session.error`,code:`delivery_too_large`,sessionId:typeof e.sessionId==`string`?e.sessionId:void 0,requestId:e.requestId,error:t});return}for(let e of ne(n,ma))this.rawSend(e)}close(){if(this.transfers.reset(),this.reassemble.reset(),this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){this.transfers.reset(),this.reassemble.reset();let e=this.ws;this.ws=null,this.connected=!1,this.pairSent=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}};function _a(){return globalThis.navigator?.platform||`Device`}var va=Object.freeze({repo:null,branch:null,sandbox:null,acknowledgeReducedProtections:!1,ephemeralConfig:null});function ya(e,t){switch(t.type){case`select-repository`:return e.repo===t.repo?{...e}:{...e,repo:t.repo,branch:null};case`select-branch`:return{...e,branch:t.branch};case`select-sandbox`:return{...e,sandbox:t.sandbox};case`acknowledge-reduced-protections`:return{...e,acknowledgeReducedProtections:t.acknowledged};case`select-ephemeral-config`:return{...e,ephemeralConfig:t.config};case`reset`:return{...va}}}var ba=512,xa=class{nextSeq=0;held=new Map;maxHeld;constructor(e={}){this.maxHeld=Math.max(1,e.maxHeld??ba)}baseline(e){let t=(Number.isFinite(e)?Math.max(0,Math.floor(e)):0)+1;t>this.nextSeq&&(this.nextSeq=t);for(let e of[...this.held.keys()])e<this.nextSeq&&this.held.delete(e)}accept(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{ready:[t]};let n=Math.floor(e);if(this.nextSeq===0)return this.nextSeq=n+1,{ready:[t]};if(n<this.nextSeq)return{ready:[]};if(n>this.nextSeq)return this.held.set(n,t),this.held.size>this.maxHeld?{ready:[],overflow:!0}:{ready:[],gapFrom:this.nextSeq-1};let r=[t];for(this.nextSeq+=1;this.held.has(this.nextSeq);)r.push(this.held.get(this.nextSeq)),this.held.delete(this.nextSeq),this.nextSeq+=1;return{ready:r}}reset(){this.nextSeq=0,this.held.clear()}get expected(){return this.nextSeq}get heldCount(){return this.held.size}};function Sa(e,t){if(t.type===`node.updated`)return typeof t.name!=`string`||!t.name||!e.currentNodeId?{handled:!0,value:e}:{handled:!0,value:{...e,nodes:e.nodes.map(n=>n.id===e.currentNodeId?{...n,name:t.name}:n)}};if(t.type===`node.update`){let n=typeof t.current==`string`?t.current:``,r=typeof t.latest==`string`?t.latest:``;return{handled:!0,value:n&&r?{...e,nodeUpdate:{current:n,latest:r}}:{...e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1}}}return t.type===`node.update.result`?t.ok===!1?{handled:!0,value:{...e,nodeUpdating:!1,nodeUpdateAcknowledged:!1},error:typeof t.error==`string`?t.error:`Couldn't start the update on this node.`}:{handled:!0,value:{...e,nodeUpdateAcknowledged:!0}}:{handled:!1,value:e}}function Ca(e,t){let n=String(t.sessionId||``);return t.type===`session.paused`?!n||e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:[...e.pausedSessionIds,n]}}:t.type===`session.resumed`?!n||!e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:e.pausedSessionIds.filter(e=>e!==n)}}:{handled:!1,value:e}}function wa(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.termId==`string`?t:void 0}function Ta(e,t,n){if(t.type===`terminal.list`){let n=Array.isArray(t.terminals)?t.terminals.map(wa).filter(e=>!!e):[];return{handled:!0,value:{...e,runTerminals:n}}}if(t.type===`terminal.created`){let n=wa(t.terminal);return n?{handled:!0,value:{...e,runTerminals:[n,...e.runTerminals.filter(e=>e.termId!==n.termId)]}}:{handled:!0,value:e}}if(t.type===`terminal.activity`){let r=String(t.termId||``);if(!r)return{handled:!0,value:e};let i=Number(t.at)||n;return{handled:!0,value:{...e,runTerminals:e.runTerminals.map(e=>e.termId===r?{...e,lastActivityAt:i}:e)}}}if(t.type===`terminal.closed`||t.type===`terminal.exit`){let n=String(t.termId||``);return n?{handled:!0,value:{...e,runTerminals:e.runTerminals.filter(e=>e.termId!==n)}}:{handled:!0,value:e}}if(t.type===`terminal.tui`){let n=String(t.sessionId||``);if(!n)return{handled:!0,value:e};let r=!!t.active;return r===e.tuiSessions.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,tuiSessions:r?[...e.tuiSessions,n]:e.tuiSessions.filter(e=>e!==n)}}}return{handled:!1,value:e}}function Ea(e){switch(e.type){case`repos.list`:return{handled:!0,catalogs:{repos:Array.isArray(e.repos)?e.repos:[],reposAuthed:e.authed!==!1,reposError:e.error||null,reposReason:e.reason===`gh-unauthed`||e.reason===`no-token`?e.reason:null,reposLoading:!1}};case`branches.list`:return{handled:!0,catalogs:{branches:Array.isArray(e.branches)?e.branches:[],branchesRepo:typeof e.repo==`string`&&e.repo?e.repo:null,branchesDefault:typeof e.defaultBranch==`string`?e.defaultBranch:null,branchesError:e.error||null,branchesLoading:!1}};case`credentials.records`:return{handled:!0,settings:{credentialRecords:Array.isArray(e.records)?e.records:[]}};case`credentials.presets`:return{handled:!0,settings:{credentialPresets:e.presets??{}}};case`models.custom.list`:return Array.isArray(e.providers)?{handled:!0,settings:{localModels:e.providers}}:{handled:!0};case`models.custom.presets`:return Array.isArray(e.presets)?{handled:!0,settings:{localModelPresets:e.presets}}:{handled:!0};case`rulesets.list`:return Array.isArray(e.rulesets)?{handled:!0,settings:{rulesets:e.rulesets}}:{handled:!0};case`stt.config`:return Array.isArray(e.providers)&&typeof e.provider==`string`?{handled:!0,settings:{sttConfig:{provider:e.provider,providers:e.providers}}}:{handled:!0};case`node.settings`:return e.settings&&typeof e.settings==`object`?{handled:!0,settings:{nodeSettings:e.settings}}:{handled:!0};default:return{handled:!1}}}function Da(e,t){if(t.type===`sessions.pr_refresh_result`)return{handled:!0,value:{...e,prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}}};let n=e.githubApp||{phase:`idle`};return t.type===`github.app.manifest.ready`?{handled:!0,value:{...e,githubApp:{...n,phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}}}:t.type===`github.app.manifest.done`?{handled:!0,value:{...e,githubApp:{...n,phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}}}:t.type===`github.app.manifest.error`?{handled:!0,value:{...e,githubApp:{...n,phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}}}:{handled:!1,value:e}}function Oa(e){return/^\/[a-zA-Z]/.test(e.trimStart())}function ka(e){return!!(e&&typeof e==`object`&&typeof e.name==`string`&&e.name.startsWith(`/`)&&e.name.length>=2)}function Aa(e){let t=e.trim();if(!Oa(t))return null;let n=/^\/(\S+)\s*([\s\S]*)$/.exec(t);if(!n||!n[1])return null;let r=(n[2]??``).trim();return{name:`/${n[1].toLowerCase()}`,args:r}}function ja(e,t=[]){let n=t.filter(ka),r=n.length>0,i=n.find(t=>t.name.toLowerCase()===e.name.toLowerCase());return i?{kind:`agent`,command:i,args:e.args}:{kind:`unknown`,name:e.name,hasCatalog:r}}function Ma(e,t=[]){let n=e.trimStart().toLowerCase();if(!n.startsWith(`/`)||/\s/.test(n))return[];let r=t.filter(ka);return n===`/`?r:r.filter(e=>e.name.toLowerCase().startsWith(n)||e.aliases?.some(e=>e.toLowerCase().startsWith(n)))}function Na(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!ka(r)||n.has(r.name))continue;n.add(r.name);let e={name:r.name};typeof r.description==`string`&&r.description&&(e.description=r.description),(r.mode===`protocol`||r.mode===`prompt`)&&(e.mode=r.mode),t.push(e)}return t}function Pa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].name!==t[n].name||e[n].description!==t[n].description||e[n].mode!==t[n].mode)return!1;return!0}function Fa(e,t){let n=[];if(Array.isArray(e))for(let t of e){let e=typeof t?.url==`string`?t.url:``;if(!e)continue;let r=t?.state===`merged`||t?.state===`closed`?t.state:`open`;n.push({url:e,state:r,number:typeof t?.number==`number`?t.number:void 0,title:typeof t?.title==`string`?t.title:void 0})}return n.length===0&&typeof t==`string`&&t&&n.push({url:t,state:`open`}),n}function Ia(e){if(e&&e.length!==0)return e.find(e=>e.state===`open`)??e[0]}var La=[`read-only`,`workspace-write`,`danger-full-access`];function Ra(e){let t=String(e??``).trim().toLowerCase().replace(/_/g,`-`);return La.includes(t)?t:void 0}function za(e){let t=String(e??``).trim().toLowerCase();return[`never`,`risky`,`always`,`autonomous`].includes(t)?t:void 0}function Ba(e){let t=String(e??``).trim().toLowerCase();return[`trusted_workstation`,`isolated_customer_cloud`,`restricted`].includes(t)?t:void 0}var Va=[`guaranteed`,`degraded`,`unavailable`];function Ha(e){return!!e&&typeof e==`object`&&Va.includes(e.state)}function Ua(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion===`session-contract.v1`&&typeof t.resolvedAt==`string`&&typeof t.preview==`boolean`&&t.agent&&typeof t.agent==`object`&&typeof t.agent.id==`string`&&Ha(t.executionMode)&&Ha(t.auth)&&Ha(t.resume)&&Ha(t.toolInterception)&&Ha(t.sandbox)&&Array.isArray(t.degradedReasons)&&typeof t.requiresAcknowledgement==`boolean`)return t}function Wa(e){return typeof e==`string`&&e.startsWith(`repo:`)?e.slice(5):null}function Ga(e){return typeof e==`string`&&(e.startsWith(`issue:`)||e.startsWith(`queue:`))}function Ka(e){if(typeof e!=`string`||!e.startsWith(`issue:`))return null;let t=e.slice(6),n=t.lastIndexOf(`#`);if(n===-1)return null;let r=t.slice(0,n),i=Number(t.slice(n+1));return!r||!Number.isFinite(i)?null:{repo:r,issueNumber:i}}function qa(e){let t=e?.source,n=Wa(t),r=e?.githubIssueUrl||null;!r&&typeof t==`string`&&t.startsWith(`github:issue`)&&(r=t.split(`:`).slice(1).join(`:`)||null);let i=Fa(e?.prs,e?.prUrl);return{issueUrl:r,prUrl:(Ia(i)?.state===`open`?Ia(i)?.url:null)??e?.prUrl??null,branch:e?.branch||null,repo:n,prs:i}}function Ja(e){return qa({source:e.source,branch:e.branch,prUrl:e.prUrl,prs:e.prs})}function Ya(e){if(!e||typeof e!=`object`)return null;let t=typeof e.costUsd==`number`,n=e.tokens&&typeof e.tokens.total==`number`,r=e.plan&&Array.isArray(e.plan.windows)&&e.plan.windows.length;return!t&&!n&&!r?null:e}function Xa(e){if(!e||typeof e!=`object`)return null;let t=e.memory?.node&&typeof e.memory.node.total==`number`,n=e.cpu?.node&&typeof e.cpu.node.usedPct==`number`,r=e.storage?.node&&typeof e.storage.node.total==`number`;return!t&&!n&&!r?null:e}function Za(e){return!e||typeof e!=`object`||!e.os||typeof e.os.platform!=`string`||typeof e.generatedAt!=`string`?null:e}function Qa(e){if(!Array.isArray(e)||!e.length)return null;for(let t of e){if(typeof t?.question!=`string`||typeof t?.header!=`string`||!Array.isArray(t.options)||t.options.length===1)return null;for(let e of t.options)if(typeof e?.label!=`string`)return null}return e}function $a(e,t=[]){if(!Array.isArray(e))return[];let n=new Map(t.map(e=>[e.sessionId,e])),r=new Map;for(let t of e){let e=String(t?.sessionId||t?.id||``);if(!e||r.has(e))continue;let i=n.get(e),a=eo(t?.sessionState);r.set(e,{sessionId:e,path:t?.path||t?.sessionFile||void 0,workspace:t?.workspace||t?.bivySession?.workspace||void 0,worktree:t?.worktree||t?.bivySession?.worktree||t?.bivySession?.workspaceContext?.worktree||void 0,name:String(t?.name||`Untitled session`),source:t?.source,bivyCreated:t?.bivyCreated===!0,forkedFrom:t?.forkedFrom||void 0,delegatedFrom:t?.delegatedFrom&&typeof t.delegatedFrom.sessionId==`string`?t.delegatedFrom:void 0,nodeId:t?.nodeId||void 0,runtimeId:t?.runtimeId,agentName:t?.agentName,updatedAt:t?.updatedAt||t?.modified,needsAction:a?.agent===`awaiting-input`||!!t?.needsAction,status:no(t?.status,!!t?.needsAction,!!t?.isStreaming,a),sessionState:a,branch:t?.branch||void 0,rebuildable:t?.rebuildable?!0:void 0,sandbox:Ra(t?.sandbox??t?.bivySession?.sandbox),approvalMode:za(t?.approvalMode??t?.bivySession?.approvalMode),ephemeral:(t?.ephemeral??t?.bivySession?.ephemeral)===!0||void 0,executionProfile:Ba(t?.executionProfile??t?.bivySession?.executionProfile),contract:Ua(t?.contract??t?.bivySession?.contract),auditHealth:t?.auditHealth??t?.bivySession?.auditHealth,eventLogHealth:t?.eventLogHealth??t?.bivySession?.eventLogHealth,prUrl:t?.prUrl||void 0,prs:Fa(t?.prs,t?.prUrl),attention:Array.isArray(t?.attention)?t.attention:i?.attention,lastSeenAt:i?.lastSeenAt,finishedAt:i?.finishedAt,failedAt:i?.failedAt,launchProgress:i?.launchProgress})}return[...r.values()]}function eo(e){if(!e||typeof e!=`object`)return;let t=e;if((t.transport===`reachable`||t.transport===`unreachable`)&&(t.process===`alive`||t.process===`exited`||t.process===`none`)&&(t.agent===`idle`||t.agent===`working`||t.agent===`waiting`||t.agent===`awaiting-input`)&&(t.workspace===`clean`||t.workspace===`dirty`||t.workspace===`checkpointing`)&&(t.displayStatus===`idle`||t.displayStatus===`working`||t.displayStatus===`needs_attention`||t.displayStatus===`failed`))return t}function to(e){return e?.displayStatus===`needs_attention`?`needs_action`:e?.displayStatus}function no(e,t,n,r){return e===`saved`?`saved`:to(r)||(t||e===`needs_action`?`needs_action`:e===`working`||n?`working`:e===`failed`?`failed`:`idle`)}function ro(e){return Array.isArray(e)?e.map(e=>({id:String(e?.id||e?.model||``),label:e?.label||e?.name,...e})):[]}function io(e){let t=Array.isArray(e?.availableThinkingLevels)&&e.availableThinkingLevels.length?e.availableThinkingLevels.map(String):[`off`];return{supportsThinking:!!e?.supportsThinking,thinkingLevel:String(e?.thinkingLevel||`off`),availableThinkingLevels:t}}function ao(e,t){return!e||!t?!1:e.id===t.id&&e.provider===t.provider}function oo(e){return e?String(e.displayName||e.name||e.id||``):``}function so(e){return Qa(e)??void 0}function co(e,t){return e.approvals.some(e=>e.sessionId===t)||e.questions.some(e=>e.sessionId===t)||e.turnAttentions.some(e=>e.sessionId===t)}function lo(e,t,n){let r=t;switch(t.type){case`approval.created`:{let i=r.approval||t;return i?.id?{handled:!0,value:{...e,approvals:[...e.approvals.filter(e=>e.id!==i.id),i]},...i.sessionId?{row:{sessionId:i.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}:{handled:!0,value:e}}case`approval.resolved`:case`approval.removed`:{let t=String(r.id||r.approvalId||``),n=e.approvals.find(e=>e.id===t),i={...e,approvals:e.approvals.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.question`:{let t=String(r.requestId||``),i=so(r.questions);if(!t||!i)return{handled:!0,value:e};let a={id:t,...r.sessionId?{sessionId:String(r.sessionId)}:{},questions:i,createdAt:Number(r.createdAt)||n};return{handled:!0,value:{...e,questions:[...e.questions.filter(e=>e.id!==t),a]},...a.sessionId?{row:{sessionId:a.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}}case`session.question.resolved`:{let t=String(r.requestId||r.id||``),n=e.questions.find(e=>e.id===t),i={...e,questions:e.questions.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.turn_attention`:{let t=String(r.sessionId||``),i=r.trigger===`wedged`||r.trigger===`stalled`?r.trigger:void 0;if(!t||!i)return{handled:!0,value:e};let a={sessionId:t,trigger:i,idleMs:Math.max(0,Number(r.idleMs)||0),at:Number(r.at)||n,message:String(r.message||`This turn may be stuck. Stop it or keep waiting?`)};return{handled:!0,value:{...e,turnAttentions:[...e.turnAttentions.filter(e=>e.sessionId!==t),a]},row:{sessionId:t,status:`needs_action`,needsAction:!0,updatedAt:n}}}case`session.turn_attention.resolved`:{let t=String(r.sessionId||``);if(!t)return{handled:!0,value:e};let n={...e,turnAttentions:e.turnAttentions.filter(e=>e.sessionId!==t)};return{handled:!0,value:n,...co(n,t)?{}:{row:{sessionId:t,status:`working`,needsAction:!1}}}}default:return{handled:!1,value:e}}}function uo(e,t){return!!t&&t!==e}function fo(e){return(Array.isArray(e.actions)?e.actions:[e.action]).filter(e=>typeof e==`string`&&e.length>0)}function po(e,t,n){let r=t,i=String(r.sessionId||``);switch(t.type){case`session.state`:{let t=eo(r.state??r.sessionState);return!i||!t?{handled:!0,commands:[]}:{handled:!0,patch:i===e.activeSessionId?{working:t.agent===`working`,...t.agent===`working`?{}:{workingLabel:``}}:void 0,commands:[{kind:`row`,sessionId:i,patch:{sessionState:t,status:to(t),needsAction:t.displayStatus===`needs_attention`}}]}}case`session.renamed`:{let t=[];return r.name&&i&&t.push({kind:`rename`,sessionId:i,name:String(r.name)}),r.branch&&i&&t.push({kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}),{handled:!0,patch:!i||i===e.activeSessionId?{...r.name?{activeTitle:String(r.name)}:{},...r.branch?{github:{...e.github,branch:String(r.branch)}}:{}}:void 0,commands:t}}case`session.branch_renamed`:return{handled:!0,patch:(!i||i===e.activeSessionId)&&r.branch?{github:{...e.github,branch:String(r.branch)}}:void 0,commands:r.branch&&i?[{kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}]:[]};case`session.error`:case`session.errored`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=r.error&&typeof r.error==`object`?r.error:null,n=t?.kind===`model_auth`&&typeof t.provider==`string`,i=n?`No credentials for ${t.provider}`:je(String(r.error||r.errorMessage||`error`)),a={kind:`entry`,role:`error`,text:i,...n?{actions:[`connect-provider:${t.provider}`]}:{}};return{handled:!0,patch:{...String(r.code||``).startsWith(`delivery_`)?{}:{working:!1},opening:!1},commands:r.sessionId?[a]:[{kind:`global-error`,message:i}]}}case`session.closed`:return{handled:!0,patch:i===e.activeSessionId?{working:!1,workingLabel:``,opening:!1}:void 0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`saved`,needsAction:!1}}]:[]};case`session.failed`:return{handled:!0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`failed`,needsAction:!1,failedAt:Number(r.failedAt)||n,updatedAt:n}}]:[]};case`session.notice`:{if(!r.message||i&&i!==e.activeSessionId)return{handled:!0,commands:[]};let t=fo(r);return{handled:!0,commands:[{kind:`entry`,role:`system`,text:String(r.message),...t.length?{actions:t}:{}}]}}case`session.cloning`:return{handled:!0,patch:!i||i===e.activeSessionId?{working:!0,workingLabel:`Cloning ${r.repo||`repo`}…`}:void 0,commands:[]};case`session.auth_required`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.provider?[{kind:`model-auth`,provider:String(r.provider),reason:String(r.reason||``)}]:[]};case`session.usage`:return{handled:!0,patch:uo(e.activeSessionId,r.sessionId)?void 0:{usage:Ya(r.usage)},commands:[]};case`session.warning`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.warning?[{kind:`entry`,role:`system`,text:String(r.warning)}]:[]};case`session.changes`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=Array.isArray(r.changes)?r.changes:[];if(!t.length)return{handled:!0,patch:{changes:null},commands:[]};let i={before:r.before?String(r.before):void 0,after:String(r.after??``),files:t};return{handled:!0,patch:{changes:i,changesHistory:[...e.changesHistory,{...i,id:e.newChangeId??`change-${e.changesHistory.length+1}`,at:n}]},commands:[]}}case`session.rewound`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{changes:null},commands:[{kind:`entry`,role:`system`,text:`Rewound the workspace to an earlier checkpoint.`}]};case`session.checkpoints`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{checkpoints:Array.isArray(r.checkpoints)?r.checkpoints.map(e=>({id:String(e.id??``),label:String(e.label??`checkpoint`),createdAt:Number(e.createdAt??0)})).filter(e=>e.id):[]},commands:[]};default:return{handled:!1,commands:[]}}}var mo=e=>{let t=e;return!!t&&typeof t.hash==`string`&&/^[0-9a-f]{64}$/.test(t.hash)&&[t.size,t.width,t.height].every(e=>typeof e==`number`&&e>=0)};function ho(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&(t.trigger===`present`||t.trigger===`run`||t.trigger===`asked`||t.trigger===`notes`)&&typeof t.at==`number`&&(t.shot===void 0||mo(t.shot))&&(t.before===void 0||mo(t.before))&&(t.note===void 0||typeof t.note==`string`)&&(t.notes===void 0||Number.isInteger(t.notes)&&t.notes>=0)}var go=[`open`,`changed`,`gone`,`done`];function _o(e){if(!e||typeof e!=`object`)return!1;let t=e,n=(e,t)=>!!e&&typeof e==`object`&&t.every(t=>typeof e[t]==`number`);return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&typeof t.words==`string`&&typeof t.at==`number`&&(t.number===void 0||Number.isInteger(t.number)&&t.number>=1)&&Array.isArray(t.selectors)&&t.selectors.every(e=>typeof e==`string`)&&n(t.region,[`x`,`y`,`width`,`height`])&&n(t.viewport,[`width`,`height`])&&go.includes(t.state)&&(t.shot===void 0||mo(t.shot))}function vo(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.sessionId==`string`&&t.sessionId.length>0&&typeof t.name==`string`&&t.name.length<=100}var yo=[{id:`1h`,label:`1 hour`,ms:36e5},{id:`1d`,label:`1 day`,ms:864e5},{id:`7d`,label:`7 days`,ms:6048e5}],bo=[`here`,`subagents`,`new`],xo=e=>e===void 0||bo.includes(e);function So(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.title===void 0||typeof t.title==`string`)&&xo(t.run)}function Co(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.urgent===void 0||typeof t.urgent==`boolean`)}function wo(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.status==`string`&&typeof t.task==`string`&&[t.agent,t.machine,t.nodeId,t.group,t.childSessionId,t.answer,t.branch,t.prUrl,t.failure].every(e=>e===void 0||typeof e==`string`)}function To(e){return!!e&&e.type===`bivy_attachment`&&!!e.ref&&typeof e.ref.hash==`string`&&(e.ref.kind===`image`||e.ref.kind===`file`)}function Eo(e,t){return{kind:e.kind,name:e.name,size:e.size,mimeType:e.mimeType,hash:e.hash,...t?.createdAt===void 0?{}:{createdAt:t.createdAt},...t?.artifact?{artifact:!0}:{}}}var Do=0,Y=()=>`e${Date.now().toString(36)}-${(Do++).toString(36)}`;function Oo(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`text`||t===`output_text`||!t&&typeof e?.text==`string`}function ko(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`thinking`||t===`reasoning`}var Ao=/^\s*(?:\[Request interrupted by user|<(?:task-notification|system-reminder)[\s>/])/;function jo(e){return Ao.test(e)}function Mo(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.filter(Oo).map(e=>String(e?.text??e?.content??``)).join(`
|
|
20
20
|
`);if(e&&typeof e==`object`){let t=e.text??e.content??e.output??e.result;if(typeof t==`string`)return t;if(t!==void 0)return Mo(t);try{return JSON.stringify(e)}catch{return String(e)}}return e==null?``:String(e)}function No(e){return Array.isArray(e)?e.filter(ko).map(e=>String(e?.text??e?.thinking??e?.reasoning??``)).join(`
|
|
21
21
|
`):``}function Po(e){if(Array.isArray(e)){let t=e.filter(Oo).map(e=>String(e?.text??e?.content??``)).join(`
|
|
22
22
|
`);if(t)return t;try{return JSON.stringify(e)}catch{return String(e)}}return Mo(e)}function Fo(e,t,n=Y){if(!Array.isArray(e))return[];let r=[];for(let i of e)if(Ce(i)){let e=ke(i)||t||``;r.push({callId:Oe(i)||n(),name:Te(i),input:Ee(i),status:`running`,detail:j(i),...e?{parentToolUseId:e}:{}})}else if(we(i)){let e=Oe(i),t=Po(i?.content),n=j(i),a=(i?.isError||i?.is_error)&&n?{...n,result:{...n.result??{},isError:!0}}:i?.isError||i?.is_error?{kind:`unknown`,result:{isError:!0}}:n;r.push({callId:e,name:Te(i),input:{},status:`done`,result:t,...a?{detail:a}:{}})}return r}function Io(e){return{callId:String(e?.toolCallId||e?.toolUseId||e?.tool_use_id||e?.id||``),name:String(e?.toolName||e?.name||`tool`).toLowerCase(),input:{},status:`done`,result:Po(e?.content),detail:e?.isError||e?.is_error?j(e)??{kind:`unknown`,result:{isError:!0}}:j(e)}}function Lo(e){let t=new Map;function n(e){if(!e||typeof e!=`object`)return;if(To(e)){t.set(e.ref.hash,Eo(e.ref));return}if(Array.isArray(e)){e.forEach(n);return}let r=e;r.content&&n(r.content)}return n(e),[...t.values()]}function Ro(e){let t=[],n=new Set,r=-1,i=0,a=()=>`h${r}.${i++}`;for(let o of e||[]){r++,i=0;let e=String(o?.role||`assistant`).toLowerCase(),s=o?.content,c=Mo(s);if(e===`user`){if(Array.isArray(s)){for(let e of s)if(we(e))for(let n of Fo([e],void 0,a))Vo(t,n,a)}let e=Lo(s);(c&&!jo(c)||e.length)&&t.push({id:a(),role:`user`,text:c,...e.length?{attachments:e}:{}})}else if(e===`system`)c&&!jo(c)&&t.push({id:a(),role:`system`,text:c});else if(e===`toolresult`||e===`tool_result`){let e=Io(o);e&&Vo(t,e,a)}else{let e=ke(o),n=e=>{let n=e.trim();n&&t.push(Me(n)?{id:a(),role:`error`,text:je(n)}:{id:a(),role:`assistant`,text:n})},r=e=>{let n=e.trim();n&&t.push({id:a(),role:`thinking`,text:n})};if(typeof s==`string`||!Array.isArray(s))n(c);else{let i=[],c=[],l=()=>{n(i.join(`
|
|
@@ -24,4 +24,4 @@ if [ -d "$BIVY_PACKAGE_DIR/node_modules/.bin" ]; then export PATH="$BIVY_PACKAGE
|
|
|
24
24
|
`)),c=[]},d=()=>{l(),u()};for(let n of s)if(Ce(n)||we(n)){d();for(let r of Fo([n],e,a))Vo(t,r,a)}else if(n?.type===`bivy_app`&&vo(n.app))d(),t.push({id:`app-${n.app.appId}`,role:`assistant`,text:``,app:n.app});else if(n?.type===`bivy_suggestion`&&So(n.suggestion))d(),t.push({id:n.suggestion.id,role:`assistant`,text:``,suggestion:n.suggestion});else if(n?.type===`bivy_notice`&&Co(n.notice))d(),t.push({id:n.notice.id,role:`assistant`,text:``,notice:n.notice});else if(n?.type===`bivy_delegation`&&wo(n.delegation))d(),t.push({id:`delegation-${n.delegation.id}`,role:`assistant`,text:``,delegation:n.delegation});else if(n?.type===`bivy_app_review`&&ho(n.review))d(),t.push({id:n.review.id,role:`assistant`,text:``,review:n.review});else if(n?.type===`bivy_app_pin`&&_o(n.pin))d(),t.push({id:n.pin.id,role:`assistant`,text:``,pin:n.pin});else if(To(n)){d();let e=typeof o?.createdAt==`number`?o.createdAt:void 0;t.push({id:a(),role:`assistant`,text:typeof n.caption==`string`?n.caption:``,attachments:[{...Eo(n.ref,{createdAt:e,artifact:n.artifact}),description:typeof n.caption==`string`?n.caption:void 0}]})}else Oo(n)?(u(),i.push(String(n?.text??n?.content??``))):ko(n)?(l(),c.push(String(n?.thinking??n?.reasoning??n?.text??``))):String(n?.type||``).toLowerCase()===`bivy_message_boundary`&&d();d()}o?.stopReason===`error`&&typeof o?.errorMessage==`string`&&o.errorMessage.trim()&&t.push({id:a(),role:`error`,text:je(o.errorMessage)})}if(e!==`user`&&e!==`system`){let r=e===`toolresult`||e===`tool_result`?[{id:o.toolCallId||o.toolUseId||o.tool_use_id||o.id,content:s}]:Array.isArray(s)?s.filter(we).map(e=>({id:Oe(e),content:e.content})):[];for(let e of r){let r=Lo(e.content).filter(t=>{let r=`${e.id||``}:${t.hash}`;return!n.has(r)&&(n.add(r),!0)});r.length&&t.push({id:a(),role:`assistant`,text:``,attachments:r})}}}let o=new Map;for(let e of t){let t=o.get(e.id)??0;o.set(e.id,t+1),t&&(e.id=`${e.id}~${t}`)}return t}function zo(e){return e&&e.replace(/\n*---\s*File attachment:[\s\S]*?---\s*end[^\n]*---/g,``).replace(/\[(?:Image|File) attachment:[^\]\n]*\]/g,``).replace(/[ \t]+\n/g,`
|
|
25
25
|
`).replace(/\n{3,}/g,`
|
|
26
26
|
|
|
27
|
-
`).trim()}function Bo(e,t){return e&&typeof e==`object`&&!Array.isArray(e)&&t&&typeof t==`object`&&!Array.isArray(t)?{...e,...t}:t??e}function Vo(e,t,n=Y){let r=t.callId?e.find(e=>e.tool&&e.tool.callId===t.callId):[...e].reverse().find(e=>e.tool&&e.tool.status===`running`&&(t.name===`tool`||e.tool.name===t.name));r&&r.tool?r.tool={...r.tool,status:t.status,result:t.result??r.tool.result,detail:t.detail??r.tool.detail,parentToolUseId:t.parentToolUseId??r.tool.parentToolUseId,name:t.status===`done`&&t.name===`tool`?r.tool.name:t.name,input:t.status===`running`?Bo(r.tool.input,t.input):r.tool.input}:e.push({id:n(),role:`assistant`,text:``,tool:t})}function Ho(e=!0){return{assistantId:null,thinkingId:null,finalized:e,thinkingText:``,sawThinking:!1,pendingText:``,committedText:``,committedThinking:``}}function Uo(e){return{...e,transcript:[...e.transcript],draft:{...e.draft}}}function Wo(e){let t=e.length+1,n=new Set(e.map(e=>e.id));for(;n.has(`live-${t}`);)t+=1;return`live-${t}`}function Go(e,t){let n={id:Wo(e.transcript),...t};return e.transcript.push(n),n}function Ko(e,t,n){e.transcript=e.transcript.map(e=>e.id===t?{...e,...n}:e)}function qo(e,t){e.transcript=e.transcript.filter(e=>e.id!==t)}function Jo(e,t){e.working=!0,e.workingLabel=t}function Yo(e,t,n,r){let i=t===`assistant`?`assistant`:`thinking`,a=t===`assistant`?`assistantId`:`thinkingId`,o=i===`assistant`&&r?ye(n):void 0,s=e.draft[a];s?Ko(e,s,{text:n,html:o,streaming:!r}):(s=Go(e,{role:i,text:n,html:o,streaming:!r}).id,e.draft[a]=s),r&&(e.draft[a]=null)}function Xo(e){e.draft.assistantId&&Ko(e,e.draft.assistantId,{streaming:!1}),e.draft.thinkingId&&Ko(e,e.draft.thinkingId,{streaming:!1}),e.draft.assistantId=null,e.draft.thinkingId=null}function Zo(e){let t=e.draft;if(!t.sawThinking)return;let n=(t.thinkingText.startsWith(t.committedThinking)?t.thinkingText.slice(t.committedThinking.length):t.thinkingText).trim();n&&(t.committedThinking=t.thinkingText,t.thinkingId=null,Yo(e,`thinking`,n,!0))}function Qo(e){return(e.pendingText.startsWith(e.committedText)?e.pendingText.slice(e.committedText.length):e.pendingText).trim()}function $o(e){let t=Qo(e.draft);t&&(e.draft.committedText=e.draft.pendingText,Me(t)?(e.draft.assistantId&&(qo(e,e.draft.assistantId),e.draft.assistantId=null),Go(e,{role:`error`,text:je(t)})):Yo(e,`assistant`,t,!0))}function es(e){let t=Qo(e.draft);t&&Yo(e,`assistant`,t,!1)}function ts(e){let t=e?.assistantMessageEvent;return t?.type===`thinking_delta`&&typeof t.delta==`string`?{kind:`delta`,text:t.delta}:t?.type===`thinking_end`&&typeof t.content==`string`?{kind:`full`,text:t.content}:{kind:`none`,text:``}}function ns(e,t,n){if(t)n.thinkingText=t;else{let t=ts(e);t.kind===`delta`?n.thinkingText+=t.text:t.kind===`full`&&(n.thinkingText=t.text)}return n.thinkingText.trim()}function rs(e,t){return e&&t&&typeof e==`object`&&typeof t==`object`&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t??e}function is(e,t){let n=t.callId?e.transcript.findIndex(e=>e.tool?.callId===t.callId):-1;if(n<0){Go(e,{role:`assistant`,text:``,tool:t});return}let r=e.transcript[n],i=r.tool;e.transcript[n]={...r,tool:{...i,status:t.status,result:t.result??i.result,detail:t.detail??i.detail,parentToolUseId:t.parentToolUseId??i.parentToolUseId,input:t.status===`running`?rs(i.input,t.input):i.input}}}function as(e){e.transcript=e.transcript.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function os(e,t){let n=Oe(e);if(n)return n;let r=Te(e),i=Ee(e),a=String(i?.command||i?.cmd||i?.path||i?.file||i?.filePath||i?.query||i?.stream||``);return a||r===`agent_output`||r===`stderr`||r===`stdout`?`${r}:${a}`:Wo(t)}function ss(e,t){let n=Te(e);if(n===`agent_output`||n===`stderr`||n===`stdout`)return`Reading agent output…`;let r=Oe(e),i=j(e)??(r?t.find(e=>e.tool?.callId===r)?.tool?.detail:void 0);return i?.kind===`delegation`?i.label?`${i.label} sub-agent is working…`:`Sub-agent is working…`:`Running ${n}…`}function cs(e,t){return e.some(e=>e.attachments?.some(e=>e.hash===t))}function ls(e,t,n){let r=xe(t);if(!r)return{handled:!1,value:e,commands:[]};let i=Uo(e),a=[];switch(r){case`agent_start`:case`turn_start`:i.draft.finalized=!1,Jo(i,r===`agent_start`?`Planning…`:`Thinking…`);break;case`message_start`:t.message?.role===`assistant`&&(i.draft.finalized&&(i.draft=Ho(!1)),Jo(i,`Drafting response…`));break;case`app_published`:{let e=t.app;if(!vo(e))break;i.transcript.some(t=>t.app?.appId===e.appId)||i.transcript.push({id:`app-${e.appId}`,role:`assistant`,text:``,app:e});break}case`delegation`:{let e=t.delegation;if(!wo(e))break;let n={id:`delegation-${e.id}`,role:`assistant`,text:``,delegation:e},r=i.transcript.findIndex(t=>t.delegation?.id===e.id);r>=0?i.transcript[r]=n:(Zo(i),$o(i),i.transcript.push(n));break}case`suggestion`:{let e=t.suggestion;if(!So(e)||i.transcript.some(t=>t.suggestion?.id===e.id))break;i.transcript.push({id:e.id,role:`assistant`,text:``,suggestion:e});break}case`notice`:{let e=t.notice;if(!Co(e)||i.transcript.some(t=>t.notice?.id===e.id))break;Zo(i),$o(i),i.transcript.push({id:e.id,role:`assistant`,text:``,notice:e});break}case`app_review`:{let e=t.review;if(!ho(e))break;let n=i.transcript.findIndex(t=>t.review?.id===e.id),r={id:e.id,role:`assistant`,text:``,review:e};n>=0&&e.expired?i.transcript[n]=r:(n>=0&&i.transcript.splice(n,1),i.transcript.push(r));break}case`app_pin`:{let e=t.pin;if(!_o(e))break;let n=i.transcript.findIndex(t=>t.pin?.id===e.id),r={id:e.id,role:`assistant`,text:``,pin:e};n>=0?i.transcript[n]=r:i.transcript.push(r);break}case`attachment`:{let r=t.ref;if(!r||typeof r.hash!=`string`||r.kind!==`image`&&r.kind!==`file`)return{handled:!0,value:e,commands:[]};if(cs(i.transcript,r.hash))break;let o=typeof t.caption==`string`?t.caption:``;Go(i,{role:`assistant`,text:o,attachments:[{kind:r.kind,name:r.name,size:r.size,mimeType:r.mimeType,hash:r.hash,description:o||void 0,createdAt:n,...t.artifact?{artifact:!0}:{}}]}),a.push({kind:`remember-agent-attachments`});break}case`inlineImage`:{let n=t.url,r=t.ref;if(typeof n!=`string`||!n||!r||typeof r.hash!=`string`)return{handled:!0,value:e,commands:[]};a.push({kind:`cache-inline-image`,url:n,ref:r}),i.transcript=i.transcript.map(e=>e.role===`assistant`&&e.text?.includes(n)&&!e.imageRefs?.[n]?{...e,imageRefs:{...e.imageRefs??{},[n]:r}}:e);break}case`message_update`:case`message_boundary`:case`message_end`:{let n=t.message;if(n?.role!==`assistant`)return{handled:!0,value:e,commands:[]};let a=Mo(n.content).trim();if(a&&(i.draft.pendingText=a),ns(t,No(n.content).trim(),i.draft)&&!a&&(i.draft.sawThinking=!0),r===`message_end`||r===`message_boundary`)Zo(i),$o(i),i.draft.finalized=!0;else{let e=a?`Drafting response…`:`Thinking…`;(!i.working||i.workingLabel!==e)&&Jo(i,e),es(i)}for(let e of Fo(n.content))is(i,e);break}case`start`:Zo(i),$o(i),Xo(i),is(i,{callId:os(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Jo(i,ss(t,i.transcript));break;case`update`:is(i,{callId:os(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Jo(i,ss(t,i.transcript));break;case`result`:is(i,{callId:os(t,i.transcript),name:Te(t),input:{},status:`done`,result:typeof t.result==`string`?t.result:Mo(t.result),detail:j(t)});break;case`turn_end`:Jo(i,`Planning next step…`);break;case`agent_end`:Xo(i),as(i),Object.assign(i.draft,{pendingText:``,committedText:``,committedThinking:``}),i.working=!1,i.workingLabel=``,a.push({kind:`turn-settled`});break;default:return{handled:!1,value:e,commands:[]}}if(r===`result`||r===`message_end`||r===`message_boundary`){let e=Lo(t.result??t.message??t.output).filter(e=>!cs(i.transcript,e.hash));e.length&&(Go(i,{role:`assistant`,text:``,attachments:e}),a.push({kind:`remember-agent-attachments`}))}return{handled:!0,value:i,commands:a}}function X(e,t=!1){return{queue:e,changed:!1,accepted:t}}function us(e,t){switch(t.type){case`enqueue`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`queued`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`schedule`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`scheduled`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`attach-automation`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAutomationId:t.automationId},{queue:r,changed:!0,accepted:!0}}case`edit`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return{...X(e),edit:{ok:!1,reason:`not_found`}};let r=e[n];if(r.status!==`queued`)return{...X(e),edit:{ok:!1,reason:`not_queued`}};if(r.version!==t.expectedVersion)return{...X(e),edit:{ok:!1,reason:`stale`}};let i={...r,...t.patch,version:r.version+1,updatedAt:t.now,scheduledAutomationId:void 0},a=e.slice();return a[n]=i,{queue:a,changed:!0,accepted:!0,item:i,edit:{ok:!0,item:i}}}case`remove`:{let n=e.find(e=>e.id===t.id);return!n||n.status!==`queued`&&n.status!==`scheduled`?X(e):{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}}case`prune-scheduled`:{let n=e.filter(e=>e.status!==`scheduled`||(e.scheduledAutomationId?t.keepIds.includes(e.scheduledAutomationId):!1));return n.length===e.length?X(e):{queue:n,changed:!0,accepted:!0}}case`reschedule`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`scheduled`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAt:t.scheduledAt,updatedAt:t.now,version:e[n].version+1},{queue:r,changed:!0,accepted:!0}}case`reorder`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=Math.max(0,Math.min(t.toIndex,e.length-1));if(r===n)return X(e,!0);let i=e.slice(),[a]=i.splice(n,1);return i.splice(r,0,a),{queue:i,changed:!0,accepted:!0}}case`mark-sending`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return X(e);let r={...e[n],status:`sending`,updatedAt:t.now},i=e.slice();return i[n]=r,{queue:i,changed:!0,accepted:!0,item:r}}case`confirm-sent`:return e.some(e=>e.id===t.id)?{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}:X(e);case`revert-to-queued`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`sending`)return X(e);let r={...e[n],status:`queued`,updatedAt:t.now};return{queue:[r,...e.filter(e=>e.id!==t.id)],changed:!0,accepted:!0,item:r}}case`settle-sending`:return e.some(e=>e.status===`sending`)?{queue:e.filter(e=>e.status!==`sending`),changed:!0,accepted:!0}:X(e);case`clear`:return e.length?{queue:[],changed:!0,accepted:!0}:X(e,!0)}}function ds(e){return e.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function fs(e){return e===`openai-codex`?`openai`:e}var ps=[`status`,`signedIn`,`nodes`,`currentNodeId`,`nodeUpdate`,`nodeUpdating`,`nodeUpdateAcknowledged`],ms=[`sessions`,`runTerminals`,`tuiSessions`,`pausedSessionIds`,`commandsBySession`,`followupsBySession`],hs=[`activeSessionId`,`activeRuntimeId`,`activeTitle`,`github`,`transcript`,`working`,`workingLabel`,`opening`,`approvals`,`questions`,`turnAttentions`,`usage`,`changes`,`changesHistory`,`checkpoints`],gs=[`models`,`modelsRuntimeId`,`currentModelId`,`currentModel`,`thinking`,`runtimes`,`currentAgentName`,`selectedAgentId`,`installingRuntimeId`,`repos`,`reposAuthed`,`reposError`,`reposLoading`,`reposReason`,`githubConnect`,`branches`,`branchesRepo`,`branchesDefault`,`branchesError`,`branchesLoading`,`providers`,`activationReadiness`],_s=[`nodeSettings`,`providerAuth`,`credentialRecords`,`credentialPresets`,`localModels`,`localModelPresets`,`rulesets`,`sttConfig`,`nodeStats`,`capabilities`],vs=[`forkProgress`,`oauth`,`needsModelAuth`,`githubApp`,`prResult`,`prRefreshAllResult`,`error`,`notice`];function ys(e,t,n){let r=[];for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&r.push([e,t[e]]);return r.length?{...e,...Object.fromEntries(r)}:e}function bs(){return{connection:{status:`offline`,signedIn:!1,nodes:[],currentNodeId:null,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1},sessionIndex:{sessions:[],runTerminals:[],tuiSessions:[],pausedSessionIds:[],commandsBySession:{},followupsBySession:{}},activeSession:{activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[]},catalogs:{models:[],modelsRuntimeId:null,currentModelId:null,currentModel:null,thinking:{supportsThinking:!1,thinkingLevel:`off`,availableThinkingLevels:[`off`]},runtimes:[],currentAgentName:`Agent`,selectedAgentId:null,installingRuntimeId:null,repos:[],reposAuthed:!0,reposError:null,reposLoading:!1,reposReason:null,githubConnect:{status:`idle`},branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,providers:[],activationReadiness:null},settings:{nodeSettings:null,providerAuth:null,credentialRecords:[],credentialPresets:null,localModels:[],localModelPresets:[],rulesets:[],sttConfig:null,nodeStats:null,capabilities:null},presentation:{oauth:null,needsModelAuth:null,githubApp:null,prResult:null,prRefreshAllResult:null,error:null,errorActions:[],notice:null,forkProgress:null},draft:{...va}}}function xs(e=!0){return Ho(e)}function Ss(e){return e.role===`assistant`&&!e.tool&&!!e.attachments?.length}function Cs(e){return e.tool?`tool:${e.tool.callId}`:`${e.role}:${e.text}`}function ws(e,t){let n=-1,r=e.length;for(let i=0,a=0;i<e.length;i++)if(e[i].role===`user`){if(a+=1,a===t.turn)n=i+1;else if(a===t.turn+1){r=i;break}}if(n<0)return t.turn===0?Ts(e,0,r):e.length;if(!t.after)return Ts(e,n,r);for(let i=r-1;i>=n;i--){let n=e[i];if(!Ss(n)&&Cs(n)===t.after)return Ts(e,i+1,r)}return r}function Ts(e,t,n){for(;t<n&&Ss(e[t]);)t++;return t}var Es=class e{state=bs();listeners=new Set;notifyPending=!1;notifyHandle=null;draft=xs();knownAgentAttachmentsBySession=new Map;draftModel=null;modelsByRuntime=new Map;cachedModelsFor(e){return this.modelsByRuntime.get(e)?.models}pending=new Map;usersBeforePending=0;attachmentsByText=new Map;static ATTACHMENTS_CACHE_MAX=100;inlineImagesByUrl=new Map;transcriptCache=new Map;static CACHE_MAX=30;recentlyDeleted=new Map;historyRaw=new Map;deferredHistory=null;awaitingOpenHistory=!1;onHistoryPersist;requestReplay;seqReassembler=new xa;seqSessionId;seqEpoch;trackSeqStream(e,t){let n=typeof t==`string`?t:void 0;(this.seqSessionId!==e||this.seqEpoch!==n)&&(this.seqReassembler.reset(),this.seqSessionId=e,this.seqEpoch=n)}requestFreshHistory;onSessionSettled;onSessionCreatedElsewhere;getState=()=>this.state;setGithubAppPhase(e,t={}){this.set({githubApp:{...this.state.presentation.githubApp||{phase:`idle`},phase:e,...t}})}setGithubConnect(e){this.set({githubConnect:e})}getHistoryCursor(e){let t=this.historyRaw.get(e);return t&&t.count>0&&t.historyHash?{have:t.count,haveToken:t.historyHash}:{}}seedHistory(e,t,n,r){if(!e||!r||!Array.isArray(t))return;this.historyRaw.set(e,{messages:t,count:n,historyHash:r});let i=this.withInlineImageRefs(this.withCachedAttachments(Ro(t)));this.cacheTranscript(e,i),this.state.activeSession.activeSessionId===e&&this.state.activeSession.transcript.length===0&&this.set({transcript:i,opening:!1})}getCachedTranscript(e){return this.transcriptCache.get(e)}withPendingUserEntries(e){if(this.pending.size===0)return e;let t=new Set(e.map(e=>e.id)),n=new Map,r=0;for(let t of e)t.role===`user`&&(n.set(t.text,(n.get(t.text)||0)+1),r+=1);let i=e=>{if(!e)return!1;let t=n.get(e)||0;return t<=0?!1:(n.set(e,t-1),!0)},a=[],o=0;for(let[e,n]of this.pending)if(!t.has(n.entry.id)){if(i(n.confirmedText)||i(n.entry.text)){n.confirmed?this.retirePending(e):n.reconciled=!0,o+=1;continue}n.reconciled=!1,a.push({cmid:e,entry:n.entry,confirmed:n.confirmed})}let s=r-this.usersBeforePending-o,c=[];for(let{cmid:e,entry:t,confirmed:n}of a){if(s>0&&n){--s,this.retirePending(e);continue}c.push(t)}return this.pending.size===0&&(this.usersBeforePending=0),c.length?[...e,...c]:e}retirePending(e){this.pending.delete(e)}rememberAttachments(t,n){if(t&&n.length&&(this.attachmentsByText.delete(t),this.attachmentsByText.set(t,n),this.attachmentsByText.size>e.ATTACHMENTS_CACHE_MAX)){let e=this.attachmentsByText.keys().next().value;e!==void 0&&this.attachmentsByText.delete(e)}}attachmentsForHistory(e){if(this.attachmentsByText.size===0)return[];let t=[];for(let n of Ro(e)){if(n.role!==`user`||!n.text)continue;let e=this.attachmentsByText.get(n.text);e&&t.push([n.text,e])}return t}restoreAttachments(e){if(e&&e.length)for(let[t,n]of e)this.rememberAttachments(t,n)}foldAttachmentRefs(e){if(e&&e.length)for(let[t,n]of e){if(!t||!n.length||this.attachmentsByText.has(t))continue;let e=n.map(e=>({kind:e.kind,name:e.name,size:e.size,mimeType:e.mimeType,hash:e.hash}));this.rememberAttachments(t,e)}}withCachedAttachments(e){if(this.attachmentsByText.size===0)return e;let t=!1,n=e.map(e=>{if(e.role!==`user`||!e.text)return e;let n=this.attachmentsByText.get(e.text);return n?(t=!0,{...e,attachments:n}):e});return t?n:e}foldInlineImageRefs(e){if(e&&e.length)for(let[t,n]of e)t&&n&&this.inlineImagesByUrl.set(t,n)}withInlineImageRefs(e){if(this.inlineImagesByUrl.size===0)return e;let t=!1,n=e.map(e=>{if(e.role!==`assistant`||!e.text)return e;let n=oe(e.text);if(!n.length)return e;let r;for(let t of n){let n=this.inlineImagesByUrl.get(t);n&&!e.imageRefs?.[t]&&(r??={...e.imageRefs??{}},r[t]=n)}return r?(t=!0,{...e,imageRefs:r}):e});return t?n:e}cacheTranscript(t,n){if(t&&(this.transcriptCache.delete(t),this.transcriptCache.set(t,n),this.transcriptCache.size>e.CACHE_MAX)){let e=this.transcriptCache.keys().next().value;e!==void 0&&this.transcriptCache.delete(e)}}beginOpen(e){this.draft=xs(),this.deferredHistory=null,this.awaitingOpenHistory=!0,this.pending.clear(),this.usersBeforePending=0;let t=this.transcriptCache.get(e),n=this.state.sessionIndex.sessions.find(t=>t.sessionId===e);this.set({activeSessionId:e,activeRuntimeId:n?.runtimeId??null,currentAgentName:n?.agentName||oo(this.state.catalogs.runtimes.find(e=>e.id===n?.runtimeId))||``,currentModel:null,currentModelId:null,models:[],modelsRuntimeId:n?.runtimeId??null,sessions:n?this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,lastSeenAt:Date.now()}:t):this.state.sessionIndex.sessions,...n?.name?{activeTitle:n.name}:{},github:n?Ja(n):{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:t??[],working:!1,workingLabel:``,opening:!t||t.length===0,usage:null,changes:null,changesHistory:[],checkpoints:[]})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));set(e){let t=ys(this.state.connection,e,ps),n=ys(this.state.sessionIndex,e,ms),r=ys(this.state.activeSession,e,hs),i=ys(this.state.catalogs,e,gs),a=ys(this.state.settings,e,_s),o=ys(this.state.presentation,e,vs);this.setValues({connection:t,sessionIndex:n,activeSession:r,catalogs:i,settings:a,presentation:o,draft:e.draft??this.state.draft})}setValues(e){if(this.state={...this.state,...e},this.state.activeSession.working){this.scheduleNotify();return}this.flushNotify()}scheduleNotify(){if(this.notifyPending)return;this.notifyPending=!0;let e=()=>{this.notifyPending=!1,this.notifyHandle=null;for(let e of this.listeners)e()};this.notifyHandle=typeof globalThis.requestAnimationFrame==`function`?globalThis.requestAnimationFrame(e):setTimeout(e,16)}flushNotify(){if(!this.notifyPending){for(let e of this.listeners)e();return}let e=this.notifyHandle;this.notifyPending=!1,this.notifyHandle=null,e!==null&&(typeof globalThis.cancelAnimationFrame==`function`&&typeof e==`number`?globalThis.cancelAnimationFrame(e):clearTimeout(e));for(let e of this.listeners)e()}mergeRuntimeCapabilities(e,t){let n=e?String(e):``;if(!n||!t||typeof t!=`object`)return;let r=this.state.catalogs.runtimes.findIndex(e=>e.id===n),i=r>=0?this.state.catalogs.runtimes[r]:void 0;if(!i)return;let a=i.capabilities||{},o={...t};delete o.commands;let s={...a,...o};if(JSON.stringify(s)===JSON.stringify(a))return;let c=this.state.catalogs.runtimes.slice();c[r]={...i,capabilities:s},this.set({runtimes:c})}setSessionCommands(e,t){let n=e?String(e):``;if(!n)return;let r=Na((t&&typeof t==`object`?t:void 0)?.commands);if(Pa(this.state.sessionIndex.commandsBySession[n]??[],r))return;let i={...this.state.sessionIndex.commandsBySession};r.length?i[n]=r:delete i[n],this.set({commandsBySession:i})}dropSessionCommands(e){if(!(e in this.state.sessionIndex.commandsBySession))return;let t={...this.state.sessionIndex.commandsBySession};delete t[e],this.set({commandsBySession:t})}getFollowups(e){return this.state.sessionIndex.followupsBySession[e]??[]}setFollowupsFor(e,t){let n={...this.state.sessionIndex.followupsBySession};t.length?n[e]=[...t]:delete n[e],this.set({followupsBySession:n})}transitionFollowups(e,t){let n=us(this.getFollowups(e),t);return n.changed&&this.setFollowupsFor(e,n.queue),n}enqueueFollowup(e,t,n){return this.transitionFollowups(e,{type:`enqueue`,item:t,now:n}).item}enqueueScheduledFollowup(e,t,n){return this.transitionFollowups(e,{type:`schedule`,item:t,now:n}).item}attachFollowupAutomation(e,t,n){return this.transitionFollowups(e,{type:`attach-automation`,id:t,automationId:n}).accepted===!0}editFollowup(e,t,n,r,i){return this.transitionFollowups(e,{type:`edit`,id:t,patch:n,expectedVersion:r,now:i}).edit}removeFollowup(e,t){return this.transitionFollowups(e,{type:`remove`,id:t}).accepted===!0}pruneScheduledFollowups(e,t){this.transitionFollowups(e,{type:`prune-scheduled`,keepIds:[...t]})}rescheduleFollowup(e,t,n,r){return this.transitionFollowups(e,{type:`reschedule`,id:t,scheduledAt:n,now:r}).accepted===!0}reorderFollowup(e,t,n){return this.transitionFollowups(e,{type:`reorder`,id:t,toIndex:n}).accepted===!0}markFollowupSending(e,t,n){return this.transitionFollowups(e,{type:`mark-sending`,id:t,now:n}).item}confirmFollowupSent(e,t){this.transitionFollowups(e,{type:`confirm-sent`,id:t})}revertFollowupToQueued(e,t,n){this.transitionFollowups(e,{type:`revert-to-queued`,id:t,now:n})}settleSendingFollowups(e){this.transitionFollowups(e,{type:`settle-sending`})}dropFollowups(e){e in this.state.sessionIndex.followupsBySession&&this.transitionFollowups(e,{type:`clear`})}clearActivationReadiness(){this.set({activationReadiness:null})}setStatus(e){if(e===this.state.connection.status)return;let t=this.state.connection.currentNodeId;this.set({status:e,...t&&e===`online`?{nodes:this.state.connection.nodes.map(e=>e.id===t?{...e,online:!0}:e)}:{}})}setSignedIn(e){e!==this.state.connection.signedIn&&this.set({signedIn:e})}setNodes(e){let t=this.state.connection.currentNodeId;this.set({nodes:t&&this.state.connection.status===`online`?e.map(e=>e.id===t?{...e,online:!0}:e):e})}setSessions(e){let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions)),n=new Set(t.map(e=>e.sessionId)),r=[...this.state.sessionIndex.sessions.filter(e=>!n.has(e.sessionId)&&(e.pendingLaunch||!(!e.launchProgress||e.launchProgress.firstResponseAt))),...t],i=this.state.activeSession.activeSessionId,a=i?r.find(e=>e.sessionId===i):void 0,o=!!(a&&a.status!==`working`&&a.sessionState?.agent!==`working`);this.set({sessions:i?r.map(e=>e.sessionId===i?{...e,lastSeenAt:Date.now()}:e):r,...o?{working:!1,workingLabel:``}:{}})}seedSessions(e){if(this.state.sessionIndex.sessions.length>0)return;let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions));t.length!==0&&this.set({sessions:t})}setCurrentNode(e){e!==this.state.connection.currentNodeId&&this.set({currentNodeId:e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1})}resetSession(){this.draft=xs(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[],commandsBySession:{},followupsBySession:{},error:null,notice:null,needsModelAuth:null,draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null}),nodeSettings:null})}setForkProgress(e){this.set({forkProgress:e})}setError(e,t=[]){this.set({error:e,errorActions:e?t:[]})}setNotice(e){this.set({notice:e})}setNodeUpdating(e){this.set({nodeUpdating:e,nodeUpdateAcknowledged:!1})}setNeedsModelAuth(e){this.set({needsModelAuth:e})}pushSystemMessage(e){this.pushEntry({id:Y(),role:`system`,text:e})}clearPrResult(){this.state.presentation.prResult&&this.set({prResult:null})}clearPrRefreshAllResult(){this.state.presentation.prRefreshAllResult&&this.set({prRefreshAllResult:null})}setReposLoading(e){this.set({reposLoading:e})}updateSessionDraft(e){let t=ya(this.state.draft,e);return this.set({draft:t}),t}setDraftEphemeralConfig(e){this.updateSessionDraft({type:`select-ephemeral-config`,config:e})}setDraftRepo(e){this.updateSessionDraft({type:`select-repository`,repo:e})}setBranchesLoading(e){this.set({branchesLoading:e})}clearBranches(){this.set({branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,draft:ya(this.state.draft,{type:`select-branch`,branch:null})})}setDraftBranch(e){this.updateSessionDraft({type:`select-branch`,branch:e})}setDraftSandbox(e){this.updateSessionDraft({type:`select-sandbox`,sandbox:e})}setDraftAcknowledgeReducedProtections(e){this.updateSessionDraft({type:`acknowledge-reduced-protections`,acknowledged:e})}setDraftModel(e){this.draftModel=e}seedDraftAgentModel(e,t){if(this.state.activeSession.activeSessionId)return;let n={},r=e=>String(e.status||`available`)===`available`,i=e?this.state.catalogs.runtimes.find(t=>t.id===e&&r(t)):void 0,a=this.state.catalogs.runtimes.find(e=>e.current&&r(e)),o=i||a;if(o){let e=oo(o);n.selectedAgentId=o.id,e&&(n.currentAgentName=e)}if(!o||this.state.catalogs.modelsRuntimeId==null||this.state.catalogs.modelsRuntimeId===o.id){let e=t?this.state.catalogs.models.find(e=>ao(e,t)):void 0,r=this.state.catalogs.models.find(e=>e.current),i=e||r;i&&(n.currentModel=i,n.currentModelId=i.id)}else n.models=[],n.modelsRuntimeId=null,n.currentModel=null,n.currentModelId=null;Object.keys(n).length&&this.set(n)}setCurrentModelLocal(e){this.set({currentModel:e,currentModelId:e.id,models:this.state.catalogs.models.map(t=>({...t,current:ao(t,e)}))})}setSelectedAgentLocal(e){let t={selectedAgentId:e,currentAgentName:oo(this.state.catalogs.runtimes.find(t=>t.id===e))||this.state.catalogs.currentAgentName,draft:ya(this.state.draft,{type:`acknowledge-reduced-protections`,acknowledged:!1})};if(this.state.catalogs.modelsRuntimeId!=null&&this.state.catalogs.modelsRuntimeId!==e){let n=this.modelsByRuntime.get(e);n?(t.models=n.models,t.modelsRuntimeId=e,t.currentModel=n.currentModel,t.currentModelId=n.currentModel?.id??null):(t.models=[],t.modelsRuntimeId=null,t.currentModel=null,t.currentModelId=null)}this.set(t)}setInstalling(e){this.set({installingRuntimeId:e})}setThinkingLevel(e){this.set({thinking:{...this.state.catalogs.thinking,thinkingLevel:e}})}resetActiveSession(){this.draft=xs(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],selectedAgentId:null,currentAgentName:``,usage:null,changes:null,changesHistory:[],checkpoints:[],draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null})})}persistPendingSession(e,t,n=!0,r,i=Date.now()){if(this.isSessionDeleted(e))return;let a=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),o={...a,sessionId:e,name:t.trim()||a?.name||`New session`,status:a?.status===`failed`?`failed`:`working`,pendingLaunch:!0,pendingNodeName:r||a?.pendingNodeName,launchProgress:a?.launchProgress??{startedAt:i,checkpoints:{account:{state:`active`,at:i}}},updatedAt:a?.updatedAt||Date.now()};this.set({...n?{activeSessionId:e,activeTitle:o.name}:{},sessions:[o,...this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)]})}retryPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>{if(t.sessionId!==e)return t;let n=t.launchProgress?Object.fromEntries(Object.entries(t.launchProgress.checkpoints).map(([e,t])=>[e,t?.state===`failed`?{state:`active`,at:Date.now()}:t])):void 0;return{...t,status:`working`,updatedAt:Date.now(),launchProgress:t.launchProgress?{...t.launchProgress,failedAt:void 0,checkpoints:n??{}}:void 0}})})}dismissPendingSession(e){this.recentlyDeleted.set(e,Date.now()),this.set({activeSessionId:this.state.activeSession.activeSessionId===e?null:this.state.activeSession.activeSessionId,sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}updateLaunchCheckpoint(e,t,n,r,i){let a=Date.now();this.set({sessions:this.state.sessionIndex.sessions.map(o=>o.sessionId===e&&o.launchProgress?{...o,launchProgress:{...o.launchProgress,...n===`failed`?{failedAt:a}:{},checkpoints:{...Object.fromEntries(Object.entries(o.launchProgress.checkpoints).map(([e,t])=>[e,n===`failed`&&t?.state===`active`?{...t,state:`waiting`}:t])),[t]:{state:n,at:a,...r?{error:r}:{},...i?{errorCode:i}:{}}}}}:o)})}setLaunchModelChoice(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress?{...n,needsAction:!(!t||t.loading||t.selecting),launchProgress:{...n.launchProgress,modelChoice:t}}:n)})}markLaunchFirstResponse(e,t=Date.now()){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress&&!n.launchProgress.firstResponseAt?{...n,launchProgress:{...n.launchProgress,firstResponseAt:t,failedAt:void 0,checkpoints:{...n.launchProgress.checkpoints,agent:{state:`done`,at:t}}}}:n)})}bindPendingSessionNode(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,nodeId:t}:n)})}completePendingSession(e,t,n){if(this.isSessionDeleted(e)||this.isSessionDeleted(t))return;let r=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),i={...r,sessionId:t,nodeId:n,name:r?.name||`New session`,status:`working`,pendingLaunch:!1,pendingNodeName:void 0,updatedAt:Date.now()};this.set({activeSessionId:this.state.activeSession.activeSessionId===e?t:this.state.activeSession.activeSessionId,sessions:[i,...this.state.sessionIndex.sessions.filter(n=>n.sessionId!==e&&n.sessionId!==t)]})}failPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,status:`failed`,launchProgress:t.launchProgress?{...t.launchProgress,failedAt:t.launchProgress.failedAt??Date.now()}:void 0}:t)})}setActiveTitle(e){this.set({activeTitle:e})}renameSessionLocal(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,name:t}:n)})}seedDeletedSessionTombstones(e){if(e&&typeof e==`object`){for(let[t,n]of Object.entries(e)){let e=Number(n);t&&Number.isFinite(e)&&this.recentlyDeleted.set(t,e)}this.set({sessions:this.withoutRecentlyDeleted(this.state.sessionIndex.sessions)})}}deletedSessionTombstones(){return Object.fromEntries(this.recentlyDeleted)}removeSessionLocal(e){this.recentlyDeleted.set(e,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}isSessionDeleted(e){return this.recentlyDeleted.has(e)}withoutRecentlyDeleted(e){return this.recentlyDeleted.size===0?e:e.filter(e=>!this.isSessionDeleted(e.sessionId))}upsertSession(e){if(!e.sessionId||this.isSessionDeleted(e.sessionId))return;let t=this.state.sessionIndex.sessions.find(t=>t.sessionId===e.sessionId);if(t){let n={...t,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))};this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e.sessionId?n:t)})}else this.set({sessions:[e,...this.state.sessionIndex.sessions]})}addUserMessage(e,t,n){let r={id:Y(),role:`user`,text:e,html:ye(e),...n&&n.length?{attachments:n}:{}};t&&(this.pending.size===0&&(this.usersBeforePending=this.state.activeSession.transcript.reduce((e,t)=>t.role===`user`?e+1:e,0)),this.pending.set(t,{entry:r,confirmed:!1})),n&&n.length&&this.rememberAttachments(e,n),this.set({transcript:[...this.state.activeSession.transcript,r]}),this.state.activeSession.activeSessionId&&this.updateSessionRow(this.state.activeSession.activeSessionId,{updatedAt:Date.now()})}apply(e){let t=String(e.type||``),n=Sa(this.state.connection,e);if(n.handled){this.setValues({connection:n.value,...n.error?{presentation:{...this.state.presentation,error:n.error}}:{}});return}let r=Ca(this.state.sessionIndex,e);if(r.handled){r.value!==this.state.sessionIndex&&this.setValues({sessionIndex:{...this.state.sessionIndex,pausedSessionIds:[...r.value.pausedSessionIds]}});return}let i=Ta({runTerminals:this.state.sessionIndex.runTerminals,tuiSessions:this.state.sessionIndex.tuiSessions},e,Date.now());if(i.handled){this.set({runTerminals:[...i.value.runTerminals],tuiSessions:[...i.value.tuiSessions]});return}let a=Ea(e);if(a.handled){(a.catalogs||a.settings)&&this.setValues({...a.catalogs?{catalogs:{...this.state.catalogs,...a.catalogs}}:{},...a.settings?{settings:{...this.state.settings,...a.settings}}:{}});return}let o=Da(this.state.presentation,e);if(o.handled){this.setValues({presentation:o.value});return}let s=lo({approvals:this.state.activeSession.approvals,questions:this.state.activeSession.questions,turnAttentions:this.state.activeSession.turnAttentions},e,Date.now());if(s.handled){this.set({approvals:s.value.approvals,questions:s.value.questions,turnAttentions:s.value.turnAttentions}),s.row&&this.updateSessionRow(s.row.sessionId,s.row);return}let c=po({activeSessionId:this.state.activeSession.activeSessionId,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel,opening:this.state.activeSession.opening,usage:this.state.activeSession.usage,changes:this.state.activeSession.changes,changesHistory:this.state.activeSession.changesHistory,checkpoints:this.state.activeSession.checkpoints,activeTitle:this.state.activeSession.activeTitle,github:this.state.activeSession.github,...t===`session.changes`?{newChangeId:Y()}:{}},e,Date.now());if(c.handled){c.patch&&this.set(c.patch);for(let e of c.commands)e.kind===`row`?this.updateSessionRow(e.sessionId,e.patch):e.kind===`entry`?this.pushEntry({id:Y(),role:e.role,text:e.text,...e.actions?.length?{actions:e.actions}:{}}):e.kind===`model-auth`&&this.state.connection.currentNodeId?this.setNeedsModelAuth({nodeId:this.state.connection.currentNodeId,provider:e.provider,reason:e.reason}):e.kind===`rename`?this.renameSessionLocal(e.sessionId,e.name):e.kind===`global-error`?this.set({error:e.message}):e.kind===`reset-active`&&this.resetActiveSession();return}this.applyStatefulEvent(e,t)}applyStatefulEvent(e,t){switch(t){case`sessions.list`:this.setSessions(e.sessions);return;case`session.created`:{let t=e,n=String(t.sessionId||t.id||``);if(n){let e=this.state.sessionIndex.sessions.find(e=>e.sessionId===n),r=eo(t.sessionState??t.bivySession?.state);this.upsertSession({sessionId:n,path:t.sessionFile||t.path,workspace:t.workspace||t.bivySession?.workspace,worktree:t.worktree||t.bivySession?.worktree||t.bivySession?.workspaceContext?.worktree,branch:t.branch||t.bivySession?.branch,name:t.name||(e?void 0:`Untitled session`),source:t.source,bivyCreated:t.bivyCreated===!0,nodeId:t.nodeId,runtimeId:t.runtimeId,agentName:t.agentName,updatedAt:t.updatedAt||t.modified||(e?void 0:Date.now()),status:to(r)??`idle`,sessionState:r,needsAction:r?.displayStatus===`needs_attention`})}this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),n&&this.setSessionCommands(n,t.capabilities),this.onSessionCreatedElsewhere?.();return}case`session.capabilities`:{let t=e;this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),this.setSessionCommands(t.sessionId,t.capabilities);return}case`session.deleted`:{let t=e,n=String(t.sessionId||``),r=t.sessionFile;n&&this.recentlyDeleted.set(n,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(e=>e.sessionId!==n&&(!r||e.path!==r))}),n&&this.dropSessionCommands(n),n&&this.dropFollowups(n),n&&this.knownAgentAttachmentsBySession.delete(n),n&&n===this.state.activeSession.activeSessionId&&this.resetActiveSession();return}case`session.history`:{let t=e,n=t.sessionId||this.state.activeSession.activeSessionId;if(n&&n===this.state.activeSession.activeSessionId&&this.state.activeSession.working&&!this.draft.finalized&&!this.awaitingOpenHistory){this.deferredHistory=t;return}this.applyHistory(t,n);return}case`session.user_message`:{let t=e,n=t.clientMessageId?this.pending.get(t.clientMessageId):void 0,r=!(!n||n.confirmed);if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId||t.sessionId&&!this.state.activeSession.activeSessionId&&!r||(this.state.activeSession.changes&&this.set({changes:null}),t.retry&&!r))return;if(r&&n){n.entry.attachments?.length&&t.text&&this.rememberAttachments(String(t.text),n.entry.attachments),n.confirmed=!0,t.text&&(n.confirmedText=String(t.text)),n.reconciled&&this.retirePending(t.clientMessageId);return}let i=String(t.text||``);this.pushEntry({id:Y(),role:`user`,text:i,html:ye(i)}),t.sessionId&&this.updateSessionRow(t.sessionId,{updatedAt:Date.now()});return}case`models.list`:{let t=e,n=t.runtimeId==null?null:String(t.runtimeId),r=ro(t.models),i=t.current?ro([t.current])[0]:null;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId){n&&n!==this.state.activeSession.activeRuntimeId&&this.modelsByRuntime.set(n,{models:r,currentModel:i});return}let a=r.filter(e=>e.configured!==!1),o=!this.state.activeSession.activeSessionId&&this.draftModel?a.find(e=>ao(e,this.draftModel)):void 0,s;if(o)s=o;else if(i)s=i;else if(a.length===0)s=null;else{let e=a.find(e=>e.current),t=a.find(e=>ao(e,this.state.catalogs.currentModel));s=e??t??a[0]}n&&this.modelsByRuntime.set(n,{models:r,currentModel:s});let c=this.state.activeSession.activeSessionId?this.state.activeSession.activeRuntimeId:this.state.catalogs.selectedAgentId;if(n&&c&&n!==c)return;this.set({models:r,modelsRuntimeId:n,currentModel:s,currentModelId:s?.id??null,...t.thinking?{thinking:io(t.thinking)}:{}});return}case`model.updated`:{let t=e;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId)return;let n=t.model?ro([t.model])[0]:this.state.catalogs.currentModel;this.set({currentModel:n,currentModelId:n?.id??this.state.catalogs.currentModelId,models:this.state.catalogs.models.map(e=>({...e,current:ao(e,n)}))});return}case`thinking.updated`:{let t=e;t.thinking&&this.set({thinking:io(t.thinking)});return}case`runtimes.list`:case`runtime.updated`:{let t=e,n=t.runtimes||this.state.catalogs.runtimes,r=t.current||n.find(e=>e.id===(this.state.catalogs.selectedAgentId||t.activeAgent)),i=(this.state.activeSession.activeSessionId?void 0:n.find(e=>e.id===this.state.catalogs.selectedAgentId))?.id||r?.id||t.activeAgent||this.state.catalogs.selectedAgentId,a=this.state.activeSession.activeSessionId?n.find(e=>e.id===this.state.activeSession.activeRuntimeId):n.find(e=>e.id===i)||r;this.set({runtimes:n,selectedAgentId:i,currentAgentName:oo(a)||this.state.catalogs.currentAgentName,...t.type===`runtime.updated`?{installingRuntimeId:null}:{}});return}case`runtime.install.done`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null});return}case`runtime.install.error`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null,error:String(t.error||`Install failed`)});return}case`activation.readiness`:{let t=e;t.credential&&t.repository&&this.set({activationReadiness:{credential:t.credential,repository:t.repository}});return}case`github.connect.status`:{let t=e,n=[`waiting`,`connected`,`expired`,`denied`,`error`,`unconfigured`,`idle`].includes(t.status)?t.status:`idle`;this.set({githubConnect:{status:n,userCode:typeof t.userCode==`string`?t.userCode:void 0,verificationUri:typeof t.verificationUri==`string`?t.verificationUri:void 0,intervalMs:typeof t.intervalMs==`number`?t.intervalMs:void 0,error:typeof t.error==`string`?t.error:void 0}});return}case`providers.list`:{let t=e,n=Array.isArray(t.providers)?t.providers:[];this.set({providers:n});let r=this.state.presentation.needsModelAuth;if(r){let e=fs(r.provider);n.some(t=>(t.id===r.provider||t.id===e)&&t.configured)&&this.set({needsModelAuth:null})}return}case`provider.auth`:this.set({providerAuth:e});return;case`provider.oauth.reset`:{let t=e;Array.isArray(t.providers)&&this.set({providers:t.providers}),this.set({oauth:null});return}case`provider.oauth.started`:{let t=e;this.set({oauth:{id:String(t.id||``),provider:t.provider,authUrl:t.authUrl,instructions:t.instructions,deviceCode:t.deviceCode||null,usesCallbackServer:t.usesCallbackServer,canOpenOnNode:t.canOpenOnNode===!0,nodeName:typeof t.nodeName==`string`?t.nodeName:void 0,status:t.error?void 0:`Waiting for sign-in…`,error:t.error}});return}case`auth.oauth.progress`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,status:String(t.message||``)}});return}case`auth.oauth.done`:{let t=e;(!this.state.presentation.oauth||this.state.presentation.oauth.id===t.id)&&this.set({oauth:null});return}case`auth.oauth.error`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,error:String(t.error||`sign-in failed`),status:void 0}});return}case`github.app.manifest.ready`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}});return}case`github.app.manifest.done`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}});return}case`github.app.manifest.error`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}});return}case`session.event`:{let t=e,n=t.sessionId,r=t.event||{},i=be(r?.type);if(n&&i!==`user_question`&&i!==`user_question_resolved`&&i!==`app_published`&&i!==`app_review`&&i!==`app_pin`&&i!==`suggestion`&&i!==`notice`){let e=i===`agent_end`,r=eo(t.state??t.sessionState);this.updateSessionRow(n,{status:to(r)??(e?`idle`:`working`),sessionState:r,needsAction:r?r.agent===`awaiting-input`:!1,...e?{updatedAt:Date.now(),finishedAt:Date.now()}:{}})}if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId||n&&!this.state.activeSession.activeSessionId)return;if(r&&r.type){let e=n&&!r.sessionId?{...r,sessionId:n}:r,i=t.seq;if(typeof i==`number`&&n){this.trackSeqStream(n,t.epoch);let r=this.seqReassembler.accept(i,e);for(let e of r.ready)this.apply(e);r.overflow?this.requestFreshHistory?.():r.gapFrom!==void 0&&this.requestReplay?.(n,r.gapFrom)}else this.apply(e)}return}case`session.replay`:{let t=e,n=t.sessionId;if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId)return;if(t.mode===`reset`){this.requestFreshHistory?.();return}let r=Array.isArray(t.events)?t.events:[];for(let e of r)this.apply(e);return}case`node.stats`:{let t=Xa(e.stats);t&&this.set({nodeStats:t});return}case`capabilities`:{let t=Za(e.capabilities);t&&this.set({capabilities:t});return}case`session.pr_result`:{let t=e,n=t.prUrl||t.url||null;this.set({prResult:{sessionId:t.sessionId,url:n||void 0,error:t.ok===!1?String(t.error||`Could not open pull request`):void 0}}),t.ok!==!1&&(n||Array.isArray(t.prs))&&this.applyPrUpdate(String(t.sessionId||``),n,t.prs);return}case`session.pr_opened`:{let t=e;this.applyPrUpdate(String(t.sessionId||``),t.prUrl||null,t.prs);return}case`sessions.pr_refresh_result`:{let t=e;this.set({prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}});return}default:{let t=ls({transcript:this.state.activeSession.transcript,draft:this.draft,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel},e,Date.now());if(!t.handled)return;this.draft=t.value.draft,this.set({transcript:t.value.transcript,working:t.value.working,workingLabel:t.value.workingLabel});for(let e of t.commands)e.kind===`cache-inline-image`?this.inlineImagesByUrl.set(e.url,e.ref):e.kind===`remember-agent-attachments`?this.rememberAgentAttachments(this.state.activeSession.activeSessionId,this.state.activeSession.transcript):e.kind===`turn-settled`&&(this.drainDeferredHistory(),this.onSessionSettled?.())}}}applyHistory(e,t){Array.isArray(e.attachmentRefs)&&this.foldAttachmentRefs(e.attachmentRefs),Array.isArray(e.inlineImageRefs)&&this.foldInlineImageRefs(e.inlineImageRefs);let n=Array.isArray(e.messages)?e.messages:[],r=t?this.historyRaw.get(t):void 0,i=e.mode===`append`&&r&&(e.baseCount===void 0||e.baseCount===r.count);if(e.mode===`append`&&!i){t&&this.historyRaw.delete(t),t&&t===this.state.activeSession.activeSessionId&&this.requestFreshHistory?.();return}let a=i?r.messages.concat(n):n,o=typeof e.count==`number`?e.count:a.length,s=typeof e.historyHash==`string`?e.historyHash:``;t&&(this.historyRaw.set(t,{messages:a,count:o,historyHash:s}),s&&this.onHistoryPersist?.(t,a,o,s));let c=eo(e.sessionState??e.bivySession?.state),l=!(c?c.agent===`working`:e.isStreaming),u=this.withCachedAttachments(l?ds(Ro(a)):Ro(a));this.rememberAgentAttachments(t,u);let d=this.withInlineImageRefs(this.withStickyAgentAttachments(t,u));if(t&&this.cacheTranscript(t,d),!(this.state.activeSession.activeSessionId===t||this.state.activeSession.activeSessionId===null&&e.requestId))return;this.draft=xs(),this.deferredHistory=null;let f=eo(e.sessionState??e.bivySession?.state);t&&f&&this.updateSessionRow(t,{sessionState:f,status:to(f),needsAction:f.agent===`awaiting-input`}),this.awaitingOpenHistory=!1,this.set({activeSessionId:t,activeRuntimeId:e.runtimeId?String(e.runtimeId):this.state.activeSession.activeRuntimeId,activeTitle:e.name||this.state.activeSession.activeTitle,currentAgentName:e.agentName||this.state.catalogs.currentAgentName,github:qa(e),transcript:this.withPendingUserEntries(d),working:f?f.agent===`working`:!!e.isStreaming,opening:!1,usage:Ya(e.usage)}),t&&typeof e.headSeq==`number`&&(this.trackSeqStream(t,e.streamEpoch),this.seqReassembler.baseline(e.headSeq))}markStreamInterrupted(){this.deferredHistory=null,this.state.activeSession.opening&&this.set({opening:!1}),!this.draft.finalized&&(this.finishDrafts(),this.draft.finalized=!0)}drainDeferredHistory(){let e=this.deferredHistory;e&&(this.deferredHistory=null,this.requestFreshHistory?this.requestFreshHistory():this.applyHistory(e,e.sessionId||this.state.activeSession.activeSessionId))}pushEntry(e){this.set({transcript:[...this.state.activeSession.transcript,e]})}rememberAgentAttachments(e,t){if(!e)return;let n=this.knownAgentAttachmentsBySession.get(e),r=0,i=``;for(let a of t){if(a.role===`user`){r+=1,i=``;continue}if(!Ss(a)){i=Cs(a);continue}for(let t of a.attachments)t.hash&&(n||(n=new Map,this.knownAgentAttachmentsBySession.set(e,n)),n.has(t.hash)||n.set(t.hash,{attachment:t,caption:a.text,turn:r,after:i}))}}withStickyAgentAttachments(e,t){if(!e)return t;let n=this.knownAgentAttachmentsBySession.get(e);if(!n||n.size===0)return t;let r=new Set;for(let e of t)for(let t of e.attachments??[])t.hash&&r.add(t.hash);let i=t;for(let e of n.values()){if(!e.attachment.hash||r.has(e.attachment.hash))continue;let t=ws(i,e);i=[...i.slice(0,t),{id:Y(),role:`assistant`,text:e.caption,attachments:[e.attachment]},...i.slice(t)]}return i}updateSessionRow(e,t){if(!e)return;let n=!1,r=this.state.sessionIndex.sessions.map(r=>{if(r.sessionId!==e)return r;let i={...r,...t};return e===this.state.activeSession.activeSessionId&&(i.lastSeenAt=Date.now()),(i.status!==r.status||i.needsAction!==r.needsAction||JSON.stringify(i.sessionState)!==JSON.stringify(r.sessionState)||i.branch!==r.branch||i.prUrl!==r.prUrl||JSON.stringify(i.prs)!==JSON.stringify(r.prs)||i.updatedAt!==r.updatedAt||i.lastSeenAt!==r.lastSeenAt||i.finishedAt!==r.finishedAt||i.failedAt!==r.failedAt)&&(n=!0),i});n&&this.set({sessions:r})}applyPrUpdate(e,t,n){let r=Fa(n,t);if(r.length===0)return;let i=r.find(e=>e.state===`open`)?.url??null;e&&this.updateSessionRow(e,{prUrl:i??void 0,prs:r}),(!e||e===this.state.activeSession.activeSessionId)&&this.set({github:{...this.state.activeSession.github,prUrl:i,prs:r}})}finishDrafts(){let e=new Set([this.draft.assistantId,this.draft.thinkingId].filter(Boolean));e.size&&this.set({transcript:this.state.activeSession.transcript.map(t=>e.has(t.id)?{...t,streaming:!1}:t)}),this.draft.assistantId=null,this.draft.thinkingId=null}};function Ds(e,t){return e>0||t}function Os(e){let t=e?.streamingBehaviors;return Array.isArray(t)&&t.includes(`steer`)}function ks(e){return e.find(e=>e.status===`queued`)}var As=`t`;function js(e={}){let t=e.indexedDB??(typeof indexedDB<`u`?indexedDB:void 0)??globalThis.indexedDB,n=e.dbName||`bivy-transcripts`,r=e.maxSessions||50,i=null;function a(){return i||(i=new Promise(e=>{let r;try{if(!t)return e(null);r=t.open(n,1)}catch{return e(null)}r.onupgradeneeded=()=>{try{r.result.createObjectStore(As,{keyPath:`sessionId`})}catch{}},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}),i)}function o(e,t){return a().then(n=>new Promise(r=>{if(!n)return r(null);let i=null,a;try{a=n.transaction(As,e)}catch{return r(null)}let o=t(a.objectStore(As));o&&(o.onsuccess=()=>i=o.result),a.oncomplete=()=>r(i),a.onerror=()=>r(null),a.onabort=()=>r(null)}))}async function s(e){return e&&await o(`readonly`,t=>t.get(e))||null}async function c(e,t,n,i,a){if(!e||!i)return;await o(`readwrite`,r=>r.put({sessionId:e,messages:t,count:n,historyHash:i,updatedAt:Date.now(),...a&&a.length?{attachments:a}:{}}));let s=await o(`readonly`,e=>e.getAll());if(Array.isArray(s)&&s.length>r){let e=s.sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)).slice(r);await o(`readwrite`,t=>{for(let n of e)t.delete(n.sessionId)})}}async function l(e){e&&await o(`readwrite`,t=>t.delete(e))}return{get:s,put:c,delete:l}}function Ms(e,t,n=15e3){let{currentNodeId:r,nodeUpdating:i}=e.getState().connection;if(i)return;e.setNodeUpdating(!0);let a=()=>{let t=e.getState().connection;return t.currentNodeId===r&&t.nodeUpdating},o=!1,s=()=>{o=!0,clearTimeout(l),u()},c=t=>{o||(s(),a()&&(e.setNodeUpdating(!1),e.setError(t)))},l=setTimeout(()=>c("The machine didn't confirm the update request. It may still be updating or waiting for active turns. Check `bivy update:log` on the machine before trying again."),n),u=e.subscribe(()=>{(!a()||e.getState().connection.nodeUpdateAcknowledged)&&s()});try{Promise.resolve(t()).catch(e=>c(e instanceof Error?e.message:String(e)))}catch(e){c(e instanceof Error?e.message:String(e))}}var Ns=`bivy-attachments-v1`,Ps=67108864,Fs=class{writes=Promise.resolve();closed=!1;key(e,t){return new URL(`/__attachment_cache__/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,location.origin).href}async get(e,t){try{if(this.closed)return null;let n=await(await caches.open(Ns)).match(this.key(e,t));if(!n)return null;let r=await n.json();return typeof r.data==`string`&&typeof r.mimeType==`string`?r:null}catch{return null}}put(e,t,n){this.closed||(this.writes=this.writes.then(async()=>{let r=JSON.stringify(n),i=new Blob([r]).size;if(i>Ps)return;let a=await caches.open(Ns),o=this.key(e,t);await a.delete(o);let s=i,c=[];for(let e of await a.keys()){let t=await a.match(e),n=Number(t?.headers.get(`Content-Length`))||0;s+=n,c.push({request:e,bytes:n})}for(let e of c){if(s<=Ps)break;await a.delete(e.request),s-=e.bytes}await a.put(o,new Response(r,{headers:{"Content-Type":`application/json`,"Content-Length":String(i)}}))}).catch(()=>{}))}async clear(){this.closed=!0,await this.writes;try{await caches.delete(Ns)}catch{}}},Is=class{pending=new Map;memory=new Map;bytes=0;queue=[];active=0;sequence=0;timer;fetch(e,t,n){let r=this.memory.get(e);if(r)return this.memory.delete(e),this.memory.set(e,r),Promise.resolve(r);let i=this.pending.get(e);if(i){let n=this.queue.find(t=>t.key===e);return n&&(n.priority=Math.max(n.priority,t)),i}let a=new Promise(r=>{this.queue.push({key:e,priority:t,sequence:this.sequence++,load:n,resolve:r})});return this.pending.set(e,a),this.schedule(),a}schedule(){this.timer===void 0&&(this.timer=setTimeout(()=>{this.timer=void 0,this.drain()},0))}drain(){for(this.queue.sort((e,t)=>t.priority-e.priority||t.sequence-e.sequence);this.active<2&&this.queue.length;){let e=this.queue.shift();this.active++,this.run(e)}}async run(e){let t=null;try{t=await e.load()}catch{}if(t){let n=t.data.length*2;if(n<=Ps){for(;this.bytes+n>Ps&&this.memory.size;){let e=this.memory.keys().next().value;this.bytes-=this.memory.get(e).data.length*2,this.memory.delete(e)}this.memory.set(e.key,t),this.bytes+=n}}this.pending.delete(e.key),this.active--,e.resolve(t),this.schedule()}},Ls=class{local;connect;changed;closed=!1;pending=new Map;attempted=new Map;constructor(e,t,n){this.local=e,this.connect=t,this.changed=n}ensure(e){if(!this.closed)for(let t of new Set(e)){if(!t||this.local.keys()[t]||this.pending.has(t)||Date.now()-(this.attempted.get(t)??0)<6e4)continue;if(this.pending.size>=3)break;this.attempted.set(t,Date.now());let n=new Proxy(this.local,{get:(e,n,r)=>n===`cur`?t:Reflect.get(e,n,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),r=!1,i=()=>{r||(r=!0,clearTimeout(o),a.close(),this.pending.delete(t))},a=this.connect(n,()=>{!r&&this.local.keys()[t]&&(i(),this.changed(),this.ensure(e))}),o=setTimeout(()=>{i(),this.ensure(e)},15e3);this.pending.set(t,i),a.connect().catch(i).finally(()=>{r&&a.close()})}}close(){this.closed=!0;for(let e of this.pending.values())e();this.attempted.clear()}},Rs=15e3,zs=()=>Error(`The machine is not reachable.`),Bs=class{local;connect;idleMs;links=new Map;seq=0;constructor(e,t,n=6e4){this.local=e,this.connect=t,this.idleMs=n}async request(e,t,n=3e4){let r=this.link(e);await r.ready,r.idle&&clearTimeout(r.idle);let i=`mr-${Date.now().toString(36)}-${(this.seq++).toString(36)}`;return new Promise((a,o)=>{let s=setTimeout(()=>this.settle(e,r,i,Error(`The machine didn't answer.`)),n);r.pending.set(i,{resolve:a,reject:o,timer:s}),r.transport.send({...t,requestId:i})})}close(){for(let e of[...this.links.keys()])this.drop(e,Error(`Closed.`))}link(e){let t=this.links.get(e);if(t)return t;let n=new Proxy(this.local,{get:(t,n,r)=>n===`cur`?e:Reflect.get(t,n,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),r,i={pending:new Map};return i.ready=new Promise((e,t)=>{r=e,i.fail=t}),i.ready.catch(()=>{}),i.connecting=setTimeout(()=>{this.links.get(e)===i&&this.drop(e,zs())},Rs),i.transport=this.connect(n,{onStatus:e=>{e===`online`&&(clearTimeout(i.connecting),r())},onEvent:t=>{let n=String(t.requestId??``);if(!i.pending.has(n))return;let r=String(t.type??``).endsWith(`.error`);this.settle(e,i,n,r?Error(String(t.error||`Request failed.`)):t)}}),this.links.set(e,i),i.transport.connect().catch(()=>{this.links.get(e)===i&&this.drop(e,zs())}),i}settle(e,t,n,r){let i=t.pending.get(n);i&&(clearTimeout(i.timer),t.pending.delete(n),r instanceof Error?i.reject(r):i.resolve(r),t.pending.size===0&&(t.idle=setTimeout(()=>{this.links.get(e)===t&&this.drop(e,Error(`Closed.`))},this.idleMs)))}drop(e,t){let n=this.links.get(e);if(n){this.links.delete(e),n.idle&&clearTimeout(n.idle),clearTimeout(n.connecting),n.fail(t);for(let e of n.pending.values())clearTimeout(e.timer),e.reject(t);n.transport.close()}}};function Vs(){return window.navigation}var Hs=0,Us=[],Ws=[],Gs,Ks=[];function qs(){if(!(Gs||Us.some(e=>e.closing)))for(let e of Ks.splice(0))e()}function Js(e){Ks.push(e),setTimeout(qs,0)}function Ys(){if(Gs)return;let e=Us.at(-1);if(e?.closing){Gs=e;let t=Vs();e.returnKey&&t?t.traverseTo(e.returnKey):history.back();return}for(let e of Ws.splice(0))e.disposed||(e.returnKey=Vs()?.currentEntry?.key,history.pushState({...history.state,__bivyModal:e.id},``,location.href),Us.push(e));Us.at(-1)?.closing?Ys():qs()}typeof window<`u`&&window.addEventListener(`popstate`,e=>{let t=Us.at(-1);if(t&&e.state?.__bivyModal===t.id){e.stopImmediatePropagation(),Gs=void 0,queueMicrotask(Ys);return}let n=Us.pop();Gs=void 0,n&&(e.stopImmediatePropagation(),n.disposed||n.onBack(),queueMicrotask(Ys))});function Xs(e){let t={id:++Hs,onBack:e,closing:!1,disposed:!1};return queueMicrotask(()=>{t.disposed||(Ws.push(t),Ys())}),{close(){t.closing||(t.closing=!0,Ys())},dispose(){t.disposed=!0,t.closing=!0,Ys()}}}var Zs=[`appearance`,`notifications`,`import`,`providers`,`models`,`instructions`,`voice`,`share`,`github`,`linear`,`slack`,`queue`,`webhooks`,`rulesets`,`nodes`,`ephemeral`,`account`,`link`];function Qs(e){return Zs.includes(e)}var $s=[`runs`,`rulesets`];function ec(e){return e===`queue`?`runs`:$s.includes(e)?e:null}var tc=/^\/(artifacts|apps)\/?$/,nc=/^\/sessions\/([^/]+)\/?$/,rc=/^\/settings(?:\/([^/]+))?\/?$/,ic=/^\/automations(?:\/([^/]+))?\/?$/;function ac(e=location.pathname){let t=nc.exec(e);if(t&&t[1]){let e=decodeURIComponent(t[1]);return e===`new`?{kind:`new`}:{kind:`session`,id:e}}let n=et(e);if(n)return{kind:`run`,id:n};let r=rc.exec(e);if(r){let e=r[1]?decodeURIComponent(r[1]):``;return{kind:`settings`,view:Qs(e)?e:null}}let i=ic.exec(e);if(i)return{kind:`automations`,section:ec(i[1]?decodeURIComponent(i[1]):``)};let a=tc.exec(e);return a?{kind:`library`,view:a[1]}:{kind:`root`}}function oc(e){return(e.kind===`session`?`/sessions/${encodeURIComponent(e.id)}`:e.kind===`run`?$e(e.id):e.kind===`new`?`/sessions/new`:e.kind===`settings`?e.view?`/settings/${e.view}`:`/settings`:e.kind===`automations`?e.section?`/automations/${e.section}`:`/automations`:e.kind===`library`?`/${e.view}`:`/`)+location.search+location.hash}function Z(e,t={}){let n=oc(e);n!==location.pathname+location.search+location.hash&&(t.replace?history.replaceState(null,``,n):history.pushState(null,``,n))}function sc(e,t){try{if(e.length>2048)return null;let n=new URL(e);if(n.protocol!==`https:`||n.origin!==t||n.username||n.password||n.hash||!/^\/(?:sessions|runs)\/[A-Za-z0-9_-]+$/.test(n.pathname)||n.pathname===`/sessions/new`||[...n.searchParams.keys()].some(e=>e!==`node`)||n.searchParams.getAll(`node`).length>1)return null;let r=n.searchParams.get(`node`);return r!==null&&(!n.pathname.startsWith(`/sessions/`)||!/^[A-Za-z0-9_-]+$/.test(r))?null:{path:n.pathname,node:r}}catch{return null}}function cc(e,t,n=globalThis.__BIVY_RUNTIME_CONFIG__){return!n||typeof n!=`object`||!(e in n)?t:n[e]===!0}var lc={BASE_URL:`/`,DEV:!1,EPHEMERAL_MACHINES_ENABLED:``,MODE:`production`,PROD:!0,SSR:!1},uc=cc(`ephemeralMachinesEnabled`,lc.EPHEMERAL_MACHINES_ENABLED===`1`),dc=lc.VITE_BIVY_KEEP_FAILED_EPHEMERAL===`1`,fc=`bivy.cloudMachines.enabled`,pc=`bivy:cloud-machines-changed`;function mc(){try{return typeof localStorage<`u`&&localStorage.getItem(fc)===`1`}catch{return!1}}function hc(e){if(typeof window>`u`)return()=>{};let t=t=>{t.key===fc&&e()};return window.addEventListener(`storage`,t),window.addEventListener(pc,e),()=>{window.removeEventListener(`storage`,t),window.removeEventListener(pc,e)}}function gc(){return mc()}function _c(e){try{e?localStorage.setItem(fc,`1`):localStorage.removeItem(fc)}catch{}typeof window<`u`&&window.dispatchEvent(new Event(pc))}function vc(){return(0,y.useSyncExternalStore)(hc,mc,()=>!1)}var yc=`bivy.pwa.first-success`,bc=`bivy.product-metric.first_useful_response`,xc=`bivy.pwa.install-dismissed`,Sc=new Set,Cc=null,wc=!1,Tc=!1,Ec=0;function Dc(){try{return localStorage.getItem(yc)===`1`||localStorage.getItem(bc)===`1`}catch{return!1}}function Oc(){return typeof window>`u`?!1:window.matchMedia?.(`(display-mode: standalone)`).matches===!0||navigator.standalone===!0}function kc(){try{return localStorage.getItem(xc)===`1`}catch{return!1}}Tc=typeof window<`u`&&kc();function Ac(e,t,n,r=!1){return r?null:/iPad|iPhone|iPod/.test(e)||t===`MacIntel`&&n>1?`ios`:/Safari/.test(e)&&!/Chrome|Chromium|CriOS|Edg|OPR|FxiOS/.test(e)?`safari`:null}function jc(){return typeof navigator>`u`?null:Ac(navigator.userAgent,navigator.platform,navigator.maxTouchPoints,Oc())}var Q={updateAvailable:!1,installChoice:null,standalone:Oc(),shellCached:!1,firstSuccess:typeof window<`u`&&Dc(),hasDraft:!1,pendingAttachments:0,readingAttachments:!1,turnActive:!1,locallyQueuedPrompts:0,queuedFollowups:0};function $(e){let t={...Q,...e};Object.keys(t).every(e=>t[e]===Q[e])||(Q=t,Sc.forEach(e=>e()))}function Mc(){let e=Oc();$({standalone:e,installChoice:e||wc||Tc||!Q.firstSuccess?null:Cc?`native`:jc()})}async function Nc(){try{$({shellCached:!!(await navigator.serviceWorker?.getRegistration())?.active})}catch{$({shellCached:!1})}}function Pc(){let e=e=>{e.preventDefault(),Cc=e,Mc()},t=()=>{Cc=null,wc=!0,Mc()},n=()=>{Nc()},r=window.matchMedia?.(`(display-mode: standalone)`);return window.addEventListener(`beforeinstallprompt`,e),window.addEventListener(`appinstalled`,t),navigator.serviceWorker?.addEventListener(`controllerchange`,n),r?.addEventListener?.(`change`,Mc),Mc(),Nc(),()=>{window.removeEventListener(`beforeinstallprompt`,e),window.removeEventListener(`appinstalled`,t),navigator.serviceWorker?.removeEventListener(`controllerchange`,n),r?.removeEventListener?.(`change`,Mc)}}function Fc(e){return Sc.add(e),()=>Sc.delete(e)}function Ic(){return Q}function Lc(e){$({updateAvailable:e})}function Rc(e){$(e)}function zc(e){$({turnActive:e})}function Bc(){Ec+=1,$({locallyQueuedPrompts:Ec})}function Vc(){Ec=0,$({locallyQueuedPrompts:0})}function Hc(e){$({queuedFollowups:Math.max(0,Math.floor(e))})}function Uc(){try{localStorage.setItem(yc,`1`)}catch{}$({firstSuccess:!0}),Mc()}function Wc(){Tc=!0,Cc=null;try{localStorage.setItem(xc,`1`)}catch{}$({installChoice:null})}async function Gc(){let e=Cc;if(!e||Q.standalone||!Q.firstSuccess)return`unavailable`;Cc=null,$({installChoice:null});try{return await e.prompt(),(await e.userChoice).outcome}catch{return`unavailable`}}function Kc(e=Q){let t=[];return e.turnActive&&t.push(`the active turn finishes`),e.readingAttachments&&t.push(`file reading finishes`),e.hasDraft&&t.push(`the unsent draft is sent or cleared`),e.pendingAttachments&&t.push(`pending attachments are sent or cleared`),e.locallyQueuedPrompts&&t.push(`locally queued prompts reach the Machine`),e.queuedFollowups&&t.push(`queued follow-ups are delivered`),t}function qc(e=Q){return e.updateAvailable&&Kc(e).length===0}var Jc="On that machine, run `bivy status` (or `bivy restart`).";function Yc(e,t,n=Q,r){let i=r?`Machine ${r}`:`The Machine`;return n.locallyQueuedPrompts>0?{kind:`local-queue`,label:n.locallyQueuedPrompts===1?`Prompt queued on this device`:`${n.locallyQueuedPrompts} prompts queued on this device`,detail:`Not yet delivered to ${r?`Machine ${r}`:`the Machine`}. Keep Bivy open — it sends as soon as the connection is back.`}:e===`reconnecting`||e===`connecting`||e===`linking`||e===`pairing`?{kind:`reconnecting`,label:r?`Reconnecting to ${r}`:`Reconnecting Machine`,detail:t?`Showing the cached transcript. Keep drafting — sending resumes once the connection is back.`:`Waiting for ${r?`Machine ${r}`:`the Machine`} to answer. If this sticks, run \`bivy status\` on that machine.`}:e===`offline`&&t?{kind:`cached-transcript`,label:`Cached transcript`,detail:`${i} is offline — this copy may be behind, and prompts can't send until it reconnects. ${Jc}`}:e===`offline`&&n.shellCached?{kind:`cached-shell`,label:`Machine offline`,detail:`${i} is offline, so there is no transcript or live control yet. Your draft is kept here. ${Jc}`}:e===`offline`?{kind:`offline-page`,label:`Offline`,detail:`${i} is unreachable. Your draft is kept on this device. ${Jc}`}:{kind:`live-control`,label:`Live control`,detail:`${i} is connected. Prompts send now and transcript changes sync live.`}}var Xc=66e4,Zc=class{deps;workflow;pending=new Map;constructor(e,t){this.deps=e,this.workflow=t}send(e){return this.deps.send(e),{type:`command-sent`,command:e}}preparePrompt(e,t){return{type:`prompt-prepared`,requestId:this.deps.createRequestId(),clientMessageId:this.deps.createClientMessageId(),text:e,...t?.length?{attachments:t}:{}}}handleEvent(e){let t=String(e.requestId||``),n=t?this.pending.get(t):void 0;if(!n)return!1;clearTimeout(n.timer),this.pending.delete(t);let r=e.error;return r?n.reject(Error(String(r))):n.resolve(e),!0}newSession(e={}){let t=this.workflowPort();e.navigate!==!1&&t.navigateNew(),t.focusComposer(),t.clearPendingPromptAndFollowups(),t.resetActiveSession(),t.seedDraftDefaults(),t.listRuntimes(),t.listModels(),t.hasNodeSettings()||t.getNodeSettings(),t.listRepos();let n=t.draftRepo();n&&t.listBranches(n)}sendPrompt(e,t){let n=this.workflowPort(),r=e.trim(),i=t?.length?t:void 0;if(!r&&!i)return;let a=this.deps.createRequestId(),o=this.deps.createClientMessageId(),s=n.activeSessionId();if(s&&n.isPendingLaunch(s)){n.addUserMessage(r,o,i),n.appendPendingLaunchFollowup(s,{text:r,clientMessageId:o,attachments:i});return}if(s){if(n.sessionIsSaved?.(s)&&n.openSession(s),n.mustQueue(s)){n.enqueueFollowup(s,{id:o,text:r,attachments:i}),n.persistFollowup(s,o,r),n.drainFollowups(s);return}n.addUserMessage(r,o,i),n.shouldAutoResume()?(n.bufferResume({sessionId:s,text:r,clientMessageId:o,attachments:i}),n.resumeNodeForSession(s)):n.send({kind:`prompt`,sessionId:s,text:r,clientMessageId:o,attachments:i});return}if(n.hasPendingPrompt()){n.addUserMessage(r,o,i),n.appendPendingFollowup({text:r,clientMessageId:o,attachments:i});return}let c={kind:`session.new`,requestId:a,title:r||void 0,...n.draftSessionFields()},l={text:r,requestId:a,clientMessageId:o,attachments:i,frame:c},u=n.draftEphemeralRunner();if(u){let e=`starting-${a}`;l.provisionalId=e,n.addUserMessage(r,o,i),n.startEphemeralLaunch(e,l,u);return}n.setPendingPrompt(l),n.addUserMessage(r,o,i),n.send(c)}deleteSession(e,t){let n=this.workflowPort();n.send({kind:`session.delete`,sessionId:e,path:t}),e===n.activeSessionId()&&n.resetDeletedActiveSession(),n.removeSessionLocal(e),n.persistDeletedSessionTombstones(),n.deleteTranscriptCache(e),n.refreshSessions()}pauseSession(e){let t=this.workflowPort(),n=t.resolveSessionId(e);n&&t.send({kind:`session.pause`,sessionId:n})}resumeSession(e){let t=this.workflowPort(),n=t.resolveSessionId(e);n&&t.send({kind:`session.resume`,sessionId:n})}async startLike(e,t,n){let r=await this.request({kind:`session.new`,like:e,title:t,prompt:t,...n?.length?{attachments:n}:{}},12e4,`Starting the session timed out`);return this.workflowPort().refreshSessions(),String(r.sessionId??``)}async importNativeSession(e,t,n=!1){return this.request({kind:`session.import`,runtimeId:e,ref:t,acceptDisclosure:n},6e4)}async promote(e,t){t&&t!==this.deps.currentNodeId()&&(this.deps.switchNode(t),await this.deps.waitForOnline());let n=await this.request({kind:`session.promote`,sessionId:e},3e4);return this.deps.refreshAccountSessions(),{epoch:Number(n.epoch??0)}}async fork(e,t={}){let n=this.deps.currentNodeId(),r=t.destNodeId??n,i=!!t.managedConfigId,a=i||!this.deps.isDirect()&&!!r&&r!==n,o=t.sourceAgentId??this.deps.sessionRuntime(e),s=t.agentId??o;if(!a&&(!s||o&&s===o)){this.deps.reportForkProgress?.(`Copying the conversation and working files…`);let n=await this.request({kind:`session.fork.local`,sessionId:e,...t.model?{model:t.model}:{}},Xc),r=String(n.sessionId||``);if(!r)throw Error(`Local fork returned no session id`);let i=this.forkResult(n,`full`);return this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(r,void 0,n),t.retireSource&&this.deps.send({kind:`session.delete`,sessionId:e}),{sessionId:r,...i}}this.deps.reportForkProgress?.(`Preparing the conversation and working files…`);let c=(await this.request({kind:`session.fork.export`,sessionId:e,...s?{agent:s}:{},...a?{crossNode:!0}:{}},6e4)).bundle;if(!c)throw Error(`Fork export returned no bundle`);let l=this.deps.transcriptUrl(e),u;try{t.managedConfigId&&(r=await this.deps.launchManagedDestination(t.managedConfigId,t.agentId)),a&&(this.deps.reportForkProgress?.(`Connecting to the destination machine…`),this.deps.switchNode(r),this.deps.reportCrossNodeFork?.(`working`,`Creating the fork on the destination machine…`),await this.deps.waitForOnline(i?12e4:void 0)),this.deps.reportForkProgress?.(`Creating the session in the destination agent…`),u=await this.request({kind:`session.fork.import`,bundle:c,transcriptUrl:l,sameNode:!a,...s?{agent:s}:{},...t.model?{model:t.model}:{}},Xc)}catch(t){throw a&&(this.deps.switchNode(n),await this.deps.waitForOnline().catch(()=>{}),this.deps.openSession(e),this.deps.reportCrossNodeFork?.(`error`,t instanceof Error?t.message:String(t))),t}let d=String(u.sessionId||``);if(!d){let e=Error(`Fork import returned no session id`);throw a&&this.deps.reportCrossNodeFork?.(`error`,e.message),e}let f=String(u.runtimeId||``);if(s&&f&&f!==s){let e=Error(`Fork requested agent ${s}, but the destination used ${f}`);throw a&&this.deps.reportCrossNodeFork?.(`error`,e.message),e}this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(d,void 0,u);let p=u.seedPrompt;if(typeof p==`string`&&p.trim()){let e=this.deps.createClientMessageId();this.deps.addUserMessage(p,e),this.deps.send({kind:`prompt`,sessionId:d,text:p,clientMessageId:e})}if(t.retireSource){this.deps.reportForkProgress?.(`Retiring the original session…`);let t={kind:`session.fork.retire-source`,sourceSessionId:e,newSessionId:d};if(a){let e;try{this.deps.switchNode(n),await this.deps.waitForOnline(),this.deps.send(t)}catch(t){e=t}finally{this.deps.switchNode(r),await this.deps.waitForOnline(),this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(d,void 0,u)}if(e){let t=Error(`Fork created, but the original session could not be retired: ${e instanceof Error?e.message:String(e)}`);throw this.deps.reportCrossNodeFork?.(`error`,t.message),t}}else this.deps.send(t)}let m=this.forkResult(u,`seeded`);if(a){let e=m.missing.map(e=>e.detail||e.label).find(Boolean);this.deps.reportCrossNodeFork?.(`success`,e?`Fork created on the destination machine. ${e}`:t.retireSource?`Session moved to the destination machine.`:`Fork created on the destination machine.`)}return{sessionId:d,...m}}workflowPort(){if(!this.workflow)throw Error(`SessionOrchestrator requires a workflow port`);return this.workflow}forkResult(e,t){let n=e.missing;return{fidelity:String(e.fidelity||t),missing:Array.isArray(n)?n:[]}}request(e,t,n=`Fork request timed out`){let r=this.deps.createRequestId();return new Promise((i,a)=>{let o=setTimeout(()=>{this.pending.delete(r),a(Error(n))},t);this.pending.set(r,{resolve:i,reject:a,timer:o}),this.deps.sendRequest({...e,requestId:r})})}},Qc=class{port;constructor(e){this.port=e}requirement(e){return!e.direct&&!e.solo&&!e.signedIn?{type:`authentication-required`}:!e.direct&&e.signedIn&&!e.currentNodeId?{type:`node-required`}:{type:`ready`}}connect(){let e=this.requiredPort();if(this.requirement(e.facts()).type!==`ready`){e.setStatus(`offline`),e.facts().signedIn&&e.refreshNodes();return}e.facts().direct||(e.setCurrentNode(e.facts().currentNodeId||``),e.refreshNodes()),e.connectTransport()}switchNode(e){let t=this.requiredPort();return e===t.facts().currentNodeId&&t.status()===`online`?!1:(t.closeTransport(),t.setCurrentNode(e),t.resetSession(),t.seedSessions(),t.rebuildTransport(),t.setStatus(`connecting`),t.connectTransport(),t.refreshAccountSessions(),!0)}async connectToNode(e,t){let n=this.requiredPort();(e!==n.facts().currentNodeId||n.status()!==`online`)&&(this.switchNode(e),await n.waitForOnline(t)),n.listProviders()}requiredPort(){if(!this.port)throw Error(`NodeConnectionCoordinator requires a port for effects`);return this.port}},$c=class{deps;accountSyncInFlight=null;constructor(e){this.deps=e}request(e,t){return this.deps.send(e),{type:`catalog-requested`,catalog:t}}selectModel(e,t){this.deps.selectModelLocally(e),this.deps.rememberModel(e);let n=t?{kind:`model.select`,provider:e.provider,id:e.id,sessionId:t}:void 0;return n&&this.deps.send(n),{type:`model-selected`,model:e,...n?{command:n}:{}}}listProviders(){this.request({kind:`providers.list`},`providers`)}getProviderAuth(e){this.deps.send({kind:`provider.auth.get`,provider:e})}saveApiKey(e,t){return this.ack({kind:`provider.apiKey`,provider:e,key:t})}removeProvider(e){this.deps.send({kind:`provider.remove`,provider:e})}resetOauth(e){this.deps.send({kind:`provider.oauth.reset`,provider:e})}startOauth(e,t){this.deps.send({kind:`provider.oauth.start`,provider:e,...t?{label:t}:{}})}async openOauthOnNode(e){let t=await this.deps.awaitAck({kind:`provider.oauth.open_on_node`,id:e});return{opened:t.opened===!0,...t.error?{error:t.error}:{}}}submitOauthCode(e,t){this.deps.send({kind:`provider.oauth.code`,id:e,code:t})}listCredentials(){this.request({kind:`credentials.list`},`credentials`)}syncAccountCredentials(){return this.deps.isOnline()?(this.accountSyncInFlight||=(async()=>{let e=await this.deps.awaitAck({kind:`credentials.account.export`,includeOAuth:this.deps.oauthRecoveryEnabled()}),t=Array.isArray(e.entries)?e.entries.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.key==`string`):[],n=this.deps.oauthRecoveryEnabled()&&Array.isArray(e.oauthEntries)?e.oauthEntries.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.label==`string`&&typeof e.refresh==`string`&&Number.isFinite(Number(e.expires))):[],r=Array.isArray(e.records)?e.records.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.label==`string`&&typeof e.kind==`string`):[],i=e.deletedAt&&typeof e.deletedAt==`object`?e.deletedAt:{},a=await this.deps.accountModelKeys();for(let e of a){let t=e.label==="default"?e.provider:`${e.provider}:${e.label}`,n=Number(i[t]),r=Date.parse(String(e.updatedAt??``));Number.isFinite(n)&&n>0&&(!Number.isFinite(r)||n>=r)&&await this.deps.removeModelKey(e.provider,e.label)}for(let e of r)e.kind!==`api_key`&&await this.deps.removeModelKey(e.provider,e.label);let o=this.deps.oauthRecoveryEnabled()?await this.deps.accountOAuthCredentials():[];for(let e of o){let t=r.find(t=>t.provider===e.provider&&t.label===e.label),n=e.label==="default"?e.provider:`${e.provider}:${e.label}`,a=Number(i[n]);(t&&t.kind!==`oauth`||Number.isFinite(a)&&a>Math.max(Number(e.refreshedAt)||0,Number(e.updatedAt)||0))&&await this.deps.removeOAuthCredential(e.provider,e.label,Number.isFinite(a)?a:this.deps.now())}await this.deps.importOAuthCredentials(n);let s=t.filter(e=>{let t=a.find(t=>t.provider===e.provider&&t.label===(e.label??`default`));if(!t)return!0;let n=typeof e.updatedAt==`number`?e.updatedAt:Date.parse(String(e.updatedAt??``)),r=Date.parse(String(t.updatedAt??``));return Number.isFinite(n)&&(!Number.isFinite(r)||n>r)});await this.deps.importModelKeys(s);for(let{provider:e,label:t,key:n}of await this.deps.accountModelKeys())r.some(n=>n.provider===e&&n.label===t&&n.kind!==`api_key`)||await this.deps.awaitAck({kind:`credential.set`,provider:e,label:t,key:n});let c=(this.deps.oauthRecoveryEnabled()?await this.deps.accountOAuthCredentials():[]).filter(({provider:e,label:t})=>{let n=r.find(n=>n.provider===e&&n.label===t);return!n||n.kind===`oauth`});c.length&&await this.deps.awaitAck({kind:`credentials.account.import`,oauthEntries:c}),this.listCredentials(),this.listProviders()})().catch(()=>{}).finally(()=>{this.accountSyncInFlight=null}),this.accountSyncInFlight):Promise.resolve()}setCredential(e,t,n){return this.ack({kind:`credential.set`,provider:e,label:t,...n})}removeCredential(e,t){return this.ack({kind:`credential.remove`,provider:e,label:t})}setCredentialSync(e,t,n){return this.ack({kind:`credential.sync.set`,provider:e,label:t,sync:n})}setCredentialUnattended(e,t,n){return this.ack({kind:`credential.unattended.set`,provider:e,label:t,unattended:n})}async testCredential(e,t){let n=await this.deps.awaitAck({kind:`credential.test`,provider:e,label:t},15e3);return{ok:!!n.ok,at:Number(n.at)||this.deps.now(),...n.reason?{reason:n.reason}:{}}}getPresets(){this.deps.send({kind:`credentials.presets.get`})}setActivePreset(e){this.deps.send({kind:`credentials.presets.setActive`,active:e})}setPresetMapping(e,t,n){return this.ack({kind:`credentials.presets.setMapping`,preset:e,provider:t,label:n})}listLocalModels(){this.deps.send({kind:`models.custom.list`})}listLocalModelPresets(){this.deps.send({kind:`models.custom.presets`})}async discoverLocalModels(){return await this.deps.awaitAck({kind:`models.custom.discover`},1e4)}async verifyLocalModel(e,t){return(await this.deps.awaitAck({kind:`models.custom.verify`,baseUrl:e,...t?{apiKey:t}:{}},1e4)).result}async saveLocalModel(e){let t=await this.deps.awaitAck({kind:`models.custom.save`,spec:e});return String(t.provider??e.providerId??`local`)}removeLocalModel(e){this.deps.send({kind:`models.custom.remove`,id:e})}ack(e){return this.deps.awaitAck(e).then(()=>void 0)}},el=class{deps;finishingMachines=new Set;constructor(e){this.deps=e}listConfigs(){return this.deps.listConfigs()}createConfig(e){return this.deps.createConfig(e)}updateConfig(e,t){return this.deps.updateConfig(e,t)}removeConfig(e){return this.deps.removeConfig(e)}listSizes(e,t){return this.deps.listSizes(e,t)}async setProviderToken(e,t){await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}async connectProvider(e,t){return await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}getProviderToken(e){return this.deps.getProviderToken(e)}removeProviderToken(e){return this.deps.removeProviderToken(e)}async runWorkItem(e,t){let n=await this.launch({...t,setupId:t.configId,hostedTasks:!0,workItemId:e,purpose:`queue-item`,name:`Ephemeral queue runner`});try{await this.deps.assignWorkItem(e,{node:this.deps.nodeLabel(n.nodeId??``),runtimeId:t.runtimeId,model:t.model,ephemeral:!0})}catch(e){throw this.deps.refreshNodes(),e}return this.deps.refreshNodes(),n}launchQueueWorker(e){return this.launch({...e,setupId:e.configId,hostedTasks:!0,purpose:`queue-default`,name:`Ephemeral queue worker`})}async ensureDefaultRunner(e){try{let t=(await this.listConfigs()).find(t=>t.provider===e);if(t)return t;let n=this.deps.defaultConfig(e);return await this.createConfig({provider:e,name:`${n.name} runner`,region:n.region,size:n.size,ttlMinutes:60,teardownOnAgentFinish:!0})}catch{return null}}async launch(e){if(!this.deps.signedIn())throw Error(`Sign in to launch an ephemeral machine.`);let t=e.githubToken??await this.deps.githubToken(),n=await this.deps.launchMachine({...e,repo:e.repo??this.deps.draftRepo(),githubToken:t||void 0});return this.deps.refreshNodes(),n}async destroy(e){await this.deps.destroyMachine(e),this.deps.refreshNodes()}async teardownFinishedSession(e){if(this.deps.direct()||this.deps.followupCount(e)>0)return;let t=this.deps.currentNodeId();if(!t)return;let n=(await this.deps.machines().catch(()=>[])).find(e=>e.nodeId===t&&e.teardownOnAgentFinish);n&&!this.finishingMachines.has(n.id)&&(this.deps.recordSessionCorrelation(e,n),this.finishingMachines.add(n.id),this.deps.schedule(()=>{if(this.deps.followupCount(e)>0||this.deps.currentNodeId()!==t){this.finishingMachines.delete(n.id);return}this.destroy(n).catch(e=>{this.finishingMachines.delete(n.id),this.deps.reportError(e instanceof Error?e:Error(String(e)))})},3e3))}async resumeAndConnect(e,t=9e4){try{await this.deps.connectToNode(e,t)}catch(e){this.deps.reportError(this.error(e))}}async reprovision(e,t){try{let n=this.deps.correlations().find(n=>n.nodeId===e||n.sessionId===t);if(n?.computeSource===`managed`){if(!n.setupId)throw Error(`This managed session no longer has a Machine profile to rebuild from.`);await this.deps.restoreManagedMachine({configId:n.setupId,nodeId:n.nodeId,sessionId:t,requestId:`restore:${t}:${n.nodeId}:${n.machineId||`legacy`}`}),await this.deps.connectToNode(n.nodeId,12e4);return}let r=this.deps.roomKey(e);if(!r)throw Error(`This device no longer holds this session's key, so it can't rebuild it.`);let i=this.deps.nodes().find(t=>t.id===e),a=(await this.deps.machines()).find(t=>t.nodeId===e)??(i?this.deps.machineFromNode(i):null)??(n?this.deps.machineFromCorrelation(n):null);if(!a)throw Error(`No record of the machine to rebuild — re-launch it from Ephemeral settings.`);await this.launch({provider:a.provider,region:a.region||void 0,ttlMinutes:a.ttlMinutes,repo:a.repo,setupId:a.setupId,teardownOnAgentFinish:a.teardownOnAgentFinish,reuseNodeId:e,reuseRoomKeyB64:r,restoreSessionId:t}),await this.deps.connectToNode(e,12e4)}catch(e){this.deps.reportError(this.error(e))}}isCurrentNodeResumable(){if(this.deps.direct())return!1;let e=this.deps.currentNodeId();if(!e)return!1;let t=this.deps.correlations().find(t=>t.nodeId===e),n=this.deps.nodes().find(t=>t.id===e);return t?.computeSource===`managed`?!n:this.deps.roomKey(e)?n?!n.online&&!!this.deps.machineFromNode(n):!!t:!1}error(e){return e instanceof Error?e:Error(String(e))}},tl=class{deps;constructor(e){this.deps=e}fetchMe(){return this.deps.api.fetchMe(this.deps.local)}fetchGithubApp(){return this.deps.api.fetchGithubApp(this.deps.local)}fetchGithubQueue(e=30){return this.deps.api.fetchGithubQueue(this.deps.local,e)}fetchAutomationRuns(e=50,t={}){return this.deps.api.fetchAutomationRuns(this.deps.local,e,t)}setGithubAppDefaultNode(e,t){return this.deps.api.setGithubAppDefaultNode(this.deps.local,e,t)}setGithubAppTriggerAccess(e,t){return this.deps.api.setGithubAppTriggerAccess(this.deps.local,e,t)}assignWorkItem(e,t){return this.deps.api.assignWorkItem(this.deps.local,e,t)}deleteWorkItem(e){return this.deps.api.deleteWorkItem(this.deps.local,e)}clearWorkQueue(){return this.deps.api.clearWorkQueue(this.deps.local)}async cancelAutomationRun(e){await this.deps.api.cancelAutomationRun(this.deps.local,e);let[t,n]=await Promise.all([this.fetchAutomationRuns(50),this.fetchGithubQueue(30)]);return{runs:t,queue:n}}async startRun(e,t){let n=e.trim();if(!n)return{error:`Describe the task this Run should complete.`};let r=this.deps.runContext();if(!r.accountMode)return{error:`Sign in to start a Run.`};if(!r.nodeId)return{error:r.sessionId?`This Session has no owning Machine.`:`Choose a Machine before starting a Run.`};if(!r.roomKey)return{error:`This Machine isn't paired on this device—open it first so the instruction can be encrypted.`};if(!r.nodeLabel)return{error:`This Machine has no routing name. Reconnect it before starting a Run.`};try{let e=await this.deps.encrypt(r.roomKey,n),i=await this.deps.api.createOneOffRun(this.deps.local,{title:(n.split(/\r?\n/,1)[0]||`Run`).slice(0,120),body:`bivy-room-v1:${r.nodeId}:${e}`,label:r.nodeLabel,repo:r.sessionId?void 0:r.repo,runtimeId:r.sessionId?void 0:r.runtimeId,model:r.sessionId?void 0:r.model,approvalMode:t.approvalMode,sandbox:r.sandbox,maxAttempts:t.maxAttempts,targetKind:r.sessionId?`existing_session`:`new_session`,targetSessionId:r.sessionId});return this.deps.recordRunAccepted(),{runId:i.id}}catch(e){return{error:e instanceof Error?e.message:`Could not start this Run.`}}}async disconnectGithubApp(e,t){this.deps.sendGithubDisconnect({appId:e,hookId:t}),await this.deps.api.disconnectGithubApp(this.deps.local,{appId:e,hookId:t})}async removeNode(e){await this.deps.api.removeNode(this.deps.local,e),await this.deps.refreshNodes()}enablePush(){return this.deps.api.enablePush(this.deps.local)}disablePush(){return this.deps.api.disablePush(this.deps.local)}pushStatus(){return this.deps.api.pushStatus()}getNotificationPreferences(){return this.deps.api.getNotificationPreferences(this.deps.local)}setNotificationPreferences(e){return this.deps.api.setNotificationPreferences(this.deps.local,e)}},nl=class{store;ports;constructor(e,t){this.store=e,this.ports=t}mustQueue(e){let t=this.store.getFollowups(e).filter(e=>e.status===`queued`).length;return Ds(t,this.store.getState().activeSession.working)}supportsSteering(){let e=this.store.getState(),t=e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId;return Os(e.catalogs.runtimes.find(e=>e.id===t)?.capabilities)}list(e){return this.store.getFollowups(e)}edit(e,t,n,r){let i=this.store.getFollowups(e).find(e=>e.id===t),a=this.store.editFollowup(e,t,n,r,this.ports.now());return a.ok&&(this.ports.cancelBackstop(i?.scheduledAutomationId),this.ports.persistBackstop(e,t,a.item.text)),a}remove(e,t){let n=this.store.getFollowups(e).find(e=>e.id===t),r=this.store.removeFollowup(e,t);return r&&this.ports.cancelBackstop(n?.scheduledAutomationId),r}reorder(e,t,n){return this.store.reorderFollowup(e,t,n)}sendNow(e,t){let n=this.store.getFollowups(e).find(e=>e.id===t);if(n&&n.status===`queued`){if(this.store.reorderFollowup(e,t,0),!this.store.getState().activeSession.working){this.drain(e);return}this.supportsSteering()&&this.dispatch(e,n,`steer`)}}steer(e,t){let n=e.trim(),r=t?.length?t:void 0;if(!n&&!r)return!1;let i=this.store.getState().activeSession.activeSessionId;if(!i||!this.store.getState().activeSession.working||!this.supportsSteering())return!1;let a=this.ports.createClientMessageId();return this.store.addUserMessage(n,a,r),this.ports.send({kind:`prompt`,sessionId:i,text:n,clientMessageId:a,attachments:r,streamingBehavior:`steer`}),!0}drain(e){if(e!==this.store.getState().activeSession.activeSessionId||this.store.getState().activeSession.working)return;let t=ks(this.store.getFollowups(e));t&&this.dispatch(e,t)}confirm(e){if(e.type!==`session.user_message`)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId,n=typeof e.clientMessageId==`string`?e.clientMessageId:void 0;if(!t||!n)return;let r=this.store.getFollowups(t).find(e=>e.id===n);r&&this.ports.cancelBackstop(r.scheduledAutomationId),this.store.confirmFollowupSent(t,n)}retrySending(e){for(let t of this.store.getFollowups(e))t.status===`sending`&&this.ports.send({kind:`prompt`,sessionId:e,text:t.text,clientMessageId:t.id,attachments:t.attachments})}dispatch(e,t,n){this.store.markFollowupSending(e,t.id,this.ports.now()),this.store.addUserMessage(t.text,t.id,t.attachments),this.ports.send({kind:`prompt`,sessionId:e,text:t.text,clientMessageId:t.id,attachments:t.attachments,...n?{streamingBehavior:n}:{}})}},rl=`bivy.device.id`,il=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android.*Mobile/,`Android phone`],[/Android/,`Android tablet`],[/CrOS/,`Chromebook`],[/Macintosh|Mac OS X/,`Mac`],[/Windows/,`Windows PC`],[/Linux/,`Linux`]];function al(e,t=0){let n=il.find(([t])=>t.test(e))?.[1]??`Browser`;return n===`Mac`&&t>1?`iPad`:n}var ol;function sl(){if(ol)return ol;let e=``;try{e=localStorage.getItem(rl)??``}catch{}if(!e){e=`web:${crypto.randomUUID()}`;try{localStorage.setItem(rl,e)}catch{}}return ol={id:e,label:al(navigator.userAgent,navigator.maxTouchPoints)},ol}var cl=class extends Error{disclosure;constructor(e){super(e),this.disclosure=e,this.name=`NeedsDisclosureError`}};function ll(){return`r-${crypto.randomUUID()}`}function ul(){return crypto.randomUUID()}var dl=/^(localhost|127\.0\.0\.1|\[?::1\]?)$/,fl=`bivy-room-v1`,pl=8e3,ml=24e4;function hl(e=_t(r())){return n?!1:cc(`directNode`,!1)||new URLSearchParams(location.search).has(`local`)?!0:dl.test(location.hostname)&&!e.s&&!location.hash.includes(`payload=`)}var gl=new class e{store=new Es;local=_t(r());direct;solo;directPairCode=``;transport;transportGeneration=0;syncingActivationCredentials=!1;pendingLaunchRestoration=Promise.resolve();pendingPrompt=null;pendingLaunches=new Map;bootProgressTimers=new Map;bootstrapPhaseByNode=new Map;pendingAgentPick=null;pendingFollowups=[];pendingResume=[];resumingNode=new Set;ephemeralCorrelations=[];correlatedSessions=new Set;terminalListeners=new Set;pendingTranscriptions=new Map;pendingSpeech=new Map;pendingAcks=new Map;transcriptCache=js({maxSessions:50});attachmentLoader=new Is;attachmentDiskCache=new Fs;pendingGithubAppCode=null;pendingRoute=null;pendingRouteNode=null;pendingCrossNodeOpen=null;promptTargetSessionId=null;sessionSelectionEpoch=0;runUpdateListeners=new Set;appsChangedListeners=new Set;presenceListeners=new Set;composerFocusListeners=new Set;composerPrefillListeners=new Set;slashOpenListeners=new Set;productMetricsInFlight=new Set;sessionCoordinator;nodeCoordinator;credentialsModelsCoordinator;ephemeralCoordinator;accountCoordinator;followupCoordinator;constructor(){this.followupCoordinator=new nl(this.store,{send:e=>this.send(e),createClientMessageId:ul,now:Date.now,persistBackstop:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},cancelBackstop:e=>this.cancelScheduledFollowup(e)}),this.nodeCoordinator=new Qc({facts:()=>({direct:this.direct,solo:this.solo,signedIn:!!this.local.s,currentNodeId:this.local.cur||null}),status:()=>this.store.getState().connection.status,closeTransport:()=>{try{this.transport.close()}catch{}},setCurrentNode:e=>{this.local.cur=e,this.store.setCurrentNode(e||null)},resetSession:()=>this.store.resetSession(),seedSessions:()=>this.seedSessionsFromCache(),rebuildTransport:()=>{this.transport=this.buildTransport()},setStatus:e=>this.store.setStatus(e),connectTransport:()=>{this.transport.connect()},refreshNodes:()=>{this.refreshNodes()},refreshAccountSessions:()=>{this.refreshAccountSessions()},waitForOnline:e=>this.waitForOnline(e),listProviders:()=>this.listProviders()}),this.sessionCoordinator=new Zc({reportForkProgress:e=>this.store.setForkProgress({status:`working`,message:e}),send:e=>{this.sendToCurrentNode(e)},sendRequest:e=>{this.sendToCurrentNode(e)},createRequestId:ll,createClientMessageId:ul,currentNodeId:()=>this.local.cur,isDirect:()=>this.direct,sessionRuntime:e=>this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.runtimeId,switchNode:e=>this.switchNode(e),waitForOnline:e=>this.waitForOnline(e),openSession:(e,t,n)=>{this.openSession(e,t,{navigate:!n}),n&&this.store.apply({...n,type:`session.history`,sessionId:e})},addUserMessage:(e,t)=>this.store.addUserMessage(e,t),transcriptUrl:e=>`${d()}${oc({kind:`session`,id:e})}`,refreshAccountSessions:()=>{this.refreshAccountSessions()},launchManagedDestination:async(e,t)=>{let n=await Ft(this.local,e,{runtimeId:t});if(!n.nodeId)throw Error(`Managed fork destination launched without a node id`);return n.nodeId},reportCrossNodeFork:(e,t)=>{e===`error`?this.store.setError(t):e===`success`&&this.store.setNotice(t)}},{navigateNew:()=>Z({kind:`new`}),focusComposer:()=>this.focusComposer(),clearPendingPromptAndFollowups:()=>{this.pendingPrompt=null,this.pendingFollowups=[]},resetActiveSession:()=>{this.promptTargetSessionId=null,this.store.resetActiveSession()},seedDraftDefaults:()=>this.seedDraftDefaults(),listRuntimes:()=>this.listRuntimes(),listModels:()=>this.listModels(),hasNodeSettings:()=>!!this.store.getState().settings.nodeSettings,getNodeSettings:()=>this.getNodeSettings(),listRepos:()=>this.listRepos(),draftRepo:()=>this.store.getState().draft.repo,listBranches:e=>this.listBranches(e),activeSessionId:()=>{if(this.promptTargetSessionId)return this.promptTargetSessionId;let e=this.store.getState(),t=ac();return t.kind===`session`?t.id:e.activeSession.activeSessionId},isPendingLaunch:e=>this.isProvisionalSessionId(e),openSession:(e,t)=>{let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e);this.openSession(e,t??n?.path)},sessionIsSaved:e=>this.store.getState().sessionIndex.sessions.some(t=>t.sessionId===e&&t.status===`saved`),appendPendingLaunchFollowup:(e,t)=>{this.appendLaunchFollowup(e,t)},addUserMessage:(e,t,n)=>this.store.addUserMessage(e,t,n),mustQueue:e=>this.followupCoordinator.mustQueue(e),enqueueFollowup:(e,t)=>this.store.enqueueFollowup(e,t,Date.now()),persistFollowup:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},drainFollowups:e=>this.followupCoordinator.drain(e),shouldAutoResume:()=>this.shouldAutoResume(),bufferResume:e=>{this.pendingResume.push(e)},resumeNodeForSession:e=>{this.resumeNodeForSession(e)},hasPendingPrompt:()=>!!this.pendingPrompt,appendPendingFollowup:e=>{this.pendingFollowups.push(e)},draftSessionFields:()=>this.draftSessionFields(),setPendingPrompt:e=>{this.pendingPrompt=e},draftEphemeralRunner:()=>uc&&gc()?this.store.getState().draft.ephemeralConfig:null,startEphemeralLaunch:(e,t,n)=>{let r=new Date().toISOString(),i={id:e,prompt:t,config:n,logs:[],followups:[],phase:`provisioning`,createdAt:r,updatedAt:r};this.pendingLaunches.set(e,i),this.pendingLaunchStore.put(i),this.store.persistPendingSession(e,t.text,!0,n.name),this.launchDraftRunnerAndBind(e)},send:e=>this.send(e),resetDeletedActiveSession:()=>{this.store.resetActiveSession(),Z({kind:`new`})},removeSessionLocal:e=>this.store.removeSessionLocal(e),persistDeletedSessionTombstones:()=>this.persistDeletedSessionTombstones(),deleteTranscriptCache:e=>{this.transcriptCache.delete(e)},refreshSessions:()=>this.refreshSessions(),resolveSessionId:e=>e||this.store.getState().activeSession.activeSessionId}),this.credentialsModelsCoordinator=new $c({send:e=>{this.sendToCurrentNode(e)},awaitAck:(e,t)=>this.awaitAck(e,t),selectModelLocally:e=>{this.store.setCurrentModelLocal(e),this.store.setDraftModel({provider:e.provider,id:e.id})},rememberModel:e=>this.local.setLastChoice({modelProvider:e.provider,modelId:e.id}),isDirect:()=>this.direct,now:()=>Date.now(),isOnline:()=>this.store.getState().connection.status===`online`,importModelKeys:e=>this.ephemeralKeys.importModelKeys(e),removeModelKey:(e,t)=>this.ephemeralKeys.removeModelKey(e,t),accountModelKeys:async()=>(await this.ephemeralKeys.modelKeyEntries()).filter(e=>e.scope===`account`),importOAuthCredentials:e=>this.ephemeralKeys.importOAuthCredentials(e),removeOAuthCredential:(e,t,n)=>this.ephemeralKeys.removeOAuthCredential(e,t,n),accountOAuthCredentials:()=>this.ephemeralKeys.oauthCredentialEntries(),oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled()}),this.ephemeralCoordinator=new el({listConfigs:()=>$t(this.local),createConfig:e=>en(this.local,e),updateConfig:(e,t)=>tn(this.local,e,t),removeConfig:e=>nn(this.local,e),listSizes:(e,t)=>ji(e,{exec:ki(this.local),keys:this.ephemeralKeys},t),signedIn:()=>this.signedIn,direct:()=>this.direct,currentNodeId:()=>this.local.cur,roomKey:e=>this.local.keys()[e],draftRepo:()=>this.store.getState().draft.repo||void 0,githubToken:()=>this.githubTaskToken.get(),machines:()=>this.ephemeralMachines.list(),nodes:()=>this.store.getState().connection.nodes,correlations:()=>this.ephemeralCorrelations,launchMachine:e=>Mi({...e,debugKeepMachine:dc},{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),restoreManagedMachine:e=>It(this.local,e),destroyMachine:e=>Ni(e,{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),machineFromNode:e=>di(e),machineFromCorrelation:ui,connectToNode:(e,t)=>this.connectToNode(e,t),refreshNodes:()=>{this.refreshNodes()},reportError:e=>this.store.setError(e.message),defaultConfig:e=>{let t=ni(e);return{name:G(e)?.name??e,region:t?.defaultRegion??null,size:t?.defaultSize??null}},validateProviderToken:(e,t)=>ri(e,t,ki(this.local)),setProviderToken:(e,t)=>this.ephemeralKeys.setToken(e,t),removeProviderToken:e=>this.ephemeralKeys.remove(e),getProviderToken:e=>this.ephemeralKeys.getToken(e),assignWorkItem:(e,t)=>Pn(this.local,e,t),nodeLabel:e=>ai(e),followupCount:e=>this.store.getFollowups(e).length,recordSessionCorrelation:(e,t)=>{this.recordSessionCorrelation(e,t)},schedule:(e,t)=>{setTimeout(e,t)}}),this.accountCoordinator=new tl({local:this.local,sendGithubDisconnect:({appId:e,hookId:t})=>this.send({kind:`github.app.disconnect`,requestId:ll(),appId:e||void 0,hookId:t||void 0}),refreshNodes:()=>this.refreshNodes(),api:{fetchMe:Vt,fetchGithubApp:Kt,fetchGithubQueue:Nn,fetchAutomationRuns:Dn,cancelAutomationRun:jn,disconnectGithubApp:qt,removeNode:Wt,enablePush:qn,disablePush:Jn,pushStatus:Yn,getNotificationPreferences:Xn,setNotificationPreferences:Zn,createOneOffRun:En,setGithubAppDefaultNode:Jt,setGithubAppTriggerAccess:Yt,assignWorkItem:Pn,deleteWorkItem:Fn,clearWorkQueue:In},runContext:()=>{let e=this.store.getState(),t=e.activeSession.activeSessionId??void 0,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t):void 0,r=t?this.resolveSessionNodeId(t):e.connection.currentNodeId??void 0,i=r?e.connection.nodes.find(e=>e.id===r):void 0;return{accountMode:this.accountMode(),sessionId:t,nodeId:r,roomKey:r?this.local.keys()[r]:void 0,nodeLabel:i?.name?`bivy/${i.name}`:void 0,repo:e.draft.repo??void 0,runtimeId:e.catalogs.selectedAgentId??void 0,model:e.catalogs.currentModel?.id,sandbox:n?.sandbox??(t?void 0:e.draft.sandbox??e.settings.nodeSettings?.defaultSandbox)}},encrypt:async(e,t)=>D(await E(C(e)),t),recordRunAccepted:()=>this.recordProductMilestone(`run_accepted`)}),this.store.onHistoryPersist=(e,t,n,r)=>{let i=this.store.attachmentsForHistory(t);this.transcriptCache.put(e,t,n,r,i)},this.store.requestFreshHistory=()=>{let e=this.store.getState().activeSession.activeSessionId;e&&this.requestHistory(e)},this.store.requestReplay=(e,t)=>{this.send({kind:`session.replay`,sessionId:e,afterSeq:t})},this.store.onSessionSettled=()=>{this.refreshSessions();let e=this.store.getState().activeSession.activeSessionId;e&&(this.store.settleSendingFollowups(e),this.followupCoordinator.drain(e),this.maybeTeardownFinishedEphemeral(e))},this.store.onSessionCreatedElsewhere=()=>this.refreshSessions();let e=/^#pair=([A-Za-z0-9_-]+)$/.exec(location.hash);e&&(this.directPairCode=e[1]??``,history.replaceState(null,``,location.pathname+location.search));try{!n&&xt(this.local,location.hash)&&history.replaceState(null,``,location.pathname+location.search)}catch{}this.seedDraftDefaults(),this.detectGithubAppReturn(),this.direct=hl(this.local),this.solo=!n&&!this.direct&&!this.local.s&&!!this.local.solo()[this.local.cur],!this.direct&&!this.local.cp&&(this.local.cp=d()),this.transport=this.buildTransport(),this.store.setCurrentNode(this.direct?null:this.local.cur||null),this.restoreDeletedSessionTombstones(),this.seedSessionsFromCache(),this.installSessionCachePersist(),this.installFollowupAutoDrain(),this.pendingLaunchRestoration=this.restorePendingLaunches().catch(()=>{this.store.setError(`Couldn't load saved Cloud startups.`)}),!this.direct&&this.local.s&&this.refreshAccountSessions(),this.store.setSignedIn(this.signedIn),this.pendingRoute=ac(),this.pendingRouteNode=this.consumeDeepLinkNode()}consumeDeepLinkNode(){try{let e=new URLSearchParams(location.search),t=(e.get(`node`)||``).trim();if(!t)return null;e.delete(`node`);let n=e.toString();return history.replaceState(null,``,location.pathname+(n?`?${n}`:``)+location.hash),t}catch{return null}}buildTransportHandlers(){let e=++this.transportGeneration;return{onEvent:t=>{if(e!==this.transportGeneration)return;let n=String(t.type||``);if(this.resolveAck(t),(n===`models.list`||n===`model.updated`)&&this.isCloudModelDraft())return;if(n===`node.theme`){p(t.theme);return}if(n===`pong`){let e=String(t.requestId||``);e&&this.pendingLivenessPings.delete(e);return}if(n===`approval.resolved`&&typeof t.remembered==`string`&&t.remembered&&this.store.setNotice(`Allowing “${t.remembered}” without asking for the rest of this session.`),n.startsWith(`terminal.`)||n.startsWith(`multiplexer.`)){if([`terminal.list`,`terminal.created`,`terminal.activity`,`terminal.closed`,`terminal.exit`].includes(n))this.store.apply(this.eventWithNodeScope(t));else if(n===`terminal.tui`)this.store.apply(t);else if(n===`terminal.takeover.result`){let e=t;e.ok&&e.sessionId?this.openSession(String(e.sessionId)):e.error&&this.store.setError(String(e.error))}for(let e of this.terminalListeners)e(t);return}if(n===`run.updated`){let e=typeof t.runId==`string`?t.runId:``,n=typeof t.revision==`string`?t.revision:void 0;if(e)for(let t of this.runUpdateListeners)t(e,n);return}if(n===`session.presence`){let e=t.presence;if(e?.sessionId)for(let t of this.presenceListeners)t(e);return}if(n===`apps.changed`){let e=typeof t.sessionId==`string`?t.sessionId:``;if(e)for(let t of this.appsChangedListeners)t(e);return}if(n===`transcription`){this.resolveTranscription(t);return}if(n===`speech.audio`){this.resolveSpeech(t);return}if(this.sessionCoordinator.handleEvent(t)||typeof t.sessionId==`string`&&this.isProvisionalSessionId(t.sessionId)||[...this.pendingLaunches.values()].some(e=>t.requestId&&t.requestId===e.prompt.requestId||e.sessionId&&t.sessionId===e.sessionId))return;let r=this.store.getState().activeSession.activeSessionId;if(t.type===`session.created`&&r&&this.pendingLaunches.get(r)?.machine?.nodeId===this.local.cur)return;let i=this.store.getState(),a=this.eventWithNodeScope(t);if(this.store.apply(a),a.type===`models.list`&&typeof a.runtimeId==`string`&&this.settleRuntimeModels(a.runtimeId),a.type===`session.error`&&a.sessionId){let e=this.store.getState().sessionIndex.sessions.find(e=>e.sessionId===a.sessionId);if(e?.launchProgress&&!e.launchProgress.firstResponseAt){let t=typeof a.error==`string`?a.error:`The agent could not respond. Check its model and credentials.`;this.store.updateLaunchCheckpoint(e.sessionId,`agent`,`failed`,t),this.store.failPendingSession(e.sessionId)}}let o=this.store.getState().activeSession;o.activeSessionId&&!i.activeSession.transcript.some(e=>e.role===`assistant`&&!!e.text&&!e.tool)&&o.transcript.some(e=>e.role===`assistant`&&!!e.text&&!e.tool)&&this.store.markLaunchFirstResponse(o.activeSessionId),this.observeActivationMilestones(i,a),a.type===`providers.list`&&!this.syncingActivationCredentials&&this.send({kind:`activation.readiness`}),a.type===`credentials.records`&&(this.maybeGrantManagedCredential(),this.isCloudModelDraft()&&this.listModels()),a.type===`session.deleted`&&this.persistDeletedSessionTombstones(),this.maybeFlushPendingPrompt(a),this.followupCoordinator.confirm(a),this.maybeRestoreDraftAgent(a),this.maybeSelectInstalledAgent(a),this.maybeRefreshModelsForRuntime(a),this.reconcileSessionList(a)},onStatus:t=>{if(e!==this.transportGeneration)return;let n=this.store.getState(),r=n.connection.status;this.store.setStatus(t),this.observeActivationMilestones(n,{type:`connection.status`}),t===`online`&&r!==`online`?this.onReconnected():(t===`reconnecting`||t===`offline`)&&(this.store.markStreamInterrupted(),r!==`reconnecting`&&r!==`offline`&&this.refreshNodesThrottled())},onError:t=>{e===this.transportGeneration&&this.store.setError(a(t))}}}buildTransport(){let e=this.buildTransportHandlers(),t=cc(`directNode`,!1);return this.direct?new sa({bootstrap:new URLSearchParams(location.search).get(`bootstrap`)||``,...t?{tokenStore:r(),pairCode:this.directPairCode,deviceName:sl().label,requireToken:!0}:{},handlers:e}):new ga({store:this.local,handlers:e})}productMetricClient(){return matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`}recordProductMilestone(e,t=!1){if(this.direct||this.solo||!this.local.s)return;let n=`bivy.product-metric.${e}`;if(t){try{if(localStorage.getItem(n)===`1`)return}catch{}if(this.productMetricsInFlight.has(e))return;this.productMetricsInFlight.add(e)}An(this.local,e,this.productMetricClient()).then(()=>{if(t)try{localStorage.setItem(n,`1`)}catch{}}).catch(()=>{}).finally(()=>this.productMetricsInFlight.delete(e))}static FIRST_RUN_STEP_EVENTS={machine_online:{ok:`first_run_machine_ready`,failed:`first_run_machine_failed`},agent_installed:{ok:`first_run_agent_verified`,failed:`first_run_agent_failed`},credential_valid:{ok:`first_run_provider_connected`,failed:`first_run_provider_failed`}};observeActivationMilestones(t,n){let r=this.store.getState(),i=e=>({direct:this.direct,signedIn:e.connection.signedIn,status:e.connection.status,runtimes:e.catalogs.runtimes,readiness:e.catalogs.activationReadiness}),a=rt(i(t)),o=rt(i(r));!a.activated&&o.activated&&this.recordProductMilestone(`activation_ready`,!0);for(let[t,n]of Object.entries(e.FIRST_RUN_STEP_EVENTS)){let e=a.checks.find(e=>e.id===t)?.state,r=o.checks.find(e=>e.id===t)?.state;e!==`passed`&&r===`passed`&&this.recordProductMilestone(n.ok,!0),e!==`failed`&&r===`failed`&&this.recordProductMilestone(n.failed,!0)}if(n.type===`session.history`)return;let s=e=>e.activeSession.transcript.filter(e=>e.role===`assistant`&&!!e.text&&!e.tool).length;s(t)===0&&s(r)>0&&(Uc(),this.recordProductMilestone(`first_useful_response`,!0))}needsAuth(){return this.connectionRequirement().type===`authentication-required`}needsNode(){return this.connectionRequirement().type===`node-required`}needsSetup(){return this.connectionRequirement().type!==`ready`}connectionRequirement(){return this.nodeCoordinator.requirement({direct:this.direct,solo:this.solo,signedIn:!!this.local.s,currentNodeId:this.local.cur||null})}listNodes(){return Et(this.local)}centralGithubApp(){return Dt(this.local)}createCentralGithubInstall(e=`/`){return Ot(this.local,e)}managedAutomationTarget(){return kt(this.local)}async managedCredentialReady(){return(await At(this.local)).ready}async waitForManagedCredential(e=2e4,t=-1){let n=Date.now()+e;for(;Date.now()<n;){let e=await At(this.local);if(e.ready&&e.generation>t)return;await new Promise(e=>setTimeout(e,750))}throw Error(`The encrypted Bivy Cloud credential was not published. Try provider setup again.`)}async setupManagedCredentials(){let e=this.store.getState().activeSession.activeSessionId;if(!e||!this.pendingLaunches.has(e))throw Error(`The original Cloud session is no longer available.`);await this.retryPendingLaunch(e)}ensureManagedSessionDefaults(){return Pt(this.local)}createNodeClaim(){return Lt(this.local)}listNodeClaims(){return Rt(this.local)}revokeNodeClaim(e){return zt(this.local,e)}selectNode(e){this.switchNode(e)}get signedIn(){return!!this.local.s}async completeSignIn(e,t=()=>!0){if(e&&t()){this.local.s=e,this.local.cp||(this.local.cp=d());try{await m()}catch(t){throw this.local.s===e&&(this.local.s=``,await m().catch(()=>{})),t}if(!t()){this.local.s===e&&(this.local.s=``,await m());return}if(this.solo){location.reload();return}this.nativeSubscriptionsStopped=!1,this.store.setSignedIn(!0),this.syncDeviceVault().catch(()=>{}),this.connect()}}nativeSubscriptionSyncAt=0;nativeSubscriptionSyncToken=``;nativeSubscriptionSyncing=!1;nativeSubscriptionsStopped=!1;syncNativeSubscriptions(){let e=this.local.s;!this.nativeSubscriptionsStopped&&e&&o()?.synchronize({token:e,controlPlane:d()}).catch(()=>{this.store.setError(`Notification registration could not be refreshed. Open Notifications to retry.`)}),!this.nativeSubscriptionsStopped&&e&&l()&&!this.nativeSubscriptionSyncing&&(e===this.nativeSubscriptionSyncToken&&Date.now()-this.nativeSubscriptionSyncAt<3e5||(this.nativeSubscriptionSyncing=!0,this.nativeSubscriptionSyncToken=e,this.nativeSubscriptionSyncAt=Date.now(),s(e).catch(()=>{!this.nativeSubscriptionsStopped&&this.local.s===e&&this.store.setError(`Subscription status could not be refreshed. Open Subscriptions to retry.`)}).finally(()=>{this.nativeSubscriptionSyncing=!1})))}connect(){this.nodeCoordinator.connect(),this.syncNativeSubscriptions()}foregroundTimer=null;backgroundDisconnectTimer=null;livenessTimer=null;pendingLivenessPings=new Set;installLifecycleHandlers(){if(typeof document>`u`)return;let n=()=>{this.backgroundDisconnectTimer&&=(clearTimeout(this.backgroundDisconnectTimer),null),this.refreshAfterForeground(),this.syncNativeSubscriptions()};document.addEventListener(`visibilitychange`,()=>{if(document.visibilityState===`visible`){n();return}this.direct||this.backgroundDisconnectTimer||(this.backgroundDisconnectTimer=setTimeout(()=>{this.backgroundDisconnectTimer=null,document.visibilityState===`hidden`&&this.transport.close()},e.BACKGROUND_DISCONNECT_DELAY_MS))}),f(n),window.addEventListener(`pageshow`,n),window.addEventListener(`focus`,n),window.addEventListener(`popstate`,e=>{e.state?.bivyNativeLink||this.applyRoute(ac(),{navigate:!1})}),t(e=>{let t=sc(e,d());t&&(history.replaceState(null,``,t.path),this.pendingRoute=ac(),this.pendingRouteNode=t.node,window.dispatchEvent(new PopStateEvent(`popstate`,{state:{bivyNativeLink:!0}})),this.signedIn&&this.store.getState().connection.status===`online`&&this.applyInitialRoute())})}onRunUpdated(e){return this.runUpdateListeners.add(e),()=>this.runUpdateListeners.delete(e)}onPresence(e){return this.presenceListeners.add(e),()=>this.presenceListeners.delete(e)}async getPresence(e){return(await this.awaitAck({kind:`session.presence.get`,sessionId:e})).presence??{sessionId:e}}publishDraft(e,t){this.store.getState().connection.status===`online`&&this.awaitAck({kind:`session.presence.draft`,sessionId:e,device:sl(),text:t}).catch(()=>{})}onAppsChanged(e){return this.appsChangedListeners.add(e),()=>this.appsChangedListeners.delete(e)}onComposerFocus(e){return this.composerFocusListeners.add(e),()=>this.composerFocusListeners.delete(e)}focusComposer(){for(let e of this.composerFocusListeners)e()}onComposerPrefill(e){return this.composerPrefillListeners.add(e),()=>this.composerPrefillListeners.delete(e)}prefillComposer(e,t=[]){for(let n of this.composerPrefillListeners)n(e,t);return this.focusComposer(),this.composerPrefillListeners.size>0}onOpenSlash(e){return this.slashOpenListeners.add(e),()=>this.slashOpenListeners.delete(e)}openSlashCommands(){let e=this.store.getState(),t=e.activeSession.activeSessionId;t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.status===`saved`&&this.openSession(t):this.listModels();for(let e of this.slashOpenListeners)e()}applyRoute(e,t={}){e.kind===`session`?this.openSession(e.id,void 0,t):e.kind!==`settings`&&e.kind!==`automations`&&e.kind!==`library`&&e.kind!==`run`&&this.newSession(t)}applyInitialRoute(){let e=this.pendingRoute;if(!e)return;this.pendingRoute=null;let t=this.pendingRouteNode;this.pendingRouteNode=null,e.kind===`session`&&(t?this.openSessionOnNode(e.id,void 0,t):this.applyRoute(e,{navigate:!1}))}refreshAfterForeground(){this.foregroundTimer&&clearTimeout(this.foregroundTimer),this.foregroundTimer=setTimeout(()=>{if(this.foregroundTimer=null,this.needsSetup())return;let e=this.store.getState().connection.status;if(e===`offline`){this.connect();return}if(e!==`online`)return;this.refreshSessions();let t=this.store.getState().activeSession.activeSessionId;t?this.requestHistory(t):this.retryPendingSessionNew(),this.listModels(),this.verifyLiveness()},150)}static BACKGROUND_DISCONNECT_DELAY_MS=15e3;static LIVENESS_TIMEOUT_MS=2e3;verifyLiveness(){this.livenessTimer&&clearTimeout(this.livenessTimer),this.pendingLivenessPings.clear();let t=ll();this.pendingLivenessPings.add(t),this.send({kind:`ping`,requestId:t}),this.livenessTimer=setTimeout(()=>{this.livenessTimer=null,this.store.getState().connection.status===`online`&&this.pendingLivenessPings.delete(t)&&this.transport.reconnect()},e.LIVENESS_TIMEOUT_MS)}async refreshNodes(){if(!this.direct&&this.signedIn){this.lastNodeRefreshAt=Date.now();try{let e=await this.listNodes();this.store.setNodes(e),this.local.cur&&!e.some(e=>e.id===this.local.cur)&&(this.currentNodeIsRebuildable()?this.markCurrentNodeAwaitingRebuild():this.clearCurrentNode()),this.refreshAccountSessions()}catch{}}}clearCurrentNode(){try{this.transport.close()}catch{}this.local.cur=``,this.store.setCurrentNode(null),this.store.resetSession(),this.store.setStatus(`offline`)}currentNodeIsRebuildable(){let e=this.local.cur;if(!e)return!1;try{if(!this.local.keys()[e])return!1}catch{return!1}return this.ephemeralCorrelations.some(t=>t.nodeId===e)}markCurrentNodeAwaitingRebuild(){if(this.store.getState().connection.status!==`offline`){try{this.transport.close()}catch{}this.store.setStatus(`offline`)}}lastNodeRefreshAt=0;refreshNodesThrottled(){!this.direct&&this.signedIn&&(Date.now()-this.lastNodeRefreshAt<1e4||this.refreshNodes())}pickDraftEphemeralRunner(e){this.store.setDraftEphemeralConfig(e),this.listModels()}switchNode(e){this.store.setDraftEphemeralConfig(null),this.nodeCoordinator.switchNode(e)}connectToNode(e,t){return this.nodeCoordinator.connectToNode(e,t)}async signOut(){this.nativeSubscriptionsStopped=!0,await Promise.allSettled([h(),c()]),this.nativeSubscriptionSyncToken=``,this.nativeSubscriptionSyncAt=0,this.sessionTitleKeys?.close(),this.machineRequests?.close();try{this.transport.close()}catch{}let e=this.local.device()?.pub;try{e=(await Ui(this.local)).pub}catch{}try{await Gn(this.local,e)}catch{}try{await Bi()}catch{}await this.attachmentDiskCache.clear(),this.local.clear(),await m(),this.store.setSignedIn(!1),location.assign(`/`)}listDevices(){return Un(this.local)}isCurrentDevice(e){return!!e&&this.local.device()?.pub===e}removeDevice(e){return Wn(this.local,e)}isProvisionalSessionId(e){return e.startsWith(`starting-`)||this.pendingLaunches.has(e)||this.store.getState().sessionIndex.sessions.some(t=>t.sessionId===e&&t.pendingLaunch)}sendToCurrentNode(e){typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId)||this.transport.send(e)}async appendLaunchFollowup(e,t){this.pendingLaunches.has(e)||await this.pendingLaunchRestoration;let n=this.pendingLaunches.get(e);if(!n){this.store.setError(`Couldn't find the saved Cloud startup. Your message has not been sent.`);return}n.followups.push(t);try{await this.pendingLaunchStore.put(n)}catch{this.store.setError(`Couldn't save the queued message. Keep this page open until startup finishes.`)}}send(e){this.sessionCoordinator.send(e.kind===`prompt`?{...e,device:sl()}:e)}updateNode(){Ms(this.store,()=>this.transport.send({kind:`node.update`}))}awaitAck(e,t=1e4){if(typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId))return Promise.reject(Error(`Cloud startup hasn't created a conversation yet.`));let n=ll();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingAcks.delete(n),i(Error(`Timed out waiting for the machine to respond.`))},t);this.pendingAcks.set(n,{resolve:r,reject:i,timer:a}),this.sendToCurrentNode({...e,requestId:n})})}fetchAttachment(e,t=0){if(!e)return Promise.resolve(null);let n=this.attachmentHomes.get(e),r=n&&n!==this.local.cur?n:null,i=r?`bivy.sessions.${r}`:this.sessionCacheKey();return this.attachmentLoader.fetch(JSON.stringify([i,e]),t,async()=>{let t=await this.attachmentDiskCache.get(i,e);if(t)return t;if(!r&&i!==this.sessionCacheKey())return null;let n={kind:`attachment.fetch`,hash:e},a=await(r?this.machineRequest(r,n,6e5):this.awaitAck(n,6e5));if(!a||typeof a.data!=`string`)return null;let o={mimeType:String(a.mimeType||`application/octet-stream`),data:a.data};return this.attachmentDiskCache.put(i,e,o),o})}async appCommand(e,t,n={},r){let{connection:i}=this.store.getState();e===`apps.open`&&Object.assign(n,{scale:typeof devicePixelRatio==`number`&&devicePixelRatio>=1.5?2:1});let a=this.isOtherMachine(r);if(!a&&i.status!==`online`)throw Error(`Connect to the machine to open its apps.`);let o=a?await this.machineRequest(r,{kind:e,sessionId:t,...n}):await this.awaitAck({kind:e,sessionId:t,...n},3e4);if(!a&&this.store.getState().connection.currentNodeId!==i.currentNodeId)throw Error(`Machine changed. Reopen Apps on the selected machine.`);let s=a?r:i.currentNodeId;if(e===`apps.list`&&s){for(let e of o.apps??[])for(let t of e.views)if(t.kind===`web`)for(let e of t.notes??[])e.shot&&this.attachmentHomes.set(e.shot.hash,s)}return o}async listMachineArtifacts(){let e=await this.acrossMachines(`artifacts.list`,e=>e.artifacts??[]);for(let t of e.items)t.nodeId&&this.attachmentHomes.set(t.hash,t.nodeId);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}async listMachineApps(){let e=await this.acrossMachines(`apps.list`,e=>e.apps??[]);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}attachmentHomes=new Map;machineRequests;isOtherMachine(e){return!this.direct&&!!e&&e!==this.local.cur}machineRequest(e,t,n=3e4){return this.isOtherMachine(e)?(this.machineRequests??=new Bs(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:t})),this.machineRequests.request(e,t,n)):this.store.getState().connection.status===`online`?this.awaitAck(t,n):Promise.reject(Error(`Connect to the machine first.`))}async acrossMachines(e,t){let{nodes:n,status:r}=this.store.getState().connection,i=r===`online`?[this.direct?null:this.local.cur||null]:[],a=this.direct?i:[...i,...n.filter(e=>e.online&&e.id!==this.local.cur).map(e=>e.id)],o=await Promise.allSettled(a.map(async n=>t(await this.machineRequest(n,{kind:e})).map(e=>({...e,nodeId:n}))));return{items:o.flatMap(e=>e.status===`fulfilled`?e.value:[]),unreachable:a.filter((e,t)=>o[t].status===`rejected`).map(e=>n.find(t=>t.id===e)?.name||`A machine`)}}resolveAck(e){let t=String(e.requestId||``),n=t?this.pendingAcks.get(t):void 0;if(n){if(clearTimeout(n.timer),this.pendingAcks.delete(t),String(e.type||``).endsWith(`.error`)){let t=Error(String(e.error||`Save failed`));Object.assign(t,e),n.reject(t)}else n.resolve(e)}}async discoverNativeSessions(){let e=(await this.awaitAck({kind:`session.discover`},2e4)).sessions;return Array.isArray(e)?e:[]}async importNativeSession(e,t,n={}){let r;try{r=await this.awaitAck({kind:`session.import`,runtimeId:e,ref:t,acceptDisclosure:n.acceptDisclosure??!1},6e4)}catch(e){let t=e;throw t?.needsDisclosure?new cl(String(t.disclosure??t.message??`This import needs your confirmation.`)):e}let i=String(r.sessionId||``);if(!i)throw Error(`Import did not return a session id`);let a=r.seedPrompt;if(typeof a==`string`&&a.trim()){this.openSession(i);let e=ul();this.store.addUserMessage(a,e),this.send({kind:`prompt`,sessionId:i,text:a,clientMessageId:e})}else this.openSession(i,t);return i}waitForOnline(e=2e4){return this.store.getState().connection.status===`online`?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{i(),n(Error(`Destination machine did not come online`))},e),i=this.store.subscribe(()=>{this.store.getState().connection.status===`online`&&(clearTimeout(r),i(),t())})})}promoteSession(e,t){return this.sessionCoordinator.promote(e,t)}forkInFlight=!1;startSessionLike(e,t,n){return this.sessionCoordinator.startLike(e,t,n)}async forkSession(e,t={},n){if(this.forkInFlight)throw Error(`A session fork is already in progress`);this.forkInFlight=!0,this.store.setForkProgress({status:`working`,message:`Preparing to fork the session…`});let r=this.store.getState(),i=r.sessionIndex.sessions.find(t=>t.sessionId===e),a=t.sourceAgentId||i?.runtimeId,o=t.agentId||a,s=(e,t)=>{let n=r.catalogs.runtimes.find(t=>t.id===e);return String(n?.displayName||n?.name||t||e||`agent`)},c=i?.name||`session ${e.slice(0,8)}`,l=s(a,i?.agentName),u=s(o,o===a?i?.agentName:void 0);try{await n?.();let r=await this.sessionCoordinator.fork(e,t);return this.store.getState().activeSession.activeSessionId!==r.sessionId&&this.openSession(r.sessionId,void 0,{navigate:!1}),await this.waitForForkReady(r.sessionId),Z({kind:`session`,id:r.sessionId}),this.store.setNotice(`This session was forked from “${c}” with ${l} to ${u}.`),this.store.setForkProgress(null),r}catch(e){throw this.store.setForkProgress({status:`error`,message:e instanceof Error?e.message:String(e)}),e}finally{this.forkInFlight=!1}}waitForForkReady(e){let t=()=>{let t=this.store.getState().activeSession;return t.activeSessionId===e&&!t.opening};return t()?Promise.resolve():(this.store.setForkProgress({status:`working`,message:`Loading the forked session…`}),new Promise((e,n)=>{let r=setTimeout(()=>{i(),n(Error(`The fork was created, but its conversation could not be loaded. Reopen it from the session list.`))},3e4),i=this.store.subscribe(()=>{t()&&(clearTimeout(r),i(),e())})}))}refreshSessions(){if(this.send({kind:`terminal.list`}),!this.direct&&this.signedIn){this.refreshAccountSessions(),this.local.cur&&this.send({kind:`sessions.list`});return}this.send({kind:`sessions.list`})}async decryptSessionTitle(e){if(!e.titleEnc)return`Untitled session`;let t=this.local.keys()[e.nodeId];if(!t)return`Untitled session`;try{return(await O(await E(C(t)),e.titleEnc)).trim()||`Untitled session`}catch{return`Untitled session`}}sessionTitleKeys;async refreshAccountSessions(){if(!this.direct&&this.signedIn)try{let e=await Bt(this.local);this.sessionTitleKeys??=new Ls(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:{onStatus:e=>{e===`online`&&t()},onEvent:()=>{}}}),()=>{this.refreshAccountSessions()}),this.sessionTitleKeys.ensure(e.filter(e=>e.titleEnc).map(e=>e.nodeId));let t=this.store.getState().sessionIndex.sessions,n=(await Promise.all(e.map(async e=>{let n=String(e.sessionId||e.id||``),r=String(e.nodeId||``),i=t.find(e=>e.sessionId===n&&(!e.nodeId||e.nodeId===r)),a=await this.decryptSessionTitle(e);return{...i,sessionId:n,nodeId:r,name:a===`Untitled session`&&i?.name||a,source:e.source||i?.source,branch:e.branch||i?.branch,status:e.status,attention:Array.isArray(e.attention)?e.attention:i?.attention,updatedAt:e.updatedAt||i?.updatedAt}}))).filter(e=>e.sessionId&&e.nodeId),r=new Set(n.map(e=>e.sessionId)),i=this.store.getState().sessionIndex.sessions,a=this.ephemeralCorrelations.filter(e=>!r.has(e.sessionId)&&!!this.local.keys()[e.nodeId]).map(e=>{let t=i.find(t=>t.sessionId===e.sessionId);return{...t,sessionId:e.sessionId,nodeId:e.nodeId,name:t?.name||(e.repo?`${e.repo}`:`Rebuildable session`),source:t?.source,status:`saved`,rebuildable:!0,updatedAt:t?.updatedAt}}),o=new Set([...this.pendingLaunches.values()].map(e=>e.sessionId));this.store.setSessions([...n,...a].filter(e=>!o.has(e.sessionId)))}catch{}}eventWithNodeScope(e){if(this.direct||!this.local.cur)return e;let t=this.local.cur;if(e.type===`sessions.list`){let n=e,r=Array.isArray(n.sessions)?n.sessions:[],i=new Set(r.map(e=>String(e?.sessionId||e?.id||``)).filter(Boolean)),a=this.store.getState().sessionIndex.sessions.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.sessionId));return{...e,sessions:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`session.created`)return{...e,nodeId:t};if(e.type===`terminal.list`){let n=e,r=Array.isArray(n.terminals)?n.terminals:[],i=new Set(r.map(e=>String(e?.termId||``)).filter(Boolean)),a=this.store.getState().sessionIndex.runTerminals.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.termId));return{...e,terminals:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`terminal.created`){let n=e;return n.terminal?{...e,terminal:{...n.terminal,nodeId:n.terminal.nodeId||t}}:e}return e}static DELETED_SESSIONS_KEY=`bivy.deleted-sessions`;restoreDeletedSessionTombstones(){try{let t=localStorage.getItem(e.DELETED_SESSIONS_KEY);t&&this.store.seedDeletedSessionTombstones(JSON.parse(t)),this.persistDeletedSessionTombstones()}catch{}}persistDeletedSessionTombstones(){try{let t=this.store.deletedSessionTombstones();Object.keys(t).length?localStorage.setItem(e.DELETED_SESSIONS_KEY,JSON.stringify(t)):localStorage.removeItem(e.DELETED_SESSIONS_KEY)}catch{}}sessionCacheKey(){return`bivy.sessions.${this.direct?`direct`:this.local.cur||``}`}seedSessionsFromCache(){if(this.direct||this.local.cur)try{let e=localStorage.getItem(this.sessionCacheKey());e&&this.store.seedSessions(JSON.parse(e))}catch{}}installSessionCachePersist(){if(typeof localStorage>`u`)return;let e=this.store.getState().sessionIndex.sessions;this.store.subscribe(()=>{let t=this.store.getState().sessionIndex.sessions;if(t!==e){e=t;try{localStorage.setItem(this.sessionCacheKey(),JSON.stringify(t.slice(0,100)))}catch{}}})}installFollowupAutoDrain(){let e=this.store.getState().activeSession.working,t=this.store.getState().activeSession.activeSessionId;this.store.subscribe(()=>{let n=this.store.getState().activeSession.activeSessionId,r=this.store.getState().activeSession.working,i=n!=null&&n===t&&e&&!r;e=r,t=n,i&&this.followupCoordinator.drain(n)})}async findLiveRunTerminal(e,t,n=4e3){let r=()=>this.store.getState().sessionIndex.runTerminals.find(n=>n.sessionId===e&&(!t||!n.nodeId||n.nodeId===t))??null;return r()||(this.direct||!t||t===this.local.cur&&this.store.getState().connection.status===`online`?null:(await this.connectToNode(t),this.send({kind:`terminal.list`}),new Promise(e=>{let t=setTimeout(()=>{i(),e(r())},n),i=this.store.subscribe(()=>{let n=r();n&&(clearTimeout(t),i(),e(n))})})))}selectSessionTarget(e){return this.promptTargetSessionId=e,this.sessionSelectionEpoch+=1,Z({kind:`session`,id:e}),this.sessionSelectionEpoch}isCurrentSessionTarget(e,t){return this.promptTargetSessionId===e&&(t===void 0||t===this.sessionSelectionEpoch)}openSessionOnNode(e,t,n){if(this.selectSessionTarget(e),this.pendingLaunches.has(e)){this.openPendingLaunch(e);return}if(!this.direct&&n&&n!==this.local.cur){this.pendingCrossNodeOpen={sessionId:e,path:t},Z({kind:`session`,id:e}),this.switchNode(n),this.store.beginOpen(e);return}this.openSession(e,t)}openSession(e,t,n={}){if(this.promptTargetSessionId=e,this.pendingLaunches.has(e)){this.openPendingLaunch(e,n);return}n.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.send({kind:`session.open`,sessionId:e,path:t}),this.listModels(),this.seedAndRequestHistory(e)}async seedAndRequestHistory(e){try{let t=await this.transcriptCache.get(e);t&&this.store.getState().activeSession.activeSessionId===e&&(this.store.restoreAttachments(t.attachments),this.store.seedHistory(e,t.messages,t.count,t.historyHash))}catch{}this.requestHistory(e)}onReconnected(){let e=!1;if(this.pendingCrossNodeOpen){let t=this.pendingCrossNodeOpen;this.pendingCrossNodeOpen=null,this.openSession(t.sessionId,t.path),e=!0}this.refreshAccountSessions(),this.store.clearActivationReadiness(),this.syncingActivationCredentials=!0;let t=this.transportGeneration;this.syncAccountCredentialsWithNode().finally(()=>{t===this.transportGeneration&&(this.syncingActivationCredentials=!1,this.send({kind:`activation.readiness`}))}),this.resyncScheduledFollowups(),this.seedEphemeralNodeIfNeeded(),this.maybePromptFirstRunModelAuth(),this.refreshEphemeralCorrelations(),e||this.applyInitialRoute();let n=this.store.getState().activeSession.activeSessionId;if(n&&!e?(this.requestHistory(n),this.listModels(),this.followupCoordinator.retrySending(n),this.drainPendingResume(n)):n||this.retryPendingSessionNew(),this.pendingGithubAppCode){let{code:e,state:t}=this.pendingGithubAppCode;this.pendingGithubAppCode=null,this.githubAppManifestCode(e,t)}}detectGithubAppReturn(){try{let e=new URLSearchParams(location.search),t=!1;try{t=sessionStorage.getItem(`bivy.githubAppPending`)===`1`,t&&sessionStorage.removeItem(`bivy.githubAppPending`)}catch{}if(!e.has(`bivy_github_app`)&&!t)return;let n=(e.get(`code`)||``).trim(),r=(e.get(`state`)||``).trim();e.delete(`bivy_github_app`),e.delete(`code`),e.delete(`state`);let i=e.toString();history.replaceState(null,``,location.pathname+(i?`?${i}`:``)+location.hash),n&&r?(this.pendingGithubAppCode={code:n,state:r},this.store.setGithubAppPhase(`completing`,{returning:!0,state:r})):this.store.setGithubAppPhase(`error`,{returning:!0,error:`GitHub did not return a code.`})}catch{}}requestHistory(e){let t=this.store.getHistoryCursor(e);this.send({kind:`history`,sessionId:e,...t})}draftSessionFields(){let e=this.store.getState(),t=e.catalogs.currentModel?{provider:e.catalogs.currentModel.provider,id:e.catalogs.currentModel.id}:void 0;return{repo:e.draft.repo||void 0,branch:e.draft.repo&&e.draft.branch||void 0,agent:e.catalogs.selectedAgentId||void 0,sandbox:e.draft.sandbox||void 0,acknowledgeReducedProtections:e.draft.acknowledgeReducedProtections||void 0,model:t}}getNodeSettings(){this.send({kind:`node.settings.get`})}setNodeSettings(e){return this.awaitAck({kind:`node.settings.set`,settings:e}).then(()=>void 0)}setSessionSandbox(e){this.store.setDraftSandbox(e)}acknowledgeSessionAgentReducedProtections(e){this.store.setDraftAcknowledgeReducedProtections(e)}newSession(e={}){let t=this.store.getState(),n=t.activeSession.activeSessionId?t.sessionIndex.sessions.find(e=>e.sessionId===t.activeSession.activeSessionId)?.nodeId??this.local.cur:this.local.cur,r=t.connection.nodes.find(e=>e.id===n)?.name??``,i=this.ephemeralCorrelations.find(e=>e.nodeId===n)?.setupId;this.sessionCoordinator.newSession(e),n?.startsWith(`eph-`)&&this.listEphemeralConfigs().then(e=>{let t=this.store.getState();if(t.activeSession.activeSessionId||t.draft.ephemeralConfig||this.local.cur!==n)return;let a=(i?e.find(e=>e.id===i):void 0)??(/^Hosted\s+/i.test(r)?e.find(e=>e.computeSource===`managed`):void 0);a&&this.pickDraftEphemeralRunner(a)}).catch(()=>{})}seedDraftDefaults(){let e=this.local.lastChoice();e.repo&&this.store.setDraftRepo(e.repo);let t=e.modelId?{provider:e.modelProvider,id:e.modelId}:null;this.store.setDraftModel(t),this.store.seedDraftAgentModel(e.agentId,t)}maybeRestoreDraftAgent(e){if(e.type!==`runtimes.list`)return;let t=this.store.getState();if(t.activeSession.activeSessionId)return;let n=this.local.lastChoice().agentId,r=n?t.catalogs.runtimes.find(e=>e.id===n):void 0;if(r&&n!==t.catalogs.selectedAgentId&&String(r.status||`available`)===`available`){this.chooseAgent(r);return}t.catalogs.selectedAgentId&&t.catalogs.modelsRuntimeId!==t.catalogs.selectedAgentId&&this.listModels()}sendPrompt(e,t){this.sessionCoordinator.sendPrompt(e,t),this.commitStagedPin(e)}stagedPin=null;stagePin(e){this.stagedPin={...e,at:Date.now()}}async commitStagedPin(e){let t=this.stagedPin;if(this.stagedPin=null,!(!t||Date.now()-t.at>6e5||!t.context||!e.includes(t.context)))try{await this.appCommand(`apps.pin`,t.sessionId,{appId:t.appId,viewId:t.viewId,words:e})}catch{}}async launchDraftRunnerAndBind(e){let t=this.pendingLaunches.get(e);if(!t)return;let{config:n}=t,r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};try{let i=t.prompt.frame&&`agent`in t.prompt.frame?String(t.prompt.frame.agent||``):``,a=n.computeSource===`managed`?this.prepareManagedCredential(i,t.prompt.frame.model?.provider):Promise.resolve(!0);this.store.updateLaunchCheckpoint(e,`capacity`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(e,`repository`,`skipped`),n.computeSource===`managed`&&r(`Reserving secure managed compute…`);let o=n.computeSource===`managed`?Ft(this.local,n.id,{runtimeId:i,requestId:e}):this.launchEphemeral({provider:n.provider,region:n.region??void 0,size:n.size??void 0,image:n.image??void 0,ttlMinutes:n.ttlMinutes??void 0,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,name:n.name,setupId:n.id,onProgress:r}),[s,c]=await Promise.all([o,a]);if(this.store.updateLaunchCheckpoint(e,`account`,`done`),!s.nodeId)throw Error(`machine launched without a node id`);this.store.updateLaunchCheckpoint(e,`capacity`,`done`),this.store.updateLaunchCheckpoint(e,`machine`,`done`),this.store.updateLaunchCheckpoint(e,`service`,`active`),t.machine=s,t.phase=`booting`,t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.bindPendingSessionNode(e,s.nodeId),n.computeSource===`managed`&&!c?await this.beginManagedCredentialSetup(e,s.nodeId):this.startPendingRunner(e)}catch(r){let i=`Launch failed: ${r?.message||r}`;t.logs.push(i),t.phase=`failed`,t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),r instanceof jt&&r.code===`managed_credentials_required`?(this.store.updateLaunchCheckpoint(e,`capacity`,`waiting`),this.store.updateLaunchCheckpoint(e,`account`,`failed`,r.message,r.code)):r instanceof jt&&r.code===`managed_image_unavailable`?this.store.updateLaunchCheckpoint(e,`machine`,`failed`,i,r.code):this.failLaunchCheckpoint(e,i),this.store.failPendingSession(e);let a=r instanceof jt?r.actions:[];this.store.setError(`Couldn't start ${n.name}: ${r?.message||r}`,a)}}managedLaunchProvider(e,t){return e.startsWith(`codex`)?`openai-codex`:e.startsWith(`claude`)?`anthropic`:t??null}async prepareManagedCredential(e,t){let n=await this.managedCredentialReady().catch(()=>!1),r=await this.tryPublishManagedCredential(e,n,t);return this.managedLaunchProvider(e,t)?r:r||n}async tryPublishManagedCredential(e,t,n){if(this.store.getState().connection.status!==`online`)return!1;let r=this.managedLaunchProvider(e,n),i=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&(!r||e.provider===r));if(!i)return!1;if(i.unattended&&t)return!0;try{i.unattended&&await this.setCredentialUnattended(i.provider,i.label,!1);let e=(await At(this.local)).generation;return await this.setCredentialUnattended(i.provider,i.label,!0),await this.waitForManagedCredential(2e4,e),!0}catch{return!1}}async beginManagedCredentialSetup(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.phase=`credential-setup`,n.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(n),this.managedCredentialSetupNodes.add(t),this.managedCredentialReturnSessionId=e,this.store.updateLaunchCheckpoint(e,`credentials`,`active`),this.switchNode(t),await this.waitForOnline(12e4),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.listProviders(),this.listCredentialRecords();let r=n.prompt.frame,i=this.managedLaunchProvider(String(r?.agent||``),r?.model?.provider)??this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`)?.provider??`anthropic`;this.store.setNeedsModelAuth({nodeId:t,provider:i})}failLaunchCheckpoint(e,t){let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.launchProgress,r=[`account`,`capacity`,`machine`,`service`,`credentials`,`repository`,`agent`,`message`],i=[...r].reverse().find(e=>n?.checkpoints[e]?.state===`active`)??r.find(e=>!n?.checkpoints[e]||n.checkpoints[e]?.state===`waiting`)??`message`;this.store.updateLaunchCheckpoint(e,i,`failed`,t)}openPendingLaunch(e,t={}){let n=this.pendingLaunches.get(e);n&&(t.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.store.addUserMessage(n.prompt.text,n.prompt.clientMessageId,n.prompt.attachments))}startPendingRunner(e){let t=this.pendingLaunches.get(e),n=t?.machine?.nodeId;if(!t||!n||t.transport)return;let r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};r(`Machine accepted. Waiting for its secure Bivy service to come online…`),this.startBootProgress(n,e,r);let i=new Proxy(this.local,{get:(e,t,r)=>t===`cur`?n:Reflect.get(e,t,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),a,o,s=()=>this.pendingLaunches.get(e)===t&&t.transport===a,c=!1,l=!1,u=()=>{if(c&&(l||t.config.computeSource!==`managed`)&&this.pendingLaunches.has(e)){let{model:e,...n}=t.prompt.frame;a.send(n)}};a=new ga({store:i,handlers:{onStatus:i=>{if(o){o.onStatus(i);return}s()&&(c=i===`online`,c&&(t.modelApproved=!1,t.modelSelecting=void 0,t.modelQuery=void 0,t.models=void 0,r(`${t.config.name} is online. Preparing credentials, repository, and agent…`),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.store.updateLaunchCheckpoint(e,`credentials`,l?`done`:`active`),this.clearBootProgress(n),u()))},onEvent:n=>{if(o){o.onEvent(n);return}if(!s())return;(n.type===`credentials.records`||n.type===`providers.list`)&&t.sessionId&&!t.modelQuery&&this.refreshLaunchModels(e);let r=n.type===`models.list`?n.current:n.model;if(n.type===`session.error`&&t.sessionId&&!t.modelApproved&&n.sessionId===t.sessionId){t.modelSelecting=void 0,t.modelQuery=void 0,t.prompt.frame={...t.prompt.frame,model:void 0},this.pendingLaunchStore.put(t).catch(()=>{}),this.store.setLaunchModelChoice(e,{models:t.models??[],error:typeof n.error==`string`?n.error:`Couldn't select this model. Choose another model or refresh.`});return}if(n.type===`models.list`&&n.sessionId===t.sessionId&&!t.modelApproved){if(t.modelQuery=void 0,n.modelSelection===!1){t.modelApproved=!0,this.sendPendingLaunchPrompt(e,t.sessionId,a);return}t.models=(Array.isArray(n.models)?n.models:[]).filter(e=>e&&e.configured!==!1&&typeof e.id==`string`&&e.id!==`unknown`&&typeof e.provider==`string`&&e.provider!==`unknown`&&e.id&&e.provider);let i=t.models?.find(e=>e.id===r?.id&&e.provider===r?.provider),o=t.prompt.frame.model;if(!t.modelSelecting&&i&&(!o||o.id===i.id&&o.provider===i.provider))t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);else{let n=t.models?.find(e=>e.id===o?.id&&e.provider===o?.provider);n&&!t.modelSelecting?this.chooseLaunchModel(e,n):(this.store.updateLaunchCheckpoint(e,`message`,`waiting`),this.store.setLaunchModelChoice(e,{models:t.models??[],current:i,selecting:!!t.modelSelecting,error:o&&!n?lt(o,t.models??[],t.config.computeSource===`managed`):void 0}))}return}if(n.type===`model.updated`&&n.sessionId===t.sessionId&&t.modelSelecting&&r?.id===t.modelSelecting.id&&r?.provider===t.modelSelecting.provider){t.modelSelecting=void 0,t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);return}if(n.type===`session.error`){this.failPendingLaunch(e,String(n.error||`Session creation failed.`));return}if(n.type===`session.history`&&n.requestId===t.prompt.requestId&&n.sessionId){t.prompt.frame&&`repo`in t.prompt.frame&&t.prompt.frame.repo&&this.store.updateLaunchCheckpoint(e,`repository`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`done`),t.sessionId=String(n.sessionId),t.modelApproved?this.sendPendingLaunchPrompt(e,t.sessionId,a):this.refreshLaunchModels(e);return}n.type===`session.user_message`&&(t.promptSent||t.promptSending)&&n.sessionId===t.sessionId&&n.clientMessageId===t.prompt.clientMessageId&&this.finishPendingLaunch(e,String(t.sessionId),a,()=>(o=this.buildTransportHandlers(),o),n)},onError:e=>{if(o){o.onError?.(e);return}s()&&(/^node offline$/i.test(e.trim())||r(`Connection retry: ${e}`))}}}),t.transport=a,this.pollBootstrapStatus(n,e,r,()=>{l=!0,u()}),a.connect()}refreshLaunchModels(e){let t=this.pendingLaunches.get(e);if(!t?.sessionId||!t.transport||t.modelApproved||t.modelSelecting)return;let n={};t.modelQuery=n,this.store.setLaunchModelChoice(e,{models:t.models??[],loading:!0});let r=()=>{this.pendingLaunches.get(e)===t&&t.modelQuery===n&&(t.modelQuery=void 0,this.store.setLaunchModelChoice(e,{models:t.models??[],error:`Couldn't load models from this machine. Refresh to try again; your prompt is still saved.`}))};setTimeout(r,15e3),Promise.resolve().then(()=>t.transport?.send({kind:`models.list`,sessionId:t.sessionId})).catch(r)}async chooseLaunchModel(e,t){let n=this.pendingLaunches.get(e);if(!n?.sessionId||!n.transport||n.modelSelecting||n.modelApproved||n.modelQuery)return;let r=n.models?.find(e=>e.id===t.id&&e.provider===t.provider);if(!r)return;let i={...r};n.modelSelecting=i,this.store.setLaunchModelChoice(e,{models:n.models??[],current:i,selecting:!0}),setTimeout(()=>{this.pendingLaunches.get(e)===n&&n.modelSelecting===i&&(n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Model selection wasn't confirmed. Refresh or choose again; your prompt is still saved.`}))},15e3);try{if(n.prompt.frame={...n.prompt.frame,model:{id:i.id,provider:String(i.provider)}},await this.pendingLaunchStore.put(n),this.pendingLaunches.get(e)!==n||n.modelSelecting!==i)return;await n.transport.send({kind:`model.select`,sessionId:n.sessionId,id:i.id,provider:i.provider})}catch{n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Couldn't select this model. Refresh and try again.`})}}async sendPendingLaunchPrompt(e,t,n){let r=this.pendingLaunches.get(e);if(r&&!r.promptSending&&r.modelApproved){this.store.updateLaunchCheckpoint(e,`message`,`active`),r.sessionId=t,r.promptSending=!0,this.store.getState().activeSession.activeSessionId===e&&this.store.pushSystemMessage(`Setup · Repository and agent are ready. Sending your prompt…`);try{if(await n.send({kind:`prompt`,sessionId:t,text:r.prompt.text,clientMessageId:r.prompt.clientMessageId,attachments:r.prompt.attachments}),!this.pendingLaunches.has(e))return;r.promptSent=!0,r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}catch(t){if(!this.pendingLaunches.has(e))return;r.logs.push(`First-message delivery retry: ${t?.message||t}`),r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}finally{r.promptSending=!1,setTimeout(()=>{let r=this.pendingLaunches.get(e);r&&r.phase!==`failed`&&r.sessionId===t&&this.sendPendingLaunchPrompt(e,t,n)},3e3)}}}async finishPendingLaunch(e,t,n,r,i){let a=this.pendingLaunches.get(e),o=a?.machine?.nodeId;if(!a||!o)return;this.store.updateLaunchCheckpoint(e,`message`,`done`),this.clearBootProgress(o),this.pendingLaunches.delete(e),this.pendingLaunchStore.remove(e).catch(()=>{}),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),this.store.completePendingSession(e,t,o);let s=this.store.getState().activeSession.activeSessionId===t;if(s){let e=r();this.transport.close(),this.local.cur=o,this.store.setCurrentNode(o),this.transport=n,this.pendingCrossNodeOpen={sessionId:t},Z({kind:`session`,id:t}),this.store.setStatus(`connecting`),e.onStatus(`online`),e.onEvent(i),this.listRuntimes(),this.listProviders(),this.getNodeSettings()}for(let e of a.followups)await n.send({kind:`prompt`,sessionId:t,...e});s||setTimeout(()=>n.close(),1e3),setTimeout(()=>this.refreshSessions(),1500)}failPendingLaunch(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.machine?.nodeId&&this.clearBootProgress(n.machine.nodeId);let r=n.transport;n.transport=void 0,r?.close(),n.logs.push(`Startup failed: ${t}`),this.store.setLaunchModelChoice(e,void 0),n.modelQuery=void 0,n.modelSelecting=void 0,n.modelApproved=!1,n.phase=`failed`,n.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(n),/not available on this node|command not found|agent is not installed/i.test(t)?(this.store.updateLaunchCheckpoint(e,`credentials`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`failed`,t)):this.failLaunchCheckpoint(e,t),this.store.failPendingSession(e),this.store.setError(`Couldn't start ${n.config.name}: ${t}`)}startBootProgress(e,t,n){this.clearBootProgress(e);let r=[[15e3,`Booting the machine and installing Bivy…`],[45e3,`Still installing Bivy (45s elapsed). A first boot can take a few minutes…`],[9e4,`Still waiting for Bivy to join the secure relay (90s elapsed)…`],[18e4,`Boot is taking longer than usual (3 min elapsed). Still retrying…`],[ml,`Still offline after ${Math.round(ml/6e4)} min. Check the provider's machine logs for a failed install.`]].map(([e,r])=>setTimeout(()=>{this.pendingLaunches.has(t)&&n(r)},e));this.bootProgressTimers.set(e,r)}clearBootProgress(e){for(let t of this.bootProgressTimers.get(e)??[])clearTimeout(t);this.bootProgressTimers.delete(e),this.bootstrapPhaseByNode.delete(e)}pollBootstrapStatus(e,t,n,r){let i={booting:`The machine booted and cloud-init started.`,installing:`Cloud-init is installing Bivy…`,starting:`Bivy is installed. Starting its secure service…`,ready:`The secure Bivy service is ready.`,failed:`Cloud-init reported that the Bivy install failed.`},a=!1,o=async()=>{let s=this.pendingLaunches.get(t);if(s&&s.machine?.nodeId===e){try{let o=await Et(this.local);this.store.setNodes(o);let c=o.find(t=>t.id===e)?.bootstrapStatus?.phase;c&&c!==this.bootstrapPhaseByNode.get(e)&&(this.bootstrapPhaseByNode.set(e,c),n(i[c]||`Bootstrap: ${c}`),c===`ready`&&this.store.updateLaunchCheckpoint(t,`service`,`done`),c===`failed`&&this.failPendingLaunch(t,i.failed)),(s.config.computeSource===`managed`?(await gn(this.local)).find(t=>t.nodeId===e)?.milestones?.credentialsReadyAt:c===`ready`)&&!a&&this.pendingLaunches.has(t)&&s.phase!==`failed`&&(a=!0,this.store.updateLaunchCheckpoint(t,`credentials`,`done`),r())}catch{}this.pendingLaunches.has(t)&&setTimeout(o,3e3)}};o()}async restorePendingLaunches(){let e=await this.pendingLaunchStore.list();for(let t of e){if(this.store.isSessionDeleted(t.id)){await this.pendingLaunchStore.remove(t.id);continue}this.pendingLaunches.set(t.id,t),this.store.persistPendingSession(t.id,t.prompt.text,!1,t.config.name,Date.parse(t.createdAt)||Date.now()),t.machine?.nodeId&&t.phase!==`failed`?(this.store.retryPendingSession(t.id),this.store.setLaunchModelChoice(t.id,void 0),this.store.updateLaunchCheckpoint(t.id,`account`,`done`),this.store.updateLaunchCheckpoint(t.id,`capacity`,`done`),this.store.updateLaunchCheckpoint(t.id,`machine`,`done`),this.store.updateLaunchCheckpoint(t.id,`service`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(t.id,`repository`,`skipped`),this.store.bindPendingSessionNode(t.id,t.machine.nodeId),t.phase===`credential-setup`?this.beginManagedCredentialSetup(t.id,t.machine.nodeId):this.startPendingRunner(t.id)):t.phase===`provisioning`?(t.phase=`failed`,t.logs.push(`Startup was interrupted before the cloud provider confirmed the machine.`),t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.failPendingSession(t.id)):t.phase===`failed`&&this.store.failPendingSession(t.id)}}async retryPendingLaunch(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close(),t.logs.push(`Retrying startup…`),t.phase=t.machine?.nodeId?`booting`:`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),t.machine?.nodeId?this.startPendingRunner(e):await this.launchDraftRunnerAndBind(e)}async retryPendingLaunchOnFreshMachine(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close();let r=t.machine?.nodeId;r&&await this.destroyHostedMachine(r).catch(()=>{}),t.machine=void 0,t.sessionId=void 0,t.promptSent=!1,t.logs.push(`Replacing the Cloud Machine and retrying the preserved first message…`),t.phase=`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),await this.launchDraftRunnerAndBind(e)}async dismissPendingLaunch(e){let t=this.pendingLaunches.get(e);this.pendingLaunches.delete(e),t?.transport?.close(),t?.machine?.nodeId&&this.clearBootProgress(t.machine.nodeId),this.store.dismissPendingSession(e),this.persistDeletedSessionTombstones(),await this.pendingLaunchStore.remove(e),this.store.getState().activeSession.activeSessionId??this.newSession()}invokeAgentCommand(e,t){let n=this.store.getState().activeSession.activeSessionId;n&&this.send({kind:`session.command.invoke`,sessionId:n,name:e,args:t})}listRepos(){this.store.getState().catalogs.repos.length===0&&this.store.setReposLoading(!0);let e=this.store.getState().draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||e)){cn(this.local).then(e=>this.store.apply({type:`repos.list`,repos:e,authed:!0})).catch(e=>this.store.apply({type:`repos.list`,repos:[],authed:!1,error:String(e?.message||e)}));return}this.send({kind:`repos.list`})}githubConnectStart(){this.store.setGithubConnect({status:`starting`}),this.send({kind:`github.connect.start`})}githubConnectPoll(){this.send({kind:`github.connect.poll`})}githubConnectReset(){this.store.setGithubConnect({status:`idle`})}chooseRepo(e){let t=e!==this.store.getState().draft.repo;this.store.setDraftRepo(e),t&&this.store.clearBranches(),this.local.setLastChoice({repo:e})}chooseRepoBranch(e,t){this.store.setDraftRepo(e),this.store.setDraftBranch(t),this.local.setLastChoice({repo:e})}listBranches(e){let t=this.store.getState();t.catalogs.branchesRepo===e&&t.catalogs.branches.length>0||this.store.setBranchesLoading(!0);let n=t.draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||n)){ln(this.local,e).then(t=>this.store.apply({type:`branches.list`,repo:e,branches:t})).catch(t=>this.store.apply({type:`branches.list`,repo:e,branches:[],error:String(t?.message||t)}));return}this.send({kind:`branches.list`,repo:e})}listRuntimes(){this.send({kind:`runtimes.list`})}requestCapabilities(){this.send({kind:`capabilities.get`})}cloudModelQuery=0;isCloudModelDraft(){let e=this.store.getState();return!e.activeSession.activeSessionId&&!this.direct&&!(!e.draft.ephemeralConfig&&this.local.cur)}async listCloudModels(){let e=++this.cloudModelQuery,t=this.store.getState(),n=t.draft.ephemeralConfig,r=t.catalogs.selectedAgentId,i=this.local.cur,a=t.catalogs.models,o=t.settings.credentialRecords;try{let[t,s]=await Promise.all([this.ephemeralKeys.modelKeyEntries(),this.ephemeralKeys.oauthCredentialEntries()]),c=this.store.getState();if(e!==this.cloudModelQuery||!this.isCloudModelDraft()||c.draft.ephemeralConfig!==n||c.catalogs.selectedAgentId!==r||this.local.cur!==i)return;let l=[...o.filter(e=>e.sync===`account`&&e.kind!==`reference`),...t.filter(e=>e.scope===`account`||n?.computeSource!==`managed`),...s].map(e=>e.provider);this.store.apply({type:`models.list`,runtimeId:r,models:ct(l,a)})}catch{e===this.cloudModelQuery&&this.isCloudModelDraft()&&this.store.setError(`Couldn't load account models. Open the model picker to try again.`)}}listModels(){if(this.isCloudModelDraft()){this.listCloudModels();return}let e=this.store.getState(),t=e.activeSession.activeSessionId,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.pendingLaunch===!0:!1,r=t&&!n?t:void 0,i=r?void 0:e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId??void 0;this.send({kind:`models.list`,sessionId:r,runtimeId:i})}runtimeModelWaiters=new Map;modelsForRuntime(e,t=2e4){return new Promise(n=>{let r=e=>{clearTimeout(i),n(e)},i=setTimeout(()=>{let t=this.runtimeModelWaiters.get(e);t?.splice(t.indexOf(r)>>>0,1),n(this.store.cachedModelsFor(e)??[])},t);this.runtimeModelWaiters.set(e,[...this.runtimeModelWaiters.get(e)??[],r]),this.send({kind:`models.list`,runtimeId:e})})}settleRuntimeModels(e){let t=this.runtimeModelWaiters.get(e);if(!t?.length)return;this.runtimeModelWaiters.delete(e);let n=this.store.cachedModelsFor(e)??[];for(let e of t)e(n)}prefetchModels(){if(this.store.getState().activeSession.activeSessionId)return;let e=this.store.getState().catalogs.runtimes.filter(e=>String(e.status||`available`)===`available`).map(e=>e.id);e.length&&this.send({kind:`models.prefetch`,runtimeIds:e})}chooseModel(e){let t=this.store.getState().activeSession.activeSessionId;if(t&&this.isProvisionalSessionId(t)){this.chooseLaunchModel(t,e);return}this.credentialsModelsCoordinator.selectModel(e,t)}setThinkingLevel(e){let t=this.store.getState().activeSession.activeSessionId??void 0;t&&this.isProvisionalSessionId(t)||(this.store.setThinkingLevel(e),this.send({kind:`thinking.set_level`,level:e,sessionId:t}))}chooseAgent(e,t){if(String(e.status||`available`)!==`available`&&e.install){this.installAgent(e.id);return}let n=this.store.getState(),r=n.activeSession.activeSessionId,i=n.activeSession.transcript.some(e=>e.role===`user`);if(r&&i){let i=n.activeSession.activeRuntimeId??n.sessionIndex.sessions.find(e=>e.sessionId===r)?.runtimeId;this.pendingPrompt=null,this.pendingFollowups=[],this.forkSession(r,{agentId:e.id,sourceAgentId:i,retireSource:!1},t).catch(e=>this.store.setError(e instanceof Error?e.message:String(e)));return}if(r&&(this.pendingPrompt=null,this.pendingFollowups=[],this.promptTargetSessionId=null,this.store.resetActiveSession(),Z({kind:`new`})),this.store.setSelectedAgentLocal(e.id),this.local.setLastChoice({agentId:e.id}),this.isCloudModelDraft()){this.listModels();return}this.send({kind:`runtime.select`,id:e.id})}installAgent(e){this.pendingAgentPick=e,this.store.setInstalling(e),this.send({kind:`runtime.install`,id:e})}maybeSelectInstalledAgent(e){if(e.type===`runtime.install.error`&&e.id===this.pendingAgentPick){this.pendingAgentPick=null;return}if(e.type!==`runtime.install.done`||!this.pendingAgentPick||e.id!==this.pendingAgentPick)return;this.pendingAgentPick=null;let t=this.store.getState();if(t.activeSession.transcript.some(e=>e.role===`user`))return;let n=t.catalogs.runtimes.find(t=>t.id===e.id);n&&String(n.status||`available`)===`available`&&this.chooseAgent(n)}listProviders(){this.credentialsModelsCoordinator.listProviders()}getProviderAuth(e){this.credentialsModelsCoordinator.getProviderAuth(e)}saveApiKey(e,t){return this.credentialsModelsCoordinator.saveApiKey(e,t)}removeProvider(e){this.credentialsModelsCoordinator.removeProvider(e)}resetOauth(e){this.credentialsModelsCoordinator.resetOauth(e)}startOauth(e,t){this.credentialsModelsCoordinator.startOauth(e,t)}openOauthOnNode(e){return this.credentialsModelsCoordinator.openOauthOnNode(e)}submitOauthCode(e,t){this.credentialsModelsCoordinator.submitOauthCode(e,t)}listCredentialRecords(){this.credentialsModelsCoordinator.listCredentials()}async previewNativeCredentials(e,t){return await this.nativeCredentialCommand(e,{kind:`credentials.native.preview`,label:t})}async importNativeCredentials(e,t,n,r){return await this.nativeCredentialCommand(e,{kind:`credentials.native.import`,previewId:t,agents:n,sync:r})}async nativeCredentialCommand(e,t){let n=this.store.getState().connection;if(n.status!==`online`||n.currentNodeId!==e)throw Error(`Connect to the selected machine before scanning or importing.`);let r=await this.awaitAck(t,2e4);if(this.store.getState().connection.currentNodeId!==e)throw Error(`Machine changed. Scan again on the selected machine.`);return r}syncAccountCredentialsWithNode(){return this.credentialsModelsCoordinator.syncAccountCredentials()}setCredential(e,t,n){return this.credentialsModelsCoordinator.setCredential(e,t,n)}removeCredential(e,t){return this.credentialsModelsCoordinator.removeCredential(e,t)}setCredentialSync(e,t,n){return this.credentialsModelsCoordinator.setCredentialSync(e,t,n)}setCredentialUnattended(e,t,n){return this.credentialsModelsCoordinator.setCredentialUnattended(e,t,n)}testCredential(e,t){return this.credentialsModelsCoordinator.testCredential(e,t)}getCredentialPresets(){this.credentialsModelsCoordinator.getPresets()}setActivePreset(e){this.credentialsModelsCoordinator.setActivePreset(e)}setPresetMapping(e,t,n){return this.credentialsModelsCoordinator.setPresetMapping(e,t,n)}listLocalModels(){this.credentialsModelsCoordinator.listLocalModels()}listLocalModelPresets(){this.credentialsModelsCoordinator.listLocalModelPresets()}discoverLocalModels(){return this.credentialsModelsCoordinator.discoverLocalModels()}verifyLocalModel(e,t){return this.credentialsModelsCoordinator.verifyLocalModel(e,t)}saveLocalModel(e){return this.credentialsModelsCoordinator.saveLocalModel(e)}removeLocalModel(e){this.credentialsModelsCoordinator.removeLocalModel(e)}listRulesets(){this.send({kind:`rulesets.list`})}saveRuleset(e,t){return this.awaitAck({kind:`rulesets.save`,ruleset:e,active:t}).then(()=>void 0)}removeRuleset(e){this.send({kind:`rulesets.remove`,name:e})}getSttConfig(){this.send({kind:`stt.config.get`})}setSttProvider(e){this.send({kind:`stt.config.set`,provider:e})}saveSttKey(e,t){return this.awaitAck({kind:`stt.config.set`,setKey:{provider:e,value:t}}).then(()=>void 0)}removeSttKey(e){this.send({kind:`stt.config.set`,removeKey:e})}transcribe(e,t){let n=ll();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingTranscriptions.delete(n),i(Error(`Transcription timed out. Check your connection and try again.`))},6e4);this.pendingTranscriptions.set(n,{resolve:r,reject:i,timer:a}),this.transport.send({kind:`transcribe`,requestId:n,audio:e,mimeType:t})})}resolveTranscription(e){let t=String(e.requestId||``),n=t?this.pendingTranscriptions.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingTranscriptions.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve(String(e.text??``).trim())}synthesize(e,t,n){let r=ll();return new Promise((i,a)=>{let o=setTimeout(()=>{this.pendingSpeech.delete(r),a(Error(`Speech generation timed out. Check your connection and try again.`))},6e4);this.pendingSpeech.set(r,{resolve:i,reject:a,timer:o}),this.transport.send({kind:`synthesize`,requestId:r,text:e,voice:t,instructions:n})})}resolveSpeech(e){let t=String(e.requestId||``),n=t?this.pendingSpeech.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingSpeech.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve({audio:String(e.audio??``),mimeType:String(e.mimeType??`audio/mpeg`)})}githubAppManifestStart(e){this.store.setGithubAppPhase(`starting`),this.send({kind:`github.app.manifest.start`,requestId:ll(),origin:d(),org:e||void 0})}githubAppManifestCode(e,t){this.store.setGithubAppPhase(`completing`),this.send({kind:`github.app.manifest.code`,requestId:ll(),code:e,state:t})}async githubAppConnectExisting(e){this.store.setGithubAppPhase(`completing`);try{await this.awaitAck({kind:`github.app.connect-existing`,appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel||void 0},6e4)}catch(e){throw this.store.setGithubAppPhase(`error`,{error:e instanceof Error?e.message:String(e),returning:!1}),e}}connectHostedGithubApp(e){return sn(this.local,e)}fetchMe(){return this.accountCoordinator.fetchMe()}deleteAccount(){return Ht(this.local)}invokeAccountExtensionAction(e){return u()?Ut(this.local,e):Promise.reject(Error(`Account service actions are unavailable in this app.`))}fetchGithubApp(){return this.accountCoordinator.fetchGithubApp()}fetchGithubQueue(e=30){return this.accountCoordinator.fetchGithubQueue(e)}fetchAutomationRuns(e=50,t={}){return this.accountCoordinator.fetchAutomationRuns(e,t)}cancelAutomationRun(e){return this.accountCoordinator.cancelAutomationRun(e)}setGithubAppDefaultNode(e,t){return this.accountCoordinator.setGithubAppDefaultNode(e,t)}setGithubAppTriggerAccess(e,t){return this.accountCoordinator.setGithubAppTriggerAccess(e,t)}assignWorkItem(e,t){return this.accountCoordinator.assignWorkItem(e,t)}deleteWorkItem(e){return this.accountCoordinator.deleteWorkItem(e)}clearWorkQueue(){return this.accountCoordinator.clearWorkQueue()}githubAppDisconnect(e,t){return this.accountCoordinator.disconnectGithubApp(e,t)}removeNode(e){return this.accountCoordinator.removeNode(e)}enablePush(){return i?o()?.enable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.enablePush()}disablePush(){return i?o()?.disable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.disablePush()}pushStatus(){return i?o()?.status({token:this.local.s,controlPlane:d()})??Promise.resolve({supported:!1,subscribed:!1,permission:`default`}):this.accountCoordinator.pushStatus()}getNotificationPreferences(){return this.accountCoordinator.getNotificationPreferences()}setNotificationPreferences(e){return this.accountCoordinator.setNotificationPreferences(e)}ephemeralModelKeys=vi();deviceOAuthCredentials=_i();ephemeralKeys=ra({local:gi(),modelKeys:this.ephemeralModelKeys,oauthCredentials:this.deviceOAuthCredentials,oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled(),remote:this.deviceVaultRemote(),device:()=>Ui(this.local),enabled:()=>!this.direct&&!!this.local.s,providerTokenSyncEnabled:()=>!this.direct&&!!this.local.s,state:{load:async()=>{try{return JSON.parse(localStorage.getItem(`bivy_device_vault_state`)||`null`)??void 0}catch{return}},save:async e=>{try{localStorage.setItem(`bivy_device_vault_state`,JSON.stringify(e))}catch{}}}});ephemeralPrefs=Si();ephemeralSetups=wi();ephemeralMachines=Ei();pendingLaunchStore=Ti();seededEphemeralNodes=new Set;firstRunAuthNodes=new Set;managedCredentialSetupNodes=new Set;managedCredentialGrantInFlight=!1;managedCredentialReturnSessionId=null;listEphemeralKeys(){return this.ephemeralKeys.list()}listEphemeralModelKeys(){return this.ephemeralKeys.listModelKeys()}setEphemeralModelKey(e,t,n=`account`,r=`default`){return this.ephemeralKeys.setModelKey(e,t,n,r)}removeEphemeralModelKey(e,t=`default`){return this.ephemeralKeys.removeModelKey(e,t)}getEphemeralToken(e){return this.ephemeralCoordinator.getProviderToken(e)}setEphemeralToken(e,t){return this.ephemeralCoordinator.setProviderToken(e,t)}connectEphemeralProvider(e,t){return this.ephemeralCoordinator.connectProvider(e,t)}defaultEphemeralRunner(e){return this.ensureDefaultRunner(e)}ensureDefaultRunner(e){return this.ephemeralCoordinator.ensureDefaultRunner(e)}removeEphemeralToken(e){return this.ephemeralCoordinator.removeProviderToken(e)}oauthRecoveryEnabled(){try{return!this.direct&&!!this.local.s&&localStorage.getItem(`bivy_oauth_browser_recovery`)===`1`}catch{return!1}}getOAuthBrowserRecovery(){return this.oauthRecoveryEnabled()}async setOAuthBrowserRecovery(e){if(this.direct)throw Error(`OAuth browser recovery requires a signed-in account`);if(!e)for(let e of await this.ephemeralKeys.oauthCredentialEntries())await this.ephemeralKeys.removeOAuthCredential(e.provider,e.label);try{localStorage.setItem(`bivy_oauth_browser_recovery`,e?`1`:`0`)}catch{}e&&await this.syncAccountCredentialsWithNode()}syncDeviceVault(){return this.ephemeralKeys.sync()}getDeviceVaultSyncState(){return this.ephemeralKeys.getSyncState()}deviceVaultRemote(){let e=()=>(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),t=()=>({authorization:`Bearer ${this.local.s}`,"content-type":`application/json`});return{get:async()=>{let t=await Ui(this.local),n=await fetch(`${e()}/device-vault?device=${encodeURIComponent(t.pub)}`,{headers:{authorization:`Bearer ${this.local.s}`}});if(!n.ok)throw Error(`device-vault get failed (${n.status})`);let r=await n.json();return{vault:r.vault??null,wrappedKey:r.wrappedKey??null,requests:Array.isArray(r.requests)?r.requests:[],generation:r.generation??0,keyGeneration:r.keyGeneration??0,recipients:Array.isArray(r.recipients)?r.recipients:[]}},putVault:async(n,r,i)=>{let a=await Ui(this.local),o=await fetch(`${e()}/device-vault`,{method:`PUT`,headers:t(),body:JSON.stringify({devicePublicKeyB64:a.pub,ciphertext:n,expectedGeneration:r,keyGeneration:i})});if(o.status===409)throw new Ji;if(!o.ok)throw Error(`device-vault put failed (${o.status})`);return{generation:(await o.json()).generation??(r??0)+1}},requestKey:async()=>{let n=await Ui(this.local);await fetch(`${e()}/device-vault/key/request`,{method:`POST`,headers:t(),body:JSON.stringify({devicePublicKeyB64:n.pub})})},putWrapped:async(n,r,i,a)=>{let o=await fetch(`${e()}/device-vault/key/wrapped`,{method:`PUT`,headers:t(),body:JSON.stringify({targetDevicePublicKeyB64:n,wrappedKey:r,wrappedByPublicKeyB64:i,generation:a})});if(o.status!==403&&!o.ok)throw Error(`device-vault wrapped-key put failed (${o.status})`)}}}getEphemeralPrefs(e){return this.ephemeralPrefs.get(e)}setEphemeralPrefs(e,t){return this.ephemeralPrefs.set(e,t)}listEphemeralSetups(e){return this.ephemeralSetups.list(e)}createEphemeralSetup(e,t){return this.ephemeralSetups.create(e,t)}updateEphemeralSetup(e,t){return this.ephemeralSetups.update(e,t)}removeEphemeralSetup(e){return this.ephemeralSetups.remove(e)}listEphemeralMachines(){return this.ephemeralMachines.list()}async seedEphemeralNodeIfNeeded(){if(!uc||this.direct)return;let e=this.local.cur;if(!e||this.seededEphemeralNodes.has(e))return;let t;try{t=await this.ephemeralMachines.list()}catch{return}if(!t.some(t=>t.nodeId===e))return;let n;try{n=await this.ephemeralKeys.modelKeyEntries()}catch{return}if(this.seededEphemeralNodes.add(e),n.length){if(this.store.getState().connection.status!==`online`||this.local.cur!==e){this.seededEphemeralNodes.delete(e);return}for(let{provider:e,key:t}of n)this.send({kind:`provider.apiKey`,provider:e,key:t})}}async maybeGrantManagedCredential(){let e=this.local.cur;if(!e||!this.managedCredentialSetupNodes.has(e)||this.managedCredentialGrantInFlight)return;let t=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&!e.unattended);if(t){this.managedCredentialGrantInFlight=!0;try{await this.setCredentialUnattended(t.provider,t.label,!0),await this.waitForManagedCredential();let e=this.managedCredentialReturnSessionId;this.managedCredentialReturnSessionId=null,e&&this.pendingLaunches.has(e)&&(this.openPendingLaunch(e),await this.retryPendingLaunch(e))}catch(e){this.store.setError(e instanceof Error?e.message:String(e))}finally{this.managedCredentialGrantInFlight=!1}}}async maybePromptFirstRunModelAuth(){if(!uc||this.direct)return;let e=this.local.cur;e&&!this.firstRunAuthNodes.has(e)&&(await this.ephemeralMachines.list().catch(()=>[])).some(t=>t.nodeId===e)&&(this.firstRunAuthNodes.add(e),this.listProviders(),setTimeout(()=>{let t=this.store.getState();if(t.connection.status!==`online`||this.local.cur!==e||t.presentation.needsModelAuth||t.presentation.oauth||t.catalogs.providers.some(e=>e.configured))return;let n=t.catalogs.providers.find(e=>e.oauth&&e.id===`anthropic`)?.id??t.catalogs.providers.find(e=>e.oauth)?.id??`anthropic`;this.store.setNeedsModelAuth({nodeId:e,provider:n})},pl))}dismissModelAuthPrompt(){this.store.setNeedsModelAuth(null)}maybeTeardownFinishedEphemeral(e){return this.isProvisionalSessionId(e)||[...this.pendingLaunches.values()].some(t=>t.sessionId===e)?Promise.resolve():this.ephemeralCoordinator.teardownFinishedSession(e)}listEphemeralSizes(e,t){return this.ephemeralCoordinator.listSizes(e,t)}launchEphemeral(e){return this.ephemeralCoordinator.launch(e)}destroyEphemeral(e){return this.ephemeralCoordinator.destroy(e)}resumeAndConnectNode(e,t=9e4){return this.ephemeralCoordinator.resumeAndConnect(e,t)}correlationApi(){return{base:(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),auth:{authorization:`Bearer ${this.local.s}`,"content-type":`application/json`}}}async refreshEphemeralCorrelations(){if(!this.direct&&this.local.s)try{let{base:e,auth:t}=this.correlationApi(),n=await fetch(`${e}/session-correlation`,{headers:{authorization:t.authorization}});if(!n.ok)return;let r=await n.json();Array.isArray(r.correlations)&&(this.ephemeralCorrelations=r.correlations)}catch{}}async recordSessionCorrelation(e,t){if(this.isProvisionalSessionId(e)||this.direct||!this.local.s||!t.nodeId||!e)return;let n=`${t.nodeId}:${e}`;if(this.correlatedSessions.has(n))return;this.correlatedSessions.add(n);let r={sessionId:e,nodeId:t.nodeId,provider:t.provider,region:t.region||void 0,ttlMinutes:t.ttlMinutes,repo:t.repo,setupId:t.setupId,machineId:t.id,app:t.app,computeSource:t.computeSource};try{let{base:t,auth:n}=this.correlationApi(),i=await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`PUT`,headers:n,body:JSON.stringify(r)});if(i.status===410){this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e);return}if(!i.ok)throw Error(`Couldn't save session routing metadata.`);this.ephemeralCorrelations=[r,...this.ephemeralCorrelations.filter(t=>t.sessionId!==e)]}catch{this.correlatedSessions.delete(n)}}reprovisionEphemeral(e,t){return this.ephemeralCoordinator.reprovision(e,t)}isCurrentNodeResumable(){return this.ephemeralCoordinator.isCurrentNodeResumable()}shouldAutoResume(){return this.store.getState().connection.status!==`online`&&this.isCurrentNodeResumable()&&!this.resumingNode.has(this.local.cur)}async resumeNodeForSession(e){let t=this.local.cur;if(t&&!this.resumingNode.has(t)){this.resumingNode.add(t);try{await this.reprovisionEphemeral(t,e)}finally{this.resumingNode.delete(t)}}}drainPendingResume(e){let t=this.pendingResume.filter(t=>t.sessionId===e);if(t.length){this.pendingResume=this.pendingResume.filter(t=>t.sessionId!==e);for(let n of t)this.send({kind:`prompt`,sessionId:e,text:n.text,clientMessageId:n.clientMessageId,attachments:n.attachments})}}githubTaskToken=bi();getGithubTaskToken(){return this.githubTaskToken.get()}setGithubTaskToken(e){return this.githubTaskToken.set(e)}removeGithubTaskToken(){return this.githubTaskToken.remove()}runWorkItemOnEphemeral(e,t){return this.ephemeralCoordinator.runWorkItem(e,t)}launchEphemeralQueueWorker(e){return this.ephemeralCoordinator.launchQueueWorker(e)}getEphemeralQueueDefault(){return Xt(this.local)}setEphemeralQueueDefault(e){return Zt(this.local,e)}listEphemeralConfigs(){return this.ephemeralCoordinator.listConfigs()}createEphemeralConfig(e){return this.ephemeralCoordinator.createConfig(e)}updateEphemeralConfig(e,t){return this.ephemeralCoordinator.updateConfig(e,t)}removeEphemeralConfig(e){return this.ephemeralCoordinator.removeConfig(e)}getQueueRouting(){return an(this.local)}setQueueRouting(e){return on(this.local,e)}getHostedProvisioning(){return fn(this.local)}setHostedProvisioning(e){return pn(this.local,e)}listHostedAudit(){return hn(this.local)}listHostedMachines(){return gn(this.local)}destroyHostedMachine(e){return _n(this.local,e)}validateHostedProviderCredential(e,t,n){return un(this.local,e,t,n)}rotateHostedProvisioning(){return mn(this.local)}triggerHostedProvision(e=!1){return vn(this.local,e)}onTerminal(e){return this.terminalListeners.add(e),()=>this.terminalListeners.delete(e)}sendTerminal(e){this.send(e)}closeSessionTui(e){this.send({kind:`terminal.close.tui`,sessionId:e})}applyLinkPayload(e){return n||!xt(this.local,e)?!1:(this.store.setSignedIn(this.signedIn),this.switchNode(this.local.cur),this.refreshNodes(),!0)}reconcileSessionList(e){switch(String(e.type||``)){case`session.renamed`:case`session.branch_renamed`:case`session.closed`:this.refreshSessions();return;case`session.deleted`:e.sessionId&&this.transcriptCache.delete(e.sessionId),this.refreshSessions();return;default:return}}maybeRefreshModelsForRuntime(e){let t=this.store.getState(),n=e.type===`session.history`&&!!e.sessionId&&e.sessionId===t.activeSession.activeSessionId&&!t.catalogs.currentModel;(e.type===`runtime.updated`||n)&&this.listModels()}retryPendingSessionNew(){!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||this.store.getState().activeSession.activeSessionId||this.send(this.pendingPrompt.frame)}maybeFlushPendingPrompt(e){if(!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||e.type!==`session.history`||e.requestId!==this.pendingPrompt.requestId)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId;if(!t)return;Z({kind:`session`,id:t},{replace:!0});let{text:n,clientMessageId:r,attachments:i}=this.pendingPrompt;this.pendingPrompt=null,this.send({kind:`prompt`,sessionId:t,text:n,clientMessageId:r,attachments:i});let a=this.pendingFollowups;this.pendingFollowups=[];for(let e of a)this.send({kind:`prompt`,sessionId:t,text:e.text,clientMessageId:e.clientMessageId,attachments:e.attachments});this.refreshSessions()}abort(){let e=this.store.getState().activeSession.activeSessionId;e&&this.send({kind:`abort`,sessionId:e})}resolveTurnAttention(e,t){this.send({kind:`session.turn_attention.resolve`,sessionId:e,action:t})}setLimitRetry(e){let t=this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.limit_retry`,sessionId:t,enabled:e})}accountMode(){return!!(this.local.s&&this.local.cp)}resolveSessionNodeId(e){return this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.nodeId}resolveNodeLabel(e){let t=this.store.getState().connection.nodes.find(t=>t.id===e);return t?.name?`bivy/${t.name}`:void 0}async persistScheduledFollowup(e,t,n){if(!this.accountMode()||!n)return;let r=this.resolveSessionNodeId(e);if(!r)return;let i=this.local.keys()[r];if(i)try{let a=await D(await E(C(i)),n),o=new Date(Date.now()+6e4).toISOString(),s=await bn(this.local,{name:`Follow-up`,templateCiphertext:`${fl}:${r}:${a}`,trigger:`schedule`,schedule:{kind:`once`,at:o},nodeLabel:this.resolveNodeLabel(r),targetKind:`existing_session`,targetSessionId:e,message:!0,enabled:!0});this.store.attachFollowupAutomation(e,t,s.id)||this.cancelScheduledFollowup(s.id)}catch{}}startRun(e,t){return this.accountCoordinator.startRun(e,t)}cancelScheduledFollowup(e){e&&wn(this.local,e).catch(()=>{})}async editScheduledFollowup(e,t,n){let r=this.store.getFollowups(e).find(e=>e.id===t);if(!r||r.status!==`scheduled`)return`This message is no longer pending.`;if(!r.scheduledAutomationId)return`This message has no automation to update.`;if(!Number.isFinite(n.getTime())||n.getTime()<=Date.now())return`Pick a time in the future.`;try{await Sn(this.local,r.scheduledAutomationId,{schedule:{kind:`once`,at:n.toISOString()}})}catch(e){return e instanceof Error?e.message:`Could not reschedule the message.`}return this.store.rescheduleFollowup(e,t,n.getTime(),Date.now()),null}async resyncScheduledFollowups(){if(!this.accountMode())return;let e;try{e=await yn(this.local)}catch{return}let t=new Set(e.filter(e=>e.enabled&&e.nextRunAt!=null).map(e=>e.id));for(let e of Object.keys(this.store.getState().sessionIndex.followupsBySession))this.store.pruneScheduledFollowups(e,t)}supportsSteering(){return this.followupCoordinator.supportsSteering()}getFollowups(e){return this.followupCoordinator.list(e)}editFollowup(e,t,n,r){return this.followupCoordinator.edit(e,t,n,r)}removeFollowup(e,t){return this.followupCoordinator.remove(e,t)}reorderFollowup(e,t,n){return this.followupCoordinator.reorder(e,t,n)}sendFollowupNow(e,t){this.followupCoordinator.sendNow(e,t)}steerNow(e,t){return this.followupCoordinator.steer(e,t)}renameSession(e,t){let n=t.trim();n&&(e===this.store.getState().activeSession.activeSessionId&&this.store.setActiveTitle(n),this.store.renameSessionLocal(e,n),this.send({kind:`session.rename`,sessionId:e,name:n}),this.refreshSessions())}async deleteSession(e,t){if(this.isProvisionalSessionId(e)&&(await this.pendingLaunchRestoration,this.pendingLaunches.has(e))){await this.dismissPendingLaunch(e);return}let n=this.ephemeralCorrelations.find(t=>t.sessionId===e),r=n&&this.store.getState().connection.nodes.some(e=>e.id===n.nodeId&&e.online);if(!this.direct&&n&&!r){await this.deleteRetiredSession(e);return}this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.sessionCoordinator.deleteSession(e,t)}async deleteRetiredSession(e){try{let{base:t,auth:n}=this.correlationApi();if(!(await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`DELETE`,headers:n,signal:AbortSignal.timeout(15e3)})).ok)throw Error(`Couldn't delete the retired session. Refresh and try again.`);this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e),this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.store.getState().activeSession.activeSessionId===e&&(this.store.resetActiveSession(),Z({kind:`new`})),this.store.removeSessionLocal(e),this.persistDeletedSessionTombstones(),await this.transcriptCache.delete(e),this.refreshSessions()}catch(e){this.store.setError(e instanceof Error?e.message:`Couldn't delete the retired session.`)}}pauseSession(e){this.sessionCoordinator.pauseSession(e)}resumeSession(e){this.sessionCoordinator.resumeSession(e)}refreshPrStatus(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.pr.refresh`,sessionId:t})}refreshAllPrStatus(){this.send({kind:`sessions.pr.refresh_all`})}rewind(e,t){let n=t||this.store.getState().activeSession.activeSessionId;n&&e&&this.send({kind:`session.rewind`,sessionId:n,checkpointId:e})}revertFile(e,t,n){let r=n||this.store.getState().activeSession.activeSessionId;r&&e&&this.send({kind:`session.revert_file`,sessionId:r,path:e,content:t})}listCheckpoints(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.checkpoints`,sessionId:t})}resolveApproval(e,t,n=!1){this.send({kind:`approval`,id:e,approved:t,...t&&n?{remember:!0}:{}}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}answerQuestion(e,t,n){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,answers:n}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}cancelQuestion(e,t){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,cancelled:!0}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}},_l=g();function vl({tone:e,variant:t=`outline`,upper:n=!1,className:r=``,children:i,...a}){return(0,_l.jsx)(`span`,{className:`badge${n?` upper`:``}${r?` ${r}`:``}`,"data-tone":e,"data-variant":t,...a,children:i})}function yl(){return(0,y.useSyncExternalStore)(gl.store.subscribe,gl.store.getState)}export{Hn as $,yo as A,D as At,G as B,Z as C,Qe as Ct,Xs as D,ye as Dt,Js as E,Ae as Et,Oa as F,tr as G,ni as H,Ma as I,jn as J,yt as K,Aa as L,Ga as M,v as Mt,Ia as N,fs as O,E as Ot,Wa as P,wn as Q,ja as R,uc as S,rt as St,oc as T,Ne as Tt,nr as U,ii as V,$n as W,Rn as X,Vn as Y,bn as Z,Lc as _,wt as _t,sl as a,Kt as at,_c as b,pt as bt,Yc as c,Ln as ct,Pc as d,Tt as dt,zn as et,Bc as f,An as ft,zc as g,Cn as gt,Hc as h,Tn as ht,gl as i,yn as it,Ka as j,C as jt,zo as k,O as kt,Wc as l,St as lt,Rc as m,xn as mt,vl as n,kn as nt,qc as o,fn as ot,Gc as p,Mn as pt,On as q,cl as r,Dn as rt,Vc as s,Bn as st,yl as t,Et as tt,Ic as u,bt as ut,Fc as v,Ct as vt,ac as w,Fe as wt,vc as x,at as xt,Kc as y,Sn as yt,li as z};
|
|
27
|
+
`).trim()}function Bo(e,t){return e&&typeof e==`object`&&!Array.isArray(e)&&t&&typeof t==`object`&&!Array.isArray(t)?{...e,...t}:t??e}function Vo(e,t,n=Y){let r=t.callId?e.find(e=>e.tool&&e.tool.callId===t.callId):[...e].reverse().find(e=>e.tool&&e.tool.status===`running`&&(t.name===`tool`||e.tool.name===t.name));r&&r.tool?r.tool={...r.tool,status:t.status,result:t.result??r.tool.result,detail:t.detail??r.tool.detail,parentToolUseId:t.parentToolUseId??r.tool.parentToolUseId,name:t.status===`done`&&t.name===`tool`?r.tool.name:t.name,input:t.status===`running`?Bo(r.tool.input,t.input):r.tool.input}:e.push({id:n(),role:`assistant`,text:``,tool:t})}function Ho(e=!0){return{assistantId:null,thinkingId:null,finalized:e,thinkingText:``,sawThinking:!1,pendingText:``,committedText:``,committedThinking:``}}function Uo(e){return{...e,transcript:[...e.transcript],draft:{...e.draft}}}function Wo(e){let t=e.length+1,n=new Set(e.map(e=>e.id));for(;n.has(`live-${t}`);)t+=1;return`live-${t}`}function Go(e,t){let n={id:Wo(e.transcript),...t};return e.transcript.push(n),n}function Ko(e,t,n){e.transcript=e.transcript.map(e=>e.id===t?{...e,...n}:e)}function qo(e,t){e.transcript=e.transcript.filter(e=>e.id!==t)}function Jo(e,t){e.working=!0,e.workingLabel=t}function Yo(e,t,n,r){let i=t===`assistant`?`assistant`:`thinking`,a=t===`assistant`?`assistantId`:`thinkingId`,o=i===`assistant`&&r?ye(n):void 0,s=e.draft[a];s?Ko(e,s,{text:n,html:o,streaming:!r}):(s=Go(e,{role:i,text:n,html:o,streaming:!r}).id,e.draft[a]=s),r&&(e.draft[a]=null)}function Xo(e){e.draft.assistantId&&Ko(e,e.draft.assistantId,{streaming:!1}),e.draft.thinkingId&&Ko(e,e.draft.thinkingId,{streaming:!1}),e.draft.assistantId=null,e.draft.thinkingId=null}function Zo(e){let t=e.draft;if(!t.sawThinking)return;let n=(t.thinkingText.startsWith(t.committedThinking)?t.thinkingText.slice(t.committedThinking.length):t.thinkingText).trim();n&&(t.committedThinking=t.thinkingText,t.thinkingId=null,Yo(e,`thinking`,n,!0))}function Qo(e){return(e.pendingText.startsWith(e.committedText)?e.pendingText.slice(e.committedText.length):e.pendingText).trim()}function $o(e){let t=Qo(e.draft);t&&(e.draft.committedText=e.draft.pendingText,Me(t)?(e.draft.assistantId&&(qo(e,e.draft.assistantId),e.draft.assistantId=null),Go(e,{role:`error`,text:je(t)})):Yo(e,`assistant`,t,!0))}function es(e){let t=Qo(e.draft);t&&Yo(e,`assistant`,t,!1)}function ts(e){let t=e?.assistantMessageEvent;return t?.type===`thinking_delta`&&typeof t.delta==`string`?{kind:`delta`,text:t.delta}:t?.type===`thinking_end`&&typeof t.content==`string`?{kind:`full`,text:t.content}:{kind:`none`,text:``}}function ns(e,t,n){if(t)n.thinkingText=t;else{let t=ts(e);t.kind===`delta`?n.thinkingText+=t.text:t.kind===`full`&&(n.thinkingText=t.text)}return n.thinkingText.trim()}function rs(e,t){return e&&t&&typeof e==`object`&&typeof t==`object`&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t??e}function is(e,t){let n=t.callId?e.transcript.findIndex(e=>e.tool?.callId===t.callId):-1;if(n<0){Go(e,{role:`assistant`,text:``,tool:t});return}let r=e.transcript[n],i=r.tool;e.transcript[n]={...r,tool:{...i,status:t.status,result:t.result??i.result,detail:t.detail??i.detail,parentToolUseId:t.parentToolUseId??i.parentToolUseId,input:t.status===`running`?rs(i.input,t.input):i.input}}}function as(e){e.transcript=e.transcript.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function os(e,t){let n=Oe(e);if(n)return n;let r=Te(e),i=Ee(e),a=String(i?.command||i?.cmd||i?.path||i?.file||i?.filePath||i?.query||i?.stream||``);return a||r===`agent_output`||r===`stderr`||r===`stdout`?`${r}:${a}`:Wo(t)}function ss(e,t){let n=Te(e);if(n===`agent_output`||n===`stderr`||n===`stdout`)return`Reading agent output…`;let r=Oe(e),i=j(e)??(r?t.find(e=>e.tool?.callId===r)?.tool?.detail:void 0);return i?.kind===`delegation`?i.label?`${i.label} sub-agent is working…`:`Sub-agent is working…`:`Running ${n}…`}function cs(e,t){return e.some(e=>e.attachments?.some(e=>e.hash===t))}function ls(e,t,n){let r=xe(t);if(!r)return{handled:!1,value:e,commands:[]};let i=Uo(e),a=[];switch(r){case`agent_start`:case`turn_start`:i.draft.finalized=!1,Jo(i,r===`agent_start`?`Planning…`:`Thinking…`);break;case`message_start`:t.message?.role===`assistant`&&(i.draft.finalized&&(i.draft=Ho(!1)),Jo(i,`Drafting response…`));break;case`app_published`:{let e=t.app;if(!vo(e))break;i.transcript.some(t=>t.app?.appId===e.appId)||i.transcript.push({id:`app-${e.appId}`,role:`assistant`,text:``,app:e});break}case`delegation`:{let e=t.delegation;if(!wo(e))break;let n={id:`delegation-${e.id}`,role:`assistant`,text:``,delegation:e},r=i.transcript.findIndex(t=>t.delegation?.id===e.id);r>=0?i.transcript[r]=n:(Zo(i),$o(i),i.transcript.push(n));break}case`suggestion`:{let e=t.suggestion;if(!So(e)||i.transcript.some(t=>t.suggestion?.id===e.id))break;i.transcript.push({id:e.id,role:`assistant`,text:``,suggestion:e});break}case`notice`:{let e=t.notice;if(!Co(e)||i.transcript.some(t=>t.notice?.id===e.id))break;Zo(i),$o(i),i.transcript.push({id:e.id,role:`assistant`,text:``,notice:e});break}case`app_review`:{let e=t.review;if(!ho(e))break;let n=i.transcript.findIndex(t=>t.review?.id===e.id),r={id:e.id,role:`assistant`,text:``,review:e};n>=0&&e.expired?i.transcript[n]=r:(n>=0&&i.transcript.splice(n,1),i.transcript.push(r));break}case`app_pin`:{let e=t.pin;if(!_o(e))break;let n=i.transcript.findIndex(t=>t.pin?.id===e.id),r={id:e.id,role:`assistant`,text:``,pin:e};n>=0?i.transcript[n]=r:i.transcript.push(r);break}case`attachment`:{let r=t.ref;if(!r||typeof r.hash!=`string`||r.kind!==`image`&&r.kind!==`file`)return{handled:!0,value:e,commands:[]};if(cs(i.transcript,r.hash))break;let o=typeof t.caption==`string`?t.caption:``;Go(i,{role:`assistant`,text:o,attachments:[{kind:r.kind,name:r.name,size:r.size,mimeType:r.mimeType,hash:r.hash,description:o||void 0,createdAt:n,...t.artifact?{artifact:!0}:{}}]}),a.push({kind:`remember-agent-attachments`});break}case`inlineImage`:{let n=t.url,r=t.ref;if(typeof n!=`string`||!n||!r||typeof r.hash!=`string`)return{handled:!0,value:e,commands:[]};a.push({kind:`cache-inline-image`,url:n,ref:r}),i.transcript=i.transcript.map(e=>e.role===`assistant`&&e.text?.includes(n)&&!e.imageRefs?.[n]?{...e,imageRefs:{...e.imageRefs??{},[n]:r}}:e);break}case`message_update`:case`message_boundary`:case`message_end`:{let n=t.message;if(n?.role!==`assistant`)return{handled:!0,value:e,commands:[]};let a=Mo(n.content).trim();if(a&&(i.draft.pendingText=a),ns(t,No(n.content).trim(),i.draft)&&!a&&(i.draft.sawThinking=!0),r===`message_end`||r===`message_boundary`)Zo(i),$o(i),i.draft.finalized=!0;else{let e=a?`Drafting response…`:`Thinking…`;(!i.working||i.workingLabel!==e)&&Jo(i,e),es(i)}for(let e of Fo(n.content))is(i,e);break}case`start`:Zo(i),$o(i),Xo(i),is(i,{callId:os(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Jo(i,ss(t,i.transcript));break;case`update`:is(i,{callId:os(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Jo(i,ss(t,i.transcript));break;case`result`:is(i,{callId:os(t,i.transcript),name:Te(t),input:{},status:`done`,result:typeof t.result==`string`?t.result:Mo(t.result),detail:j(t)});break;case`turn_end`:Jo(i,`Planning next step…`);break;case`agent_end`:Xo(i),as(i),Object.assign(i.draft,{pendingText:``,committedText:``,committedThinking:``}),i.working=!1,i.workingLabel=``,a.push({kind:`turn-settled`});break;default:return{handled:!1,value:e,commands:[]}}if(r===`result`||r===`message_end`||r===`message_boundary`){let e=Lo(t.result??t.message??t.output).filter(e=>!cs(i.transcript,e.hash));e.length&&(Go(i,{role:`assistant`,text:``,attachments:e}),a.push({kind:`remember-agent-attachments`}))}return{handled:!0,value:i,commands:a}}function X(e,t=!1){return{queue:e,changed:!1,accepted:t}}function us(e,t){switch(t.type){case`enqueue`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`queued`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`schedule`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`scheduled`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`attach-automation`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAutomationId:t.automationId},{queue:r,changed:!0,accepted:!0}}case`edit`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return{...X(e),edit:{ok:!1,reason:`not_found`}};let r=e[n];if(r.status!==`queued`)return{...X(e),edit:{ok:!1,reason:`not_queued`}};if(r.version!==t.expectedVersion)return{...X(e),edit:{ok:!1,reason:`stale`}};let i={...r,...t.patch,version:r.version+1,updatedAt:t.now,scheduledAutomationId:void 0},a=e.slice();return a[n]=i,{queue:a,changed:!0,accepted:!0,item:i,edit:{ok:!0,item:i}}}case`remove`:{let n=e.find(e=>e.id===t.id);return!n||n.status!==`queued`&&n.status!==`scheduled`?X(e):{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}}case`prune-scheduled`:{let n=e.filter(e=>e.status!==`scheduled`||(e.scheduledAutomationId?t.keepIds.includes(e.scheduledAutomationId):!1));return n.length===e.length?X(e):{queue:n,changed:!0,accepted:!0}}case`reschedule`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`scheduled`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAt:t.scheduledAt,updatedAt:t.now,version:e[n].version+1},{queue:r,changed:!0,accepted:!0}}case`reorder`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=Math.max(0,Math.min(t.toIndex,e.length-1));if(r===n)return X(e,!0);let i=e.slice(),[a]=i.splice(n,1);return i.splice(r,0,a),{queue:i,changed:!0,accepted:!0}}case`mark-sending`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return X(e);let r={...e[n],status:`sending`,updatedAt:t.now},i=e.slice();return i[n]=r,{queue:i,changed:!0,accepted:!0,item:r}}case`confirm-sent`:return e.some(e=>e.id===t.id)?{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}:X(e);case`revert-to-queued`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`sending`)return X(e);let r={...e[n],status:`queued`,updatedAt:t.now};return{queue:[r,...e.filter(e=>e.id!==t.id)],changed:!0,accepted:!0,item:r}}case`settle-sending`:return e.some(e=>e.status===`sending`)?{queue:e.filter(e=>e.status!==`sending`),changed:!0,accepted:!0}:X(e);case`clear`:return e.length?{queue:[],changed:!0,accepted:!0}:X(e,!0)}}function ds(e){return e.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function fs(e){return e===`openai-codex`?`openai`:e}var ps=[`status`,`signedIn`,`nodes`,`currentNodeId`,`nodeUpdate`,`nodeUpdating`,`nodeUpdateAcknowledged`],ms=[`sessions`,`runTerminals`,`tuiSessions`,`pausedSessionIds`,`commandsBySession`,`followupsBySession`],hs=[`activeSessionId`,`activeRuntimeId`,`activeTitle`,`github`,`transcript`,`working`,`workingLabel`,`opening`,`approvals`,`questions`,`turnAttentions`,`usage`,`changes`,`changesHistory`,`checkpoints`],gs=[`models`,`modelsRuntimeId`,`currentModelId`,`currentModel`,`thinking`,`runtimes`,`currentAgentName`,`selectedAgentId`,`installingRuntimeId`,`repos`,`reposAuthed`,`reposError`,`reposLoading`,`reposReason`,`githubConnect`,`branches`,`branchesRepo`,`branchesDefault`,`branchesError`,`branchesLoading`,`providers`,`activationReadiness`],_s=[`nodeSettings`,`providerAuth`,`credentialRecords`,`credentialPresets`,`localModels`,`localModelPresets`,`rulesets`,`sttConfig`,`nodeStats`,`capabilities`],vs=[`forkProgress`,`oauth`,`needsModelAuth`,`githubApp`,`prResult`,`prRefreshAllResult`,`error`,`notice`];function ys(e,t,n){let r=[];for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&r.push([e,t[e]]);return r.length?{...e,...Object.fromEntries(r)}:e}function bs(){return{connection:{status:`offline`,signedIn:!1,nodes:[],currentNodeId:null,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1},sessionIndex:{sessions:[],runTerminals:[],tuiSessions:[],pausedSessionIds:[],commandsBySession:{},followupsBySession:{}},activeSession:{activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[]},catalogs:{models:[],modelsRuntimeId:null,currentModelId:null,currentModel:null,thinking:{supportsThinking:!1,thinkingLevel:`off`,availableThinkingLevels:[`off`]},runtimes:[],currentAgentName:`Agent`,selectedAgentId:null,installingRuntimeId:null,repos:[],reposAuthed:!0,reposError:null,reposLoading:!1,reposReason:null,githubConnect:{status:`idle`},branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,providers:[],activationReadiness:null},settings:{nodeSettings:null,providerAuth:null,credentialRecords:[],credentialPresets:null,localModels:[],localModelPresets:[],rulesets:[],sttConfig:null,nodeStats:null,capabilities:null},presentation:{oauth:null,needsModelAuth:null,githubApp:null,prResult:null,prRefreshAllResult:null,error:null,errorActions:[],notice:null,forkProgress:null},draft:{...va}}}function xs(e=!0){return Ho(e)}function Ss(e){return e.role===`assistant`&&!e.tool&&!!e.attachments?.length}function Cs(e){return e.tool?`tool:${e.tool.callId}`:`${e.role}:${e.text}`}function ws(e,t){let n=-1,r=e.length;for(let i=0,a=0;i<e.length;i++)if(e[i].role===`user`){if(a+=1,a===t.turn)n=i+1;else if(a===t.turn+1){r=i;break}}if(n<0)return t.turn===0?Ts(e,0,r):e.length;if(!t.after)return Ts(e,n,r);for(let i=r-1;i>=n;i--){let n=e[i];if(!Ss(n)&&Cs(n)===t.after)return Ts(e,i+1,r)}return r}function Ts(e,t,n){for(;t<n&&Ss(e[t]);)t++;return t}var Es=class e{state=bs();listeners=new Set;notifyPending=!1;notifyHandle=null;draft=xs();knownAgentAttachmentsBySession=new Map;draftModel=null;modelsByRuntime=new Map;cachedModelsFor(e){return this.modelsByRuntime.get(e)?.models}pending=new Map;usersBeforePending=0;attachmentsByText=new Map;static ATTACHMENTS_CACHE_MAX=100;inlineImagesByUrl=new Map;transcriptCache=new Map;static CACHE_MAX=30;recentlyDeleted=new Map;historyRaw=new Map;deferredHistory=null;awaitingOpenHistory=!1;onHistoryPersist;requestReplay;seqReassembler=new xa;seqSessionId;seqEpoch;trackSeqStream(e,t){let n=typeof t==`string`?t:void 0;(this.seqSessionId!==e||this.seqEpoch!==n)&&(this.seqReassembler.reset(),this.seqSessionId=e,this.seqEpoch=n)}requestFreshHistory;onSessionSettled;onSessionCreatedElsewhere;getState=()=>this.state;setGithubAppPhase(e,t={}){this.set({githubApp:{...this.state.presentation.githubApp||{phase:`idle`},phase:e,...t}})}setGithubConnect(e){this.set({githubConnect:e})}getHistoryCursor(e){let t=this.historyRaw.get(e);return t&&t.count>0&&t.historyHash?{have:t.count,haveToken:t.historyHash}:{}}seedHistory(e,t,n,r){if(!e||!r||!Array.isArray(t))return;this.historyRaw.set(e,{messages:t,count:n,historyHash:r});let i=this.withInlineImageRefs(this.withCachedAttachments(Ro(t)));this.cacheTranscript(e,i),this.state.activeSession.activeSessionId===e&&this.state.activeSession.transcript.length===0&&this.set({transcript:i,opening:!1})}getCachedTranscript(e){return this.transcriptCache.get(e)}withPendingUserEntries(e){if(this.pending.size===0)return e;let t=new Set(e.map(e=>e.id)),n=new Map,r=0;for(let t of e)t.role===`user`&&(n.set(t.text,(n.get(t.text)||0)+1),r+=1);let i=e=>{if(!e)return!1;let t=n.get(e)||0;return t<=0?!1:(n.set(e,t-1),!0)},a=[],o=0;for(let[e,n]of this.pending)if(!t.has(n.entry.id)){if(i(n.confirmedText)||i(n.entry.text)){n.confirmed?this.retirePending(e):n.reconciled=!0,o+=1;continue}n.reconciled=!1,a.push({cmid:e,entry:n.entry,confirmed:n.confirmed})}let s=r-this.usersBeforePending-o,c=[];for(let{cmid:e,entry:t,confirmed:n}of a){if(s>0&&n){--s,this.retirePending(e);continue}c.push(t)}return this.pending.size===0&&(this.usersBeforePending=0),c.length?[...e,...c]:e}retirePending(e){this.pending.delete(e)}rememberAttachments(t,n){if(t&&n.length&&(this.attachmentsByText.delete(t),this.attachmentsByText.set(t,n),this.attachmentsByText.size>e.ATTACHMENTS_CACHE_MAX)){let e=this.attachmentsByText.keys().next().value;e!==void 0&&this.attachmentsByText.delete(e)}}attachmentsForHistory(e){if(this.attachmentsByText.size===0)return[];let t=[];for(let n of Ro(e)){if(n.role!==`user`||!n.text)continue;let e=this.attachmentsByText.get(n.text);e&&t.push([n.text,e])}return t}restoreAttachments(e){if(e&&e.length)for(let[t,n]of e)this.rememberAttachments(t,n)}foldAttachmentRefs(e){if(e&&e.length)for(let[t,n]of e){if(!t||!n.length||this.attachmentsByText.has(t))continue;let e=n.map(e=>({kind:e.kind,name:e.name,size:e.size,mimeType:e.mimeType,hash:e.hash}));this.rememberAttachments(t,e)}}withCachedAttachments(e){if(this.attachmentsByText.size===0)return e;let t=!1,n=e.map(e=>{if(e.role!==`user`||!e.text)return e;let n=this.attachmentsByText.get(e.text);return n?(t=!0,{...e,attachments:n}):e});return t?n:e}foldInlineImageRefs(e){if(e&&e.length)for(let[t,n]of e)t&&n&&this.inlineImagesByUrl.set(t,n)}withInlineImageRefs(e){if(this.inlineImagesByUrl.size===0)return e;let t=!1,n=e.map(e=>{if(e.role!==`assistant`||!e.text)return e;let n=oe(e.text);if(!n.length)return e;let r;for(let t of n){let n=this.inlineImagesByUrl.get(t);n&&!e.imageRefs?.[t]&&(r??={...e.imageRefs??{}},r[t]=n)}return r?(t=!0,{...e,imageRefs:r}):e});return t?n:e}cacheTranscript(t,n){if(t&&(this.transcriptCache.delete(t),this.transcriptCache.set(t,n),this.transcriptCache.size>e.CACHE_MAX)){let e=this.transcriptCache.keys().next().value;e!==void 0&&this.transcriptCache.delete(e)}}beginOpen(e){this.draft=xs(),this.deferredHistory=null,this.awaitingOpenHistory=!0,this.pending.clear(),this.usersBeforePending=0;let t=this.transcriptCache.get(e),n=this.state.sessionIndex.sessions.find(t=>t.sessionId===e);this.set({activeSessionId:e,activeRuntimeId:n?.runtimeId??null,currentAgentName:n?.agentName||oo(this.state.catalogs.runtimes.find(e=>e.id===n?.runtimeId))||``,currentModel:null,currentModelId:null,models:[],modelsRuntimeId:n?.runtimeId??null,sessions:n?this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,lastSeenAt:Date.now()}:t):this.state.sessionIndex.sessions,...n?.name?{activeTitle:n.name}:{},github:n?Ja(n):{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:t??[],working:!1,workingLabel:``,opening:!t||t.length===0,usage:null,changes:null,changesHistory:[],checkpoints:[]})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));set(e){let t=ys(this.state.connection,e,ps),n=ys(this.state.sessionIndex,e,ms),r=ys(this.state.activeSession,e,hs),i=ys(this.state.catalogs,e,gs),a=ys(this.state.settings,e,_s),o=ys(this.state.presentation,e,vs);this.setValues({connection:t,sessionIndex:n,activeSession:r,catalogs:i,settings:a,presentation:o,draft:e.draft??this.state.draft})}setValues(e){if(this.state={...this.state,...e},this.state.activeSession.working){this.scheduleNotify();return}this.flushNotify()}scheduleNotify(){if(this.notifyPending)return;this.notifyPending=!0;let e=()=>{this.notifyPending=!1,this.notifyHandle=null;for(let e of this.listeners)e()};this.notifyHandle=typeof globalThis.requestAnimationFrame==`function`?globalThis.requestAnimationFrame(e):setTimeout(e,16)}flushNotify(){if(!this.notifyPending){for(let e of this.listeners)e();return}let e=this.notifyHandle;this.notifyPending=!1,this.notifyHandle=null,e!==null&&(typeof globalThis.cancelAnimationFrame==`function`&&typeof e==`number`?globalThis.cancelAnimationFrame(e):clearTimeout(e));for(let e of this.listeners)e()}mergeRuntimeCapabilities(e,t){let n=e?String(e):``;if(!n||!t||typeof t!=`object`)return;let r=this.state.catalogs.runtimes.findIndex(e=>e.id===n),i=r>=0?this.state.catalogs.runtimes[r]:void 0;if(!i)return;let a=i.capabilities||{},o={...t};delete o.commands;let s={...a,...o};if(JSON.stringify(s)===JSON.stringify(a))return;let c=this.state.catalogs.runtimes.slice();c[r]={...i,capabilities:s},this.set({runtimes:c})}setSessionCommands(e,t){let n=e?String(e):``;if(!n)return;let r=Na((t&&typeof t==`object`?t:void 0)?.commands);if(Pa(this.state.sessionIndex.commandsBySession[n]??[],r))return;let i={...this.state.sessionIndex.commandsBySession};r.length?i[n]=r:delete i[n],this.set({commandsBySession:i})}dropSessionCommands(e){if(!(e in this.state.sessionIndex.commandsBySession))return;let t={...this.state.sessionIndex.commandsBySession};delete t[e],this.set({commandsBySession:t})}getFollowups(e){return this.state.sessionIndex.followupsBySession[e]??[]}setFollowupsFor(e,t){let n={...this.state.sessionIndex.followupsBySession};t.length?n[e]=[...t]:delete n[e],this.set({followupsBySession:n})}transitionFollowups(e,t){let n=us(this.getFollowups(e),t);return n.changed&&this.setFollowupsFor(e,n.queue),n}enqueueFollowup(e,t,n){return this.transitionFollowups(e,{type:`enqueue`,item:t,now:n}).item}enqueueScheduledFollowup(e,t,n){return this.transitionFollowups(e,{type:`schedule`,item:t,now:n}).item}attachFollowupAutomation(e,t,n){return this.transitionFollowups(e,{type:`attach-automation`,id:t,automationId:n}).accepted===!0}editFollowup(e,t,n,r,i){return this.transitionFollowups(e,{type:`edit`,id:t,patch:n,expectedVersion:r,now:i}).edit}removeFollowup(e,t){return this.transitionFollowups(e,{type:`remove`,id:t}).accepted===!0}pruneScheduledFollowups(e,t){this.transitionFollowups(e,{type:`prune-scheduled`,keepIds:[...t]})}rescheduleFollowup(e,t,n,r){return this.transitionFollowups(e,{type:`reschedule`,id:t,scheduledAt:n,now:r}).accepted===!0}reorderFollowup(e,t,n){return this.transitionFollowups(e,{type:`reorder`,id:t,toIndex:n}).accepted===!0}markFollowupSending(e,t,n){return this.transitionFollowups(e,{type:`mark-sending`,id:t,now:n}).item}confirmFollowupSent(e,t){this.transitionFollowups(e,{type:`confirm-sent`,id:t})}revertFollowupToQueued(e,t,n){this.transitionFollowups(e,{type:`revert-to-queued`,id:t,now:n})}settleSendingFollowups(e){this.transitionFollowups(e,{type:`settle-sending`})}dropFollowups(e){e in this.state.sessionIndex.followupsBySession&&this.transitionFollowups(e,{type:`clear`})}clearActivationReadiness(){this.set({activationReadiness:null})}setStatus(e){if(e===this.state.connection.status)return;let t=this.state.connection.currentNodeId;this.set({status:e,...t&&e===`online`?{nodes:this.state.connection.nodes.map(e=>e.id===t?{...e,online:!0}:e)}:{}})}setSignedIn(e){e!==this.state.connection.signedIn&&this.set({signedIn:e})}setNodes(e){let t=this.state.connection.currentNodeId;this.set({nodes:t&&this.state.connection.status===`online`?e.map(e=>e.id===t?{...e,online:!0}:e):e})}setSessions(e){let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions)),n=new Set(t.map(e=>e.sessionId)),r=[...this.state.sessionIndex.sessions.filter(e=>!n.has(e.sessionId)&&(e.pendingLaunch||!(!e.launchProgress||e.launchProgress.firstResponseAt))),...t],i=this.state.activeSession.activeSessionId,a=i?r.find(e=>e.sessionId===i):void 0,o=!!(a&&a.status!==`working`&&a.sessionState?.agent!==`working`);this.set({sessions:i?r.map(e=>e.sessionId===i?{...e,lastSeenAt:Date.now()}:e):r,...o?{working:!1,workingLabel:``}:{}})}seedSessions(e){if(this.state.sessionIndex.sessions.length>0)return;let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions));t.length!==0&&this.set({sessions:t})}setCurrentNode(e){e!==this.state.connection.currentNodeId&&this.set({currentNodeId:e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1})}resetSession(){this.draft=xs(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[],commandsBySession:{},followupsBySession:{},error:null,notice:null,needsModelAuth:null,draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null}),nodeSettings:null})}setForkProgress(e){this.set({forkProgress:e})}setError(e,t=[]){this.set({error:e,errorActions:e?t:[]})}setNotice(e){this.set({notice:e})}setNodeUpdating(e){this.set({nodeUpdating:e,nodeUpdateAcknowledged:!1})}setNeedsModelAuth(e){this.set({needsModelAuth:e})}pushSystemMessage(e){this.pushEntry({id:Y(),role:`system`,text:e})}clearPrResult(){this.state.presentation.prResult&&this.set({prResult:null})}clearPrRefreshAllResult(){this.state.presentation.prRefreshAllResult&&this.set({prRefreshAllResult:null})}setReposLoading(e){this.set({reposLoading:e})}updateSessionDraft(e){let t=ya(this.state.draft,e);return this.set({draft:t}),t}setDraftEphemeralConfig(e){this.updateSessionDraft({type:`select-ephemeral-config`,config:e})}setDraftRepo(e){this.updateSessionDraft({type:`select-repository`,repo:e})}setBranchesLoading(e){this.set({branchesLoading:e})}clearBranches(){this.set({branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,draft:ya(this.state.draft,{type:`select-branch`,branch:null})})}setDraftBranch(e){this.updateSessionDraft({type:`select-branch`,branch:e})}setDraftSandbox(e){this.updateSessionDraft({type:`select-sandbox`,sandbox:e})}setDraftAcknowledgeReducedProtections(e){this.updateSessionDraft({type:`acknowledge-reduced-protections`,acknowledged:e})}setDraftModel(e){this.draftModel=e}seedDraftAgentModel(e,t){if(this.state.activeSession.activeSessionId)return;let n={},r=e=>String(e.status||`available`)===`available`,i=e?this.state.catalogs.runtimes.find(t=>t.id===e&&r(t)):void 0,a=this.state.catalogs.runtimes.find(e=>e.current&&r(e)),o=i||a;if(o){let e=oo(o);n.selectedAgentId=o.id,e&&(n.currentAgentName=e)}if(!o||this.state.catalogs.modelsRuntimeId==null||this.state.catalogs.modelsRuntimeId===o.id){let e=t?this.state.catalogs.models.find(e=>ao(e,t)):void 0,r=this.state.catalogs.models.find(e=>e.current),i=e||r;i&&(n.currentModel=i,n.currentModelId=i.id)}else n.models=[],n.modelsRuntimeId=null,n.currentModel=null,n.currentModelId=null;Object.keys(n).length&&this.set(n)}setCurrentModelLocal(e){this.set({currentModel:e,currentModelId:e.id,models:this.state.catalogs.models.map(t=>({...t,current:ao(t,e)}))})}setSelectedAgentLocal(e){let t={selectedAgentId:e,currentAgentName:oo(this.state.catalogs.runtimes.find(t=>t.id===e))||this.state.catalogs.currentAgentName,draft:ya(this.state.draft,{type:`acknowledge-reduced-protections`,acknowledged:!1})};if(this.state.catalogs.modelsRuntimeId!=null&&this.state.catalogs.modelsRuntimeId!==e){let n=this.modelsByRuntime.get(e);n?(t.models=n.models,t.modelsRuntimeId=e,t.currentModel=n.currentModel,t.currentModelId=n.currentModel?.id??null):(t.models=[],t.modelsRuntimeId=null,t.currentModel=null,t.currentModelId=null)}this.set(t)}setInstalling(e){this.set({installingRuntimeId:e})}setThinkingLevel(e){this.set({thinking:{...this.state.catalogs.thinking,thinkingLevel:e}})}resetActiveSession(){this.draft=xs(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],selectedAgentId:null,currentAgentName:``,usage:null,changes:null,changesHistory:[],checkpoints:[],draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null})})}persistPendingSession(e,t,n=!0,r,i=Date.now()){if(this.isSessionDeleted(e))return;let a=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),o={...a,sessionId:e,name:t.trim()||a?.name||`New session`,status:a?.status===`failed`?`failed`:`working`,pendingLaunch:!0,pendingNodeName:r||a?.pendingNodeName,launchProgress:a?.launchProgress??{startedAt:i,checkpoints:{account:{state:`active`,at:i}}},updatedAt:a?.updatedAt||Date.now()};this.set({...n?{activeSessionId:e,activeTitle:o.name}:{},sessions:[o,...this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)]})}retryPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>{if(t.sessionId!==e)return t;let n=t.launchProgress?Object.fromEntries(Object.entries(t.launchProgress.checkpoints).map(([e,t])=>[e,t?.state===`failed`?{state:`active`,at:Date.now()}:t])):void 0;return{...t,status:`working`,updatedAt:Date.now(),launchProgress:t.launchProgress?{...t.launchProgress,failedAt:void 0,checkpoints:n??{}}:void 0}})})}dismissPendingSession(e){this.recentlyDeleted.set(e,Date.now()),this.set({activeSessionId:this.state.activeSession.activeSessionId===e?null:this.state.activeSession.activeSessionId,sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}updateLaunchCheckpoint(e,t,n,r,i){let a=Date.now();this.set({sessions:this.state.sessionIndex.sessions.map(o=>o.sessionId===e&&o.launchProgress?{...o,launchProgress:{...o.launchProgress,...n===`failed`?{failedAt:a}:{},checkpoints:{...Object.fromEntries(Object.entries(o.launchProgress.checkpoints).map(([e,t])=>[e,n===`failed`&&t?.state===`active`?{...t,state:`waiting`}:t])),[t]:{state:n,at:a,...r?{error:r}:{},...i?{errorCode:i}:{}}}}}:o)})}setLaunchModelChoice(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress?{...n,needsAction:!(!t||t.loading||t.selecting),launchProgress:{...n.launchProgress,modelChoice:t}}:n)})}markLaunchFirstResponse(e,t=Date.now()){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress&&!n.launchProgress.firstResponseAt?{...n,launchProgress:{...n.launchProgress,firstResponseAt:t,failedAt:void 0,checkpoints:{...n.launchProgress.checkpoints,agent:{state:`done`,at:t}}}}:n)})}bindPendingSessionNode(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,nodeId:t}:n)})}completePendingSession(e,t,n){if(this.isSessionDeleted(e)||this.isSessionDeleted(t))return;let r=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),i={...r,sessionId:t,nodeId:n,name:r?.name||`New session`,status:`working`,pendingLaunch:!1,pendingNodeName:void 0,updatedAt:Date.now()};this.set({activeSessionId:this.state.activeSession.activeSessionId===e?t:this.state.activeSession.activeSessionId,sessions:[i,...this.state.sessionIndex.sessions.filter(n=>n.sessionId!==e&&n.sessionId!==t)]})}failPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,status:`failed`,launchProgress:t.launchProgress?{...t.launchProgress,failedAt:t.launchProgress.failedAt??Date.now()}:void 0}:t)})}setActiveTitle(e){this.set({activeTitle:e})}renameSessionLocal(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,name:t}:n)})}seedDeletedSessionTombstones(e){if(e&&typeof e==`object`){for(let[t,n]of Object.entries(e)){let e=Number(n);t&&Number.isFinite(e)&&this.recentlyDeleted.set(t,e)}this.set({sessions:this.withoutRecentlyDeleted(this.state.sessionIndex.sessions)})}}deletedSessionTombstones(){return Object.fromEntries(this.recentlyDeleted)}removeSessionLocal(e){this.recentlyDeleted.set(e,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}isSessionDeleted(e){return this.recentlyDeleted.has(e)}withoutRecentlyDeleted(e){return this.recentlyDeleted.size===0?e:e.filter(e=>!this.isSessionDeleted(e.sessionId))}upsertSession(e){if(!e.sessionId||this.isSessionDeleted(e.sessionId))return;let t=this.state.sessionIndex.sessions.find(t=>t.sessionId===e.sessionId);if(t){let n={...t,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))};this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e.sessionId?n:t)})}else this.set({sessions:[e,...this.state.sessionIndex.sessions]})}addUserMessage(e,t,n){let r={id:Y(),role:`user`,text:e,html:ye(e),...n&&n.length?{attachments:n}:{}};t&&(this.pending.size===0&&(this.usersBeforePending=this.state.activeSession.transcript.reduce((e,t)=>t.role===`user`?e+1:e,0)),this.pending.set(t,{entry:r,confirmed:!1})),n&&n.length&&this.rememberAttachments(e,n),this.set({transcript:[...this.state.activeSession.transcript,r]}),this.state.activeSession.activeSessionId&&this.updateSessionRow(this.state.activeSession.activeSessionId,{updatedAt:Date.now()})}apply(e){let t=String(e.type||``),n=Sa(this.state.connection,e);if(n.handled){this.setValues({connection:n.value,...n.error?{presentation:{...this.state.presentation,error:n.error}}:{}});return}let r=Ca(this.state.sessionIndex,e);if(r.handled){r.value!==this.state.sessionIndex&&this.setValues({sessionIndex:{...this.state.sessionIndex,pausedSessionIds:[...r.value.pausedSessionIds]}});return}let i=Ta({runTerminals:this.state.sessionIndex.runTerminals,tuiSessions:this.state.sessionIndex.tuiSessions},e,Date.now());if(i.handled){this.set({runTerminals:[...i.value.runTerminals],tuiSessions:[...i.value.tuiSessions]});return}let a=Ea(e);if(a.handled){(a.catalogs||a.settings)&&this.setValues({...a.catalogs?{catalogs:{...this.state.catalogs,...a.catalogs}}:{},...a.settings?{settings:{...this.state.settings,...a.settings}}:{}});return}let o=Da(this.state.presentation,e);if(o.handled){this.setValues({presentation:o.value});return}let s=lo({approvals:this.state.activeSession.approvals,questions:this.state.activeSession.questions,turnAttentions:this.state.activeSession.turnAttentions},e,Date.now());if(s.handled){this.set({approvals:s.value.approvals,questions:s.value.questions,turnAttentions:s.value.turnAttentions}),s.row&&this.updateSessionRow(s.row.sessionId,s.row);return}let c=po({activeSessionId:this.state.activeSession.activeSessionId,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel,opening:this.state.activeSession.opening,usage:this.state.activeSession.usage,changes:this.state.activeSession.changes,changesHistory:this.state.activeSession.changesHistory,checkpoints:this.state.activeSession.checkpoints,activeTitle:this.state.activeSession.activeTitle,github:this.state.activeSession.github,...t===`session.changes`?{newChangeId:Y()}:{}},e,Date.now());if(c.handled){c.patch&&this.set(c.patch);for(let e of c.commands)e.kind===`row`?this.updateSessionRow(e.sessionId,e.patch):e.kind===`entry`?this.pushEntry({id:Y(),role:e.role,text:e.text,...e.actions?.length?{actions:e.actions}:{}}):e.kind===`model-auth`&&this.state.connection.currentNodeId?this.setNeedsModelAuth({nodeId:this.state.connection.currentNodeId,provider:e.provider,reason:e.reason}):e.kind===`rename`?this.renameSessionLocal(e.sessionId,e.name):e.kind===`global-error`?this.set({error:e.message}):e.kind===`reset-active`&&this.resetActiveSession();return}this.applyStatefulEvent(e,t)}applyStatefulEvent(e,t){switch(t){case`sessions.list`:this.setSessions(e.sessions);return;case`session.created`:{let t=e,n=String(t.sessionId||t.id||``);if(n){let e=this.state.sessionIndex.sessions.find(e=>e.sessionId===n),r=eo(t.sessionState??t.bivySession?.state);this.upsertSession({sessionId:n,path:t.sessionFile||t.path,workspace:t.workspace||t.bivySession?.workspace,worktree:t.worktree||t.bivySession?.worktree||t.bivySession?.workspaceContext?.worktree,branch:t.branch||t.bivySession?.branch,name:t.name||(e?void 0:`Untitled session`),source:t.source,bivyCreated:t.bivyCreated===!0,nodeId:t.nodeId,runtimeId:t.runtimeId,agentName:t.agentName,updatedAt:t.updatedAt||t.modified||(e?void 0:Date.now()),status:to(r)??`idle`,sessionState:r,needsAction:r?.displayStatus===`needs_attention`})}this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),n&&this.setSessionCommands(n,t.capabilities),this.onSessionCreatedElsewhere?.();return}case`session.capabilities`:{let t=e;this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),this.setSessionCommands(t.sessionId,t.capabilities);return}case`session.deleted`:{let t=e,n=String(t.sessionId||``),r=t.sessionFile;n&&this.recentlyDeleted.set(n,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(e=>e.sessionId!==n&&(!r||e.path!==r))}),n&&this.dropSessionCommands(n),n&&this.dropFollowups(n),n&&this.knownAgentAttachmentsBySession.delete(n),n&&n===this.state.activeSession.activeSessionId&&this.resetActiveSession();return}case`session.history`:{let t=e,n=t.sessionId||this.state.activeSession.activeSessionId;if(n&&n===this.state.activeSession.activeSessionId&&this.state.activeSession.working&&!this.draft.finalized&&!this.awaitingOpenHistory){this.deferredHistory=t;return}this.applyHistory(t,n);return}case`session.user_message`:{let t=e,n=t.clientMessageId?this.pending.get(t.clientMessageId):void 0,r=!(!n||n.confirmed);if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId||t.sessionId&&!this.state.activeSession.activeSessionId&&!r||(this.state.activeSession.changes&&this.set({changes:null}),t.retry&&!r))return;if(r&&n){n.entry.attachments?.length&&t.text&&this.rememberAttachments(String(t.text),n.entry.attachments),n.confirmed=!0,t.text&&(n.confirmedText=String(t.text)),n.reconciled&&this.retirePending(t.clientMessageId);return}let i=String(t.text||``);this.pushEntry({id:Y(),role:`user`,text:i,html:ye(i)}),t.sessionId&&this.updateSessionRow(t.sessionId,{updatedAt:Date.now()});return}case`models.list`:{let t=e,n=t.runtimeId==null?null:String(t.runtimeId),r=ro(t.models),i=t.current?ro([t.current])[0]:null;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId){n&&n!==this.state.activeSession.activeRuntimeId&&this.modelsByRuntime.set(n,{models:r,currentModel:i});return}let a=r.filter(e=>e.configured!==!1),o=!this.state.activeSession.activeSessionId&&this.draftModel?a.find(e=>ao(e,this.draftModel)):void 0,s;if(o)s=o;else if(i)s=i;else if(a.length===0)s=null;else{let e=a.find(e=>e.current),t=a.find(e=>ao(e,this.state.catalogs.currentModel));s=e??t??a[0]}n&&this.modelsByRuntime.set(n,{models:r,currentModel:s});let c=this.state.activeSession.activeSessionId?this.state.activeSession.activeRuntimeId:this.state.catalogs.selectedAgentId;if(n&&c&&n!==c)return;this.set({models:r,modelsRuntimeId:n,currentModel:s,currentModelId:s?.id??null,...t.thinking?{thinking:io(t.thinking)}:{}});return}case`model.updated`:{let t=e;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId)return;let n=t.model?ro([t.model])[0]:this.state.catalogs.currentModel;this.set({currentModel:n,currentModelId:n?.id??this.state.catalogs.currentModelId,models:this.state.catalogs.models.map(e=>({...e,current:ao(e,n)}))});return}case`thinking.updated`:{let t=e;t.thinking&&this.set({thinking:io(t.thinking)});return}case`runtimes.list`:case`runtime.updated`:{let t=e,n=t.runtimes||this.state.catalogs.runtimes,r=t.current||n.find(e=>e.id===(this.state.catalogs.selectedAgentId||t.activeAgent)),i=(this.state.activeSession.activeSessionId?void 0:n.find(e=>e.id===this.state.catalogs.selectedAgentId))?.id||r?.id||t.activeAgent||this.state.catalogs.selectedAgentId,a=this.state.activeSession.activeSessionId?n.find(e=>e.id===this.state.activeSession.activeRuntimeId):n.find(e=>e.id===i)||r;this.set({runtimes:n,selectedAgentId:i,currentAgentName:oo(a)||this.state.catalogs.currentAgentName,...t.type===`runtime.updated`?{installingRuntimeId:null}:{}});return}case`runtime.install.done`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null});return}case`runtime.install.error`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null,error:String(t.error||`Install failed`)});return}case`activation.readiness`:{let t=e;t.credential&&t.repository&&this.set({activationReadiness:{credential:t.credential,repository:t.repository}});return}case`github.connect.status`:{let t=e,n=[`waiting`,`connected`,`expired`,`denied`,`error`,`unconfigured`,`idle`].includes(t.status)?t.status:`idle`;this.set({githubConnect:{status:n,userCode:typeof t.userCode==`string`?t.userCode:void 0,verificationUri:typeof t.verificationUri==`string`?t.verificationUri:void 0,intervalMs:typeof t.intervalMs==`number`?t.intervalMs:void 0,error:typeof t.error==`string`?t.error:void 0}});return}case`providers.list`:{let t=e,n=Array.isArray(t.providers)?t.providers:[];this.set({providers:n});let r=this.state.presentation.needsModelAuth;if(r){let e=fs(r.provider);n.some(t=>(t.id===r.provider||t.id===e)&&t.configured)&&this.set({needsModelAuth:null})}return}case`provider.auth`:this.set({providerAuth:e});return;case`provider.oauth.reset`:{let t=e;Array.isArray(t.providers)&&this.set({providers:t.providers}),this.set({oauth:null});return}case`provider.oauth.started`:{let t=e;this.set({oauth:{id:String(t.id||``),provider:t.provider,authUrl:t.authUrl,instructions:t.instructions,deviceCode:t.deviceCode||null,usesCallbackServer:t.usesCallbackServer,canOpenOnNode:t.canOpenOnNode===!0,nodeName:typeof t.nodeName==`string`?t.nodeName:void 0,status:t.error?void 0:`Waiting for sign-in…`,error:t.error}});return}case`auth.oauth.progress`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,status:String(t.message||``)}});return}case`auth.oauth.done`:{let t=e;(!this.state.presentation.oauth||this.state.presentation.oauth.id===t.id)&&this.set({oauth:null});return}case`auth.oauth.error`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,error:String(t.error||`sign-in failed`),status:void 0}});return}case`github.app.manifest.ready`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}});return}case`github.app.manifest.done`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}});return}case`github.app.manifest.error`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}});return}case`session.event`:{let t=e,n=t.sessionId,r=t.event||{},i=be(r?.type);if(n&&i!==`user_question`&&i!==`user_question_resolved`&&i!==`app_published`&&i!==`app_review`&&i!==`app_pin`&&i!==`suggestion`&&i!==`notice`){let e=i===`agent_end`,r=eo(t.state??t.sessionState);this.updateSessionRow(n,{status:to(r)??(e?`idle`:`working`),sessionState:r,needsAction:r?r.agent===`awaiting-input`:!1,...e?{updatedAt:Date.now(),finishedAt:Date.now()}:{}})}if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId||n&&!this.state.activeSession.activeSessionId)return;if(r&&r.type){let e=n&&!r.sessionId?{...r,sessionId:n}:r,i=t.seq;if(typeof i==`number`&&n){this.trackSeqStream(n,t.epoch);let r=this.seqReassembler.accept(i,e);for(let e of r.ready)this.apply(e);r.overflow?this.requestFreshHistory?.():r.gapFrom!==void 0&&this.requestReplay?.(n,r.gapFrom)}else this.apply(e)}return}case`session.replay`:{let t=e,n=t.sessionId;if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId)return;if(t.mode===`reset`){this.requestFreshHistory?.();return}let r=Array.isArray(t.events)?t.events:[];for(let e of r)this.apply(e);return}case`node.stats`:{let t=Xa(e.stats);t&&this.set({nodeStats:t});return}case`capabilities`:{let t=Za(e.capabilities);t&&this.set({capabilities:t});return}case`session.pr_result`:{let t=e,n=t.prUrl||t.url||null;this.set({prResult:{sessionId:t.sessionId,url:n||void 0,error:t.ok===!1?String(t.error||`Could not open pull request`):void 0}}),t.ok!==!1&&(n||Array.isArray(t.prs))&&this.applyPrUpdate(String(t.sessionId||``),n,t.prs);return}case`session.pr_opened`:{let t=e;this.applyPrUpdate(String(t.sessionId||``),t.prUrl||null,t.prs);return}case`sessions.pr_refresh_result`:{let t=e;this.set({prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}});return}default:{let t=ls({transcript:this.state.activeSession.transcript,draft:this.draft,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel},e,Date.now());if(!t.handled)return;this.draft=t.value.draft,this.set({transcript:t.value.transcript,working:t.value.working,workingLabel:t.value.workingLabel});for(let e of t.commands)e.kind===`cache-inline-image`?this.inlineImagesByUrl.set(e.url,e.ref):e.kind===`remember-agent-attachments`?this.rememberAgentAttachments(this.state.activeSession.activeSessionId,this.state.activeSession.transcript):e.kind===`turn-settled`&&(this.drainDeferredHistory(),this.onSessionSettled?.())}}}applyHistory(e,t){Array.isArray(e.attachmentRefs)&&this.foldAttachmentRefs(e.attachmentRefs),Array.isArray(e.inlineImageRefs)&&this.foldInlineImageRefs(e.inlineImageRefs);let n=Array.isArray(e.messages)?e.messages:[],r=t?this.historyRaw.get(t):void 0,i=e.mode===`append`&&r&&(e.baseCount===void 0||e.baseCount===r.count);if(e.mode===`append`&&!i){t&&this.historyRaw.delete(t),t&&t===this.state.activeSession.activeSessionId&&this.requestFreshHistory?.();return}let a=i?r.messages.concat(n):n,o=typeof e.count==`number`?e.count:a.length,s=typeof e.historyHash==`string`?e.historyHash:``;t&&(this.historyRaw.set(t,{messages:a,count:o,historyHash:s}),s&&this.onHistoryPersist?.(t,a,o,s));let c=eo(e.sessionState??e.bivySession?.state),l=!(c?c.agent===`working`:e.isStreaming),u=this.withCachedAttachments(l?ds(Ro(a)):Ro(a));this.rememberAgentAttachments(t,u);let d=this.withInlineImageRefs(this.withStickyAgentAttachments(t,u));if(t&&this.cacheTranscript(t,d),!(this.state.activeSession.activeSessionId===t||this.state.activeSession.activeSessionId===null&&e.requestId))return;this.draft=xs(),this.deferredHistory=null;let f=eo(e.sessionState??e.bivySession?.state);t&&f&&this.updateSessionRow(t,{sessionState:f,status:to(f),needsAction:f.agent===`awaiting-input`}),this.awaitingOpenHistory=!1,this.set({activeSessionId:t,activeRuntimeId:e.runtimeId?String(e.runtimeId):this.state.activeSession.activeRuntimeId,activeTitle:e.name||this.state.activeSession.activeTitle,currentAgentName:e.agentName||this.state.catalogs.currentAgentName,github:qa(e),transcript:this.withPendingUserEntries(d),working:f?f.agent===`working`:!!e.isStreaming,opening:!1,usage:Ya(e.usage)}),t&&typeof e.headSeq==`number`&&(this.trackSeqStream(t,e.streamEpoch),this.seqReassembler.baseline(e.headSeq))}markStreamInterrupted(){this.deferredHistory=null,this.state.activeSession.opening&&this.set({opening:!1}),!this.draft.finalized&&(this.finishDrafts(),this.draft.finalized=!0)}drainDeferredHistory(){let e=this.deferredHistory;e&&(this.deferredHistory=null,this.requestFreshHistory?this.requestFreshHistory():this.applyHistory(e,e.sessionId||this.state.activeSession.activeSessionId))}pushEntry(e){this.set({transcript:[...this.state.activeSession.transcript,e]})}rememberAgentAttachments(e,t){if(!e)return;let n=this.knownAgentAttachmentsBySession.get(e),r=0,i=``;for(let a of t){if(a.role===`user`){r+=1,i=``;continue}if(!Ss(a)){i=Cs(a);continue}for(let t of a.attachments)t.hash&&(n||(n=new Map,this.knownAgentAttachmentsBySession.set(e,n)),n.has(t.hash)||n.set(t.hash,{attachment:t,caption:a.text,turn:r,after:i}))}}withStickyAgentAttachments(e,t){if(!e)return t;let n=this.knownAgentAttachmentsBySession.get(e);if(!n||n.size===0)return t;let r=new Set;for(let e of t)for(let t of e.attachments??[])t.hash&&r.add(t.hash);let i=t;for(let e of n.values()){if(!e.attachment.hash||r.has(e.attachment.hash))continue;let t=ws(i,e);i=[...i.slice(0,t),{id:Y(),role:`assistant`,text:e.caption,attachments:[e.attachment]},...i.slice(t)]}return i}updateSessionRow(e,t){if(!e)return;let n=!1,r=this.state.sessionIndex.sessions.map(r=>{if(r.sessionId!==e)return r;let i={...r,...t};return e===this.state.activeSession.activeSessionId&&(i.lastSeenAt=Date.now()),(i.status!==r.status||i.needsAction!==r.needsAction||JSON.stringify(i.sessionState)!==JSON.stringify(r.sessionState)||i.branch!==r.branch||i.prUrl!==r.prUrl||JSON.stringify(i.prs)!==JSON.stringify(r.prs)||i.updatedAt!==r.updatedAt||i.lastSeenAt!==r.lastSeenAt||i.finishedAt!==r.finishedAt||i.failedAt!==r.failedAt)&&(n=!0),i});n&&this.set({sessions:r})}applyPrUpdate(e,t,n){let r=Fa(n,t);if(r.length===0)return;let i=r.find(e=>e.state===`open`)?.url??null;e&&this.updateSessionRow(e,{prUrl:i??void 0,prs:r}),(!e||e===this.state.activeSession.activeSessionId)&&this.set({github:{...this.state.activeSession.github,prUrl:i,prs:r}})}finishDrafts(){let e=new Set([this.draft.assistantId,this.draft.thinkingId].filter(Boolean));e.size&&this.set({transcript:this.state.activeSession.transcript.map(t=>e.has(t.id)?{...t,streaming:!1}:t)}),this.draft.assistantId=null,this.draft.thinkingId=null}};function Ds(e,t){return e>0||t}function Os(e){let t=e?.streamingBehaviors;return Array.isArray(t)&&t.includes(`steer`)}function ks(e){return e.find(e=>e.status===`queued`)}var As=`t`;function js(e={}){let t=e.indexedDB??(typeof indexedDB<`u`?indexedDB:void 0)??globalThis.indexedDB,n=e.dbName||`bivy-transcripts`,r=e.maxSessions||50,i=null;function a(){return i||(i=new Promise(e=>{let r;try{if(!t)return e(null);r=t.open(n,1)}catch{return e(null)}r.onupgradeneeded=()=>{try{r.result.createObjectStore(As,{keyPath:`sessionId`})}catch{}},r.onsuccess=()=>e(r.result),r.onerror=()=>e(null)}),i)}function o(e,t){return a().then(n=>new Promise(r=>{if(!n)return r(null);let i=null,a;try{a=n.transaction(As,e)}catch{return r(null)}let o=t(a.objectStore(As));o&&(o.onsuccess=()=>i=o.result),a.oncomplete=()=>r(i),a.onerror=()=>r(null),a.onabort=()=>r(null)}))}async function s(e){return e&&await o(`readonly`,t=>t.get(e))||null}async function c(e,t,n,i,a){if(!e||!i)return;await o(`readwrite`,r=>r.put({sessionId:e,messages:t,count:n,historyHash:i,updatedAt:Date.now(),...a&&a.length?{attachments:a}:{}}));let s=await o(`readonly`,e=>e.getAll());if(Array.isArray(s)&&s.length>r){let e=s.sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)).slice(r);await o(`readwrite`,t=>{for(let n of e)t.delete(n.sessionId)})}}async function l(e){e&&await o(`readwrite`,t=>t.delete(e))}return{get:s,put:c,delete:l}}function Ms(e,t,n=15e3){let{currentNodeId:r,nodeUpdating:i}=e.getState().connection;if(i)return;e.setNodeUpdating(!0);let a=()=>{let t=e.getState().connection;return t.currentNodeId===r&&t.nodeUpdating},o=!1,s=()=>{o=!0,clearTimeout(l),u()},c=t=>{o||(s(),a()&&(e.setNodeUpdating(!1),e.setError(t)))},l=setTimeout(()=>c("The machine didn't confirm the update request. It may still be updating or waiting for active turns. Check `bivy update:log` on the machine before trying again."),n),u=e.subscribe(()=>{(!a()||e.getState().connection.nodeUpdateAcknowledged)&&s()});try{Promise.resolve(t()).catch(e=>c(e instanceof Error?e.message:String(e)))}catch(e){c(e instanceof Error?e.message:String(e))}}var Ns=`bivy-attachments-v1`,Ps=67108864,Fs=class{writes=Promise.resolve();closed=!1;key(e,t){return new URL(`/__attachment_cache__/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,location.origin).href}async get(e,t){try{if(this.closed)return null;let n=await(await caches.open(Ns)).match(this.key(e,t));if(!n)return null;let r=await n.json();return typeof r.data==`string`&&typeof r.mimeType==`string`?r:null}catch{return null}}put(e,t,n){this.closed||(this.writes=this.writes.then(async()=>{let r=JSON.stringify(n),i=new Blob([r]).size;if(i>Ps)return;let a=await caches.open(Ns),o=this.key(e,t);await a.delete(o);let s=i,c=[];for(let e of await a.keys()){let t=await a.match(e),n=Number(t?.headers.get(`Content-Length`))||0;s+=n,c.push({request:e,bytes:n})}for(let e of c){if(s<=Ps)break;await a.delete(e.request),s-=e.bytes}await a.put(o,new Response(r,{headers:{"Content-Type":`application/json`,"Content-Length":String(i)}}))}).catch(()=>{}))}async clear(){this.closed=!0,await this.writes;try{await caches.delete(Ns)}catch{}}},Is=class{pending=new Map;memory=new Map;bytes=0;queue=[];active=0;sequence=0;timer;fetch(e,t,n){let r=this.memory.get(e);if(r)return this.memory.delete(e),this.memory.set(e,r),Promise.resolve(r);let i=this.pending.get(e);if(i){let n=this.queue.find(t=>t.key===e);return n&&(n.priority=Math.max(n.priority,t)),i}let a=new Promise(r=>{this.queue.push({key:e,priority:t,sequence:this.sequence++,load:n,resolve:r})});return this.pending.set(e,a),this.schedule(),a}schedule(){this.timer===void 0&&(this.timer=setTimeout(()=>{this.timer=void 0,this.drain()},0))}drain(){for(this.queue.sort((e,t)=>t.priority-e.priority||t.sequence-e.sequence);this.active<2&&this.queue.length;){let e=this.queue.shift();this.active++,this.run(e)}}async run(e){let t=null;try{t=await e.load()}catch{}if(t){let n=t.data.length*2;if(n<=Ps){for(;this.bytes+n>Ps&&this.memory.size;){let e=this.memory.keys().next().value;this.bytes-=this.memory.get(e).data.length*2,this.memory.delete(e)}this.memory.set(e.key,t),this.bytes+=n}}this.pending.delete(e.key),this.active--,e.resolve(t),this.schedule()}},Ls=class{local;connect;changed;closed=!1;pending=new Map;attempted=new Map;constructor(e,t,n){this.local=e,this.connect=t,this.changed=n}ensure(e){if(!this.closed)for(let t of new Set(e)){if(!t||this.local.keys()[t]||this.pending.has(t)||Date.now()-(this.attempted.get(t)??0)<6e4)continue;if(this.pending.size>=3)break;this.attempted.set(t,Date.now());let n=new Proxy(this.local,{get:(e,n,r)=>n===`cur`?t:Reflect.get(e,n,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),r=!1,i=()=>{r||(r=!0,clearTimeout(o),a.close(),this.pending.delete(t))},a=this.connect(n,()=>{!r&&this.local.keys()[t]&&(i(),this.changed(),this.ensure(e))}),o=setTimeout(()=>{i(),this.ensure(e)},15e3);this.pending.set(t,i),a.connect().catch(i).finally(()=>{r&&a.close()})}}close(){this.closed=!0;for(let e of this.pending.values())e();this.attempted.clear()}},Rs=15e3,zs=()=>Error(`The machine is not reachable.`),Bs=class{local;connect;idleMs;links=new Map;seq=0;constructor(e,t,n=6e4){this.local=e,this.connect=t,this.idleMs=n}async request(e,t,n=3e4){let r=this.link(e);await r.ready,r.idle&&clearTimeout(r.idle);let i=`mr-${Date.now().toString(36)}-${(this.seq++).toString(36)}`;return new Promise((a,o)=>{let s=setTimeout(()=>this.settle(e,r,i,Error(`The machine didn't answer.`)),n);r.pending.set(i,{resolve:a,reject:o,timer:s}),r.transport.send({...t,requestId:i})})}close(){for(let e of[...this.links.keys()])this.drop(e,Error(`Closed.`))}link(e){let t=this.links.get(e);if(t)return t;let n=new Proxy(this.local,{get:(t,n,r)=>n===`cur`?e:Reflect.get(t,n,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),r,i={pending:new Map};return i.ready=new Promise((e,t)=>{r=e,i.fail=t}),i.ready.catch(()=>{}),i.connecting=setTimeout(()=>{this.links.get(e)===i&&this.drop(e,zs())},Rs),i.transport=this.connect(n,{onStatus:e=>{e===`online`&&(clearTimeout(i.connecting),r())},onEvent:t=>{let n=String(t.requestId??``);if(!i.pending.has(n))return;let r=String(t.type??``).endsWith(`.error`);this.settle(e,i,n,r?Error(String(t.error||`Request failed.`)):t)}}),this.links.set(e,i),i.transport.connect().catch(()=>{this.links.get(e)===i&&this.drop(e,zs())}),i}settle(e,t,n,r){let i=t.pending.get(n);i&&(clearTimeout(i.timer),t.pending.delete(n),r instanceof Error?i.reject(r):i.resolve(r),t.pending.size===0&&(t.idle=setTimeout(()=>{this.links.get(e)===t&&this.drop(e,Error(`Closed.`))},this.idleMs)))}drop(e,t){let n=this.links.get(e);if(n){this.links.delete(e),n.idle&&clearTimeout(n.idle),clearTimeout(n.connecting),n.fail(t);for(let e of n.pending.values())clearTimeout(e.timer),e.reject(t);n.transport.close()}}};function Vs(){return window.navigation}var Hs=0,Us=[],Ws=[],Gs,Ks=[];function qs(){if(!(Gs||Us.some(e=>e.closing)))for(let e of Ks.splice(0))e()}function Js(e){Ks.push(e),setTimeout(qs,0)}function Ys(){if(Gs)return;let e=Us.at(-1);if(e?.closing){Gs=e;let t=Vs();e.returnKey&&t?t.traverseTo(e.returnKey):history.back();return}for(let e of Ws.splice(0))e.disposed||(e.returnKey=Vs()?.currentEntry?.key,history.pushState({...history.state,__bivyModal:e.id},``,location.href),Us.push(e));Us.at(-1)?.closing?Ys():qs()}typeof window<`u`&&window.addEventListener(`popstate`,e=>{let t=Us.at(-1);if(t&&e.state?.__bivyModal===t.id){e.stopImmediatePropagation(),Gs=void 0,queueMicrotask(Ys);return}let n=Us.pop();Gs=void 0,n&&(e.stopImmediatePropagation(),n.disposed||n.onBack(),queueMicrotask(Ys))});function Xs(e){let t={id:++Hs,onBack:e,closing:!1,disposed:!1};return queueMicrotask(()=>{t.disposed||(Ws.push(t),Ys())}),{close(){t.closing||(t.closing=!0,Ys())},dispose(){t.disposed=!0,t.closing=!0,Ys()}}}var Zs=[`appearance`,`notifications`,`import`,`providers`,`models`,`instructions`,`voice`,`share`,`github`,`linear`,`slack`,`queue`,`webhooks`,`rulesets`,`nodes`,`ephemeral`,`account`,`link`];function Qs(e){return Zs.includes(e)}var $s=[`runs`,`rulesets`];function ec(e){return e===`queue`?`runs`:$s.includes(e)?e:null}var tc=/^\/(artifacts|apps)\/?$/,nc=/^\/sessions\/([^/]+)\/?$/,rc=/^\/settings(?:\/([^/]+))?\/?$/,ic=/^\/automations(?:\/([^/]+))?\/?$/;function ac(e=location.pathname){let t=nc.exec(e);if(t&&t[1]){let e=decodeURIComponent(t[1]);return e===`new`?{kind:`new`}:{kind:`session`,id:e}}let n=et(e);if(n)return{kind:`run`,id:n};let r=rc.exec(e);if(r){let e=r[1]?decodeURIComponent(r[1]):``;return{kind:`settings`,view:Qs(e)?e:null}}let i=ic.exec(e);if(i)return{kind:`automations`,section:ec(i[1]?decodeURIComponent(i[1]):``)};let a=tc.exec(e);return a?{kind:`library`,view:a[1]}:{kind:`root`}}function oc(e){return(e.kind===`session`?`/sessions/${encodeURIComponent(e.id)}`:e.kind===`run`?$e(e.id):e.kind===`new`?`/sessions/new`:e.kind===`settings`?e.view?`/settings/${e.view}`:`/settings`:e.kind===`automations`?e.section?`/automations/${e.section}`:`/automations`:e.kind===`library`?`/${e.view}`:`/`)+location.search+location.hash}function Z(e,t={}){let n=oc(e);n!==location.pathname+location.search+location.hash&&(t.replace?history.replaceState(null,``,n):history.pushState(null,``,n))}function sc(e,t){try{if(e.length>2048)return null;let n=new URL(e);if(n.protocol!==`https:`||n.origin!==t||n.username||n.password||n.hash||!/^\/(?:sessions|runs)\/[A-Za-z0-9_-]+$/.test(n.pathname)||n.pathname===`/sessions/new`||[...n.searchParams.keys()].some(e=>e!==`node`)||n.searchParams.getAll(`node`).length>1)return null;let r=n.searchParams.get(`node`);return r!==null&&(!n.pathname.startsWith(`/sessions/`)||!/^[A-Za-z0-9_-]+$/.test(r))?null:{path:n.pathname,node:r}}catch{return null}}function cc(e,t,n=globalThis.__BIVY_RUNTIME_CONFIG__){return!n||typeof n!=`object`||!(e in n)?t:n[e]===!0}var lc={BASE_URL:`/`,DEV:!1,EPHEMERAL_MACHINES_ENABLED:``,MODE:`production`,PROD:!0,SSR:!1},uc=cc(`ephemeralMachinesEnabled`,lc.EPHEMERAL_MACHINES_ENABLED===`1`),dc=lc.VITE_BIVY_KEEP_FAILED_EPHEMERAL===`1`,fc=`bivy.cloudMachines.enabled`,pc=`bivy:cloud-machines-changed`;function mc(){try{return typeof localStorage<`u`&&localStorage.getItem(fc)===`1`}catch{return!1}}function hc(e){if(typeof window>`u`)return()=>{};let t=t=>{t.key===fc&&e()};return window.addEventListener(`storage`,t),window.addEventListener(pc,e),()=>{window.removeEventListener(`storage`,t),window.removeEventListener(pc,e)}}function gc(){return mc()}function _c(e){try{e?localStorage.setItem(fc,`1`):localStorage.removeItem(fc)}catch{}typeof window<`u`&&window.dispatchEvent(new Event(pc))}function vc(){return(0,y.useSyncExternalStore)(hc,mc,()=>!1)}var yc=`bivy.pwa.first-success`,bc=`bivy.product-metric.first_useful_response`,xc=`bivy.pwa.install-dismissed`,Sc=new Set,Cc=null,wc=!1,Tc=!1,Ec=0;function Dc(){try{return localStorage.getItem(yc)===`1`||localStorage.getItem(bc)===`1`}catch{return!1}}function Oc(){return typeof window>`u`?!1:window.matchMedia?.(`(display-mode: standalone)`).matches===!0||navigator.standalone===!0}function kc(){try{return localStorage.getItem(xc)===`1`}catch{return!1}}Tc=typeof window<`u`&&kc();function Ac(e,t,n,r=!1){return r?null:/iPad|iPhone|iPod/.test(e)||t===`MacIntel`&&n>1?`ios`:/Safari/.test(e)&&!/Chrome|Chromium|CriOS|Edg|OPR|FxiOS/.test(e)?`safari`:null}function jc(){return typeof navigator>`u`?null:Ac(navigator.userAgent,navigator.platform,navigator.maxTouchPoints,Oc())}var Q={updateAvailable:!1,installChoice:null,standalone:Oc(),shellCached:!1,firstSuccess:typeof window<`u`&&Dc(),hasDraft:!1,pendingAttachments:0,readingAttachments:!1,turnActive:!1,locallyQueuedPrompts:0,queuedFollowups:0};function $(e){let t={...Q,...e};Object.keys(t).every(e=>t[e]===Q[e])||(Q=t,Sc.forEach(e=>e()))}function Mc(){let e=Oc();$({standalone:e,installChoice:e||wc||Tc||!Q.firstSuccess?null:Cc?`native`:jc()})}async function Nc(){try{$({shellCached:!!(await navigator.serviceWorker?.getRegistration())?.active})}catch{$({shellCached:!1})}}function Pc(){let e=e=>{e.preventDefault(),Cc=e,Mc()},t=()=>{Cc=null,wc=!0,Mc()},n=()=>{Nc()},r=window.matchMedia?.(`(display-mode: standalone)`);return window.addEventListener(`beforeinstallprompt`,e),window.addEventListener(`appinstalled`,t),navigator.serviceWorker?.addEventListener(`controllerchange`,n),r?.addEventListener?.(`change`,Mc),Mc(),Nc(),()=>{window.removeEventListener(`beforeinstallprompt`,e),window.removeEventListener(`appinstalled`,t),navigator.serviceWorker?.removeEventListener(`controllerchange`,n),r?.removeEventListener?.(`change`,Mc)}}function Fc(e){return Sc.add(e),()=>Sc.delete(e)}function Ic(){return Q}function Lc(e){$({updateAvailable:e})}function Rc(e){$(e)}function zc(e){$({turnActive:e})}function Bc(){Ec+=1,$({locallyQueuedPrompts:Ec})}function Vc(){Ec=0,$({locallyQueuedPrompts:0})}function Hc(e){$({queuedFollowups:Math.max(0,Math.floor(e))})}function Uc(){try{localStorage.setItem(yc,`1`)}catch{}$({firstSuccess:!0}),Mc()}function Wc(){Tc=!0,Cc=null;try{localStorage.setItem(xc,`1`)}catch{}$({installChoice:null})}async function Gc(){let e=Cc;if(!e||Q.standalone||!Q.firstSuccess)return`unavailable`;Cc=null,$({installChoice:null});try{return await e.prompt(),(await e.userChoice).outcome}catch{return`unavailable`}}function Kc(e=Q){let t=[];return e.turnActive&&t.push(`the active turn finishes`),e.readingAttachments&&t.push(`file reading finishes`),e.hasDraft&&t.push(`the unsent draft is sent or cleared`),e.pendingAttachments&&t.push(`pending attachments are sent or cleared`),e.locallyQueuedPrompts&&t.push(`locally queued prompts reach the Machine`),e.queuedFollowups&&t.push(`queued follow-ups are delivered`),t}function qc(e=Q){return e.updateAvailable&&Kc(e).length===0}var Jc="On that machine, run `bivy status` (or `bivy restart`).";function Yc(e,t,n=Q,r){let i=r?`Machine ${r}`:`The Machine`;return n.locallyQueuedPrompts>0?{kind:`local-queue`,label:n.locallyQueuedPrompts===1?`Prompt queued on this device`:`${n.locallyQueuedPrompts} prompts queued on this device`,detail:`Not yet delivered to ${r?`Machine ${r}`:`the Machine`}. Keep Bivy open — it sends as soon as the connection is back.`}:e===`reconnecting`||e===`connecting`||e===`linking`||e===`pairing`?{kind:`reconnecting`,label:r?`Reconnecting to ${r}`:`Reconnecting Machine`,detail:t?`Showing the cached transcript. Keep drafting — sending resumes once the connection is back.`:`Waiting for ${r?`Machine ${r}`:`the Machine`} to answer. If this sticks, run \`bivy status\` on that machine.`}:e===`offline`&&t?{kind:`cached-transcript`,label:`Cached transcript`,detail:`${i} is offline — this copy may be behind, and prompts can't send until it reconnects. ${Jc}`}:e===`offline`&&n.shellCached?{kind:`cached-shell`,label:`Machine offline`,detail:`${i} is offline, so there is no transcript or live control yet. Your draft is kept here. ${Jc}`}:e===`offline`?{kind:`offline-page`,label:`Offline`,detail:`${i} is unreachable. Your draft is kept on this device. ${Jc}`}:{kind:`live-control`,label:`Live control`,detail:`${i} is connected. Prompts send now and transcript changes sync live.`}}var Xc=66e4,Zc=class{deps;workflow;pending=new Map;constructor(e,t){this.deps=e,this.workflow=t}send(e){return this.deps.send(e),{type:`command-sent`,command:e}}preparePrompt(e,t){return{type:`prompt-prepared`,requestId:this.deps.createRequestId(),clientMessageId:this.deps.createClientMessageId(),text:e,...t?.length?{attachments:t}:{}}}handleEvent(e){let t=String(e.requestId||``),n=t?this.pending.get(t):void 0;if(!n)return!1;clearTimeout(n.timer),this.pending.delete(t);let r=e.error;return r?n.reject(Error(String(r))):n.resolve(e),!0}newSession(e={}){let t=this.workflowPort();e.navigate!==!1&&t.navigateNew(),t.focusComposer(),t.clearPendingPromptAndFollowups(),t.resetActiveSession(),t.seedDraftDefaults(),t.listRuntimes(),t.listModels(),t.hasNodeSettings()||t.getNodeSettings(),t.listRepos();let n=t.draftRepo();n&&t.listBranches(n)}sendPrompt(e,t,n){let r=this.workflowPort(),i=e.trim(),a=t?.length?t:void 0;if(!i&&!a)return;let o=this.deps.createRequestId(),s=this.deps.createClientMessageId(),c=r.activeSessionId();if(c&&r.isPendingLaunch(c)){r.addUserMessage(i,s,a),r.appendPendingLaunchFollowup(c,{text:i,clientMessageId:s,attachments:a});return}if(c){if(r.sessionIsSaved?.(c)&&r.openSession(c),r.mustQueue(c)){r.enqueueFollowup(c,{id:s,text:i,attachments:a}),r.persistFollowup(c,s,i),r.drainFollowups(c);return}r.addUserMessage(i,s,a),r.shouldAutoResume()?(r.bufferResume({sessionId:c,text:i,clientMessageId:s,attachments:a}),r.resumeNodeForSession(c)):r.send({kind:`prompt`,sessionId:c,text:i,clientMessageId:s,attachments:a});return}if(r.hasPendingPrompt()){r.addUserMessage(i,s,a),r.appendPendingFollowup({text:i,clientMessageId:s,attachments:a});return}let l={kind:`session.new`,requestId:o,title:i||void 0,...r.draftSessionFields(),...n},u={text:i,requestId:o,clientMessageId:s,attachments:a,frame:l},d=r.draftEphemeralRunner();if(d){let e=`starting-${o}`;u.provisionalId=e,r.addUserMessage(i,s,a),r.startEphemeralLaunch(e,u,d);return}r.setPendingPrompt(u),r.addUserMessage(i,s,a),r.send(l)}deleteSession(e,t){let n=this.workflowPort();n.send({kind:`session.delete`,sessionId:e,path:t}),e===n.activeSessionId()&&n.resetDeletedActiveSession(),n.removeSessionLocal(e),n.persistDeletedSessionTombstones(),n.deleteTranscriptCache(e),n.refreshSessions()}pauseSession(e){let t=this.workflowPort(),n=t.resolveSessionId(e);n&&t.send({kind:`session.pause`,sessionId:n})}resumeSession(e){let t=this.workflowPort(),n=t.resolveSessionId(e);n&&t.send({kind:`session.resume`,sessionId:n})}async startLike(e,t,n){let r=await this.request({kind:`session.new`,like:e,title:t,prompt:t,...n?.length?{attachments:n}:{}},12e4,`Starting the session timed out`);return this.workflowPort().refreshSessions(),String(r.sessionId??``)}async importNativeSession(e,t,n=!1){return this.request({kind:`session.import`,runtimeId:e,ref:t,acceptDisclosure:n},6e4)}async promote(e,t){t&&t!==this.deps.currentNodeId()&&(this.deps.switchNode(t),await this.deps.waitForOnline());let n=await this.request({kind:`session.promote`,sessionId:e},3e4);return this.deps.refreshAccountSessions(),{epoch:Number(n.epoch??0)}}async fork(e,t={}){let n=this.deps.currentNodeId(),r=t.destNodeId??n,i=!!t.managedConfigId,a=i||!this.deps.isDirect()&&!!r&&r!==n,o=t.sourceAgentId??this.deps.sessionRuntime(e),s=t.agentId??o;if(!a&&(!s||o&&s===o)){this.deps.reportForkProgress?.(`Copying the conversation and working files…`);let n=await this.request({kind:`session.fork.local`,sessionId:e,...t.model?{model:t.model}:{}},Xc),r=String(n.sessionId||``);if(!r)throw Error(`Local fork returned no session id`);let i=this.forkResult(n,`full`);return this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(r,void 0,n),t.retireSource&&this.deps.send({kind:`session.delete`,sessionId:e}),{sessionId:r,...i}}this.deps.reportForkProgress?.(`Preparing the conversation and working files…`);let c=(await this.request({kind:`session.fork.export`,sessionId:e,...s?{agent:s}:{},...a?{crossNode:!0}:{}},6e4)).bundle;if(!c)throw Error(`Fork export returned no bundle`);let l=this.deps.transcriptUrl(e),u;try{t.managedConfigId&&(r=await this.deps.launchManagedDestination(t.managedConfigId,t.agentId)),a&&(this.deps.reportForkProgress?.(`Connecting to the destination machine…`),this.deps.switchNode(r),this.deps.reportCrossNodeFork?.(`working`,`Creating the fork on the destination machine…`),await this.deps.waitForOnline(i?12e4:void 0)),this.deps.reportForkProgress?.(`Creating the session in the destination agent…`),u=await this.request({kind:`session.fork.import`,bundle:c,transcriptUrl:l,sameNode:!a,...s?{agent:s}:{},...t.model?{model:t.model}:{}},Xc)}catch(t){throw a&&(this.deps.switchNode(n),await this.deps.waitForOnline().catch(()=>{}),this.deps.openSession(e),this.deps.reportCrossNodeFork?.(`error`,t instanceof Error?t.message:String(t))),t}let d=String(u.sessionId||``);if(!d){let e=Error(`Fork import returned no session id`);throw a&&this.deps.reportCrossNodeFork?.(`error`,e.message),e}let f=String(u.runtimeId||``);if(s&&f&&f!==s){let e=Error(`Fork requested agent ${s}, but the destination used ${f}`);throw a&&this.deps.reportCrossNodeFork?.(`error`,e.message),e}this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(d,void 0,u);let p=u.seedPrompt;if(typeof p==`string`&&p.trim()){let e=this.deps.createClientMessageId();this.deps.addUserMessage(p,e),this.deps.send({kind:`prompt`,sessionId:d,text:p,clientMessageId:e})}if(t.retireSource){this.deps.reportForkProgress?.(`Retiring the original session…`);let t={kind:`session.fork.retire-source`,sourceSessionId:e,newSessionId:d};if(a){let e;try{this.deps.switchNode(n),await this.deps.waitForOnline(),this.deps.send(t)}catch(t){e=t}finally{this.deps.switchNode(r),await this.deps.waitForOnline(),this.deps.reportForkProgress?.(`Loading the forked session…`),this.deps.openSession(d,void 0,u)}if(e){let t=Error(`Fork created, but the original session could not be retired: ${e instanceof Error?e.message:String(e)}`);throw this.deps.reportCrossNodeFork?.(`error`,t.message),t}}else this.deps.send(t)}let m=this.forkResult(u,`seeded`);if(a){let e=m.missing.map(e=>e.detail||e.label).find(Boolean);this.deps.reportCrossNodeFork?.(`success`,e?`Fork created on the destination machine. ${e}`:t.retireSource?`Session moved to the destination machine.`:`Fork created on the destination machine.`)}return{sessionId:d,...m}}workflowPort(){if(!this.workflow)throw Error(`SessionOrchestrator requires a workflow port`);return this.workflow}forkResult(e,t){let n=e.missing;return{fidelity:String(e.fidelity||t),missing:Array.isArray(n)?n:[]}}request(e,t,n=`Fork request timed out`){let r=this.deps.createRequestId();return new Promise((i,a)=>{let o=setTimeout(()=>{this.pending.delete(r),a(Error(n))},t);this.pending.set(r,{resolve:i,reject:a,timer:o}),this.deps.sendRequest({...e,requestId:r})})}},Qc=class{port;constructor(e){this.port=e}requirement(e){return!e.direct&&!e.solo&&!e.signedIn?{type:`authentication-required`}:!e.direct&&e.signedIn&&!e.currentNodeId?{type:`node-required`}:{type:`ready`}}connect(){let e=this.requiredPort();if(this.requirement(e.facts()).type!==`ready`){e.setStatus(`offline`),e.facts().signedIn&&e.refreshNodes();return}e.facts().direct||(e.setCurrentNode(e.facts().currentNodeId||``),e.refreshNodes()),e.connectTransport()}switchNode(e){let t=this.requiredPort();return e===t.facts().currentNodeId&&t.status()===`online`?!1:(t.closeTransport(),t.setCurrentNode(e),t.resetSession(),t.seedSessions(),t.rebuildTransport(),t.setStatus(`connecting`),t.connectTransport(),t.refreshAccountSessions(),!0)}async connectToNode(e,t){let n=this.requiredPort();(e!==n.facts().currentNodeId||n.status()!==`online`)&&(this.switchNode(e),await n.waitForOnline(t)),n.listProviders()}requiredPort(){if(!this.port)throw Error(`NodeConnectionCoordinator requires a port for effects`);return this.port}},$c=class{deps;accountSyncInFlight=null;constructor(e){this.deps=e}request(e,t){return this.deps.send(e),{type:`catalog-requested`,catalog:t}}selectModel(e,t){this.deps.selectModelLocally(e),this.deps.rememberModel(e);let n=t?{kind:`model.select`,provider:e.provider,id:e.id,sessionId:t}:void 0;return n&&this.deps.send(n),{type:`model-selected`,model:e,...n?{command:n}:{}}}listProviders(){this.request({kind:`providers.list`},`providers`)}getProviderAuth(e){this.deps.send({kind:`provider.auth.get`,provider:e})}saveApiKey(e,t){return this.ack({kind:`provider.apiKey`,provider:e,key:t})}removeProvider(e){this.deps.send({kind:`provider.remove`,provider:e})}resetOauth(e){this.deps.send({kind:`provider.oauth.reset`,provider:e})}startOauth(e,t){this.deps.send({kind:`provider.oauth.start`,provider:e,...t?{label:t}:{}})}async openOauthOnNode(e){let t=await this.deps.awaitAck({kind:`provider.oauth.open_on_node`,id:e});return{opened:t.opened===!0,...t.error?{error:t.error}:{}}}submitOauthCode(e,t){this.deps.send({kind:`provider.oauth.code`,id:e,code:t})}listCredentials(){this.request({kind:`credentials.list`},`credentials`)}syncAccountCredentials(){return this.deps.isOnline()?(this.accountSyncInFlight||=(async()=>{let e=await this.deps.awaitAck({kind:`credentials.account.export`,includeOAuth:this.deps.oauthRecoveryEnabled()}),t=Array.isArray(e.entries)?e.entries.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.key==`string`):[],n=this.deps.oauthRecoveryEnabled()&&Array.isArray(e.oauthEntries)?e.oauthEntries.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.label==`string`&&typeof e.refresh==`string`&&Number.isFinite(Number(e.expires))):[],r=Array.isArray(e.records)?e.records.filter(e=>!!e&&typeof e.provider==`string`&&typeof e.label==`string`&&typeof e.kind==`string`):[],i=e.deletedAt&&typeof e.deletedAt==`object`?e.deletedAt:{},a=await this.deps.accountModelKeys();for(let e of a){let t=e.label==="default"?e.provider:`${e.provider}:${e.label}`,n=Number(i[t]),r=Date.parse(String(e.updatedAt??``));Number.isFinite(n)&&n>0&&(!Number.isFinite(r)||n>=r)&&await this.deps.removeModelKey(e.provider,e.label)}for(let e of r)e.kind!==`api_key`&&await this.deps.removeModelKey(e.provider,e.label);let o=this.deps.oauthRecoveryEnabled()?await this.deps.accountOAuthCredentials():[];for(let e of o){let t=r.find(t=>t.provider===e.provider&&t.label===e.label),n=e.label==="default"?e.provider:`${e.provider}:${e.label}`,a=Number(i[n]);(t&&t.kind!==`oauth`||Number.isFinite(a)&&a>Math.max(Number(e.refreshedAt)||0,Number(e.updatedAt)||0))&&await this.deps.removeOAuthCredential(e.provider,e.label,Number.isFinite(a)?a:this.deps.now())}await this.deps.importOAuthCredentials(n);let s=t.filter(e=>{let t=a.find(t=>t.provider===e.provider&&t.label===(e.label??`default`));if(!t)return!0;let n=typeof e.updatedAt==`number`?e.updatedAt:Date.parse(String(e.updatedAt??``)),r=Date.parse(String(t.updatedAt??``));return Number.isFinite(n)&&(!Number.isFinite(r)||n>r)});await this.deps.importModelKeys(s);for(let{provider:e,label:t,key:n}of await this.deps.accountModelKeys())r.some(n=>n.provider===e&&n.label===t&&n.kind!==`api_key`)||await this.deps.awaitAck({kind:`credential.set`,provider:e,label:t,key:n});let c=(this.deps.oauthRecoveryEnabled()?await this.deps.accountOAuthCredentials():[]).filter(({provider:e,label:t})=>{let n=r.find(n=>n.provider===e&&n.label===t);return!n||n.kind===`oauth`});c.length&&await this.deps.awaitAck({kind:`credentials.account.import`,oauthEntries:c}),this.listCredentials(),this.listProviders()})().catch(()=>{}).finally(()=>{this.accountSyncInFlight=null}),this.accountSyncInFlight):Promise.resolve()}setCredential(e,t,n){return this.ack({kind:`credential.set`,provider:e,label:t,...n})}removeCredential(e,t){return this.ack({kind:`credential.remove`,provider:e,label:t})}setCredentialSync(e,t,n){return this.ack({kind:`credential.sync.set`,provider:e,label:t,sync:n})}setCredentialUnattended(e,t,n){return this.ack({kind:`credential.unattended.set`,provider:e,label:t,unattended:n})}async testCredential(e,t){let n=await this.deps.awaitAck({kind:`credential.test`,provider:e,label:t},15e3);return{ok:!!n.ok,at:Number(n.at)||this.deps.now(),...n.reason?{reason:n.reason}:{}}}getPresets(){this.deps.send({kind:`credentials.presets.get`})}setActivePreset(e){this.deps.send({kind:`credentials.presets.setActive`,active:e})}setPresetMapping(e,t,n){return this.ack({kind:`credentials.presets.setMapping`,preset:e,provider:t,label:n})}listLocalModels(){this.deps.send({kind:`models.custom.list`})}listLocalModelPresets(){this.deps.send({kind:`models.custom.presets`})}async discoverLocalModels(){return await this.deps.awaitAck({kind:`models.custom.discover`},1e4)}async verifyLocalModel(e,t){return(await this.deps.awaitAck({kind:`models.custom.verify`,baseUrl:e,...t?{apiKey:t}:{}},1e4)).result}async saveLocalModel(e){let t=await this.deps.awaitAck({kind:`models.custom.save`,spec:e});return String(t.provider??e.providerId??`local`)}removeLocalModel(e){this.deps.send({kind:`models.custom.remove`,id:e})}ack(e){return this.deps.awaitAck(e).then(()=>void 0)}},el=class{deps;finishingMachines=new Set;constructor(e){this.deps=e}listConfigs(){return this.deps.listConfigs()}createConfig(e){return this.deps.createConfig(e)}updateConfig(e,t){return this.deps.updateConfig(e,t)}removeConfig(e){return this.deps.removeConfig(e)}listSizes(e,t){return this.deps.listSizes(e,t)}async setProviderToken(e,t){await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}async connectProvider(e,t){return await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}getProviderToken(e){return this.deps.getProviderToken(e)}removeProviderToken(e){return this.deps.removeProviderToken(e)}async runWorkItem(e,t){let n=await this.launch({...t,setupId:t.configId,hostedTasks:!0,workItemId:e,purpose:`queue-item`,name:`Ephemeral queue runner`});try{await this.deps.assignWorkItem(e,{node:this.deps.nodeLabel(n.nodeId??``),runtimeId:t.runtimeId,model:t.model,ephemeral:!0})}catch(e){throw this.deps.refreshNodes(),e}return this.deps.refreshNodes(),n}launchQueueWorker(e){return this.launch({...e,setupId:e.configId,hostedTasks:!0,purpose:`queue-default`,name:`Ephemeral queue worker`})}async ensureDefaultRunner(e){try{let t=(await this.listConfigs()).find(t=>t.provider===e);if(t)return t;let n=this.deps.defaultConfig(e);return await this.createConfig({provider:e,name:`${n.name} runner`,region:n.region,size:n.size,ttlMinutes:60,teardownOnAgentFinish:!0})}catch{return null}}async launch(e){if(!this.deps.signedIn())throw Error(`Sign in to launch an ephemeral machine.`);let t=e.githubToken??await this.deps.githubToken(),n=await this.deps.launchMachine({...e,repo:e.repo??this.deps.draftRepo(),githubToken:t||void 0});return this.deps.refreshNodes(),n}async destroy(e){await this.deps.destroyMachine(e),this.deps.refreshNodes()}async teardownFinishedSession(e){if(this.deps.direct()||this.deps.followupCount(e)>0)return;let t=this.deps.currentNodeId();if(!t)return;let n=(await this.deps.machines().catch(()=>[])).find(e=>e.nodeId===t&&e.teardownOnAgentFinish);n&&!this.finishingMachines.has(n.id)&&(this.deps.recordSessionCorrelation(e,n),this.finishingMachines.add(n.id),this.deps.schedule(()=>{if(this.deps.followupCount(e)>0||this.deps.currentNodeId()!==t){this.finishingMachines.delete(n.id);return}this.destroy(n).catch(e=>{this.finishingMachines.delete(n.id),this.deps.reportError(e instanceof Error?e:Error(String(e)))})},3e3))}async resumeAndConnect(e,t=9e4){try{await this.deps.connectToNode(e,t)}catch(e){this.deps.reportError(this.error(e))}}async reprovision(e,t){try{let n=this.deps.correlations().find(n=>n.nodeId===e||n.sessionId===t);if(n?.computeSource===`managed`){if(!n.setupId)throw Error(`This managed session no longer has a Machine profile to rebuild from.`);await this.deps.restoreManagedMachine({configId:n.setupId,nodeId:n.nodeId,sessionId:t,requestId:`restore:${t}:${n.nodeId}:${n.machineId||`legacy`}`}),await this.deps.connectToNode(n.nodeId,12e4);return}let r=this.deps.roomKey(e);if(!r)throw Error(`This device no longer holds this session's key, so it can't rebuild it.`);let i=this.deps.nodes().find(t=>t.id===e),a=(await this.deps.machines()).find(t=>t.nodeId===e)??(i?this.deps.machineFromNode(i):null)??(n?this.deps.machineFromCorrelation(n):null);if(!a)throw Error(`No record of the machine to rebuild — re-launch it from Ephemeral settings.`);await this.launch({provider:a.provider,region:a.region||void 0,ttlMinutes:a.ttlMinutes,repo:a.repo,setupId:a.setupId,teardownOnAgentFinish:a.teardownOnAgentFinish,reuseNodeId:e,reuseRoomKeyB64:r,restoreSessionId:t}),await this.deps.connectToNode(e,12e4)}catch(e){this.deps.reportError(this.error(e))}}isCurrentNodeResumable(){if(this.deps.direct())return!1;let e=this.deps.currentNodeId();if(!e)return!1;let t=this.deps.correlations().find(t=>t.nodeId===e),n=this.deps.nodes().find(t=>t.id===e);return t?.computeSource===`managed`?!n:this.deps.roomKey(e)?n?!n.online&&!!this.deps.machineFromNode(n):!!t:!1}error(e){return e instanceof Error?e:Error(String(e))}},tl=class{deps;constructor(e){this.deps=e}fetchMe(){return this.deps.api.fetchMe(this.deps.local)}fetchGithubApp(){return this.deps.api.fetchGithubApp(this.deps.local)}fetchGithubQueue(e=30){return this.deps.api.fetchGithubQueue(this.deps.local,e)}fetchAutomationRuns(e=50,t={}){return this.deps.api.fetchAutomationRuns(this.deps.local,e,t)}setGithubAppDefaultNode(e,t){return this.deps.api.setGithubAppDefaultNode(this.deps.local,e,t)}setGithubAppTriggerAccess(e,t){return this.deps.api.setGithubAppTriggerAccess(this.deps.local,e,t)}assignWorkItem(e,t){return this.deps.api.assignWorkItem(this.deps.local,e,t)}deleteWorkItem(e){return this.deps.api.deleteWorkItem(this.deps.local,e)}clearWorkQueue(){return this.deps.api.clearWorkQueue(this.deps.local)}async cancelAutomationRun(e){await this.deps.api.cancelAutomationRun(this.deps.local,e);let[t,n]=await Promise.all([this.fetchAutomationRuns(50),this.fetchGithubQueue(30)]);return{runs:t,queue:n}}async startRun(e,t){let n=e.trim();if(!n)return{error:`Describe the task this Run should complete.`};let r=this.deps.runContext();if(!r.accountMode)return{error:`Sign in to start a Run.`};if(!r.nodeId)return{error:r.sessionId?`This Session has no owning Machine.`:`Choose a Machine before starting a Run.`};if(!r.roomKey)return{error:`This Machine isn't paired on this device—open it first so the instruction can be encrypted.`};if(!r.nodeLabel)return{error:`This Machine has no routing name. Reconnect it before starting a Run.`};try{let e=await this.deps.encrypt(r.roomKey,n),i=await this.deps.api.createOneOffRun(this.deps.local,{title:(n.split(/\r?\n/,1)[0]||`Run`).slice(0,120),body:`bivy-room-v1:${r.nodeId}:${e}`,label:r.nodeLabel,repo:r.sessionId?void 0:r.repo,runtimeId:r.sessionId?void 0:r.runtimeId,model:r.sessionId?void 0:r.model,approvalMode:t.approvalMode,sandbox:r.sandbox,maxAttempts:t.maxAttempts,targetKind:r.sessionId?`existing_session`:`new_session`,targetSessionId:r.sessionId});return this.deps.recordRunAccepted(),{runId:i.id}}catch(e){return{error:e instanceof Error?e.message:`Could not start this Run.`}}}async disconnectGithubApp(e,t){this.deps.sendGithubDisconnect({appId:e,hookId:t}),await this.deps.api.disconnectGithubApp(this.deps.local,{appId:e,hookId:t})}async removeNode(e){await this.deps.api.removeNode(this.deps.local,e),await this.deps.refreshNodes()}enablePush(){return this.deps.api.enablePush(this.deps.local)}disablePush(){return this.deps.api.disablePush(this.deps.local)}pushStatus(){return this.deps.api.pushStatus()}getNotificationPreferences(){return this.deps.api.getNotificationPreferences(this.deps.local)}setNotificationPreferences(e){return this.deps.api.setNotificationPreferences(this.deps.local,e)}},nl=class{store;ports;constructor(e,t){this.store=e,this.ports=t}mustQueue(e){let t=this.store.getFollowups(e).filter(e=>e.status===`queued`).length;return Ds(t,this.store.getState().activeSession.working)}supportsSteering(){let e=this.store.getState(),t=e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId;return Os(e.catalogs.runtimes.find(e=>e.id===t)?.capabilities)}list(e){return this.store.getFollowups(e)}edit(e,t,n,r){let i=this.store.getFollowups(e).find(e=>e.id===t),a=this.store.editFollowup(e,t,n,r,this.ports.now());return a.ok&&(this.ports.cancelBackstop(i?.scheduledAutomationId),this.ports.persistBackstop(e,t,a.item.text)),a}remove(e,t){let n=this.store.getFollowups(e).find(e=>e.id===t),r=this.store.removeFollowup(e,t);return r&&this.ports.cancelBackstop(n?.scheduledAutomationId),r}reorder(e,t,n){return this.store.reorderFollowup(e,t,n)}sendNow(e,t){let n=this.store.getFollowups(e).find(e=>e.id===t);if(n&&n.status===`queued`){if(this.store.reorderFollowup(e,t,0),!this.store.getState().activeSession.working){this.drain(e);return}this.supportsSteering()&&this.dispatch(e,n,`steer`)}}steer(e,t){let n=e.trim(),r=t?.length?t:void 0;if(!n&&!r)return!1;let i=this.store.getState().activeSession.activeSessionId;if(!i||!this.store.getState().activeSession.working||!this.supportsSteering())return!1;let a=this.ports.createClientMessageId();return this.store.addUserMessage(n,a,r),this.ports.send({kind:`prompt`,sessionId:i,text:n,clientMessageId:a,attachments:r,streamingBehavior:`steer`}),!0}drain(e){if(e!==this.store.getState().activeSession.activeSessionId||this.store.getState().activeSession.working)return;let t=ks(this.store.getFollowups(e));t&&this.dispatch(e,t)}confirm(e){if(e.type!==`session.user_message`)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId,n=typeof e.clientMessageId==`string`?e.clientMessageId:void 0;if(!t||!n)return;let r=this.store.getFollowups(t).find(e=>e.id===n);r&&this.ports.cancelBackstop(r.scheduledAutomationId),this.store.confirmFollowupSent(t,n)}retrySending(e){for(let t of this.store.getFollowups(e))t.status===`sending`&&this.ports.send({kind:`prompt`,sessionId:e,text:t.text,clientMessageId:t.id,attachments:t.attachments})}dispatch(e,t,n){this.store.markFollowupSending(e,t.id,this.ports.now()),this.store.addUserMessage(t.text,t.id,t.attachments),this.ports.send({kind:`prompt`,sessionId:e,text:t.text,clientMessageId:t.id,attachments:t.attachments,...n?{streamingBehavior:n}:{}})}},rl=`bivy.device.id`,il=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android.*Mobile/,`Android phone`],[/Android/,`Android tablet`],[/CrOS/,`Chromebook`],[/Macintosh|Mac OS X/,`Mac`],[/Windows/,`Windows PC`],[/Linux/,`Linux`]];function al(e,t=0){let n=il.find(([t])=>t.test(e))?.[1]??`Browser`;return n===`Mac`&&t>1?`iPad`:n}var ol;function sl(){if(ol)return ol;let e=``;try{e=localStorage.getItem(rl)??``}catch{}if(!e){e=`web:${crypto.randomUUID()}`;try{localStorage.setItem(rl,e)}catch{}}return ol={id:e,label:al(navigator.userAgent,navigator.maxTouchPoints)},ol}var cl=class extends Error{disclosure;constructor(e){super(e),this.disclosure=e,this.name=`NeedsDisclosureError`}};function ll(){return`r-${crypto.randomUUID()}`}function ul(){return crypto.randomUUID()}var dl=/^(localhost|127\.0\.0\.1|\[?::1\]?)$/,fl=`bivy-room-v1`,pl=8e3,ml=24e4;function hl(e=_t(r())){return n?!1:cc(`directNode`,!1)||new URLSearchParams(location.search).has(`local`)?!0:dl.test(location.hostname)&&!e.s&&!location.hash.includes(`payload=`)}var gl=new class e{store=new Es;local=_t(r());direct;solo;directPairCode=``;transport;transportGeneration=0;syncingActivationCredentials=!1;pendingLaunchRestoration=Promise.resolve();pendingPrompt=null;pendingLaunches=new Map;bootProgressTimers=new Map;bootstrapPhaseByNode=new Map;pendingAgentPick=null;pendingFollowups=[];pendingResume=[];resumingNode=new Set;ephemeralCorrelations=[];correlatedSessions=new Set;terminalListeners=new Set;pendingTranscriptions=new Map;pendingSpeech=new Map;pendingAcks=new Map;transcriptCache=js({maxSessions:50});attachmentLoader=new Is;attachmentDiskCache=new Fs;pendingGithubAppCode=null;pendingRoute=null;pendingRouteNode=null;pendingCrossNodeOpen=null;promptTargetSessionId=null;sessionSelectionEpoch=0;runUpdateListeners=new Set;appsChangedListeners=new Set;presenceListeners=new Set;composerFocusListeners=new Set;composerPrefillListeners=new Set;slashOpenListeners=new Set;productMetricsInFlight=new Set;sessionCoordinator;nodeCoordinator;credentialsModelsCoordinator;ephemeralCoordinator;accountCoordinator;followupCoordinator;constructor(){this.followupCoordinator=new nl(this.store,{send:e=>this.send(e),createClientMessageId:ul,now:Date.now,persistBackstop:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},cancelBackstop:e=>this.cancelScheduledFollowup(e)}),this.nodeCoordinator=new Qc({facts:()=>({direct:this.direct,solo:this.solo,signedIn:!!this.local.s,currentNodeId:this.local.cur||null}),status:()=>this.store.getState().connection.status,closeTransport:()=>{try{this.transport.close()}catch{}},setCurrentNode:e=>{this.local.cur=e,this.store.setCurrentNode(e||null)},resetSession:()=>this.store.resetSession(),seedSessions:()=>this.seedSessionsFromCache(),rebuildTransport:()=>{this.transport=this.buildTransport()},setStatus:e=>this.store.setStatus(e),connectTransport:()=>{this.transport.connect()},refreshNodes:()=>{this.refreshNodes()},refreshAccountSessions:()=>{this.refreshAccountSessions()},waitForOnline:e=>this.waitForOnline(e),listProviders:()=>this.listProviders()}),this.sessionCoordinator=new Zc({reportForkProgress:e=>this.store.setForkProgress({status:`working`,message:e}),send:e=>{this.sendToCurrentNode(e)},sendRequest:e=>{this.sendToCurrentNode(e)},createRequestId:ll,createClientMessageId:ul,currentNodeId:()=>this.local.cur,isDirect:()=>this.direct,sessionRuntime:e=>this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.runtimeId,switchNode:e=>this.switchNode(e),waitForOnline:e=>this.waitForOnline(e),openSession:(e,t,n)=>{this.openSession(e,t,{navigate:!n}),n&&this.store.apply({...n,type:`session.history`,sessionId:e})},addUserMessage:(e,t)=>this.store.addUserMessage(e,t),transcriptUrl:e=>`${d()}${oc({kind:`session`,id:e})}`,refreshAccountSessions:()=>{this.refreshAccountSessions()},launchManagedDestination:async(e,t)=>{let n=await Ft(this.local,e,{runtimeId:t});if(!n.nodeId)throw Error(`Managed fork destination launched without a node id`);return n.nodeId},reportCrossNodeFork:(e,t)=>{e===`error`?this.store.setError(t):e===`success`&&this.store.setNotice(t)}},{navigateNew:()=>Z({kind:`new`}),focusComposer:()=>this.focusComposer(),clearPendingPromptAndFollowups:()=>{this.pendingPrompt=null,this.pendingFollowups=[]},resetActiveSession:()=>{this.promptTargetSessionId=null,this.store.resetActiveSession()},seedDraftDefaults:()=>this.seedDraftDefaults(),listRuntimes:()=>this.listRuntimes(),listModels:()=>this.listModels(),hasNodeSettings:()=>!!this.store.getState().settings.nodeSettings,getNodeSettings:()=>this.getNodeSettings(),listRepos:()=>this.listRepos(),draftRepo:()=>this.store.getState().draft.repo,listBranches:e=>this.listBranches(e),activeSessionId:()=>{if(this.promptTargetSessionId)return this.promptTargetSessionId;let e=this.store.getState(),t=ac();return t.kind===`session`?t.id:e.activeSession.activeSessionId},isPendingLaunch:e=>this.isProvisionalSessionId(e),openSession:(e,t)=>{let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e);this.openSession(e,t??n?.path)},sessionIsSaved:e=>this.store.getState().sessionIndex.sessions.some(t=>t.sessionId===e&&t.status===`saved`),appendPendingLaunchFollowup:(e,t)=>{this.appendLaunchFollowup(e,t)},addUserMessage:(e,t,n)=>this.store.addUserMessage(e,t,n),mustQueue:e=>this.followupCoordinator.mustQueue(e),enqueueFollowup:(e,t)=>this.store.enqueueFollowup(e,t,Date.now()),persistFollowup:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},drainFollowups:e=>this.followupCoordinator.drain(e),shouldAutoResume:()=>this.shouldAutoResume(),bufferResume:e=>{this.pendingResume.push(e)},resumeNodeForSession:e=>{this.resumeNodeForSession(e)},hasPendingPrompt:()=>!!this.pendingPrompt,appendPendingFollowup:e=>{this.pendingFollowups.push(e)},draftSessionFields:()=>this.draftSessionFields(),setPendingPrompt:e=>{this.pendingPrompt=e},draftEphemeralRunner:()=>uc&&gc()?this.store.getState().draft.ephemeralConfig:null,startEphemeralLaunch:(e,t,n)=>{let r=new Date().toISOString(),i={id:e,prompt:t,config:n,logs:[],followups:[],phase:`provisioning`,createdAt:r,updatedAt:r};this.pendingLaunches.set(e,i),this.pendingLaunchStore.put(i),this.store.persistPendingSession(e,t.text,!0,n.name),this.launchDraftRunnerAndBind(e)},send:e=>this.send(e),resetDeletedActiveSession:()=>{this.store.resetActiveSession(),Z({kind:`new`})},removeSessionLocal:e=>this.store.removeSessionLocal(e),persistDeletedSessionTombstones:()=>this.persistDeletedSessionTombstones(),deleteTranscriptCache:e=>{this.transcriptCache.delete(e)},refreshSessions:()=>this.refreshSessions(),resolveSessionId:e=>e||this.store.getState().activeSession.activeSessionId}),this.credentialsModelsCoordinator=new $c({send:e=>{this.sendToCurrentNode(e)},awaitAck:(e,t)=>this.awaitAck(e,t),selectModelLocally:e=>{this.store.setCurrentModelLocal(e),this.store.setDraftModel({provider:e.provider,id:e.id})},rememberModel:e=>this.local.setLastChoice({modelProvider:e.provider,modelId:e.id}),isDirect:()=>this.direct,now:()=>Date.now(),isOnline:()=>this.store.getState().connection.status===`online`,importModelKeys:e=>this.ephemeralKeys.importModelKeys(e),removeModelKey:(e,t)=>this.ephemeralKeys.removeModelKey(e,t),accountModelKeys:async()=>(await this.ephemeralKeys.modelKeyEntries()).filter(e=>e.scope===`account`),importOAuthCredentials:e=>this.ephemeralKeys.importOAuthCredentials(e),removeOAuthCredential:(e,t,n)=>this.ephemeralKeys.removeOAuthCredential(e,t,n),accountOAuthCredentials:()=>this.ephemeralKeys.oauthCredentialEntries(),oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled()}),this.ephemeralCoordinator=new el({listConfigs:()=>$t(this.local),createConfig:e=>en(this.local,e),updateConfig:(e,t)=>tn(this.local,e,t),removeConfig:e=>nn(this.local,e),listSizes:(e,t)=>ji(e,{exec:ki(this.local),keys:this.ephemeralKeys},t),signedIn:()=>this.signedIn,direct:()=>this.direct,currentNodeId:()=>this.local.cur,roomKey:e=>this.local.keys()[e],draftRepo:()=>this.store.getState().draft.repo||void 0,githubToken:()=>this.githubTaskToken.get(),machines:()=>this.ephemeralMachines.list(),nodes:()=>this.store.getState().connection.nodes,correlations:()=>this.ephemeralCorrelations,launchMachine:e=>Mi({...e,debugKeepMachine:dc},{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),restoreManagedMachine:e=>It(this.local,e),destroyMachine:e=>Ni(e,{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),machineFromNode:e=>di(e),machineFromCorrelation:ui,connectToNode:(e,t)=>this.connectToNode(e,t),refreshNodes:()=>{this.refreshNodes()},reportError:e=>this.store.setError(e.message),defaultConfig:e=>{let t=ni(e);return{name:G(e)?.name??e,region:t?.defaultRegion??null,size:t?.defaultSize??null}},validateProviderToken:(e,t)=>ri(e,t,ki(this.local)),setProviderToken:(e,t)=>this.ephemeralKeys.setToken(e,t),removeProviderToken:e=>this.ephemeralKeys.remove(e),getProviderToken:e=>this.ephemeralKeys.getToken(e),assignWorkItem:(e,t)=>Pn(this.local,e,t),nodeLabel:e=>ai(e),followupCount:e=>this.store.getFollowups(e).length,recordSessionCorrelation:(e,t)=>{this.recordSessionCorrelation(e,t)},schedule:(e,t)=>{setTimeout(e,t)}}),this.accountCoordinator=new tl({local:this.local,sendGithubDisconnect:({appId:e,hookId:t})=>this.send({kind:`github.app.disconnect`,requestId:ll(),appId:e||void 0,hookId:t||void 0}),refreshNodes:()=>this.refreshNodes(),api:{fetchMe:Vt,fetchGithubApp:Kt,fetchGithubQueue:Nn,fetchAutomationRuns:Dn,cancelAutomationRun:jn,disconnectGithubApp:qt,removeNode:Wt,enablePush:qn,disablePush:Jn,pushStatus:Yn,getNotificationPreferences:Xn,setNotificationPreferences:Zn,createOneOffRun:En,setGithubAppDefaultNode:Jt,setGithubAppTriggerAccess:Yt,assignWorkItem:Pn,deleteWorkItem:Fn,clearWorkQueue:In},runContext:()=>{let e=this.store.getState(),t=e.activeSession.activeSessionId??void 0,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t):void 0,r=t?this.resolveSessionNodeId(t):e.connection.currentNodeId??void 0,i=r?e.connection.nodes.find(e=>e.id===r):void 0;return{accountMode:this.accountMode(),sessionId:t,nodeId:r,roomKey:r?this.local.keys()[r]:void 0,nodeLabel:i?.name?`bivy/${i.name}`:void 0,repo:e.draft.repo??void 0,runtimeId:e.catalogs.selectedAgentId??void 0,model:e.catalogs.currentModel?.id,sandbox:n?.sandbox??(t?void 0:e.draft.sandbox??e.settings.nodeSettings?.defaultSandbox)}},encrypt:async(e,t)=>D(await E(C(e)),t),recordRunAccepted:()=>this.recordProductMilestone(`run_accepted`)}),this.store.onHistoryPersist=(e,t,n,r)=>{let i=this.store.attachmentsForHistory(t);this.transcriptCache.put(e,t,n,r,i)},this.store.requestFreshHistory=()=>{let e=this.store.getState().activeSession.activeSessionId;e&&this.requestHistory(e)},this.store.requestReplay=(e,t)=>{this.send({kind:`session.replay`,sessionId:e,afterSeq:t})},this.store.onSessionSettled=()=>{this.refreshSessions();let e=this.store.getState().activeSession.activeSessionId;e&&(this.store.settleSendingFollowups(e),this.followupCoordinator.drain(e),this.maybeTeardownFinishedEphemeral(e))},this.store.onSessionCreatedElsewhere=()=>this.refreshSessions();let e=/^#pair=([A-Za-z0-9_-]+)$/.exec(location.hash);e&&(this.directPairCode=e[1]??``,history.replaceState(null,``,location.pathname+location.search));try{!n&&xt(this.local,location.hash)&&history.replaceState(null,``,location.pathname+location.search)}catch{}this.seedDraftDefaults(),this.detectGithubAppReturn(),this.direct=hl(this.local),this.solo=!n&&!this.direct&&!this.local.s&&!!this.local.solo()[this.local.cur],!this.direct&&!this.local.cp&&(this.local.cp=d()),this.transport=this.buildTransport(),this.store.setCurrentNode(this.direct?null:this.local.cur||null),this.restoreDeletedSessionTombstones(),this.seedSessionsFromCache(),this.installSessionCachePersist(),this.installFollowupAutoDrain(),this.pendingLaunchRestoration=this.restorePendingLaunches().catch(()=>{this.store.setError(`Couldn't load saved Cloud startups.`)}),!this.direct&&this.local.s&&this.refreshAccountSessions(),this.store.setSignedIn(this.signedIn),this.pendingRoute=ac(),this.pendingRouteNode=this.consumeDeepLinkNode()}consumeDeepLinkNode(){try{let e=new URLSearchParams(location.search),t=(e.get(`node`)||``).trim();if(!t)return null;e.delete(`node`);let n=e.toString();return history.replaceState(null,``,location.pathname+(n?`?${n}`:``)+location.hash),t}catch{return null}}buildTransportHandlers(){let e=++this.transportGeneration;return{onEvent:t=>{if(e!==this.transportGeneration)return;let n=String(t.type||``);if(this.resolveAck(t),(n===`models.list`||n===`model.updated`)&&this.isCloudModelDraft())return;if(n===`node.theme`){p(t.theme);return}if(n===`pong`){let e=String(t.requestId||``);e&&this.pendingLivenessPings.delete(e);return}if(n===`approval.resolved`&&typeof t.remembered==`string`&&t.remembered&&this.store.setNotice(`Allowing “${t.remembered}” without asking for the rest of this session.`),n.startsWith(`terminal.`)||n.startsWith(`multiplexer.`)){if([`terminal.list`,`terminal.created`,`terminal.activity`,`terminal.closed`,`terminal.exit`].includes(n))this.store.apply(this.eventWithNodeScope(t));else if(n===`terminal.tui`)this.store.apply(t);else if(n===`terminal.takeover.result`){let e=t;e.ok&&e.sessionId?this.openSession(String(e.sessionId)):e.error&&this.store.setError(String(e.error))}for(let e of this.terminalListeners)e(t);return}if(n===`run.updated`){let e=typeof t.runId==`string`?t.runId:``,n=typeof t.revision==`string`?t.revision:void 0;if(e)for(let t of this.runUpdateListeners)t(e,n);return}if(n===`session.presence`){let e=t.presence;if(e?.sessionId)for(let t of this.presenceListeners)t(e);return}if(n===`apps.changed`){let e=typeof t.sessionId==`string`?t.sessionId:``;if(e)for(let t of this.appsChangedListeners)t(e);return}if(n===`transcription`){this.resolveTranscription(t);return}if(n===`speech.audio`){this.resolveSpeech(t);return}if(this.sessionCoordinator.handleEvent(t)||typeof t.sessionId==`string`&&this.isProvisionalSessionId(t.sessionId)||[...this.pendingLaunches.values()].some(e=>t.requestId&&t.requestId===e.prompt.requestId||e.sessionId&&t.sessionId===e.sessionId))return;let r=this.store.getState().activeSession.activeSessionId;if(t.type===`session.created`&&r&&this.pendingLaunches.get(r)?.machine?.nodeId===this.local.cur)return;let i=this.store.getState(),a=this.eventWithNodeScope(t);if(this.store.apply(a),a.type===`models.list`&&typeof a.runtimeId==`string`&&this.settleRuntimeModels(a.runtimeId),a.type===`session.error`&&a.sessionId){let e=this.store.getState().sessionIndex.sessions.find(e=>e.sessionId===a.sessionId);if(e?.launchProgress&&!e.launchProgress.firstResponseAt){let t=typeof a.error==`string`?a.error:`The agent could not respond. Check its model and credentials.`;this.store.updateLaunchCheckpoint(e.sessionId,`agent`,`failed`,t),this.store.failPendingSession(e.sessionId)}}let o=this.store.getState().activeSession;o.activeSessionId&&!i.activeSession.transcript.some(e=>e.role===`assistant`&&!!e.text&&!e.tool)&&o.transcript.some(e=>e.role===`assistant`&&!!e.text&&!e.tool)&&this.store.markLaunchFirstResponse(o.activeSessionId),this.observeActivationMilestones(i,a),a.type===`providers.list`&&!this.syncingActivationCredentials&&this.send({kind:`activation.readiness`}),a.type===`credentials.records`&&(this.maybeGrantManagedCredential(),this.isCloudModelDraft()&&this.listModels()),a.type===`session.deleted`&&this.persistDeletedSessionTombstones(),this.maybeFlushPendingPrompt(a),this.followupCoordinator.confirm(a),this.maybeRestoreDraftAgent(a),this.maybeSelectInstalledAgent(a),this.maybeRefreshModelsForRuntime(a),this.reconcileSessionList(a)},onStatus:t=>{if(e!==this.transportGeneration)return;let n=this.store.getState(),r=n.connection.status;this.store.setStatus(t),this.observeActivationMilestones(n,{type:`connection.status`}),t===`online`&&r!==`online`?this.onReconnected():(t===`reconnecting`||t===`offline`)&&(this.store.markStreamInterrupted(),r!==`reconnecting`&&r!==`offline`&&this.refreshNodesThrottled())},onError:t=>{e===this.transportGeneration&&this.store.setError(a(t))}}}buildTransport(){let e=this.buildTransportHandlers(),t=cc(`directNode`,!1);return this.direct?new sa({bootstrap:new URLSearchParams(location.search).get(`bootstrap`)||``,...t?{tokenStore:r(),pairCode:this.directPairCode,deviceName:sl().label,requireToken:!0}:{},handlers:e}):new ga({store:this.local,handlers:e})}productMetricClient(){return matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`}recordProductMilestone(e,t=!1){if(this.direct||this.solo||!this.local.s)return;let n=`bivy.product-metric.${e}`;if(t){try{if(localStorage.getItem(n)===`1`)return}catch{}if(this.productMetricsInFlight.has(e))return;this.productMetricsInFlight.add(e)}An(this.local,e,this.productMetricClient()).then(()=>{if(t)try{localStorage.setItem(n,`1`)}catch{}}).catch(()=>{}).finally(()=>this.productMetricsInFlight.delete(e))}static FIRST_RUN_STEP_EVENTS={machine_online:{ok:`first_run_machine_ready`,failed:`first_run_machine_failed`},agent_installed:{ok:`first_run_agent_verified`,failed:`first_run_agent_failed`},credential_valid:{ok:`first_run_provider_connected`,failed:`first_run_provider_failed`}};observeActivationMilestones(t,n){let r=this.store.getState(),i=e=>({direct:this.direct,signedIn:e.connection.signedIn,status:e.connection.status,runtimes:e.catalogs.runtimes,readiness:e.catalogs.activationReadiness}),a=rt(i(t)),o=rt(i(r));!a.activated&&o.activated&&this.recordProductMilestone(`activation_ready`,!0);for(let[t,n]of Object.entries(e.FIRST_RUN_STEP_EVENTS)){let e=a.checks.find(e=>e.id===t)?.state,r=o.checks.find(e=>e.id===t)?.state;e!==`passed`&&r===`passed`&&this.recordProductMilestone(n.ok,!0),e!==`failed`&&r===`failed`&&this.recordProductMilestone(n.failed,!0)}if(n.type===`session.history`)return;let s=e=>e.activeSession.transcript.filter(e=>e.role===`assistant`&&!!e.text&&!e.tool).length;s(t)===0&&s(r)>0&&(Uc(),this.recordProductMilestone(`first_useful_response`,!0))}needsAuth(){return this.connectionRequirement().type===`authentication-required`}needsNode(){return this.connectionRequirement().type===`node-required`}needsSetup(){return this.connectionRequirement().type!==`ready`}connectionRequirement(){return this.nodeCoordinator.requirement({direct:this.direct,solo:this.solo,signedIn:!!this.local.s,currentNodeId:this.local.cur||null})}listNodes(){return Et(this.local)}centralGithubApp(){return Dt(this.local)}createCentralGithubInstall(e=`/`){return Ot(this.local,e)}managedAutomationTarget(){return kt(this.local)}async managedCredentialReady(){return(await At(this.local)).ready}async waitForManagedCredential(e=2e4,t=-1){let n=Date.now()+e;for(;Date.now()<n;){let e=await At(this.local);if(e.ready&&e.generation>t)return;await new Promise(e=>setTimeout(e,750))}throw Error(`The encrypted Bivy Cloud credential was not published. Try provider setup again.`)}async setupManagedCredentials(){let e=this.store.getState().activeSession.activeSessionId;if(!e||!this.pendingLaunches.has(e))throw Error(`The original Cloud session is no longer available.`);await this.retryPendingLaunch(e)}ensureManagedSessionDefaults(){return Pt(this.local)}createNodeClaim(){return Lt(this.local)}listNodeClaims(){return Rt(this.local)}revokeNodeClaim(e){return zt(this.local,e)}selectNode(e){this.switchNode(e)}get signedIn(){return!!this.local.s}async completeSignIn(e,t=()=>!0){if(e&&t()){this.local.s=e,this.local.cp||(this.local.cp=d());try{await m()}catch(t){throw this.local.s===e&&(this.local.s=``,await m().catch(()=>{})),t}if(!t()){this.local.s===e&&(this.local.s=``,await m());return}if(this.solo){location.reload();return}this.nativeSubscriptionsStopped=!1,this.store.setSignedIn(!0),this.syncDeviceVault().catch(()=>{}),this.connect()}}nativeSubscriptionSyncAt=0;nativeSubscriptionSyncToken=``;nativeSubscriptionSyncing=!1;nativeSubscriptionsStopped=!1;syncNativeSubscriptions(){let e=this.local.s;!this.nativeSubscriptionsStopped&&e&&o()?.synchronize({token:e,controlPlane:d()}).catch(()=>{this.store.setError(`Notification registration could not be refreshed. Open Notifications to retry.`)}),!this.nativeSubscriptionsStopped&&e&&l()&&!this.nativeSubscriptionSyncing&&(e===this.nativeSubscriptionSyncToken&&Date.now()-this.nativeSubscriptionSyncAt<3e5||(this.nativeSubscriptionSyncing=!0,this.nativeSubscriptionSyncToken=e,this.nativeSubscriptionSyncAt=Date.now(),s(e).catch(()=>{!this.nativeSubscriptionsStopped&&this.local.s===e&&this.store.setError(`Subscription status could not be refreshed. Open Subscriptions to retry.`)}).finally(()=>{this.nativeSubscriptionSyncing=!1})))}connect(){this.nodeCoordinator.connect(),this.syncNativeSubscriptions()}foregroundTimer=null;backgroundDisconnectTimer=null;livenessTimer=null;pendingLivenessPings=new Set;installLifecycleHandlers(){if(typeof document>`u`)return;let n=()=>{this.backgroundDisconnectTimer&&=(clearTimeout(this.backgroundDisconnectTimer),null),this.refreshAfterForeground(),this.syncNativeSubscriptions()};document.addEventListener(`visibilitychange`,()=>{if(document.visibilityState===`visible`){n();return}this.direct||this.backgroundDisconnectTimer||(this.backgroundDisconnectTimer=setTimeout(()=>{this.backgroundDisconnectTimer=null,document.visibilityState===`hidden`&&this.transport.close()},e.BACKGROUND_DISCONNECT_DELAY_MS))}),f(n),window.addEventListener(`pageshow`,n),window.addEventListener(`focus`,n),window.addEventListener(`popstate`,e=>{e.state?.bivyNativeLink||this.applyRoute(ac(),{navigate:!1})}),t(e=>{let t=sc(e,d());t&&(history.replaceState(null,``,t.path),this.pendingRoute=ac(),this.pendingRouteNode=t.node,window.dispatchEvent(new PopStateEvent(`popstate`,{state:{bivyNativeLink:!0}})),this.signedIn&&this.store.getState().connection.status===`online`&&this.applyInitialRoute())})}onRunUpdated(e){return this.runUpdateListeners.add(e),()=>this.runUpdateListeners.delete(e)}onPresence(e){return this.presenceListeners.add(e),()=>this.presenceListeners.delete(e)}async getPresence(e){return(await this.awaitAck({kind:`session.presence.get`,sessionId:e})).presence??{sessionId:e}}publishDraft(e,t){this.store.getState().connection.status===`online`&&this.awaitAck({kind:`session.presence.draft`,sessionId:e,device:sl(),text:t}).catch(()=>{})}onAppsChanged(e){return this.appsChangedListeners.add(e),()=>this.appsChangedListeners.delete(e)}onComposerFocus(e){return this.composerFocusListeners.add(e),()=>this.composerFocusListeners.delete(e)}focusComposer(){for(let e of this.composerFocusListeners)e()}onComposerPrefill(e){return this.composerPrefillListeners.add(e),()=>this.composerPrefillListeners.delete(e)}prefillComposer(e,t=[]){for(let n of this.composerPrefillListeners)n(e,t);return this.focusComposer(),this.composerPrefillListeners.size>0}onOpenSlash(e){return this.slashOpenListeners.add(e),()=>this.slashOpenListeners.delete(e)}openSlashCommands(){let e=this.store.getState(),t=e.activeSession.activeSessionId;t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.status===`saved`&&this.openSession(t):this.listModels();for(let e of this.slashOpenListeners)e()}applyRoute(e,t={}){e.kind===`session`?this.openSession(e.id,void 0,t):e.kind!==`settings`&&e.kind!==`automations`&&e.kind!==`library`&&e.kind!==`run`&&this.newSession(t)}applyInitialRoute(){let e=this.pendingRoute;if(!e)return;this.pendingRoute=null;let t=this.pendingRouteNode;this.pendingRouteNode=null,e.kind===`session`&&(t?this.openSessionOnNode(e.id,void 0,t):this.applyRoute(e,{navigate:!1}))}refreshAfterForeground(){this.foregroundTimer&&clearTimeout(this.foregroundTimer),this.foregroundTimer=setTimeout(()=>{if(this.foregroundTimer=null,this.needsSetup())return;let e=this.store.getState().connection.status;if(e===`offline`){this.connect();return}if(e!==`online`)return;this.refreshSessions();let t=this.store.getState().activeSession.activeSessionId;t?this.requestHistory(t):this.retryPendingSessionNew(),this.listModels(),this.verifyLiveness()},150)}static BACKGROUND_DISCONNECT_DELAY_MS=15e3;static LIVENESS_TIMEOUT_MS=2e3;verifyLiveness(){this.livenessTimer&&clearTimeout(this.livenessTimer),this.pendingLivenessPings.clear();let t=ll();this.pendingLivenessPings.add(t),this.send({kind:`ping`,requestId:t}),this.livenessTimer=setTimeout(()=>{this.livenessTimer=null,this.store.getState().connection.status===`online`&&this.pendingLivenessPings.delete(t)&&this.transport.reconnect()},e.LIVENESS_TIMEOUT_MS)}async refreshNodes(){if(!this.direct&&this.signedIn){this.lastNodeRefreshAt=Date.now();try{let e=await this.listNodes();this.store.setNodes(e),this.local.cur&&!e.some(e=>e.id===this.local.cur)&&(this.currentNodeIsRebuildable()?this.markCurrentNodeAwaitingRebuild():this.clearCurrentNode()),this.refreshAccountSessions()}catch{}}}clearCurrentNode(){try{this.transport.close()}catch{}this.local.cur=``,this.store.setCurrentNode(null),this.store.resetSession(),this.store.setStatus(`offline`)}currentNodeIsRebuildable(){let e=this.local.cur;if(!e)return!1;try{if(!this.local.keys()[e])return!1}catch{return!1}return this.ephemeralCorrelations.some(t=>t.nodeId===e)}markCurrentNodeAwaitingRebuild(){if(this.store.getState().connection.status!==`offline`){try{this.transport.close()}catch{}this.store.setStatus(`offline`)}}lastNodeRefreshAt=0;refreshNodesThrottled(){!this.direct&&this.signedIn&&(Date.now()-this.lastNodeRefreshAt<1e4||this.refreshNodes())}pickDraftEphemeralRunner(e){this.store.setDraftEphemeralConfig(e),this.listModels()}switchNode(e){this.store.setDraftEphemeralConfig(null),this.nodeCoordinator.switchNode(e)}connectToNode(e,t){return this.nodeCoordinator.connectToNode(e,t)}async signOut(){this.nativeSubscriptionsStopped=!0,await Promise.allSettled([h(),c()]),this.nativeSubscriptionSyncToken=``,this.nativeSubscriptionSyncAt=0,this.sessionTitleKeys?.close(),this.machineRequests?.close();try{this.transport.close()}catch{}let e=this.local.device()?.pub;try{e=(await Ui(this.local)).pub}catch{}try{await Gn(this.local,e)}catch{}try{await Bi()}catch{}await this.attachmentDiskCache.clear(),this.local.clear(),await m(),this.store.setSignedIn(!1),location.assign(`/`)}listDevices(){return Un(this.local)}isCurrentDevice(e){return!!e&&this.local.device()?.pub===e}removeDevice(e){return Wn(this.local,e)}isProvisionalSessionId(e){return e.startsWith(`starting-`)||this.pendingLaunches.has(e)||this.store.getState().sessionIndex.sessions.some(t=>t.sessionId===e&&t.pendingLaunch)}sendToCurrentNode(e){typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId)||this.transport.send(e)}async appendLaunchFollowup(e,t){this.pendingLaunches.has(e)||await this.pendingLaunchRestoration;let n=this.pendingLaunches.get(e);if(!n){this.store.setError(`Couldn't find the saved Cloud startup. Your message has not been sent.`);return}n.followups.push(t);try{await this.pendingLaunchStore.put(n)}catch{this.store.setError(`Couldn't save the queued message. Keep this page open until startup finishes.`)}}send(e){this.sessionCoordinator.send(e.kind===`prompt`?{...e,device:sl()}:e)}updateNode(){Ms(this.store,()=>this.transport.send({kind:`node.update`}))}awaitAck(e,t=1e4){if(typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId))return Promise.reject(Error(`Cloud startup hasn't created a conversation yet.`));let n=ll();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingAcks.delete(n),i(Error(`Timed out waiting for the machine to respond.`))},t);this.pendingAcks.set(n,{resolve:r,reject:i,timer:a}),this.sendToCurrentNode({...e,requestId:n})})}fetchAttachment(e,t=0){if(!e)return Promise.resolve(null);let n=this.attachmentHomes.get(e),r=n&&n!==this.local.cur?n:null,i=r?`bivy.sessions.${r}`:this.sessionCacheKey();return this.attachmentLoader.fetch(JSON.stringify([i,e]),t,async()=>{let t=await this.attachmentDiskCache.get(i,e);if(t)return t;if(!r&&i!==this.sessionCacheKey())return null;let n={kind:`attachment.fetch`,hash:e},a=await(r?this.machineRequest(r,n,6e5):this.awaitAck(n,6e5));if(!a||typeof a.data!=`string`)return null;let o={mimeType:String(a.mimeType||`application/octet-stream`),data:a.data};return this.attachmentDiskCache.put(i,e,o),o})}async appCommand(e,t,n={},r){let{connection:i}=this.store.getState();e===`apps.open`&&Object.assign(n,{scale:typeof devicePixelRatio==`number`&&devicePixelRatio>=1.5?2:1});let a=this.isOtherMachine(r);if(!a&&i.status!==`online`)throw Error(`Connect to the machine to open its apps.`);let o=a?await this.machineRequest(r,{kind:e,sessionId:t,...n}):await this.awaitAck({kind:e,sessionId:t,...n},3e4);if(!a&&this.store.getState().connection.currentNodeId!==i.currentNodeId)throw Error(`Machine changed. Reopen Apps on the selected machine.`);let s=a?r:i.currentNodeId;if(e===`apps.list`&&s){for(let e of o.apps??[])for(let t of e.views)if(t.kind===`web`)for(let e of t.notes??[])e.shot&&this.attachmentHomes.set(e.shot.hash,s)}return o}async listMachineArtifacts(){let e=await this.acrossMachines(`artifacts.list`,e=>e.artifacts??[]);for(let t of e.items)t.nodeId&&this.attachmentHomes.set(t.hash,t.nodeId);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}async listMachineApps(){let e=await this.acrossMachines(`apps.list`,e=>e.apps??[]);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}attachmentHomes=new Map;machineRequests;isOtherMachine(e){return!this.direct&&!!e&&e!==this.local.cur}machineRequest(e,t,n=3e4){return this.isOtherMachine(e)?(this.machineRequests??=new Bs(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:t})),this.machineRequests.request(e,t,n)):this.store.getState().connection.status===`online`?this.awaitAck(t,n):Promise.reject(Error(`Connect to the machine first.`))}async acrossMachines(e,t){let{nodes:n,status:r}=this.store.getState().connection,i=r===`online`?[this.direct?null:this.local.cur||null]:[],a=this.direct?i:[...i,...n.filter(e=>e.online&&e.id!==this.local.cur).map(e=>e.id)],o=await Promise.allSettled(a.map(async n=>t(await this.machineRequest(n,{kind:e})).map(e=>({...e,nodeId:n}))));return{items:o.flatMap(e=>e.status===`fulfilled`?e.value:[]),unreachable:a.filter((e,t)=>o[t].status===`rejected`).map(e=>n.find(t=>t.id===e)?.name||`A machine`)}}resolveAck(e){let t=String(e.requestId||``),n=t?this.pendingAcks.get(t):void 0;if(n){if(clearTimeout(n.timer),this.pendingAcks.delete(t),String(e.type||``).endsWith(`.error`)){let t=Error(String(e.error||`Save failed`));Object.assign(t,e),n.reject(t)}else n.resolve(e)}}async discoverNativeSessions(){let e=(await this.awaitAck({kind:`session.discover`},2e4)).sessions;return Array.isArray(e)?e:[]}async importNativeSession(e,t,n={}){let r;try{r=await this.awaitAck({kind:`session.import`,runtimeId:e,ref:t,acceptDisclosure:n.acceptDisclosure??!1},6e4)}catch(e){let t=e;throw t?.needsDisclosure?new cl(String(t.disclosure??t.message??`This import needs your confirmation.`)):e}let i=String(r.sessionId||``);if(!i)throw Error(`Import did not return a session id`);let a=r.seedPrompt;if(typeof a==`string`&&a.trim()){this.openSession(i);let e=ul();this.store.addUserMessage(a,e),this.send({kind:`prompt`,sessionId:i,text:a,clientMessageId:e})}else this.openSession(i,t);return i}waitForOnline(e=2e4){return this.store.getState().connection.status===`online`?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{i(),n(Error(`Destination machine did not come online`))},e),i=this.store.subscribe(()=>{this.store.getState().connection.status===`online`&&(clearTimeout(r),i(),t())})})}promoteSession(e,t){return this.sessionCoordinator.promote(e,t)}forkInFlight=!1;startSessionLike(e,t,n){return this.sessionCoordinator.startLike(e,t,n)}async forkSession(e,t={},n){if(this.forkInFlight)throw Error(`A session fork is already in progress`);this.forkInFlight=!0,this.store.setForkProgress({status:`working`,message:`Preparing to fork the session…`});let r=this.store.getState(),i=r.sessionIndex.sessions.find(t=>t.sessionId===e),a=t.sourceAgentId||i?.runtimeId,o=t.agentId||a,s=(e,t)=>{let n=r.catalogs.runtimes.find(t=>t.id===e);return String(n?.displayName||n?.name||t||e||`agent`)},c=i?.name||`session ${e.slice(0,8)}`,l=s(a,i?.agentName),u=s(o,o===a?i?.agentName:void 0);try{await n?.();let r=await this.sessionCoordinator.fork(e,t);return this.store.getState().activeSession.activeSessionId!==r.sessionId&&this.openSession(r.sessionId,void 0,{navigate:!1}),await this.waitForForkReady(r.sessionId),Z({kind:`session`,id:r.sessionId}),this.store.setNotice(`This session was forked from “${c}” with ${l} to ${u}.`),this.store.setForkProgress(null),r}catch(e){throw this.store.setForkProgress({status:`error`,message:e instanceof Error?e.message:String(e)}),e}finally{this.forkInFlight=!1}}waitForForkReady(e){let t=()=>{let t=this.store.getState().activeSession;return t.activeSessionId===e&&!t.opening};return t()?Promise.resolve():(this.store.setForkProgress({status:`working`,message:`Loading the forked session…`}),new Promise((e,n)=>{let r=setTimeout(()=>{i(),n(Error(`The fork was created, but its conversation could not be loaded. Reopen it from the session list.`))},3e4),i=this.store.subscribe(()=>{t()&&(clearTimeout(r),i(),e())})}))}refreshSessions(){if(this.send({kind:`terminal.list`}),!this.direct&&this.signedIn){this.refreshAccountSessions(),this.local.cur&&this.send({kind:`sessions.list`});return}this.send({kind:`sessions.list`})}async decryptSessionTitle(e){if(!e.titleEnc)return`Untitled session`;let t=this.local.keys()[e.nodeId];if(!t)return`Untitled session`;try{return(await O(await E(C(t)),e.titleEnc)).trim()||`Untitled session`}catch{return`Untitled session`}}sessionTitleKeys;async refreshAccountSessions(){if(!this.direct&&this.signedIn)try{let e=await Bt(this.local);this.sessionTitleKeys??=new Ls(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:{onStatus:e=>{e===`online`&&t()},onEvent:()=>{}}}),()=>{this.refreshAccountSessions()}),this.sessionTitleKeys.ensure(e.filter(e=>e.titleEnc).map(e=>e.nodeId));let t=this.store.getState().sessionIndex.sessions,n=(await Promise.all(e.map(async e=>{let n=String(e.sessionId||e.id||``),r=String(e.nodeId||``),i=t.find(e=>e.sessionId===n&&(!e.nodeId||e.nodeId===r)),a=await this.decryptSessionTitle(e);return{...i,sessionId:n,nodeId:r,name:a===`Untitled session`&&i?.name||a,source:e.source||i?.source,branch:e.branch||i?.branch,status:e.status,attention:Array.isArray(e.attention)?e.attention:i?.attention,updatedAt:e.updatedAt||i?.updatedAt}}))).filter(e=>e.sessionId&&e.nodeId),r=new Set(n.map(e=>e.sessionId)),i=this.store.getState().sessionIndex.sessions,a=this.ephemeralCorrelations.filter(e=>!r.has(e.sessionId)&&!!this.local.keys()[e.nodeId]).map(e=>{let t=i.find(t=>t.sessionId===e.sessionId);return{...t,sessionId:e.sessionId,nodeId:e.nodeId,name:t?.name||(e.repo?`${e.repo}`:`Rebuildable session`),source:t?.source,status:`saved`,rebuildable:!0,updatedAt:t?.updatedAt}}),o=new Set([...this.pendingLaunches.values()].map(e=>e.sessionId));this.store.setSessions([...n,...a].filter(e=>!o.has(e.sessionId)))}catch{}}eventWithNodeScope(e){if(this.direct||!this.local.cur)return e;let t=this.local.cur;if(e.type===`sessions.list`){let n=e,r=Array.isArray(n.sessions)?n.sessions:[],i=new Set(r.map(e=>String(e?.sessionId||e?.id||``)).filter(Boolean)),a=this.store.getState().sessionIndex.sessions.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.sessionId));return{...e,sessions:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`session.created`)return{...e,nodeId:t};if(e.type===`terminal.list`){let n=e,r=Array.isArray(n.terminals)?n.terminals:[],i=new Set(r.map(e=>String(e?.termId||``)).filter(Boolean)),a=this.store.getState().sessionIndex.runTerminals.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.termId));return{...e,terminals:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`terminal.created`){let n=e;return n.terminal?{...e,terminal:{...n.terminal,nodeId:n.terminal.nodeId||t}}:e}return e}static DELETED_SESSIONS_KEY=`bivy.deleted-sessions`;restoreDeletedSessionTombstones(){try{let t=localStorage.getItem(e.DELETED_SESSIONS_KEY);t&&this.store.seedDeletedSessionTombstones(JSON.parse(t)),this.persistDeletedSessionTombstones()}catch{}}persistDeletedSessionTombstones(){try{let t=this.store.deletedSessionTombstones();Object.keys(t).length?localStorage.setItem(e.DELETED_SESSIONS_KEY,JSON.stringify(t)):localStorage.removeItem(e.DELETED_SESSIONS_KEY)}catch{}}sessionCacheKey(){return`bivy.sessions.${this.direct?`direct`:this.local.cur||``}`}seedSessionsFromCache(){if(this.direct||this.local.cur)try{let e=localStorage.getItem(this.sessionCacheKey());e&&this.store.seedSessions(JSON.parse(e))}catch{}}installSessionCachePersist(){if(typeof localStorage>`u`)return;let e=this.store.getState().sessionIndex.sessions;this.store.subscribe(()=>{let t=this.store.getState().sessionIndex.sessions;if(t!==e){e=t;try{localStorage.setItem(this.sessionCacheKey(),JSON.stringify(t.slice(0,100)))}catch{}}})}installFollowupAutoDrain(){let e=this.store.getState().activeSession.working,t=this.store.getState().activeSession.activeSessionId;this.store.subscribe(()=>{let n=this.store.getState().activeSession.activeSessionId,r=this.store.getState().activeSession.working,i=n!=null&&n===t&&e&&!r;e=r,t=n,i&&this.followupCoordinator.drain(n)})}async findLiveRunTerminal(e,t,n=4e3){let r=()=>this.store.getState().sessionIndex.runTerminals.find(n=>n.sessionId===e&&(!t||!n.nodeId||n.nodeId===t))??null;return r()||(this.direct||!t||t===this.local.cur&&this.store.getState().connection.status===`online`?null:(await this.connectToNode(t),this.send({kind:`terminal.list`}),new Promise(e=>{let t=setTimeout(()=>{i(),e(r())},n),i=this.store.subscribe(()=>{let n=r();n&&(clearTimeout(t),i(),e(n))})})))}selectSessionTarget(e){return this.promptTargetSessionId=e,this.sessionSelectionEpoch+=1,Z({kind:`session`,id:e}),this.sessionSelectionEpoch}isCurrentSessionTarget(e,t){return this.promptTargetSessionId===e&&(t===void 0||t===this.sessionSelectionEpoch)}openSessionOnNode(e,t,n){if(this.selectSessionTarget(e),this.pendingLaunches.has(e)){this.openPendingLaunch(e);return}if(!this.direct&&n&&n!==this.local.cur){this.pendingCrossNodeOpen={sessionId:e,path:t},Z({kind:`session`,id:e}),this.switchNode(n),this.store.beginOpen(e);return}this.openSession(e,t)}openSession(e,t,n={}){if(this.promptTargetSessionId=e,this.pendingLaunches.has(e)){this.openPendingLaunch(e,n);return}n.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.send({kind:`session.open`,sessionId:e,path:t}),this.listModels(),this.seedAndRequestHistory(e)}async seedAndRequestHistory(e){try{let t=await this.transcriptCache.get(e);t&&this.store.getState().activeSession.activeSessionId===e&&(this.store.restoreAttachments(t.attachments),this.store.seedHistory(e,t.messages,t.count,t.historyHash))}catch{}this.requestHistory(e)}onReconnected(){let e=!1;if(this.pendingCrossNodeOpen){let t=this.pendingCrossNodeOpen;this.pendingCrossNodeOpen=null,this.openSession(t.sessionId,t.path),e=!0}this.refreshAccountSessions(),this.store.clearActivationReadiness(),this.syncingActivationCredentials=!0;let t=this.transportGeneration;this.syncAccountCredentialsWithNode().finally(()=>{t===this.transportGeneration&&(this.syncingActivationCredentials=!1,this.send({kind:`activation.readiness`}))}),this.resyncScheduledFollowups(),this.seedEphemeralNodeIfNeeded(),this.maybePromptFirstRunModelAuth(),this.refreshEphemeralCorrelations(),e||this.applyInitialRoute();let n=this.store.getState().activeSession.activeSessionId;if(n&&!e?(this.requestHistory(n),this.listModels(),this.followupCoordinator.retrySending(n),this.drainPendingResume(n)):n||this.retryPendingSessionNew(),this.pendingGithubAppCode){let{code:e,state:t}=this.pendingGithubAppCode;this.pendingGithubAppCode=null,this.githubAppManifestCode(e,t)}}detectGithubAppReturn(){try{let e=new URLSearchParams(location.search),t=!1;try{t=sessionStorage.getItem(`bivy.githubAppPending`)===`1`,t&&sessionStorage.removeItem(`bivy.githubAppPending`)}catch{}if(!e.has(`bivy_github_app`)&&!t)return;let n=(e.get(`code`)||``).trim(),r=(e.get(`state`)||``).trim();e.delete(`bivy_github_app`),e.delete(`code`),e.delete(`state`);let i=e.toString();history.replaceState(null,``,location.pathname+(i?`?${i}`:``)+location.hash),n&&r?(this.pendingGithubAppCode={code:n,state:r},this.store.setGithubAppPhase(`completing`,{returning:!0,state:r})):this.store.setGithubAppPhase(`error`,{returning:!0,error:`GitHub did not return a code.`})}catch{}}requestHistory(e){let t=this.store.getHistoryCursor(e);this.send({kind:`history`,sessionId:e,...t})}draftSessionFields(){let e=this.store.getState(),t=e.catalogs.currentModel?{provider:e.catalogs.currentModel.provider,id:e.catalogs.currentModel.id}:void 0;return{repo:e.draft.repo||void 0,branch:e.draft.repo&&e.draft.branch||void 0,agent:e.catalogs.selectedAgentId||void 0,sandbox:e.draft.sandbox||void 0,acknowledgeReducedProtections:e.draft.acknowledgeReducedProtections||void 0,model:t}}getNodeSettings(){this.send({kind:`node.settings.get`})}setNodeSettings(e){return this.awaitAck({kind:`node.settings.set`,settings:e}).then(()=>void 0)}setSessionSandbox(e){this.store.setDraftSandbox(e)}acknowledgeSessionAgentReducedProtections(e){this.store.setDraftAcknowledgeReducedProtections(e)}newSession(e={}){let t=this.store.getState(),n=t.activeSession.activeSessionId?t.sessionIndex.sessions.find(e=>e.sessionId===t.activeSession.activeSessionId)?.nodeId??this.local.cur:this.local.cur,r=t.connection.nodes.find(e=>e.id===n)?.name??``,i=this.ephemeralCorrelations.find(e=>e.nodeId===n)?.setupId;this.sessionCoordinator.newSession(e),n?.startsWith(`eph-`)&&this.listEphemeralConfigs().then(e=>{let t=this.store.getState();if(t.activeSession.activeSessionId||t.draft.ephemeralConfig||this.local.cur!==n)return;let a=(i?e.find(e=>e.id===i):void 0)??(/^Hosted\s+/i.test(r)?e.find(e=>e.computeSource===`managed`):void 0);a&&this.pickDraftEphemeralRunner(a)}).catch(()=>{})}seedDraftDefaults(){let e=this.local.lastChoice();e.repo&&this.store.setDraftRepo(e.repo);let t=e.modelId?{provider:e.modelProvider,id:e.modelId}:null;this.store.setDraftModel(t),this.store.seedDraftAgentModel(e.agentId,t)}maybeRestoreDraftAgent(e){if(e.type!==`runtimes.list`)return;let t=this.store.getState();if(t.activeSession.activeSessionId)return;let n=this.local.lastChoice().agentId,r=n?t.catalogs.runtimes.find(e=>e.id===n):void 0;if(r&&n!==t.catalogs.selectedAgentId&&String(r.status||`available`)===`available`){this.chooseAgent(r);return}t.catalogs.selectedAgentId&&t.catalogs.modelsRuntimeId!==t.catalogs.selectedAgentId&&this.listModels()}sendPrompt(e,t,n){this.sessionCoordinator.sendPrompt(e,t,n),this.commitStagedPin(e)}stagedPin=null;stagePin(e){this.stagedPin={...e,at:Date.now()}}async commitStagedPin(e){let t=this.stagedPin;if(this.stagedPin=null,!(!t||Date.now()-t.at>6e5||!t.context||!e.includes(t.context)))try{await this.appCommand(`apps.pin`,t.sessionId,{appId:t.appId,viewId:t.viewId,words:e})}catch{}}async launchDraftRunnerAndBind(e){let t=this.pendingLaunches.get(e);if(!t)return;let{config:n}=t,r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};try{let i=t.prompt.frame&&`agent`in t.prompt.frame?String(t.prompt.frame.agent||``):``,a=n.computeSource===`managed`?this.prepareManagedCredential(i,t.prompt.frame.model?.provider):Promise.resolve(!0);this.store.updateLaunchCheckpoint(e,`capacity`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(e,`repository`,`skipped`),n.computeSource===`managed`&&r(`Reserving secure managed compute…`);let o=n.computeSource===`managed`?Ft(this.local,n.id,{runtimeId:i,requestId:e}):this.launchEphemeral({provider:n.provider,region:n.region??void 0,size:n.size??void 0,image:n.image??void 0,ttlMinutes:n.ttlMinutes??void 0,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,name:n.name,setupId:n.id,onProgress:r}),[s,c]=await Promise.all([o,a]);if(this.store.updateLaunchCheckpoint(e,`account`,`done`),!s.nodeId)throw Error(`machine launched without a node id`);this.store.updateLaunchCheckpoint(e,`capacity`,`done`),this.store.updateLaunchCheckpoint(e,`machine`,`done`),this.store.updateLaunchCheckpoint(e,`service`,`active`),t.machine=s,t.phase=`booting`,t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.bindPendingSessionNode(e,s.nodeId),n.computeSource===`managed`&&!c?await this.beginManagedCredentialSetup(e,s.nodeId):this.startPendingRunner(e)}catch(r){let i=`Launch failed: ${r?.message||r}`;t.logs.push(i),t.phase=`failed`,t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),r instanceof jt&&r.code===`managed_credentials_required`?(this.store.updateLaunchCheckpoint(e,`capacity`,`waiting`),this.store.updateLaunchCheckpoint(e,`account`,`failed`,r.message,r.code)):r instanceof jt&&r.code===`managed_image_unavailable`?this.store.updateLaunchCheckpoint(e,`machine`,`failed`,i,r.code):this.failLaunchCheckpoint(e,i),this.store.failPendingSession(e);let a=r instanceof jt?r.actions:[];this.store.setError(`Couldn't start ${n.name}: ${r?.message||r}`,a)}}managedLaunchProvider(e,t){return e.startsWith(`codex`)?`openai-codex`:e.startsWith(`claude`)?`anthropic`:t??null}async prepareManagedCredential(e,t){let n=await this.managedCredentialReady().catch(()=>!1),r=await this.tryPublishManagedCredential(e,n,t);return this.managedLaunchProvider(e,t)?r:r||n}async tryPublishManagedCredential(e,t,n){if(this.store.getState().connection.status!==`online`)return!1;let r=this.managedLaunchProvider(e,n),i=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&(!r||e.provider===r));if(!i)return!1;if(i.unattended&&t)return!0;try{i.unattended&&await this.setCredentialUnattended(i.provider,i.label,!1);let e=(await At(this.local)).generation;return await this.setCredentialUnattended(i.provider,i.label,!0),await this.waitForManagedCredential(2e4,e),!0}catch{return!1}}async beginManagedCredentialSetup(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.phase=`credential-setup`,n.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(n),this.managedCredentialSetupNodes.add(t),this.managedCredentialReturnSessionId=e,this.store.updateLaunchCheckpoint(e,`credentials`,`active`),this.switchNode(t),await this.waitForOnline(12e4),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.listProviders(),this.listCredentialRecords();let r=n.prompt.frame,i=this.managedLaunchProvider(String(r?.agent||``),r?.model?.provider)??this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`)?.provider??`anthropic`;this.store.setNeedsModelAuth({nodeId:t,provider:i})}failLaunchCheckpoint(e,t){let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.launchProgress,r=[`account`,`capacity`,`machine`,`service`,`credentials`,`repository`,`agent`,`message`],i=[...r].reverse().find(e=>n?.checkpoints[e]?.state===`active`)??r.find(e=>!n?.checkpoints[e]||n.checkpoints[e]?.state===`waiting`)??`message`;this.store.updateLaunchCheckpoint(e,i,`failed`,t)}openPendingLaunch(e,t={}){let n=this.pendingLaunches.get(e);n&&(t.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.store.addUserMessage(n.prompt.text,n.prompt.clientMessageId,n.prompt.attachments))}startPendingRunner(e){let t=this.pendingLaunches.get(e),n=t?.machine?.nodeId;if(!t||!n||t.transport)return;let r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};r(`Machine accepted. Waiting for its secure Bivy service to come online…`),this.startBootProgress(n,e,r);let i=new Proxy(this.local,{get:(e,t,r)=>t===`cur`?n:Reflect.get(e,t,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),a,o,s=()=>this.pendingLaunches.get(e)===t&&t.transport===a,c=!1,l=!1,u=()=>{if(c&&(l||t.config.computeSource!==`managed`)&&this.pendingLaunches.has(e)){let{model:e,...n}=t.prompt.frame;a.send(n)}};a=new ga({store:i,handlers:{onStatus:i=>{if(o){o.onStatus(i);return}s()&&(c=i===`online`,c&&(t.modelApproved=!1,t.modelSelecting=void 0,t.modelQuery=void 0,t.models=void 0,r(`${t.config.name} is online. Preparing credentials, repository, and agent…`),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.store.updateLaunchCheckpoint(e,`credentials`,l?`done`:`active`),this.clearBootProgress(n),u()))},onEvent:n=>{if(o){o.onEvent(n);return}if(!s())return;(n.type===`credentials.records`||n.type===`providers.list`)&&t.sessionId&&!t.modelQuery&&this.refreshLaunchModels(e);let r=n.type===`models.list`?n.current:n.model;if(n.type===`session.error`&&t.sessionId&&!t.modelApproved&&n.sessionId===t.sessionId){t.modelSelecting=void 0,t.modelQuery=void 0,t.prompt.frame={...t.prompt.frame,model:void 0},this.pendingLaunchStore.put(t).catch(()=>{}),this.store.setLaunchModelChoice(e,{models:t.models??[],error:typeof n.error==`string`?n.error:`Couldn't select this model. Choose another model or refresh.`});return}if(n.type===`models.list`&&n.sessionId===t.sessionId&&!t.modelApproved){if(t.modelQuery=void 0,n.modelSelection===!1){t.modelApproved=!0,this.sendPendingLaunchPrompt(e,t.sessionId,a);return}t.models=(Array.isArray(n.models)?n.models:[]).filter(e=>e&&e.configured!==!1&&typeof e.id==`string`&&e.id!==`unknown`&&typeof e.provider==`string`&&e.provider!==`unknown`&&e.id&&e.provider);let i=t.models?.find(e=>e.id===r?.id&&e.provider===r?.provider),o=t.prompt.frame.model;if(!t.modelSelecting&&i&&(!o||o.id===i.id&&o.provider===i.provider))t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);else{let n=t.models?.find(e=>e.id===o?.id&&e.provider===o?.provider);n&&!t.modelSelecting?this.chooseLaunchModel(e,n):(this.store.updateLaunchCheckpoint(e,`message`,`waiting`),this.store.setLaunchModelChoice(e,{models:t.models??[],current:i,selecting:!!t.modelSelecting,error:o&&!n?lt(o,t.models??[],t.config.computeSource===`managed`):void 0}))}return}if(n.type===`model.updated`&&n.sessionId===t.sessionId&&t.modelSelecting&&r?.id===t.modelSelecting.id&&r?.provider===t.modelSelecting.provider){t.modelSelecting=void 0,t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);return}if(n.type===`session.error`){this.failPendingLaunch(e,String(n.error||`Session creation failed.`));return}if(n.type===`session.history`&&n.requestId===t.prompt.requestId&&n.sessionId){t.prompt.frame&&`repo`in t.prompt.frame&&t.prompt.frame.repo&&this.store.updateLaunchCheckpoint(e,`repository`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`done`),t.sessionId=String(n.sessionId),t.modelApproved?this.sendPendingLaunchPrompt(e,t.sessionId,a):this.refreshLaunchModels(e);return}n.type===`session.user_message`&&(t.promptSent||t.promptSending)&&n.sessionId===t.sessionId&&n.clientMessageId===t.prompt.clientMessageId&&this.finishPendingLaunch(e,String(t.sessionId),a,()=>(o=this.buildTransportHandlers(),o),n)},onError:e=>{if(o){o.onError?.(e);return}s()&&(/^node offline$/i.test(e.trim())||r(`Connection retry: ${e}`))}}}),t.transport=a,this.pollBootstrapStatus(n,e,r,()=>{l=!0,u()}),a.connect()}refreshLaunchModels(e){let t=this.pendingLaunches.get(e);if(!t?.sessionId||!t.transport||t.modelApproved||t.modelSelecting)return;let n={};t.modelQuery=n,this.store.setLaunchModelChoice(e,{models:t.models??[],loading:!0});let r=()=>{this.pendingLaunches.get(e)===t&&t.modelQuery===n&&(t.modelQuery=void 0,this.store.setLaunchModelChoice(e,{models:t.models??[],error:`Couldn't load models from this machine. Refresh to try again; your prompt is still saved.`}))};setTimeout(r,15e3),Promise.resolve().then(()=>t.transport?.send({kind:`models.list`,sessionId:t.sessionId})).catch(r)}async chooseLaunchModel(e,t){let n=this.pendingLaunches.get(e);if(!n?.sessionId||!n.transport||n.modelSelecting||n.modelApproved||n.modelQuery)return;let r=n.models?.find(e=>e.id===t.id&&e.provider===t.provider);if(!r)return;let i={...r};n.modelSelecting=i,this.store.setLaunchModelChoice(e,{models:n.models??[],current:i,selecting:!0}),setTimeout(()=>{this.pendingLaunches.get(e)===n&&n.modelSelecting===i&&(n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Model selection wasn't confirmed. Refresh or choose again; your prompt is still saved.`}))},15e3);try{if(n.prompt.frame={...n.prompt.frame,model:{id:i.id,provider:String(i.provider)}},await this.pendingLaunchStore.put(n),this.pendingLaunches.get(e)!==n||n.modelSelecting!==i)return;await n.transport.send({kind:`model.select`,sessionId:n.sessionId,id:i.id,provider:i.provider})}catch{n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Couldn't select this model. Refresh and try again.`})}}async sendPendingLaunchPrompt(e,t,n){let r=this.pendingLaunches.get(e);if(r&&!r.promptSending&&r.modelApproved){this.store.updateLaunchCheckpoint(e,`message`,`active`),r.sessionId=t,r.promptSending=!0,this.store.getState().activeSession.activeSessionId===e&&this.store.pushSystemMessage(`Setup · Repository and agent are ready. Sending your prompt…`);try{if(await n.send({kind:`prompt`,sessionId:t,text:r.prompt.text,clientMessageId:r.prompt.clientMessageId,attachments:r.prompt.attachments}),!this.pendingLaunches.has(e))return;r.promptSent=!0,r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}catch(t){if(!this.pendingLaunches.has(e))return;r.logs.push(`First-message delivery retry: ${t?.message||t}`),r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}finally{r.promptSending=!1,setTimeout(()=>{let r=this.pendingLaunches.get(e);r&&r.phase!==`failed`&&r.sessionId===t&&this.sendPendingLaunchPrompt(e,t,n)},3e3)}}}async finishPendingLaunch(e,t,n,r,i){let a=this.pendingLaunches.get(e),o=a?.machine?.nodeId;if(!a||!o)return;this.store.updateLaunchCheckpoint(e,`message`,`done`),this.clearBootProgress(o),this.pendingLaunches.delete(e),this.pendingLaunchStore.remove(e).catch(()=>{}),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),this.store.completePendingSession(e,t,o);let s=this.store.getState().activeSession.activeSessionId===t;if(s){let e=r();this.transport.close(),this.local.cur=o,this.store.setCurrentNode(o),this.transport=n,this.pendingCrossNodeOpen={sessionId:t},Z({kind:`session`,id:t}),this.store.setStatus(`connecting`),e.onStatus(`online`),e.onEvent(i),this.listRuntimes(),this.listProviders(),this.getNodeSettings()}for(let e of a.followups)await n.send({kind:`prompt`,sessionId:t,...e});s||setTimeout(()=>n.close(),1e3),setTimeout(()=>this.refreshSessions(),1500)}failPendingLaunch(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.machine?.nodeId&&this.clearBootProgress(n.machine.nodeId);let r=n.transport;n.transport=void 0,r?.close(),n.logs.push(`Startup failed: ${t}`),this.store.setLaunchModelChoice(e,void 0),n.modelQuery=void 0,n.modelSelecting=void 0,n.modelApproved=!1,n.phase=`failed`,n.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(n),/not available on this node|command not found|agent is not installed/i.test(t)?(this.store.updateLaunchCheckpoint(e,`credentials`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`failed`,t)):this.failLaunchCheckpoint(e,t),this.store.failPendingSession(e),this.store.setError(`Couldn't start ${n.config.name}: ${t}`)}startBootProgress(e,t,n){this.clearBootProgress(e);let r=[[15e3,`Booting the machine and installing Bivy…`],[45e3,`Still installing Bivy (45s elapsed). A first boot can take a few minutes…`],[9e4,`Still waiting for Bivy to join the secure relay (90s elapsed)…`],[18e4,`Boot is taking longer than usual (3 min elapsed). Still retrying…`],[ml,`Still offline after ${Math.round(ml/6e4)} min. Check the provider's machine logs for a failed install.`]].map(([e,r])=>setTimeout(()=>{this.pendingLaunches.has(t)&&n(r)},e));this.bootProgressTimers.set(e,r)}clearBootProgress(e){for(let t of this.bootProgressTimers.get(e)??[])clearTimeout(t);this.bootProgressTimers.delete(e),this.bootstrapPhaseByNode.delete(e)}pollBootstrapStatus(e,t,n,r){let i={booting:`The machine booted and cloud-init started.`,installing:`Cloud-init is installing Bivy…`,starting:`Bivy is installed. Starting its secure service…`,ready:`The secure Bivy service is ready.`,failed:`Cloud-init reported that the Bivy install failed.`},a=!1,o=async()=>{let s=this.pendingLaunches.get(t);if(s&&s.machine?.nodeId===e){try{let o=await Et(this.local);this.store.setNodes(o);let c=o.find(t=>t.id===e)?.bootstrapStatus?.phase;c&&c!==this.bootstrapPhaseByNode.get(e)&&(this.bootstrapPhaseByNode.set(e,c),n(i[c]||`Bootstrap: ${c}`),c===`ready`&&this.store.updateLaunchCheckpoint(t,`service`,`done`),c===`failed`&&this.failPendingLaunch(t,i.failed)),(s.config.computeSource===`managed`?(await gn(this.local)).find(t=>t.nodeId===e)?.milestones?.credentialsReadyAt:c===`ready`)&&!a&&this.pendingLaunches.has(t)&&s.phase!==`failed`&&(a=!0,this.store.updateLaunchCheckpoint(t,`credentials`,`done`),r())}catch{}this.pendingLaunches.has(t)&&setTimeout(o,3e3)}};o()}async restorePendingLaunches(){let e=await this.pendingLaunchStore.list();for(let t of e){if(this.store.isSessionDeleted(t.id)){await this.pendingLaunchStore.remove(t.id);continue}this.pendingLaunches.set(t.id,t),this.store.persistPendingSession(t.id,t.prompt.text,!1,t.config.name,Date.parse(t.createdAt)||Date.now()),t.machine?.nodeId&&t.phase!==`failed`?(this.store.retryPendingSession(t.id),this.store.setLaunchModelChoice(t.id,void 0),this.store.updateLaunchCheckpoint(t.id,`account`,`done`),this.store.updateLaunchCheckpoint(t.id,`capacity`,`done`),this.store.updateLaunchCheckpoint(t.id,`machine`,`done`),this.store.updateLaunchCheckpoint(t.id,`service`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(t.id,`repository`,`skipped`),this.store.bindPendingSessionNode(t.id,t.machine.nodeId),t.phase===`credential-setup`?this.beginManagedCredentialSetup(t.id,t.machine.nodeId):this.startPendingRunner(t.id)):t.phase===`provisioning`?(t.phase=`failed`,t.logs.push(`Startup was interrupted before the cloud provider confirmed the machine.`),t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.failPendingSession(t.id)):t.phase===`failed`&&this.store.failPendingSession(t.id)}}async retryPendingLaunch(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close(),t.logs.push(`Retrying startup…`),t.phase=t.machine?.nodeId?`booting`:`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),t.machine?.nodeId?this.startPendingRunner(e):await this.launchDraftRunnerAndBind(e)}async retryPendingLaunchOnFreshMachine(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close();let r=t.machine?.nodeId;r&&await this.destroyHostedMachine(r).catch(()=>{}),t.machine=void 0,t.sessionId=void 0,t.promptSent=!1,t.logs.push(`Replacing the Cloud Machine and retrying the preserved first message…`),t.phase=`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),await this.launchDraftRunnerAndBind(e)}async dismissPendingLaunch(e){let t=this.pendingLaunches.get(e);this.pendingLaunches.delete(e),t?.transport?.close(),t?.machine?.nodeId&&this.clearBootProgress(t.machine.nodeId),this.store.dismissPendingSession(e),this.persistDeletedSessionTombstones(),await this.pendingLaunchStore.remove(e),this.store.getState().activeSession.activeSessionId??this.newSession()}invokeAgentCommand(e,t){let n=this.store.getState().activeSession.activeSessionId;n&&this.send({kind:`session.command.invoke`,sessionId:n,name:e,args:t})}listRepos(){this.store.getState().catalogs.repos.length===0&&this.store.setReposLoading(!0);let e=this.store.getState().draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||e)){cn(this.local).then(e=>this.store.apply({type:`repos.list`,repos:e,authed:!0})).catch(e=>this.store.apply({type:`repos.list`,repos:[],authed:!1,error:String(e?.message||e)}));return}this.send({kind:`repos.list`})}githubConnectStart(){this.store.setGithubConnect({status:`starting`}),this.send({kind:`github.connect.start`})}githubConnectPoll(){this.send({kind:`github.connect.poll`})}githubConnectReset(){this.store.setGithubConnect({status:`idle`})}chooseRepo(e){let t=e!==this.store.getState().draft.repo;this.store.setDraftRepo(e),t&&this.store.clearBranches(),this.local.setLastChoice({repo:e})}chooseRepoBranch(e,t){this.store.setDraftRepo(e),this.store.setDraftBranch(t),this.local.setLastChoice({repo:e})}listBranches(e){let t=this.store.getState();t.catalogs.branchesRepo===e&&t.catalogs.branches.length>0||this.store.setBranchesLoading(!0);let n=t.draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||n)){ln(this.local,e).then(t=>this.store.apply({type:`branches.list`,repo:e,branches:t})).catch(t=>this.store.apply({type:`branches.list`,repo:e,branches:[],error:String(t?.message||t)}));return}this.send({kind:`branches.list`,repo:e})}listRuntimes(){this.send({kind:`runtimes.list`})}requestCapabilities(){this.send({kind:`capabilities.get`})}cloudModelQuery=0;isCloudModelDraft(){let e=this.store.getState();return!e.activeSession.activeSessionId&&!this.direct&&!(!e.draft.ephemeralConfig&&this.local.cur)}async listCloudModels(){let e=++this.cloudModelQuery,t=this.store.getState(),n=t.draft.ephemeralConfig,r=t.catalogs.selectedAgentId,i=this.local.cur,a=t.catalogs.models,o=t.settings.credentialRecords;try{let[t,s]=await Promise.all([this.ephemeralKeys.modelKeyEntries(),this.ephemeralKeys.oauthCredentialEntries()]),c=this.store.getState();if(e!==this.cloudModelQuery||!this.isCloudModelDraft()||c.draft.ephemeralConfig!==n||c.catalogs.selectedAgentId!==r||this.local.cur!==i)return;let l=[...o.filter(e=>e.sync===`account`&&e.kind!==`reference`),...t.filter(e=>e.scope===`account`||n?.computeSource!==`managed`),...s].map(e=>e.provider);this.store.apply({type:`models.list`,runtimeId:r,models:ct(l,a)})}catch{e===this.cloudModelQuery&&this.isCloudModelDraft()&&this.store.setError(`Couldn't load account models. Open the model picker to try again.`)}}listModels(){if(this.isCloudModelDraft()){this.listCloudModels();return}let e=this.store.getState(),t=e.activeSession.activeSessionId,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.pendingLaunch===!0:!1,r=t&&!n?t:void 0,i=r?void 0:e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId??void 0;this.send({kind:`models.list`,sessionId:r,runtimeId:i})}runtimeModelWaiters=new Map;modelsForRuntime(e,t=2e4){return new Promise(n=>{let r=e=>{clearTimeout(i),n(e)},i=setTimeout(()=>{let t=this.runtimeModelWaiters.get(e);t?.splice(t.indexOf(r)>>>0,1),n(this.store.cachedModelsFor(e)??[])},t);this.runtimeModelWaiters.set(e,[...this.runtimeModelWaiters.get(e)??[],r]),this.send({kind:`models.list`,runtimeId:e})})}settleRuntimeModels(e){let t=this.runtimeModelWaiters.get(e);if(!t?.length)return;this.runtimeModelWaiters.delete(e);let n=this.store.cachedModelsFor(e)??[];for(let e of t)e(n)}prefetchModels(){if(this.store.getState().activeSession.activeSessionId)return;let e=this.store.getState().catalogs.runtimes.filter(e=>String(e.status||`available`)===`available`).map(e=>e.id);e.length&&this.send({kind:`models.prefetch`,runtimeIds:e})}chooseModel(e){let t=this.store.getState().activeSession.activeSessionId;if(t&&this.isProvisionalSessionId(t)){this.chooseLaunchModel(t,e);return}this.credentialsModelsCoordinator.selectModel(e,t)}setThinkingLevel(e){let t=this.store.getState().activeSession.activeSessionId??void 0;t&&this.isProvisionalSessionId(t)||(this.store.setThinkingLevel(e),this.send({kind:`thinking.set_level`,level:e,sessionId:t}))}chooseAgent(e,t){if(String(e.status||`available`)!==`available`&&e.install){this.installAgent(e.id);return}let n=this.store.getState(),r=n.activeSession.activeSessionId,i=n.activeSession.transcript.some(e=>e.role===`user`);if(r&&i){let i=n.activeSession.activeRuntimeId??n.sessionIndex.sessions.find(e=>e.sessionId===r)?.runtimeId;this.pendingPrompt=null,this.pendingFollowups=[],this.forkSession(r,{agentId:e.id,sourceAgentId:i,retireSource:!1},t).catch(e=>this.store.setError(e instanceof Error?e.message:String(e)));return}if(r&&(this.pendingPrompt=null,this.pendingFollowups=[],this.promptTargetSessionId=null,this.store.resetActiveSession(),Z({kind:`new`})),this.store.setSelectedAgentLocal(e.id),this.local.setLastChoice({agentId:e.id}),this.isCloudModelDraft()){this.listModels();return}this.send({kind:`runtime.select`,id:e.id})}installAgent(e){this.pendingAgentPick=e,this.store.setInstalling(e),this.send({kind:`runtime.install`,id:e})}maybeSelectInstalledAgent(e){if(e.type===`runtime.install.error`&&e.id===this.pendingAgentPick){this.pendingAgentPick=null;return}if(e.type!==`runtime.install.done`||!this.pendingAgentPick||e.id!==this.pendingAgentPick)return;this.pendingAgentPick=null;let t=this.store.getState();if(t.activeSession.transcript.some(e=>e.role===`user`))return;let n=t.catalogs.runtimes.find(t=>t.id===e.id);n&&String(n.status||`available`)===`available`&&this.chooseAgent(n)}listProviders(){this.credentialsModelsCoordinator.listProviders()}getProviderAuth(e){this.credentialsModelsCoordinator.getProviderAuth(e)}saveApiKey(e,t){return this.credentialsModelsCoordinator.saveApiKey(e,t)}removeProvider(e){this.credentialsModelsCoordinator.removeProvider(e)}resetOauth(e){this.credentialsModelsCoordinator.resetOauth(e)}startOauth(e,t){this.credentialsModelsCoordinator.startOauth(e,t)}openOauthOnNode(e){return this.credentialsModelsCoordinator.openOauthOnNode(e)}submitOauthCode(e,t){this.credentialsModelsCoordinator.submitOauthCode(e,t)}listCredentialRecords(){this.credentialsModelsCoordinator.listCredentials()}async previewNativeCredentials(e,t){return await this.nativeCredentialCommand(e,{kind:`credentials.native.preview`,label:t})}async importNativeCredentials(e,t,n,r){return await this.nativeCredentialCommand(e,{kind:`credentials.native.import`,previewId:t,agents:n,sync:r})}async nativeCredentialCommand(e,t){let n=this.store.getState().connection;if(n.status!==`online`||n.currentNodeId!==e)throw Error(`Connect to the selected machine before scanning or importing.`);let r=await this.awaitAck(t,2e4);if(this.store.getState().connection.currentNodeId!==e)throw Error(`Machine changed. Scan again on the selected machine.`);return r}syncAccountCredentialsWithNode(){return this.credentialsModelsCoordinator.syncAccountCredentials()}setCredential(e,t,n){return this.credentialsModelsCoordinator.setCredential(e,t,n)}removeCredential(e,t){return this.credentialsModelsCoordinator.removeCredential(e,t)}setCredentialSync(e,t,n){return this.credentialsModelsCoordinator.setCredentialSync(e,t,n)}setCredentialUnattended(e,t,n){return this.credentialsModelsCoordinator.setCredentialUnattended(e,t,n)}testCredential(e,t){return this.credentialsModelsCoordinator.testCredential(e,t)}getCredentialPresets(){this.credentialsModelsCoordinator.getPresets()}setActivePreset(e){this.credentialsModelsCoordinator.setActivePreset(e)}setPresetMapping(e,t,n){return this.credentialsModelsCoordinator.setPresetMapping(e,t,n)}listLocalModels(){this.credentialsModelsCoordinator.listLocalModels()}listLocalModelPresets(){this.credentialsModelsCoordinator.listLocalModelPresets()}discoverLocalModels(){return this.credentialsModelsCoordinator.discoverLocalModels()}verifyLocalModel(e,t){return this.credentialsModelsCoordinator.verifyLocalModel(e,t)}saveLocalModel(e){return this.credentialsModelsCoordinator.saveLocalModel(e)}removeLocalModel(e){this.credentialsModelsCoordinator.removeLocalModel(e)}listRulesets(){this.send({kind:`rulesets.list`})}saveRuleset(e,t){return this.awaitAck({kind:`rulesets.save`,ruleset:e,active:t}).then(()=>void 0)}removeRuleset(e){this.send({kind:`rulesets.remove`,name:e})}getSttConfig(){this.send({kind:`stt.config.get`})}setSttProvider(e){this.send({kind:`stt.config.set`,provider:e})}saveSttKey(e,t){return this.awaitAck({kind:`stt.config.set`,setKey:{provider:e,value:t}}).then(()=>void 0)}removeSttKey(e){this.send({kind:`stt.config.set`,removeKey:e})}transcribe(e,t){let n=ll();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingTranscriptions.delete(n),i(Error(`Transcription timed out. Check your connection and try again.`))},6e4);this.pendingTranscriptions.set(n,{resolve:r,reject:i,timer:a}),this.transport.send({kind:`transcribe`,requestId:n,audio:e,mimeType:t})})}resolveTranscription(e){let t=String(e.requestId||``),n=t?this.pendingTranscriptions.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingTranscriptions.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve(String(e.text??``).trim())}synthesize(e,t,n){let r=ll();return new Promise((i,a)=>{let o=setTimeout(()=>{this.pendingSpeech.delete(r),a(Error(`Speech generation timed out. Check your connection and try again.`))},6e4);this.pendingSpeech.set(r,{resolve:i,reject:a,timer:o}),this.transport.send({kind:`synthesize`,requestId:r,text:e,voice:t,instructions:n})})}resolveSpeech(e){let t=String(e.requestId||``),n=t?this.pendingSpeech.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingSpeech.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve({audio:String(e.audio??``),mimeType:String(e.mimeType??`audio/mpeg`)})}githubAppManifestStart(e){this.store.setGithubAppPhase(`starting`),this.send({kind:`github.app.manifest.start`,requestId:ll(),origin:d(),org:e||void 0})}githubAppManifestCode(e,t){this.store.setGithubAppPhase(`completing`),this.send({kind:`github.app.manifest.code`,requestId:ll(),code:e,state:t})}async githubAppConnectExisting(e){this.store.setGithubAppPhase(`completing`);try{await this.awaitAck({kind:`github.app.connect-existing`,appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel||void 0},6e4)}catch(e){throw this.store.setGithubAppPhase(`error`,{error:e instanceof Error?e.message:String(e),returning:!1}),e}}connectHostedGithubApp(e){return sn(this.local,e)}fetchMe(){return this.accountCoordinator.fetchMe()}deleteAccount(){return Ht(this.local)}invokeAccountExtensionAction(e){return u()?Ut(this.local,e):Promise.reject(Error(`Account service actions are unavailable in this app.`))}fetchGithubApp(){return this.accountCoordinator.fetchGithubApp()}fetchGithubQueue(e=30){return this.accountCoordinator.fetchGithubQueue(e)}fetchAutomationRuns(e=50,t={}){return this.accountCoordinator.fetchAutomationRuns(e,t)}cancelAutomationRun(e){return this.accountCoordinator.cancelAutomationRun(e)}setGithubAppDefaultNode(e,t){return this.accountCoordinator.setGithubAppDefaultNode(e,t)}setGithubAppTriggerAccess(e,t){return this.accountCoordinator.setGithubAppTriggerAccess(e,t)}assignWorkItem(e,t){return this.accountCoordinator.assignWorkItem(e,t)}deleteWorkItem(e){return this.accountCoordinator.deleteWorkItem(e)}clearWorkQueue(){return this.accountCoordinator.clearWorkQueue()}githubAppDisconnect(e,t){return this.accountCoordinator.disconnectGithubApp(e,t)}removeNode(e){return this.accountCoordinator.removeNode(e)}enablePush(){return i?o()?.enable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.enablePush()}disablePush(){return i?o()?.disable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.disablePush()}async listTailnetMachines(){let e=await this.awaitAck({kind:`tailnet.machines`},15e3);return Array.isArray(e.machines)?e.machines:[]}async getAccess(){return await this.awaitAck({kind:`access.get`},15e3)}pushStatus(){return i?o()?.status({token:this.local.s,controlPlane:d()})??Promise.resolve({supported:!1,subscribed:!1,permission:`default`}):this.accountCoordinator.pushStatus()}getNotificationPreferences(){return this.accountCoordinator.getNotificationPreferences()}setNotificationPreferences(e){return this.accountCoordinator.setNotificationPreferences(e)}ephemeralModelKeys=vi();deviceOAuthCredentials=_i();ephemeralKeys=ra({local:gi(),modelKeys:this.ephemeralModelKeys,oauthCredentials:this.deviceOAuthCredentials,oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled(),remote:this.deviceVaultRemote(),device:()=>Ui(this.local),enabled:()=>!this.direct&&!!this.local.s,providerTokenSyncEnabled:()=>!this.direct&&!!this.local.s,state:{load:async()=>{try{return JSON.parse(localStorage.getItem(`bivy_device_vault_state`)||`null`)??void 0}catch{return}},save:async e=>{try{localStorage.setItem(`bivy_device_vault_state`,JSON.stringify(e))}catch{}}}});ephemeralPrefs=Si();ephemeralSetups=wi();ephemeralMachines=Ei();pendingLaunchStore=Ti();seededEphemeralNodes=new Set;firstRunAuthNodes=new Set;managedCredentialSetupNodes=new Set;managedCredentialGrantInFlight=!1;managedCredentialReturnSessionId=null;listEphemeralKeys(){return this.ephemeralKeys.list()}listEphemeralModelKeys(){return this.ephemeralKeys.listModelKeys()}setEphemeralModelKey(e,t,n=`account`,r=`default`){return this.ephemeralKeys.setModelKey(e,t,n,r)}removeEphemeralModelKey(e,t=`default`){return this.ephemeralKeys.removeModelKey(e,t)}getEphemeralToken(e){return this.ephemeralCoordinator.getProviderToken(e)}setEphemeralToken(e,t){return this.ephemeralCoordinator.setProviderToken(e,t)}connectEphemeralProvider(e,t){return this.ephemeralCoordinator.connectProvider(e,t)}defaultEphemeralRunner(e){return this.ensureDefaultRunner(e)}ensureDefaultRunner(e){return this.ephemeralCoordinator.ensureDefaultRunner(e)}removeEphemeralToken(e){return this.ephemeralCoordinator.removeProviderToken(e)}oauthRecoveryEnabled(){try{return!this.direct&&!!this.local.s&&localStorage.getItem(`bivy_oauth_browser_recovery`)===`1`}catch{return!1}}getOAuthBrowserRecovery(){return this.oauthRecoveryEnabled()}async setOAuthBrowserRecovery(e){if(this.direct)throw Error(`OAuth browser recovery requires a signed-in account`);if(!e)for(let e of await this.ephemeralKeys.oauthCredentialEntries())await this.ephemeralKeys.removeOAuthCredential(e.provider,e.label);try{localStorage.setItem(`bivy_oauth_browser_recovery`,e?`1`:`0`)}catch{}e&&await this.syncAccountCredentialsWithNode()}syncDeviceVault(){return this.ephemeralKeys.sync()}getDeviceVaultSyncState(){return this.ephemeralKeys.getSyncState()}deviceVaultRemote(){let e=()=>(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),t=()=>({authorization:`Bearer ${this.local.s}`,"content-type":`application/json`});return{get:async()=>{let t=await Ui(this.local),n=await fetch(`${e()}/device-vault?device=${encodeURIComponent(t.pub)}`,{headers:{authorization:`Bearer ${this.local.s}`}});if(!n.ok)throw Error(`device-vault get failed (${n.status})`);let r=await n.json();return{vault:r.vault??null,wrappedKey:r.wrappedKey??null,requests:Array.isArray(r.requests)?r.requests:[],generation:r.generation??0,keyGeneration:r.keyGeneration??0,recipients:Array.isArray(r.recipients)?r.recipients:[]}},putVault:async(n,r,i)=>{let a=await Ui(this.local),o=await fetch(`${e()}/device-vault`,{method:`PUT`,headers:t(),body:JSON.stringify({devicePublicKeyB64:a.pub,ciphertext:n,expectedGeneration:r,keyGeneration:i})});if(o.status===409)throw new Ji;if(!o.ok)throw Error(`device-vault put failed (${o.status})`);return{generation:(await o.json()).generation??(r??0)+1}},requestKey:async()=>{let n=await Ui(this.local);await fetch(`${e()}/device-vault/key/request`,{method:`POST`,headers:t(),body:JSON.stringify({devicePublicKeyB64:n.pub})})},putWrapped:async(n,r,i,a)=>{let o=await fetch(`${e()}/device-vault/key/wrapped`,{method:`PUT`,headers:t(),body:JSON.stringify({targetDevicePublicKeyB64:n,wrappedKey:r,wrappedByPublicKeyB64:i,generation:a})});if(o.status!==403&&!o.ok)throw Error(`device-vault wrapped-key put failed (${o.status})`)}}}getEphemeralPrefs(e){return this.ephemeralPrefs.get(e)}setEphemeralPrefs(e,t){return this.ephemeralPrefs.set(e,t)}listEphemeralSetups(e){return this.ephemeralSetups.list(e)}createEphemeralSetup(e,t){return this.ephemeralSetups.create(e,t)}updateEphemeralSetup(e,t){return this.ephemeralSetups.update(e,t)}removeEphemeralSetup(e){return this.ephemeralSetups.remove(e)}listEphemeralMachines(){return this.ephemeralMachines.list()}async seedEphemeralNodeIfNeeded(){if(!uc||this.direct)return;let e=this.local.cur;if(!e||this.seededEphemeralNodes.has(e))return;let t;try{t=await this.ephemeralMachines.list()}catch{return}if(!t.some(t=>t.nodeId===e))return;let n;try{n=await this.ephemeralKeys.modelKeyEntries()}catch{return}if(this.seededEphemeralNodes.add(e),n.length){if(this.store.getState().connection.status!==`online`||this.local.cur!==e){this.seededEphemeralNodes.delete(e);return}for(let{provider:e,key:t}of n)this.send({kind:`provider.apiKey`,provider:e,key:t})}}async maybeGrantManagedCredential(){let e=this.local.cur;if(!e||!this.managedCredentialSetupNodes.has(e)||this.managedCredentialGrantInFlight)return;let t=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&!e.unattended);if(t){this.managedCredentialGrantInFlight=!0;try{await this.setCredentialUnattended(t.provider,t.label,!0),await this.waitForManagedCredential();let e=this.managedCredentialReturnSessionId;this.managedCredentialReturnSessionId=null,e&&this.pendingLaunches.has(e)&&(this.openPendingLaunch(e),await this.retryPendingLaunch(e))}catch(e){this.store.setError(e instanceof Error?e.message:String(e))}finally{this.managedCredentialGrantInFlight=!1}}}async maybePromptFirstRunModelAuth(){if(!uc||this.direct)return;let e=this.local.cur;e&&!this.firstRunAuthNodes.has(e)&&(await this.ephemeralMachines.list().catch(()=>[])).some(t=>t.nodeId===e)&&(this.firstRunAuthNodes.add(e),this.listProviders(),setTimeout(()=>{let t=this.store.getState();if(t.connection.status!==`online`||this.local.cur!==e||t.presentation.needsModelAuth||t.presentation.oauth||t.catalogs.providers.some(e=>e.configured))return;let n=t.catalogs.providers.find(e=>e.oauth&&e.id===`anthropic`)?.id??t.catalogs.providers.find(e=>e.oauth)?.id??`anthropic`;this.store.setNeedsModelAuth({nodeId:e,provider:n})},pl))}dismissModelAuthPrompt(){this.store.setNeedsModelAuth(null)}maybeTeardownFinishedEphemeral(e){return this.isProvisionalSessionId(e)||[...this.pendingLaunches.values()].some(t=>t.sessionId===e)?Promise.resolve():this.ephemeralCoordinator.teardownFinishedSession(e)}listEphemeralSizes(e,t){return this.ephemeralCoordinator.listSizes(e,t)}launchEphemeral(e){return this.ephemeralCoordinator.launch(e)}destroyEphemeral(e){return this.ephemeralCoordinator.destroy(e)}resumeAndConnectNode(e,t=9e4){return this.ephemeralCoordinator.resumeAndConnect(e,t)}correlationApi(){return{base:(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),auth:{authorization:`Bearer ${this.local.s}`,"content-type":`application/json`}}}async refreshEphemeralCorrelations(){if(!this.direct&&this.local.s)try{let{base:e,auth:t}=this.correlationApi(),n=await fetch(`${e}/session-correlation`,{headers:{authorization:t.authorization}});if(!n.ok)return;let r=await n.json();Array.isArray(r.correlations)&&(this.ephemeralCorrelations=r.correlations)}catch{}}async recordSessionCorrelation(e,t){if(this.isProvisionalSessionId(e)||this.direct||!this.local.s||!t.nodeId||!e)return;let n=`${t.nodeId}:${e}`;if(this.correlatedSessions.has(n))return;this.correlatedSessions.add(n);let r={sessionId:e,nodeId:t.nodeId,provider:t.provider,region:t.region||void 0,ttlMinutes:t.ttlMinutes,repo:t.repo,setupId:t.setupId,machineId:t.id,app:t.app,computeSource:t.computeSource};try{let{base:t,auth:n}=this.correlationApi(),i=await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`PUT`,headers:n,body:JSON.stringify(r)});if(i.status===410){this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e);return}if(!i.ok)throw Error(`Couldn't save session routing metadata.`);this.ephemeralCorrelations=[r,...this.ephemeralCorrelations.filter(t=>t.sessionId!==e)]}catch{this.correlatedSessions.delete(n)}}reprovisionEphemeral(e,t){return this.ephemeralCoordinator.reprovision(e,t)}isCurrentNodeResumable(){return this.ephemeralCoordinator.isCurrentNodeResumable()}shouldAutoResume(){return this.store.getState().connection.status!==`online`&&this.isCurrentNodeResumable()&&!this.resumingNode.has(this.local.cur)}async resumeNodeForSession(e){let t=this.local.cur;if(t&&!this.resumingNode.has(t)){this.resumingNode.add(t);try{await this.reprovisionEphemeral(t,e)}finally{this.resumingNode.delete(t)}}}drainPendingResume(e){let t=this.pendingResume.filter(t=>t.sessionId===e);if(t.length){this.pendingResume=this.pendingResume.filter(t=>t.sessionId!==e);for(let n of t)this.send({kind:`prompt`,sessionId:e,text:n.text,clientMessageId:n.clientMessageId,attachments:n.attachments})}}githubTaskToken=bi();getGithubTaskToken(){return this.githubTaskToken.get()}setGithubTaskToken(e){return this.githubTaskToken.set(e)}removeGithubTaskToken(){return this.githubTaskToken.remove()}runWorkItemOnEphemeral(e,t){return this.ephemeralCoordinator.runWorkItem(e,t)}launchEphemeralQueueWorker(e){return this.ephemeralCoordinator.launchQueueWorker(e)}getEphemeralQueueDefault(){return Xt(this.local)}setEphemeralQueueDefault(e){return Zt(this.local,e)}listEphemeralConfigs(){return this.ephemeralCoordinator.listConfigs()}createEphemeralConfig(e){return this.ephemeralCoordinator.createConfig(e)}updateEphemeralConfig(e,t){return this.ephemeralCoordinator.updateConfig(e,t)}removeEphemeralConfig(e){return this.ephemeralCoordinator.removeConfig(e)}getQueueRouting(){return an(this.local)}setQueueRouting(e){return on(this.local,e)}getHostedProvisioning(){return fn(this.local)}setHostedProvisioning(e){return pn(this.local,e)}listHostedAudit(){return hn(this.local)}listHostedMachines(){return gn(this.local)}destroyHostedMachine(e){return _n(this.local,e)}validateHostedProviderCredential(e,t,n){return un(this.local,e,t,n)}rotateHostedProvisioning(){return mn(this.local)}triggerHostedProvision(e=!1){return vn(this.local,e)}onTerminal(e){return this.terminalListeners.add(e),()=>this.terminalListeners.delete(e)}sendTerminal(e){this.send(e)}closeSessionTui(e){this.send({kind:`terminal.close.tui`,sessionId:e})}applyLinkPayload(e){return n||!xt(this.local,e)?!1:(this.store.setSignedIn(this.signedIn),this.switchNode(this.local.cur),this.refreshNodes(),!0)}reconcileSessionList(e){switch(String(e.type||``)){case`session.renamed`:case`session.branch_renamed`:case`session.closed`:this.refreshSessions();return;case`session.deleted`:e.sessionId&&this.transcriptCache.delete(e.sessionId),this.refreshSessions();return;default:return}}maybeRefreshModelsForRuntime(e){let t=this.store.getState(),n=e.type===`session.history`&&!!e.sessionId&&e.sessionId===t.activeSession.activeSessionId&&!t.catalogs.currentModel;(e.type===`runtime.updated`||n)&&this.listModels()}retryPendingSessionNew(){!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||this.store.getState().activeSession.activeSessionId||this.send(this.pendingPrompt.frame)}maybeFlushPendingPrompt(e){if(!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||e.type!==`session.history`||e.requestId!==this.pendingPrompt.requestId)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId;if(!t)return;Z({kind:`session`,id:t},{replace:!0});let{text:n,clientMessageId:r,attachments:i}=this.pendingPrompt;this.pendingPrompt=null,this.send({kind:`prompt`,sessionId:t,text:n,clientMessageId:r,attachments:i});let a=this.pendingFollowups;this.pendingFollowups=[];for(let e of a)this.send({kind:`prompt`,sessionId:t,text:e.text,clientMessageId:e.clientMessageId,attachments:e.attachments});this.refreshSessions()}abort(){let e=this.store.getState().activeSession.activeSessionId;e&&this.send({kind:`abort`,sessionId:e})}resolveTurnAttention(e,t){this.send({kind:`session.turn_attention.resolve`,sessionId:e,action:t})}setLimitRetry(e){let t=this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.limit_retry`,sessionId:t,enabled:e})}accountMode(){return!!(this.local.s&&this.local.cp)}resolveSessionNodeId(e){return this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.nodeId}resolveNodeLabel(e){let t=this.store.getState().connection.nodes.find(t=>t.id===e);return t?.name?`bivy/${t.name}`:void 0}async persistScheduledFollowup(e,t,n){if(!this.accountMode()||!n)return;let r=this.resolveSessionNodeId(e);if(!r)return;let i=this.local.keys()[r];if(i)try{let a=await D(await E(C(i)),n),o=new Date(Date.now()+6e4).toISOString(),s=await bn(this.local,{name:`Follow-up`,templateCiphertext:`${fl}:${r}:${a}`,trigger:`schedule`,schedule:{kind:`once`,at:o},nodeLabel:this.resolveNodeLabel(r),targetKind:`existing_session`,targetSessionId:e,message:!0,enabled:!0});this.store.attachFollowupAutomation(e,t,s.id)||this.cancelScheduledFollowup(s.id)}catch{}}startRun(e,t){return this.accountCoordinator.startRun(e,t)}cancelScheduledFollowup(e){e&&wn(this.local,e).catch(()=>{})}async editScheduledFollowup(e,t,n){let r=this.store.getFollowups(e).find(e=>e.id===t);if(!r||r.status!==`scheduled`)return`This message is no longer pending.`;if(!r.scheduledAutomationId)return`This message has no automation to update.`;if(!Number.isFinite(n.getTime())||n.getTime()<=Date.now())return`Pick a time in the future.`;try{await Sn(this.local,r.scheduledAutomationId,{schedule:{kind:`once`,at:n.toISOString()}})}catch(e){return e instanceof Error?e.message:`Could not reschedule the message.`}return this.store.rescheduleFollowup(e,t,n.getTime(),Date.now()),null}async resyncScheduledFollowups(){if(!this.accountMode())return;let e;try{e=await yn(this.local)}catch{return}let t=new Set(e.filter(e=>e.enabled&&e.nextRunAt!=null).map(e=>e.id));for(let e of Object.keys(this.store.getState().sessionIndex.followupsBySession))this.store.pruneScheduledFollowups(e,t)}supportsSteering(){return this.followupCoordinator.supportsSteering()}getFollowups(e){return this.followupCoordinator.list(e)}editFollowup(e,t,n,r){return this.followupCoordinator.edit(e,t,n,r)}removeFollowup(e,t){return this.followupCoordinator.remove(e,t)}reorderFollowup(e,t,n){return this.followupCoordinator.reorder(e,t,n)}sendFollowupNow(e,t){this.followupCoordinator.sendNow(e,t)}steerNow(e,t){return this.followupCoordinator.steer(e,t)}renameSession(e,t){let n=t.trim();n&&(e===this.store.getState().activeSession.activeSessionId&&this.store.setActiveTitle(n),this.store.renameSessionLocal(e,n),this.send({kind:`session.rename`,sessionId:e,name:n}),this.refreshSessions())}async deleteSession(e,t){if(this.isProvisionalSessionId(e)&&(await this.pendingLaunchRestoration,this.pendingLaunches.has(e))){await this.dismissPendingLaunch(e);return}let n=this.ephemeralCorrelations.find(t=>t.sessionId===e),r=n&&this.store.getState().connection.nodes.some(e=>e.id===n.nodeId&&e.online);if(!this.direct&&n&&!r){await this.deleteRetiredSession(e);return}this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.sessionCoordinator.deleteSession(e,t)}async deleteRetiredSession(e){try{let{base:t,auth:n}=this.correlationApi();if(!(await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`DELETE`,headers:n,signal:AbortSignal.timeout(15e3)})).ok)throw Error(`Couldn't delete the retired session. Refresh and try again.`);this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e),this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.store.getState().activeSession.activeSessionId===e&&(this.store.resetActiveSession(),Z({kind:`new`})),this.store.removeSessionLocal(e),this.persistDeletedSessionTombstones(),await this.transcriptCache.delete(e),this.refreshSessions()}catch(e){this.store.setError(e instanceof Error?e.message:`Couldn't delete the retired session.`)}}pauseSession(e){this.sessionCoordinator.pauseSession(e)}resumeSession(e){this.sessionCoordinator.resumeSession(e)}refreshPrStatus(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.pr.refresh`,sessionId:t})}refreshAllPrStatus(){this.send({kind:`sessions.pr.refresh_all`})}rewind(e,t){let n=t||this.store.getState().activeSession.activeSessionId;n&&e&&this.send({kind:`session.rewind`,sessionId:n,checkpointId:e})}revertFile(e,t,n){let r=n||this.store.getState().activeSession.activeSessionId;r&&e&&this.send({kind:`session.revert_file`,sessionId:r,path:e,content:t})}listCheckpoints(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.checkpoints`,sessionId:t})}resolveApproval(e,t,n=!1){this.send({kind:`approval`,id:e,approved:t,...t&&n?{remember:!0}:{}}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}answerQuestion(e,t,n){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,answers:n}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}cancelQuestion(e,t){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,cancelled:!0}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}},_l=g();function vl({tone:e,variant:t=`outline`,upper:n=!1,className:r=``,children:i,...a}){return(0,_l.jsx)(`span`,{className:`badge${n?` upper`:``}${r?` ${r}`:``}`,"data-tone":e,"data-variant":t,...a,children:i})}function yl(){return(0,y.useSyncExternalStore)(gl.store.subscribe,gl.store.getState)}export{wn as $,zo as A,O as At,li as B,cc as C,rt as Ct,Js as D,Ae as Dt,oc as E,Ne as Et,Wa as F,$n as G,ii as H,Oa as I,On as J,tr as K,Ma as L,Ka as M,C as Mt,Ga as N,v as Nt,Xs as O,ye as Ot,Ia as P,bn as Q,Aa as R,uc as S,at as St,ac as T,Fe as Tt,ni as U,G as V,nr as W,Vn as X,jn as Y,Rn as Z,Lc as _,Cn as _t,sl as a,yn as at,_c as b,Sn as bt,Yc as c,Bn as ct,Pc as d,bt as dt,Hn as et,Bc as f,Tt as ft,zc as g,Tn as gt,Hc as h,xn as ht,gl as i,Dn as it,yo as j,D as jt,fs as k,E as kt,Wc as l,Ln as lt,Rc as m,Mn as mt,vl as n,Et as nt,qc as o,Kt as ot,Gc as p,An as pt,yt as q,cl as r,kn as rt,Vc as s,fn as st,yl as t,zn as tt,Ic as u,St as ut,Fc as v,wt as vt,Z as w,Qe as wt,vc as x,pt as xt,Kc as y,Ct as yt,ja as z};
|