@bivy/bivy 0.20.1-staging.9 → 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/bivy.mjs +13 -0
- package/dist/apps/listeners.js +31 -3
- package/dist/apps/service.js +8 -1
- package/dist/apps/styles.css +3 -0
- package/dist/controllers/app-commands.js +7 -2
- package/dist/protocol/client-command-schemas.js +1 -1
- package/dist/session/run-terminal.js +6 -2
- package/package.json +1 -1
- package/web/assets/{AutomationsView-DjOv4IMn.js → AutomationsView-fnzmthnq.js} +1 -1
- package/web/assets/{ChangesCard-Bcd6mp08.js → ChangesCard-BWUgQ40Y.js} +1 -1
- package/web/assets/{LibraryView-CiRErGG3.js → LibraryView-JlSOji08.js} +1 -1
- package/web/assets/{ProviderConnect-htTjSJzb.js → ProviderConnect-BFFZWHsW.js} +1 -1
- package/web/assets/{Settings-oBsZwFcG.js → Settings-BAHWxYDH.js} +3 -3
- package/web/assets/{Sheet-lYov8PLo.js → Sheet-cVfLQVwf.js} +1 -1
- package/web/assets/{Terminal-B9d4Ijmc.js → Terminal-C3QFXkbI.js} +1 -1
- package/web/assets/{VoiceSettings-BIADw4Ll.js → VoiceSettings-CWOtAlAV.js} +1 -1
- package/web/assets/{abnfDiagram-VCTEODGH-gRoFYqU5.js → abnfDiagram-VCTEODGH-7cQ-bgry.js} +1 -1
- package/web/assets/architecture-7GRP2DOG-DVlvlW8H.js +1 -0
- package/web/assets/{architectureDiagram-5GKGNRK7-C4cNJboP.js → architectureDiagram-5GKGNRK7-BWOpNQNn.js} +1 -1
- package/web/assets/{blockDiagram-I7D4REHJ-DAICqtG4.js → blockDiagram-I7D4REHJ-8eE7JD9I.js} +1 -1
- package/web/assets/{c4Diagram-7LVT6UL2-DRswRDNz.js → c4Diagram-7LVT6UL2-DgiPr6K1.js} +1 -1
- package/web/assets/channel-Coq89lsO.js +1 -0
- package/web/assets/{chunk-4HAMMTFA-2joFftNJ.js → chunk-4HAMMTFA-C8GTT_rj.js} +1 -1
- package/web/assets/{chunk-75Z2AOVW-XWOFp1H_.js → chunk-75Z2AOVW-BRMKvs-_.js} +1 -1
- package/web/assets/{chunk-DU6HZSFF-DS4Nz4nA.js → chunk-DU6HZSFF-A-GuRJzV.js} +1 -1
- package/web/assets/{chunk-F27PBJKO-Dx_X9qdN.js → chunk-F27PBJKO-D34kNJfE.js} +1 -1
- package/web/assets/{chunk-GMAD6QVW-DxV6twrr.js → chunk-GMAD6QVW-CzLW6Gbl.js} +1 -1
- package/web/assets/{chunk-GVQU2GXP-MSIDLTHB.js → chunk-GVQU2GXP-CqTFATNd.js} +1 -1
- package/web/assets/{chunk-IMKFNOWR-CELsloet.js → chunk-IMKFNOWR-BLo_6uPl.js} +1 -1
- package/web/assets/{chunk-L3NEJ4N5-BZ3ozIZf.js → chunk-L3NEJ4N5-CFSYYra2.js} +1 -1
- package/web/assets/{chunk-OSK3NFVY-BXjogSMs.js → chunk-OSK3NFVY-DJ3F-6TB.js} +1 -1
- package/web/assets/{chunk-P2QGCYS3-DFcISUhA.js → chunk-P2QGCYS3-B3qbBF6d.js} +1 -1
- package/web/assets/{chunk-POPQ4Y6H-CMv8VcTR.js → chunk-POPQ4Y6H-DbN8xQ-f.js} +1 -1
- package/web/assets/{chunk-PWAF6VOD-Ck43wPZJ.js → chunk-PWAF6VOD-C7BBYtAa.js} +1 -1
- package/web/assets/{chunk-SHT3W25Y-Dd3YYPpo.js → chunk-SHT3W25Y-B3wT37BE.js} +1 -1
- package/web/assets/{chunk-SVP7TREG-1wHIX2u8.js → chunk-SVP7TREG-OXvICZat.js} +1 -1
- package/web/assets/{chunk-TICWLB2K-C2RL-jix.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-L3cCx0-a.js → cynefin-OW5HDTMX-BFhdG87z.js} +1 -1
- package/web/assets/{cynefinDiagram-5FMLGOSQ-B-p9_QH8.js → cynefinDiagram-5FMLGOSQ-BlBRhJR5.js} +1 -1
- package/web/assets/{dagre-GXQ25YYZ-CNcD81ab.js → dagre-GXQ25YYZ-COxHf3g-.js} +1 -1
- package/web/assets/{diagram-S7CK7UJ4-CLXtZ4aE.js → diagram-S7CK7UJ4-mWtNPBS9.js} +1 -1
- package/web/assets/{diagram-UQ7AKVKN-Bj1-misl.js → diagram-UQ7AKVKN-CAvoNcsc.js} +1 -1
- package/web/assets/{diagram-VSXAHHWV-BsncRf1X.js → diagram-VSXAHHWV-DA9LJqgE.js} +1 -1
- package/web/assets/{diagram-VX7I27RA-DgnUNiqR.js → diagram-VX7I27RA-7RswVDku.js} +1 -1
- package/web/assets/{diagram-Z3DM3KII-CYA1FOfJ.js → diagram-Z3DM3KII-DknRBMRd.js} +1 -1
- package/web/assets/{ebnfDiagram-PWID7BFC-EN37F-ZX.js → ebnfDiagram-PWID7BFC-hAmbemf1.js} +1 -1
- package/web/assets/{erDiagram-RLTQ6QDP-7khCs6R0.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-X2fCrUiA.js → ganttDiagram-EL5Y4UJY-BV-zpuyt.js} +1 -1
- package/web/assets/{gitGraph-4MIJSDKK-C1jg4oXv.js → gitGraph-4MIJSDKK-BfZe7_3E.js} +1 -1
- package/web/assets/{gitGraphDiagram-WWUBYQGX-aRlKIG1q.js → gitGraphDiagram-WWUBYQGX-3_hHUbBU.js} +1 -1
- package/web/assets/{index-Cik3irwJ.css → index-D36pVYmX.css} +1 -1
- package/web/assets/{index-BYhnjcv5.js → index-x_iImoSf.js} +2 -2
- package/web/assets/{info-A6RAGUB7-knTxGQzP.js → info-A6RAGUB7-DUWO2H1L.js} +1 -1
- package/web/assets/{infoDiagram-27XIBGKW-CZ5eWH_5.js → infoDiagram-27XIBGKW-BKxWRZYw.js} +1 -1
- package/web/assets/{ishikawaDiagram-5VMMS53U-BaN7oiXe.js → ishikawaDiagram-5VMMS53U-CxQdy8l3.js} +1 -1
- package/web/assets/{journeyDiagram-3NMN7TZE-DSKzoitB.js → journeyDiagram-3NMN7TZE-DplhU31X.js} +1 -1
- package/web/assets/{kanban-definition-UXKFOSKX-Do-Ybw2Z.js → kanban-definition-UXKFOSKX-Cmls5FZv.js} +1 -1
- package/web/assets/{line-CwAjwUaG.js → line-NoU3PhOc.js} +1 -1
- package/web/assets/{mermaid-parser.core-DgfSoRZF.js → mermaid-parser.core-CyOqjoOF.js} +3 -3
- package/web/assets/{mermaid.core-BmmLukUA.js → mermaid.core-BbpKlZWj.js} +4 -4
- package/web/assets/{mindmap-definition-YA3MSWOX-BvYA7HOJ.js → mindmap-definition-YA3MSWOX-CfDDhyG9.js} +1 -1
- package/web/assets/mount-GHVLdZcl.js +27 -0
- package/web/assets/{packet-AYTQ26CC-z5xJrrsj.js → packet-AYTQ26CC-CEyZqXlC.js} +1 -1
- package/web/assets/{pegDiagram-XKGWAZYB-Dlnf2qqP.js → pegDiagram-XKGWAZYB-BsQ551jM.js} +1 -1
- package/web/assets/{pie-WAS4IAKB-Bcc2ZLgF.js → pie-WAS4IAKB-Cy_8_ris.js} +1 -1
- package/web/assets/{pieDiagram-E7YTZNPT-DK6Bm2ct.js → pieDiagram-E7YTZNPT-DQHtyFkg.js} +1 -1
- package/web/assets/{quadrantDiagram-AXDQQJYC-CGdNrgH7.js → quadrantDiagram-AXDQQJYC-iSVEwT1y.js} +1 -1
- package/web/assets/{radar-RG4KPBEZ-DvDzdzlV.js → radar-RG4KPBEZ-BO-qdlYd.js} +1 -1
- package/web/assets/{railroad-74A4TZTK-DAk4jBzt.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-qghivQgJ.js → railroadDiagram-O6MQD6OU-Bmp5czol.js} +1 -1
- package/web/assets/{requirementDiagram-BXWQKSXE-BB2VHwAe.js → requirementDiagram-BXWQKSXE-CflpYj7d.js} +1 -1
- package/web/assets/{sankeyDiagram-P5KCCOFB-DYsK6FvP.js → sankeyDiagram-P5KCCOFB-D3xDfaLR.js} +1 -1
- package/web/assets/{sequenceDiagram-WJ2MYXX4-DN7_ECVu.js → sequenceDiagram-WJ2MYXX4-C6ZWIJwX.js} +1 -1
- package/web/assets/{settingsRoute-BryKVhsu.js → settingsRoute-COWp-9BH.js} +1 -1
- package/web/assets/{stateDiagram-D77RDMKH-CMoUI-nz.js → stateDiagram-D77RDMKH-BXjL8DPv.js} +1 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-BCGm337k.js +1 -0
- package/web/assets/{swimlanes-42K2YHIH-Dg9Ds-zo.js → swimlanes-42K2YHIH-CkyaLI3E.js} +1 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-RZPHF_4s.js +8 -0
- package/web/assets/{timeline-definition-24CTP7MA-B71AxnxY.js → timeline-definition-24CTP7MA-BdMWCl3_.js} +1 -1
- package/web/assets/{treeView-Q6P3EWNA-CcYDvc71.js → treeView-Q6P3EWNA-C4MMyFq1.js} +1 -1
- package/web/assets/{treemap-WGGIJYW6-COuLLLjA.js → treemap-WGGIJYW6-BUER7WW0.js} +1 -1
- package/web/assets/{useStore-CVAcdLfm.js → useStore-B5xeFBSp.js} +2 -2
- package/web/assets/{vennDiagram-4TSXK5OY-Dyg63v_c.js → vennDiagram-4TSXK5OY-CmcfuybF.js} +1 -1
- package/web/assets/{wardley-WFR3VGLG-FAnOXgo0.js → wardley-WFR3VGLG-CbuHqcZs.js} +1 -1
- package/web/assets/{wardleyDiagram-VM6X3IG4-fhlKAloZ.js → wardleyDiagram-VM6X3IG4-B-dD7NPY.js} +1 -1
- package/web/assets/{xychartDiagram-S5SC5T6Z-DbM80CJG.js → xychartDiagram-S5SC5T6Z-DkJf1OlB.js} +1 -1
- package/web/index.html +2 -2
- package/web/sw.js +1 -1
- package/web/assets/architecture-7GRP2DOG-BEJ5aLoK.js +0 -1
- package/web/assets/channel-BPXvQ5Jt.js +0 -1
- package/web/assets/classDiagram-ZZMXUADV-DicIinQk.js +0 -1
- package/web/assets/classDiagram-v2-VYDZK3BY-DicIinQk.js +0 -1
- package/web/assets/eventmodeling-NTZA5JFV-DPlKwCgg.js +0 -1
- package/web/assets/flowDiagram-HODETNUW-CuyexHJ1.js +0 -1
- package/web/assets/mount-YpsogRG1.js +0 -26
- package/web/assets/railroad-abnf-HS5TGJTU-BboXzbI7.js +0 -1
- package/web/assets/railroad-ebnf-LZEXJU2U-2aWLf6tt.js +0 -1
- package/web/assets/railroad-peg-WCYAUIDC-DkEFbMwn.js +0 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-DVVMJFff.js +0 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-CMp2P5bx.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-BYhnjcv5.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(`
|
|
@@ -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()}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};
|
|
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};
|