@bivy/bivy 0.20.8 → 0.20.9-staging.10
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/README.md +6 -5
- package/bin/bivy.mjs +13 -56
- package/bin/cli-commands.mjs +2 -4
- package/bin/guides/talk-to-the-user.md +13 -24
- package/dist/agent-instructions.js +4 -10
- package/dist/agents/pi/integration.js +1 -1
- package/dist/apps/styles.css +14 -47
- package/dist/certification/generated.js +1 -1
- package/dist/ephemeral-teardown.js +11 -1
- package/dist/exec.js +4 -1
- package/dist/server.js +10 -52
- package/dist/session/event-log.js +15 -18
- package/dist/session/inline-image-fetch.js +1 -3
- package/dist/session/session-tokens.js +1 -1
- package/package.json +6 -6
- package/web/assets/AutomationsView-CqKikjyc.js +51 -0
- package/web/assets/{ChangesCard-CPnPUh6N.js → ChangesCard-C6LeCjVH.js} +1 -1
- package/web/assets/{LibraryView-CbEXd0eI.js → LibraryView-BR9OMhze.js} +1 -1
- package/web/assets/{ProviderConnect-CoqAK5Wk.js → ProviderConnect-CKYP_-dW.js} +1 -1
- package/web/assets/Settings-D9myJbO-.js +10 -0
- package/web/assets/{Sheet-DDK1zw1r.js → Sheet-CL3dk1Sa.js} +1 -1
- package/web/assets/{Terminal-1RXw5d-8.js → Terminal-DuzTWmq_.js} +1 -1
- package/web/assets/{VoiceSettings-XKgK-rHp.js → VoiceSettings-C5xiXXg-.js} +1 -1
- package/web/assets/{abnfDiagram-VCTEODGH-mGY2XgpR.js → abnfDiagram-VCTEODGH-CiuYisMe.js} +1 -1
- package/web/assets/architecture-7GRP2DOG-CmGiKLJd.js +1 -0
- package/web/assets/{architectureDiagram-5GKGNRK7-iODllUCA.js → architectureDiagram-5GKGNRK7-DQEZKeJf.js} +1 -1
- package/web/assets/{blockDiagram-I7D4REHJ-Ge7J4mPm.js → blockDiagram-I7D4REHJ-BXifaI4s.js} +1 -1
- package/web/assets/{c4Diagram-7LVT6UL2-f-kX3zo7.js → c4Diagram-7LVT6UL2-BUI1_QJ6.js} +1 -1
- package/web/assets/channel-GfgWPXVn.js +1 -0
- package/web/assets/{chunk-4HAMMTFA-DgLlEu-R.js → chunk-4HAMMTFA-CAqAnSt0.js} +1 -1
- package/web/assets/{chunk-75Z2AOVW-Dml242zI.js → chunk-75Z2AOVW-CmAfksq6.js} +1 -1
- package/web/assets/{chunk-DU6HZSFF-DHGHAQj_.js → chunk-DU6HZSFF-CBn3E1kV.js} +1 -1
- package/web/assets/{chunk-F27PBJKO-DYJWgQwW.js → chunk-F27PBJKO-Cqca621p.js} +1 -1
- package/web/assets/{chunk-GMAD6QVW-Be6XrE8S.js → chunk-GMAD6QVW-DuNHDMjw.js} +1 -1
- package/web/assets/{chunk-GVQU2GXP-CrJtrbng.js → chunk-GVQU2GXP-DadmdXvU.js} +1 -1
- package/web/assets/{chunk-IMKFNOWR-BNoFxzwg.js → chunk-IMKFNOWR-D7xvXSnw.js} +1 -1
- package/web/assets/{chunk-L3NEJ4N5-8rFD5H7o.js → chunk-L3NEJ4N5-Drxtq2Z1.js} +1 -1
- package/web/assets/{chunk-OSK3NFVY-Df7-4Mnn.js → chunk-OSK3NFVY-UWX78yLv.js} +1 -1
- package/web/assets/{chunk-P2QGCYS3-rHBlhB9b.js → chunk-P2QGCYS3-D6hNBxaT.js} +1 -1
- package/web/assets/{chunk-POPQ4Y6H-TtIAtZss.js → chunk-POPQ4Y6H-CmUjfAOD.js} +1 -1
- package/web/assets/{chunk-PWAF6VOD-CkwX1I_u.js → chunk-PWAF6VOD-CTJIWOj-.js} +1 -1
- package/web/assets/{chunk-SHT3W25Y-QK-L20Uq.js → chunk-SHT3W25Y-CIPO0-2c.js} +1 -1
- package/web/assets/{chunk-SVP7TREG-r_Z2GtSi.js → chunk-SVP7TREG-DkeeA16U.js} +1 -1
- package/web/assets/{chunk-TICWLB2K-CUKfLR5q.js → chunk-TICWLB2K-CCCgUMTk.js} +1 -1
- package/web/assets/classDiagram-ZZMXUADV-AnSFdiZo.js +1 -0
- package/web/assets/classDiagram-v2-VYDZK3BY-AnSFdiZo.js +1 -0
- package/web/assets/{cynefin-OW5HDTMX-Dt3Y2U_d.js → cynefin-OW5HDTMX-lsnbNwYx.js} +1 -1
- package/web/assets/{cynefinDiagram-5FMLGOSQ-Y5k7qfOG.js → cynefinDiagram-5FMLGOSQ-CmT6IHRO.js} +1 -1
- package/web/assets/{dagre-GXQ25YYZ-D6uSyP7i.js → dagre-GXQ25YYZ-CaVNKxQq.js} +1 -1
- package/web/assets/{diagram-S7CK7UJ4-cy3iJG3K.js → diagram-S7CK7UJ4-DOPXiiOU.js} +1 -1
- package/web/assets/{diagram-UQ7AKVKN-D-Dujcue.js → diagram-UQ7AKVKN-Bxe6jYPE.js} +1 -1
- package/web/assets/{diagram-VSXAHHWV-BmI9Opjx.js → diagram-VSXAHHWV-D2IPWUER.js} +1 -1
- package/web/assets/{diagram-VX7I27RA-Ca81_y4A.js → diagram-VX7I27RA-DPA8OR7z.js} +1 -1
- package/web/assets/{diagram-Z3DM3KII-BBMq_KK4.js → diagram-Z3DM3KII-qlgZN9mg.js} +1 -1
- package/web/assets/{ebnfDiagram-PWID7BFC-Bc-yp1-u.js → ebnfDiagram-PWID7BFC-BG3oYfMg.js} +1 -1
- package/web/assets/{erDiagram-RLTQ6QDP-C4not1_u.js → erDiagram-RLTQ6QDP-39wsY2SV.js} +1 -1
- package/web/assets/eventmodeling-NTZA5JFV-COSR-_D4.js +1 -0
- package/web/assets/flowDiagram-HODETNUW-Bv4slDx7.js +1 -0
- package/web/assets/{ganttDiagram-EL5Y4UJY-eOqP4w8u.js → ganttDiagram-EL5Y4UJY-9m79cMnC.js} +1 -1
- package/web/assets/{gitGraph-4MIJSDKK-CNyrdfwo.js → gitGraph-4MIJSDKK-B5lfxsxx.js} +1 -1
- package/web/assets/{gitGraphDiagram-WWUBYQGX-DWlo-lrH.js → gitGraphDiagram-WWUBYQGX-DWl1V9gk.js} +1 -1
- package/web/assets/{index-C1fVIjSt.js → index-DKaLVMgX.js} +2 -2
- package/web/assets/index-DZb12uRj.css +1 -0
- package/web/assets/{info-A6RAGUB7-CUQ_micy.js → info-A6RAGUB7-CVPplCTQ.js} +1 -1
- package/web/assets/{infoDiagram-27XIBGKW-BGpJ5FNT.js → infoDiagram-27XIBGKW-B-yaJrP2.js} +1 -1
- package/web/assets/{ishikawaDiagram-5VMMS53U-BPHiUQm6.js → ishikawaDiagram-5VMMS53U-DtJ480L8.js} +1 -1
- package/web/assets/{journeyDiagram-3NMN7TZE-B4LBaWaP.js → journeyDiagram-3NMN7TZE-CsvTgPXC.js} +1 -1
- package/web/assets/{kanban-definition-UXKFOSKX-DNVvNHrT.js → kanban-definition-UXKFOSKX-CqTcD1hf.js} +1 -1
- package/web/assets/{line-DEBH51YO.js → line-D2guJ01j.js} +1 -1
- package/web/assets/{mermaid-parser.core-DKGY5TTe.js → mermaid-parser.core-NJMkrhfu.js} +3 -3
- package/web/assets/{mermaid.core-SY5t-W54.js → mermaid.core-D-4da6CZ.js} +4 -4
- package/web/assets/{mindmap-definition-YA3MSWOX-DNzu0vrE.js → mindmap-definition-YA3MSWOX-CsHyNaAw.js} +1 -1
- package/web/assets/mount-DAtUokCH.js +31 -0
- package/web/assets/{packet-AYTQ26CC-BFmJxIPS.js → packet-AYTQ26CC-CXMWsuib.js} +1 -1
- package/web/assets/{pegDiagram-XKGWAZYB-Cg4XSQXq.js → pegDiagram-XKGWAZYB-ByQqRbph.js} +1 -1
- package/web/assets/{pie-WAS4IAKB-BjugvaCZ.js → pie-WAS4IAKB-eRy6tqdo.js} +1 -1
- package/web/assets/{pieDiagram-E7YTZNPT-CZUoS4VP.js → pieDiagram-E7YTZNPT-D9CMUNwI.js} +1 -1
- package/web/assets/{quadrantDiagram-AXDQQJYC-Dt2ha5S3.js → quadrantDiagram-AXDQQJYC-BqrSq-tU.js} +1 -1
- package/web/assets/{radar-RG4KPBEZ-wvkY1jFj.js → radar-RG4KPBEZ-BASdVQAe.js} +1 -1
- package/web/assets/{railroad-74A4TZTK-C0urSGwW.js → railroad-74A4TZTK-MbyNUFW2.js} +1 -1
- package/web/assets/railroad-abnf-HS5TGJTU-DzZc8bRA.js +1 -0
- package/web/assets/railroad-ebnf-LZEXJU2U-d86-7YjJ.js +1 -0
- package/web/assets/railroad-peg-WCYAUIDC-yBlZPQK8.js +1 -0
- package/web/assets/{railroadDiagram-O6MQD6OU-CMPDMFEF.js → railroadDiagram-O6MQD6OU-CPhS-1_c.js} +1 -1
- package/web/assets/{requirementDiagram-BXWQKSXE-CgG1fTgc.js → requirementDiagram-BXWQKSXE-CtX1iQsg.js} +1 -1
- package/web/assets/{sankeyDiagram-P5KCCOFB-CqQc0C6b.js → sankeyDiagram-P5KCCOFB-BBSZVi3s.js} +1 -1
- package/web/assets/{sequenceDiagram-WJ2MYXX4-CCar7eyP.js → sequenceDiagram-WJ2MYXX4-Zwj2R6Ua.js} +1 -1
- package/web/assets/{settingsRoute-D75Kl5qJ.js → settingsRoute-DYF97n3g.js} +1 -1
- package/web/assets/{stateDiagram-D77RDMKH-hZdV5Olo.js → stateDiagram-D77RDMKH-DTB9F1f2.js} +1 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-BlWD3kYd.js +1 -0
- package/web/assets/{swimlanes-42K2YHIH-BOjTGDck.js → swimlanes-42K2YHIH-Bf5m1Adz.js} +1 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-B4wYjUsJ.js +8 -0
- package/web/assets/{timeline-definition-24CTP7MA-EQ9J2i8-.js → timeline-definition-24CTP7MA-CehYDFxs.js} +1 -1
- package/web/assets/{treeView-Q6P3EWNA-C_5CbmSf.js → treeView-Q6P3EWNA-CQmjQcQJ.js} +1 -1
- package/web/assets/{treemap-WGGIJYW6-C37qSFRc.js → treemap-WGGIJYW6-DMV5jymC.js} +1 -1
- package/web/assets/useStore-DrZiS5P_.js +22 -0
- package/web/assets/{vennDiagram-4TSXK5OY-Dz_rYEly.js → vennDiagram-4TSXK5OY-CJGwwuUA.js} +1 -1
- package/web/assets/{wardley-WFR3VGLG-ByC5Xl0N.js → wardley-WFR3VGLG-S6KEgq1P.js} +1 -1
- package/web/assets/{wardleyDiagram-VM6X3IG4-ZORHthei.js → wardleyDiagram-VM6X3IG4-B1eaMBr1.js} +1 -1
- package/web/assets/{xychartDiagram-S5SC5T6Z-BsEewrR8.js → xychartDiagram-S5SC5T6Z-C5emgjT-.js} +1 -1
- package/web/index.html +2 -2
- package/web/sw.js +1 -1
- package/dist/ephemeral-exec.js +0 -108
- package/dist/session/suggestions.js +0 -17
- package/web/assets/AutomationsView-CI8mce5b.js +0 -51
- package/web/assets/Settings-DzwwvcJY.js +0 -10
- package/web/assets/architecture-7GRP2DOG-iTGIo6ed.js +0 -1
- package/web/assets/channel-CZ9L6iYi.js +0 -1
- package/web/assets/classDiagram-ZZMXUADV-D_pQOsdw.js +0 -1
- package/web/assets/classDiagram-v2-VYDZK3BY-D_pQOsdw.js +0 -1
- package/web/assets/eventmodeling-NTZA5JFV-kTJMsPPZ.js +0 -1
- package/web/assets/flowDiagram-HODETNUW-BKXsEnEc.js +0 -1
- package/web/assets/index-D76QD5dl.css +0 -1
- package/web/assets/mount-BAMZ2poC.js +0 -33
- package/web/assets/railroad-abnf-HS5TGJTU-D3fB8KBr.js +0 -1
- package/web/assets/railroad-ebnf-LZEXJU2U-DxtPt5hF.js +0 -1
- package/web/assets/railroad-peg-WCYAUIDC-DSr1P8IJ.js +0 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-DSUfNYnq.js +0 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-6bUIqkAR.js +0 -8
- package/web/assets/useStore-BjrbW265.js +0 -29
|
@@ -0,0 +1,22 @@
|
|
|
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-DKaLVMgX.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
|
+
`))}</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
|
+
`))}</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
|
+
`).split(`
|
|
5
|
+
`)).html;if(_e.set(t,r),_e.size>ve){let e=_e.keys().next().value;e!==void 0&&_e.delete(e)}return r}function be(e){return String(e||``).trim().toLowerCase().replace(/[.\-\s]+/g,`_`)}function xe(e){let t=be(e?.type||e?.event||e?.kind||e?.assistantMessageEvent?.type);return t?/^(tool|function)_(call|use|start|execution_start|call_start|use_start)$/.test(t)?`start`:/^(tool|function)_(result|end|execution_end|call_end|use_end)$/.test(t)?`result`:/^(tool|function)_(update|progress|execution_update|delta)$/.test(t)?`update`:t:``}function Se(e){return be(e?.type||e?.kind||e?.name)}function Ce(e){let t=Se(e);return t?t===`tool`||t===`tool_use`||t===`toolcall`||t===`tool_call`||t===`function_call`||t.endsWith(`_tool_use`)||t.endsWith(`_tool_call`):!1}function we(e){let t=Se(e);return t?t===`tool_result`||t===`toolresult`||t===`function_result`||t.endsWith(`_tool_result`)||t.endsWith(`_function_result`):!1}function Te(e){return String(e?.toolName||e?.name||e?.tool?.name||e?.tool||e?.function?.name||e?.toolCall?.name||e?.call?.name||`tool`).toLowerCase()}function Ee(e){return e?.input||e?.toolInput||e?.args||e?.arguments||e?.parameters||e?.function?.arguments||e?.toolCall?.arguments||e?.toolCall?.input||e?.call?.input||{}}var De=new Set([`shell`,`read`,`write`,`edit`,`search`,`fetch`,`plan`,`delegation`]);function j(e){let t=e?.detail;if(t&&typeof t==`object`&&typeof t.kind==`string`&&De.has(t.kind))return t}function Oe(e){return e?.toolCallId||e?.toolUseId||e?.tool_use_id||e?.callId||e?.id||e?.toolCall?.id||e?.call?.id||e?.function?.id||``}function ke(e){return String(e?.parentToolUseId||e?.parent_tool_use_id||e?.parentToolCallId||e?.parentCallId||``)}var M={running:{kind:`running`,label:`Running`,tone:`neutral`,terminal:!1,reviewable:!1},waiting:{kind:`waiting`,label:`Waiting`,tone:`neutral`,terminal:!1,reviewable:!1},pr_open:{kind:`pr_open`,label:`PR open`,tone:`success`,terminal:!0,reviewable:!0},changes_ready:{kind:`changes_ready`,label:`Changes ready`,tone:`success`,terminal:!0,reviewable:!0},checks_failed:{kind:`checks_failed`,label:`Checks failed`,tone:`danger`,terminal:!0,reviewable:!0},needs_review:{kind:`needs_review`,label:`Needs review`,tone:`warning`,terminal:!0,reviewable:!0},no_changes:{kind:`no_changes`,label:`No changes`,tone:`neutral`,terminal:!0,reviewable:!1},agent_failed:{kind:`agent_failed`,label:`Agent failed`,tone:`danger`,terminal:!0,reviewable:!0},timed_out:{kind:`timed_out`,label:`Timed out`,tone:`danger`,terminal:!0,reviewable:!0},cancelled:{kind:`cancelled`,label:`Cancelled`,tone:`neutral`,terminal:!0,reviewable:!1}};function Ae(e){if(e.status===`cancelled`)return M.cancelled;if(e.checks?.some(e=>e.status===`failed`))return M.checks_failed;let t=e.output?.failure?.toLowerCase()??``;if(e.status===`failed`)return/timed?\s*out/.test(t)?M.timed_out:M.agent_failed;if(e.status===`needs_attention`)return M.needs_review;let n=e.status===`pending`||e.status===`claimed`||e.status===`running`,r=e.events??[],i=r[r.length-1];return e.status===`waiting`||n&&i?.kind===`rate_limited`?M.waiting:n?M.running:e.output?.prUrl?M.pr_open:e.output?.branch||e.output?.commit||e.output?.checkpoint||e.output?.artifactUrl?M.changes_ready:(e.events??[]).map(e=>e.summary.toLowerCase()).some(e=>e.includes(`no file changes`)||e.includes(`no changes`))?M.no_changes:M.needs_review}function je(e){let t=String(e??``).trim();if(/^WebSocket closed 1006\b/i.test(t))return`The agent/provider connection dropped unexpectedly (WebSocket 1006). Bivy will keep the session; retry your message or continue from the latest saved state.`;let n=t.indexOf(`{`);if(n>=0)try{let e=JSON.parse(t.slice(n)),r=e.error,i=typeof r==`object`&&r&&typeof r.message==`string`&&r.message||typeof e.message==`string`&&e.message||typeof r==`string`&&r||``;if(i&&i.trim())return i.trim()}catch{}return t}function Me(e){let t=String(e??``).trim();return t?/^Failed to authenticate\b/i.test(t)||/^API Error:\s*\d{3}\b/i.test(t)||/^WebSocket closed 1006\b/i.test(t):!1}function Ne(e){let t=String(e??``);return t.trim()?/\b401\b|\b403\b|unauthori[sz]ed|authenticat|oauth|subscription|invalid x-api-key|(missing|no|expired|invalid)[\s\S]*(bearer|api[\s_-]?key|token|credential)/i.test(t):!1}var Pe=[[`codex`,`openai-codex`],[`claude`,`anthropic`],[`grok`,`xai`],[`gemini`,`google`]];function Fe(e,t){let n=String(e??``).trim().toLowerCase(),r=Pe.find(([e])=>n.startsWith(e));return r?r[1]:String(t??``).trim().toLowerCase()||void 0}var Ie=240,Le=50,Re=new Set([`pending`,`claimed`,`running`]),ze=new Set([`succeeded`,`failed`,`cancelled`,`done`]),Be=new Set([`pending`,`claimed`,`running`,`waiting`,`needs_attention`]),Ve=new Set([`checks_failed`,`needs_review`,`agent_failed`,`timed_out`]);function He(e){return e===`waiting`?`waiting`:e===`needs_attention`?`needs_attention`:Re.has(e)?e===`running`?`running`:`queued`:ze.has(e)?`finished`:`queued`}function Ue(e){return e.repo?`${e.repo}${Number.isInteger(e.issueNumber)?`#${e.issueNumber}`:``}`:e.externalId||e.url||void 0}function We(e){let t=e.startedAt??e.claimedAt;if(!t||!e.completedAt)return;let n=Date.parse(e.completedAt)-Date.parse(t);return Number.isFinite(n)&&n>=0?n:void 0}function Ge(e,t){if(t&&Ne(t))return Fe(e)}var Ke=new Set([`trigger_received`,`trigger_matched`,`queued`,`routed`,`provisioning`,`claimed`,`agent_started`,`checks_started`,`checks_completed`,`result_delivery`,`notification`,`retry`,`cancel_requested`,`terminal`]),qe={triggered:`trigger_received`,attempt_started:`agent_started`,completed:`terminal`,cancelled:`terminal`};function Je(e){let t=(e.events??[]).flatMap(e=>{let t=Ke.has(e.kind)?e.kind:qe[e.kind];return!t||!e.at?[]:[{stage:t,at:e.at,summary:e.summary,attempt:e.attempt,reasonCode:e.reasonCode,evidenceRef:e.evidenceRef,status:e.status}]}),n=e=>t.some(t=>t.stage===e);return!n(`trigger_received`)&&e.createdAt&&t.unshift({stage:`trigger_received`,at:e.createdAt,summary:`Run record created.`}),!n(`claimed`)&&e.claimedAt&&t.push({stage:`claimed`,at:e.claimedAt,summary:`Run claimed.`}),!n(`agent_started`)&&e.startedAt&&t.push({stage:`agent_started`,at:e.startedAt,summary:`Agent execution started.`}),!n(`terminal`)&&e.completedAt&&t.push({stage:`terminal`,at:e.completedAt,summary:`Run reached the ${e.status} outcome.`}),t.slice(-200)}function Ye(e){return e.status===`needs_attention`||e.status===`waiting`?`parked`:e.status===`failed`?`dead_letter`:e.status===`succeeded`||e.status===`cancelled`||e.status===`done`?`terminal`:`active`}function Xe(e,t,n){let r=[],i=Math.max(1,Math.trunc(e.attempt??1)),a=t.kind===`agent_failed`?Ge(e.runtimeId,e.output?.failure):void 0;t.kind===`checks_failed`&&e.checks?.some(e=>e.status===`failed`)&&r.push({kind:`inspect_checks`,label:`Review failed checks`}),a&&r.push({kind:`reauthenticate`,label:`Re-authenticate`,provider:a}),t.kind===`needs_review`&&n&&r.push({kind:`review_session`,label:`Review Session`}),Be.has(e.status)&&r.push({kind:`cancel`,label:`Cancel Run`});let o=e.events?.some(e=>e.kind===`policy_denial`);return(ze.has(e.status)&&Ve.has(t.kind)||e.status===`needs_attention`&&o)&&(!e.maxAttempts||i<e.maxAttempts)&&r.push({kind:`retry`,label:`Retry Run`}),r}function Ze(e,t,n){let r=Ae(e),i={createdAt:e.createdAt,...e.claimedAt?{claimedAt:e.claimedAt}:{},...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{},...e.leaseExpiresAt?{leaseExpiresAt:e.leaseExpiresAt}:{}},a=e.output?.sessionId||e.targetSessionId||void 0,o=e.claimedByNodeId,s=e.output?.failure,c={...e.output?.branch?{branch:e.output.branch}:{},...e.output?.commit?{commit:e.output.commit}:{},...e.output?.prUrl?{pullRequest:e.output.prUrl}:{},...e.output?.checkpoint?{checkpoint:e.output.checkpoint}:{},...e.output?.artifactUrl?{artifact:e.output.artifactUrl}:{}},l=Xe(e,r,a),u=Je(e),d=[...e.events??[]].reverse().find(e=>e.kind===`fallback`||e.kind===`retry`)?.summary??e.routingReason;return{id:e.id,origin:{projection:t,status:e.status},lifecycle:He(e.status),outcome:r,attempt:Math.max(1,Math.trunc(e.attempt??1)),...e.maxAttempts?{maxAttempts:e.maxAttempts}:{},title:e.title,source:{kind:e.source||e.triggerKind||`manual`,...Ue(e)?{reference:Ue(e)}:{},...e.definitionId?{automationId:e.definitionId}:{}},...a?{sessionId:a}:{},...o?{machine:{id:o,...n?.resolveMachineName?.(o)?{name:n.resolveMachineName(o)}:{}}}:{},timestamps:i,...We(i)===void 0?{}:{durationMs:We(i)},requested:{...e.approvalMode?{approvalMode:e.approvalMode}:{},...e.sandbox?{sandbox:e.sandbox}:{},...e.runtimeId?{runtimeId:e.runtimeId}:{},...e.model?{model:e.model}:{}},checks:(e.checks??[]).slice(0,Le),events:(e.events??[]).slice(-200),...e.receiptEvidence?{receiptEvidence:e.receiptEvidence}:{},references:c,...s?{failureSummary:s.slice(0,Ie)}:{},timeline:u,operationalState:Ye(e),...d?{attemptReason:d}:{},...e.usage?{usage:e.usage}:{},...e.notification?{notification:e.notification}:{},operationalReferences:(e.references??[]).slice(-20),...e.attention?{attention:e.attention}:{},actions:l,...l[0]?{nextAction:l[0]}:{}}}function Qe(e,t){return Ze(e,`automation_run`,t)}function $e(e){return`/runs/${encodeURIComponent(e)}`}function et(e){let t=String(e||``).trim();if(!t)return null;try{t=new URL(t).pathname}catch{let e=Math.min(...[`?`,`#`].map(e=>t.indexOf(e)).filter(e=>e>=0),t.length);t=t.slice(0,e)}let n=/^\/runs\/([^/]+)\/?$/.exec(t);if(!n||!n[1])return null;try{return decodeURIComponent(n[1])||null}catch{return null}}var tt=[{id:`account_signed_in`,label:`Signed in`,signal:e=>e.accountSignedIn,passed:`You're signed in.`,checking:`Checking your sign-in…`,failed:`You're not signed in yet.`,remediation:{kind:`sign_in`,label:`Sign in`}},{id:`machine_online`,label:`Machine online`,signal:e=>e.machineOnline,passed:`Your Machine is connected.`,checking:`Waiting for your Machine to come online…`,failed:`Your Machine isn't reachable yet.`,remediation:{kind:`connect_machine`,label:`Connect a Machine`}},{id:`agent_installed`,label:`Supported agent`,signal:e=>e.agentInstalled,passed:`A certified agent's capability is verified.`,checking:`Verifying a supported agent's capability…`,failed:`No certified, supported agent was found on the Machine.`,remediation:{kind:`install_agent`,label:`Install the agent`}},{id:`credential_valid`,label:`Credential valid`,signal:e=>e.credentialValid,passed:`The model credential is valid.`,checking:`Validating the model credential…`,failed:`The model credential is missing or invalid.`,remediation:{kind:`authenticate_credential`,label:`Authenticate`}},{id:`repository_ready`,label:`Workspace ready`,signal:e=>e.repositoryReady,passed:`Your workspace is ready on the Machine.`,checking:`Checking your workspace…`,failed:`The workspace isn't available to the agent.`,remediation:{kind:`grant_repository`,label:`Grant repository access`}}];function nt(e){let t=[],n,r=!1;for(let i of tt){if(n||r){t.push({id:i.id,label:i.label,state:`pending`});continue}let a=i.signal(e);a===!0?t.push({id:i.id,label:i.label,state:`passed`,detail:i.passed}):a===!1?(n=i.id,t.push({id:i.id,label:i.label,state:`failed`,detail:i.failed,remediation:i.remediation})):(r=!0,t.push({id:i.id,label:i.label,state:`checking`,detail:i.checking}))}let i=t[t.length-1]?.state===`passed`,a=t.some(e=>e.state===`passed`),o=i?`activated`:n?`blocked`:a?`in_progress`:`not_started`,s;if(!i){let e=t.find(e=>e.state===`failed`)??t.find(e=>e.state===`checking`),n=e?tt.find(t=>t.id===e.id):void 0;e&&n&&(s={...n.remediation,checkId:e.id})}return{checks:t,stage:o,activated:i,...n?{blockingCheckId:n}:{},...s?{nextAction:s}:{}}}function rt(e){let t=e.direct?!0:e.signedIn,n=e.status===`online`||e.status!==`offline`&&void 0,r=e.runtimes.length?e.runtimes.some(e=>String(e.status??`available`)===`available`&&e.supportTier===`supported`):void 0,i=e.readiness?.credential.ok,a=e.readiness?.repository.ok;return nt({accountSignedIn:t,machineOnline:n,agentInstalled:r,credentialValid:i,repositoryReady:a})}var N=(e,t)=>({kind:`api_key`,label:e,...t?{helpUrl:t}:{}}),it=(e,t)=>({kind:`oauth`,label:e,...t?{oauthProviderId:t}:{}}),P={kind:`reference`,label:`Password manager or environment`},at=[{id:`anthropic`,name:`Anthropic`,authMethods:[it(`Claude Pro / Max`,`anthropic`),N(`Anthropic API key`,`https://console.anthropic.com/settings/keys`),P],env:[`ANTHROPIC_API_KEY`,`CLAUDE_CODE_OAUTH_TOKEN`],compatibility:`anthropic`,helpUrl:`https://docs.anthropic.com/`,models:[{id:`claude-opus-4-8`,name:`Claude Opus 4.8`,reasoning:!0},{id:`claude-opus-4-1`,name:`Claude Opus 4.1`,reasoning:!0},{id:`claude-sonnet-4-5`,name:`Claude Sonnet 4.5`,reasoning:!0},{id:`claude-haiku-4-5-20251001`,name:`Claude Haiku 4.5`}]},{id:`openai`,name:`OpenAI API`,aliases:[`openai-api`],authMethods:[N(`OpenAI API key`,`https://platform.openai.com/api-keys`),P],env:[`OPENAI_API_KEY`],compatibility:`openai`,helpUrl:`https://platform.openai.com/docs/`,models:[{id:`gpt-5.4`,name:`GPT-5.4`,reasoning:!0},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,reasoning:!0},{id:`gpt-4o`,name:`GPT-4o`}]},{id:`openai-codex`,name:`OpenAI — ChatGPT subscription`,aliases:[`codex`],authMethods:[it(`ChatGPT Plus / Pro`,`openai-codex`)],compatibility:`openai`,models:[{id:`gpt-5.6-sol`,name:`GPT-5.6 Sol`,reasoning:!0},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,reasoning:!0},{id:`gpt-5-codex`,name:`GPT-5 Codex`,reasoning:!0}]},{id:`google`,name:`Google Gemini`,aliases:[`gemini`],authMethods:[N(`Gemini API key`,`https://aistudio.google.com/app/apikey`),P],env:[`GEMINI_API_KEY`,`GOOGLE_API_KEY`],compatibility:`google`,helpUrl:`https://ai.google.dev/gemini-api/docs`,models:[{id:`gemini-2.5-pro`,name:`Gemini 2.5 Pro`,reasoning:!0},{id:`gemini-2.5-flash`,name:`Gemini 2.5 Flash`,reasoning:!0}]},{id:`xai`,name:`xAI`,authMethods:[it(`Grok / X subscription`,`xai`),N(`xAI API key`,`https://console.x.ai`),P],env:[`XAI_API_KEY`,`GROK_API_KEY`],compatibility:`openai`,models:[]},{id:`openrouter`,name:`OpenRouter`,authMethods:[N(`OpenRouter API key`,`https://openrouter.ai/keys`),P],env:[`OPENROUTER_API_KEY`],compatibility:`openai`,models:[]},{id:`groq`,name:`Groq`,authMethods:[N(`Groq API key`,`https://console.groq.com/keys`),P],env:[`GROQ_API_KEY`],compatibility:`openai`,models:[]},{id:`mistral`,name:`Mistral`,authMethods:[N(`Mistral API key`,`https://console.mistral.ai/api-keys`),P],env:[`MISTRAL_API_KEY`],compatibility:`openai`,models:[]},{id:`deepseek`,name:`DeepSeek`,authMethods:[N(`DeepSeek API key`,`https://platform.deepseek.com/api_keys`),P],env:[`DEEPSEEK_API_KEY`],compatibility:`openai`,models:[]},{id:`together`,name:`Together AI`,authMethods:[N(`Together API key`,`https://api.together.ai/settings/api-keys`),P],env:[`TOGETHER_API_KEY`],compatibility:`openai`,models:[]},{id:`fireworks`,name:`Fireworks AI`,authMethods:[N(`Fireworks API key`,`https://fireworks.ai/account/api-keys`),P],env:[`FIREWORKS_API_KEY`],compatibility:`openai`,models:[]},{id:`cohere`,name:`Cohere`,authMethods:[N(`Cohere API key`,`https://dashboard.cohere.com/api-keys`),P],env:[`COHERE_API_KEY`],models:[]},{id:`perplexity`,name:`Perplexity`,authMethods:[N(`Perplexity API key`,`https://www.perplexity.ai/settings/api`),P],env:[`PERPLEXITY_API_KEY`],compatibility:`openai`,models:[]}];at.filter(e=>e.authMethods.some(e=>e.kind===`api_key`)).map(e=>e.id);var ot=new Map;for(let e of at){ot.set(e.id,e);for(let t of e.aliases??[])ot.set(t,e)}function st(e){return ot.get(String(e||``).trim().toLowerCase())}function ct(e,t=[]){let n=new Set(e.map(e=>st(e)?.id??e)),r=new Map;for(let e of at)if(n.has(e.id))for(let t of e.models)r.set(`${e.id}\0${t.id}`,{...t,label:t.name,provider:e.id,configured:!0});for(let e of t){let t=String(e.provider??``);n.has(st(t)?.id??t)&&e.id&&e.id!==`unknown`&&e.modelCount==null&&r.set(`${t}\0${e.id}`,{...e,configured:!0,current:!1})}return[...r.values()]}function lt(e,t,n){return t.some(t=>t.provider===e.provider)?`Your saved model isn't available on this machine. Choose another model.`:n?`Your saved model isn't available on this machine — its ${e.provider} credential didn't reach Bivy Cloud. Check its unattended-runs grant in Settings → Models & keys (with a machine online), then refresh, or choose another model.`:`Your saved model isn't available on this machine — no ${e.provider} credential is connected here. Connect ${e.provider} on this machine, then refresh, or choose another model.`}var ut=`session-contract.v1`,dt={agent_version_unknown:`The running agent's build/version was not reported; capability guarantees fall back to the pinned default.`,execution_mode_unstructured:`The agent is driven over a raw text pipe, not a structured message/event stream — tool-call and turn boundaries are inferred, not reported.`,execution_mode_unknown:`The session's communication mode has not been resolved yet.`,auth_unknown:`The credential kind backing this session was not identified.`,auth_unconfigured:`No credential is configured for this provider.`,resume_unsupported:`This agent cannot resume a persisted session; a stopped session restarts from a seeded continuation instead.`,tool_interception_unavailable:`Tool calls are not intercepted by Bivy's approval gate; the agent runs unmoderated.`,tool_interception_mcp_only:`Only this agent's MCP tool calls are gated by Bivy's approval flow — its built-in tools are not.`,sandbox_unavailable:`No sandbox or tool-control enforcement was observed; the agent runs with the OS user's full permissions.`,sandbox_observed_only:`Containment relies on Bivy's own tool controls rather than the agent's native sandbox — observed, not independently enforced.`};function F(e,t){return{area:e,code:t,message:dt[t]??t}}var ft=new Set([`auth`,`resume`,`toolInterception`,`sandbox`]);function pt(e){let t=[],n=e.detectedVersion?e.versionSource??`reported`:`unknown`;n===`unknown`&&t.push(F(`agent`,`agent_version_unknown`));let r={id:e.agentId,...e.agentDisplayName?{displayName:e.agentDisplayName}:{},...e.detectedVersion?{detectedVersion:e.detectedVersion}:{},versionSource:n},i=e.executionMode??`unknown`,a=i===`protocol`||i===`structured-pipe`,o=i===`unknown`?`unavailable`:a?`guaranteed`:`degraded`;o===`degraded`&&t.push(F(`executionMode`,`execution_mode_unstructured`)),o===`unavailable`&&t.push(F(`executionMode`,`execution_mode_unknown`));let s={effective:i,structuredStreaming:a,state:o},c={...e.provider?{provider:e.provider}:{},...e.modelId?{modelId:e.modelId}:{},configured:e.modelConfigured??!1},l=e.authKind??`unknown`,u=l===`unknown`||l===`none`?`unavailable`:`guaranteed`;l===`unknown`&&t.push(F(`auth`,`auth_unknown`)),l===`none`&&t.push(F(`auth`,`auth_unconfigured`));let d={kind:l,origin:e.authOrigin??`unknown`,state:u},f=e.resumeAdvertised??!1,p=f?`guaranteed`:`unavailable`;f||t.push(F(`resume`,`resume_unsupported`));let m={advertised:f,refIsPath:e.resumeRefIsPath??!1,state:p},h=e.toolInterceptionEnforced??!1,g=!h&&!!e.mcpToolApprovalsOnly,_=h?`guaranteed`:g?`degraded`:`unavailable`;_===`degraded`&&t.push(F(`toolInterception`,`tool_interception_mcp_only`)),_===`unavailable`&&t.push(F(`toolInterception`,`tool_interception_unavailable`));let v={enforced:h,mcpOnly:g,...e.approvalMode?{approvalMode:e.approvalMode}:{},state:_},y=e.runtimeEnforcement??`none`,b=y===`native-sandbox`?`enforced`:y===`tool-controls`?`observed`:`unavailable`,x=b===`enforced`?`guaranteed`:b===`observed`?`degraded`:`unavailable`;x===`degraded`&&t.push(F(`sandbox`,`sandbox_observed_only`)),x===`unavailable`&&t.push(F(`sandbox`,`sandbox_unavailable`));let S={...e.sandboxTier?{tier:e.sandboxTier}:{},runtimeEnforcement:y,evidenceClass:b,state:x},C=e.supportTier??`experimental`,w=t.some(e=>ft.has(e.area)),T=e.certification===`release-tested`&&w&&!e.acknowledgedAt;return{schemaVersion:ut,resolvedAt:e.now,preview:e.preview,supportTier:C,certification:e.certification??`unverified`,agent:r,executionMode:s,model:c,auth:d,resume:m,toolInterception:v,sandbox:S,degradedReasons:t,requiresAcknowledgement:T,...e.acknowledgedAt?{acknowledgedAt:e.acknowledgedAt}:{}}}function mt(e){let t=String(e||``).trim().replace(/^#/,``);if(!t)return null;let n=t.replace(/-/g,`+`).replace(/_/g,`/`)+`=`.repeat((4-t.length%4)%4);return JSON.parse(atob(n))}function ht(e){let t=String(e||``).trim();if(!t)return null;try{t=new URL(t).hash.replace(/^#/,``)||t}catch{}return mt(t)}function I(e,t,n){try{return JSON.parse(e.getItem(t)||JSON.stringify(n))}catch{return n}}function gt(e,t){let n=t??(()=>{try{return globalThis.sessionStorage||e}catch{return e}})();return{get s(){return e.getItem(`bivy_session`)||``},set s(t){e.setItem(`bivy_session`,t)},get cp(){return e.getItem(`bivy_cp`)||``},set cp(t){e.setItem(`bivy_cp`,t)},get relay(){return e.getItem(`bivy_relay`)||``},set relay(t){e.setItem(`bivy_relay`,t)},get cur(){return e.getItem(`bivy_current`)||``},set cur(t){e.setItem(`bivy_current`,t)},keys(){return I(e,`bivy_keys`,{})},addKey(t,n){let r=this.keys();r[t]=n,e.setItem(`bivy_keys`,JSON.stringify(r))},nodePubs(){return I(e,`bivy_nodepubs`,{})},addNodePub(t,n){let r=this.nodePubs();r[t]=n,e.setItem(`bivy_nodepubs`,JSON.stringify(r))},pairSecrets(){return I(n,`bivy_pairsecrets`,{})},setPairSecret(t,r){let i=this.pairSecrets();i[t]=r,n.setItem(`bivy_pairsecrets`,JSON.stringify(i));try{e.removeItem(`bivy_pairsecrets`)}catch{}},clearPairSecret(t){let r=this.pairSecrets();delete r[t],n.setItem(`bivy_pairsecrets`,JSON.stringify(r));try{e.removeItem(`bivy_pairsecrets`)}catch{}},solo(){return I(e,`bivy_solo`,{})},setSolo(t,n){if(!t||!n?.room||!n?.roomToken)return;let r=this.solo();r[t]={room:n.room,roomToken:n.roomToken},e.setItem(`bivy_solo`,JSON.stringify(r))},device(){return I(e,`bivy_device`,null)},setDevice(t){e.setItem(`bivy_device`,JSON.stringify(t))},clearDevice(){try{e.removeItem(`bivy_device`)}catch{}},sessions(){return I(e,`bivy_session_lists`,{})},setSessions(t,n){if(!t)return;let r=this.sessions();r[t]=(n||[]).slice(0,100),e.setItem(`bivy_session_lists`,JSON.stringify(r))},lastChoice(){return I(e,`bivy_last_choice`,{})},setLastChoice(t){e.setItem(`bivy_last_choice`,JSON.stringify({...this.lastChoice(),...t}))},clear(){for(let t of[`bivy_session`,`bivy_cp`,`bivy_relay`,`bivy_current`,`bivy_keys`,`bivy_nodepubs`,`bivy_pairsecrets`,`bivy_solo`,`bivy_device`,`bivy_session_lists`,`bivy_session_index`,`bivy_deleted_sessions`,`bivy_last_choice`])e.removeItem(t)}}}var _t=[`question_asked`,`agent_notice`,`approval_requested`,`agent_waiting`,`session_done`,`session_error`,`terminal_bell`,`automation_blocked`,`app_notes`],vt=[{id:`question_asked`,label:`Agent asked a question`,description:`An agent is waiting on an answer from you.`},{id:`agent_notice`,label:`Agent messages`,description:"An agent asked you to take a look with `bivy notify` while you were away."},{id:`approval_requested`,label:`Approval needed`,description:`A tool wants to run and needs you to approve or deny it.`},{id:`agent_waiting`,label:`Agent waiting`,description:"A `bivy run` agent went quiet and may need input."},{id:`session_done`,label:`Session finished`,description:`A session completed its turn — ready to review.`},{id:`session_error`,label:`Session error`,description:`The last turn failed and needs attention.`},{id:`terminal_bell`,label:`Terminal bell`,description:`A terminal rang the bell while you were away.`},{id:`automation_blocked`,label:`Automation blocked`,description:`An automation run could not start because of plan limits or policy.`},{id:`app_notes`,label:`Reviewer notes`,description:`Someone with a shared preview link left notes on your app.`}];function yt(e){let t={};for(let n of _t){let r=e&&typeof e==`object`?e[n]:void 0;t[n]=typeof r!=`boolean`||r}return t}function bt(e,t){let n;try{n=ht(t)}catch{return!1}if(!n||typeof n!=`object`)return!1;if(n.session&&(e.s=n.session),n.controlPlane&&(e.cp=n.controlPlane),n.relay&&(e.relay=n.relay),n.node?.id){e.cur=n.node.id,n.node.pub&&e.addNodePub(n.node.id,n.node.pub),n.pairSecret&&e.setPairSecret(n.node.id,n.pairSecret),n.room&&n.roomToken&&e.setSolo(n.node.id,{room:n.room,roomToken:n.roomToken});let t=typeof n.defaultAgent==`string`?n.defaultAgent.trim().toLowerCase():``;t&&e.setLastChoice({agentId:t})}return!!(n.session||n.node?.id)}function xt(){if(typeof window>`u`)return!1;let e=window.matchMedia?.bind(window),t=!!e?.(`(display-mode: standalone)`).matches||!!e?.(`(display-mode: fullscreen)`).matches||!!e?.(`(display-mode: minimal-ui)`).matches,n=globalThis.navigator?.standalone===!0,r=globalThis.Capacitor?.isNativePlatform?.()===!0;return t||n||r}async function St(e,t=fetch){let n=await t(`${L(e)}/auth/device/github/start`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}),r=await n.json().catch(()=>({}));if(!n.ok||!r.authorizeUrl)throw Error(r.error||`Could not start GitHub sign-in.`);return{deviceId:String(r.deviceId),deviceSecret:String(r.deviceSecret),authorizeUrl:String(r.authorizeUrl),intervalMs:Number(r.intervalMs)||2e3,expiresInMs:Number(r.expiresInMs)||6e5}}async function Ct(e,t,n=fetch){let r=await n(`${L(e)}/auth/device/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t})}),i=await r.json().catch(()=>({}));if(!r.ok||!i.deviceId)throw Error(i.error||`Could not send sign-in link.`);return{deviceId:String(i.deviceId),deviceSecret:String(i.deviceSecret),intervalMs:Number(i.intervalMs)||2e3,expiresInMs:Number(i.expiresInMs)||9e5,sent:!!i.sent,...i.devLink?{devLink:String(i.devLink)}:{}}}async function wt(e,t,n,r=fetch){let i=await r(`${L(e)}/auth/device/poll`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({deviceId:t,deviceSecret:n})}),a=await i.json().catch(()=>({}));return i.ok?a:{status:`error`,error:a.error||`poll failed: ${i.status}`}}function L(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}async function Tt(e,t=fetch){let n=await t(`${L(e)}/nodes`,{headers:{authorization:`Bearer ${e.s}`}});if(!n.ok)throw Error(`nodes request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:[]}async function Et(e,t=fetch){let n=await t(`${L(e)}/account/github/central-app`,{headers:{authorization:`Bearer ${e.s}`}});if(!n.ok)throw Error(`GitHub App status request failed: ${n.status}`);return await n.json()}async function Dt(e,t=`/`,n=fetch){let r=await n(`${L(e)}/account/github/central-app/install-state`,{method:`POST`,headers:{authorization:`Bearer ${e.s}`,"content-type":`application/json`},body:JSON.stringify({returnPath:t})}),i=await r.json().catch(()=>({}));if(!r.ok||!i.installUrl)throw Error(i.error||`GitHub App install request failed: ${r.status}`);return i}async function Ot(e,t=fetch){let n=await t(`${L(e)}/account/managed-automation-target`,{method:`POST`,headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.nodeId||!r.roomKey||!r.config)throw Error(r.error||`managed automation setup failed: ${n.status}`);return r}async function kt(e,t=fetch){let n=await t(`${L(e)}/account/managed-credential-status`,{headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`managed credential status failed: ${n.status}`);return{ready:r.ready===!0,generation:Number(r.generation)||0}}var At=class extends Error{status;code;actions;constructor(e,t,n,r=[]){super(e),this.status=t,this.code=n,this.actions=r,this.name=`ManagedLaunchError`}};function jt(e,t,n){let r=Array.isArray(e.actions)?e.actions.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e,n=typeof t.id==`string`?t.id.trim():``,r=typeof t.label==`string`?t.label.trim():``;if(!n||!r)return[];let i=t.kind===`primary`||t.kind===`secondary`?t.kind:void 0;return[{id:n,label:r,...i?{kind:i}:{}}]}):[];return new At(e.reason||e.error||n,t,e.code,r)}function Mt(e,t){t.machine?.nodeId&&t.roomKey&&e.addKey(t.machine.nodeId,t.roomKey)}async function Nt(e,t=fetch){let n=await t(`${L(e)}/account/onboarding/managed-defaults`,{method:`POST`,headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.reason||r.error||`managed session setup failed: ${n.status}`);return Yt(r.config)}async function Pt(e,t,n=fetch){let r=typeof n==`function`?n:n.fetchImpl??fetch,i=typeof n==`function`?void 0:n.runtimeId,a=typeof n==`function`?void 0:n.requestId,o=await r(`${L(e)}/account/managed-machines`,{method:`POST`,headers:R(e),body:JSON.stringify({configId:t,...i?{runtimeId:i}:{},...a?{requestId:a}:{}})}),s=await o.json().catch(()=>({}));if(!o.ok||!s.machine)throw jt(s,o.status,`managed Machine launch failed: ${o.status}`);return Mt(e,s),s.machine}async function Ft(e,t,n=fetch){let r=await n(`${L(e)}/account/managed-machines/restore`,{method:`POST`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok||!i.machine)throw jt(i,r.status,`managed Machine restore failed: ${r.status}`);return Mt(e,i),i.machine}async function It(e,t=fetch){let n=await t(`${L(e)}/account/node-claims`,{method:`POST`,headers:{authorization:`Bearer ${e.s}`}});if(!n.ok)throw Error(`machine claim request failed: ${n.status}`);return await n.json()}async function Lt(e,t=fetch){let n=await t(`${L(e)}/account/node-claims`,{headers:{authorization:`Bearer ${e.s}`}});if(!n.ok)throw Error(`machine claims request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:[]}async function Rt(e,t,n=fetch){let r=await n(`${L(e)}/account/node-claims/${encodeURIComponent(t)}`,{method:`DELETE`,headers:{authorization:`Bearer ${e.s}`}});if(!r.ok)throw Error(`machine claim revoke failed: ${r.status}`)}async function zt(e,t=fetch){let n=await t(`${L(e)}/sessions`,{headers:{authorization:`Bearer ${e.s}`}});if(!n.ok)throw Error(`sessions request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:Array.isArray(r?.sessions)?r.sessions:[]}function R(e){return{authorization:`Bearer ${e.s}`,"content-type":`application/json`}}async function Bt(e,t=fetch){let n=await t(`${L(e)}/me`,{headers:R(e)});if(!n.ok)throw Error(`account request failed: ${n.status}`);return await n.json()}async function Vt(e,t=fetch){let n=await t(`${L(e)}/account`,{method:`DELETE`,headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`account deletion failed: ${n.status}`)}async function Ht(e,t,n=fetch){let r=await n(`${L(e)}/account/extension/actions/${encodeURIComponent(t)}`,{method:`POST`,headers:R(e),body:`{}`}),i=await r.json().catch(()=>({}));if(!r.ok||!i.url)throw Error(i.error||`account action failed: ${r.status}`);return{url:i.url}}async function Ut(e,t,n=fetch){let r=await n(`${L(e)}/nodes/${encodeURIComponent(t)}`,{method:`DELETE`,headers:R(e)});if(!r.ok)throw Error(`remove node failed: ${r.status}`)}function Wt(e){let{apps:t,...n}=e&&typeof e==`object`?e:{},r=Array.isArray(t)?t.filter(e=>!!e?.connected):n.connected?[n]:[];return{...r[0],...n,connected:r.length>0,apps:r}}async function Gt(e,t=fetch){let n=await t(`${L(e)}/account/github-app`,{headers:R(e)});if(!n.ok)throw Error(`github-app request failed: ${n.status}`);return Wt(await n.json())}async function Kt(e,t,n=fetch){let r=typeof t==`string`?t:t?.appId,i=typeof t==`string`?void 0:t?.hookId,a=r?`?appId=${encodeURIComponent(r)}`:i?`?hookId=${encodeURIComponent(i)}`:``,o=await n(`${L(e)}/account/github-app${a}`,{method:`DELETE`,headers:R(e)});if(!o.ok)throw Error(`disconnect failed: ${o.status}`)}async function qt(e,t,n,r=fetch){let i=await r(`${L(e)}/account/github-app/default-node`,{method:`POST`,headers:R(e),body:JSON.stringify(n?{node:t,appId:n}:{node:t})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`set default node failed: ${i.status}`);return a.defaultNode}async function Jt(e,t,n,r=fetch){let i=await r(`${L(e)}/account/github-app/trigger-access`,{method:`POST`,headers:R(e),body:JSON.stringify(n?{triggerAccess:t,appId:n}:{triggerAccess:t})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`set trigger access failed: ${i.status}`);return a.triggerAccess??`everyone`}function Yt(e){return{id:String(e?.id??``),name:String(e?.name??``),provider:String(e?.provider??``),region:typeof e?.region==`string`&&e.region?e.region:void 0,size:typeof e?.size==`string`&&e.size?e.size:void 0,image:typeof e?.image==`string`&&e.image?e.image:void 0,readyCapacity:typeof e?.readyCapacity==`number`?Math.max(0,Math.min(1,Math.floor(e.readyCapacity))):void 0,ttlMinutes:typeof e?.ttlMinutes==`number`?e.ttlMinutes:void 0,teardownOnAgentFinish:!!e?.teardownOnAgentFinish||void 0,computeSource:e?.computeSource===`managed`?`managed`:void 0,createdAt:String(e?.createdAt??``),updatedAt:String(e?.updatedAt??``)}}async function Xt(e,t=fetch){let n=await t(`${L(e)}/account/ephemeral-configs`,{headers:R(e)});if(!n.ok)throw Error(`ephemeral-configs request failed: ${n.status}`);let r=await n.json().catch(()=>[]);return Array.isArray(r)?r.map(Yt).filter(e=>e.id):[]}function Zt(e){let t=e?.primary,n={kind:`shared`};t?.kind===`node`&&typeof t.node==`string`&&t.node.trim()?n={kind:`node`,node:t.node.trim()}:t?.kind===`config`&&typeof t.configId==`string`&&t.configId&&(n={kind:`config`,configId:t.configId});let r=e?.fallback,i=r?.kind===`config`&&typeof r.configId==`string`&&r.configId?{kind:`config`,configId:r.configId}:void 0;return n.kind===`node`&&i?{primary:n,fallback:i}:{primary:n}}async function Qt(e,t=fetch){let n=await t(`${L(e)}/account/queue-routing`,{headers:R(e)});if(!n.ok)throw Error(`queue-routing request failed: ${n.status}`);return Zt(await n.json().catch(()=>({})))}async function $t(e,t,n=fetch){let r=await n(`${L(e)}/account/queue-routing`,{method:`PUT`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set queue routing failed: ${r.status}`);return Zt(i)}async function en(e,t,n=fetch){let r=await n(`${L(e)}/account/hosted-github-app/connect`,{method:`POST`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`hosted GitHub App connection failed: ${r.status}`);return i}async function tn(e,t=fetch){let n=await t(`${L(e)}/account/hosted-github-repositories`,{headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r?.error||`hosted repository request failed: ${n.status}`);return Array.isArray(r?.repos)?r.repos:[]}async function nn(e,t,n=fetch){let[r,i]=t.split(`/`);if(!r||!i)throw Error(`Repository must be owner/name`);let a=await n(`${L(e)}/account/hosted-github-repositories/${encodeURIComponent(r)}/${encodeURIComponent(i)}/branches`,{headers:R(e)}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o?.error||`hosted branch request failed: ${a.status}`);return Array.isArray(o?.branches)?o.branches:[]}function rn(e){return{enabled:!!e?.enabled,credential:e?.credential===`app`||e?.credential===`pat`?e.credential:`none`,githubAppId:typeof e?.githubAppId==`string`?e.githubAppId:void 0,providers:Array.isArray(e?.providers)?e.providers:[],validatedProviders:Array.isArray(e?.validatedProviders)?e.validatedProviders:[],encryptionReady:!!e?.encryptionReady,keyId:typeof e?.keyId==`string`?e.keyId:void 0,execution:{ready:!!e?.execution?.ready,reason:String(e?.execution?.reason||`unavailable`),configId:typeof e?.execution?.configId==`string`?e.execution.configId:void 0}}}async function an(e,t=fetch){let n=await t(`${L(e)}/account/hosted-provisioning`,{headers:R(e)});if(!n.ok)throw Error(`hosted-provisioning request failed: ${n.status}`);return rn(await n.json().catch(()=>({})))}async function on(e,t,n=fetch){let r=await n(`${L(e)}/account/hosted-provisioning`,{method:`PUT`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set hosted provisioning failed: ${r.status}`);return rn(i)}async function sn(e,t=fetch){let n=await t(`${L(e)}/account/hosted-machines`,{headers:R(e)});if(!n.ok)throw Error(`hosted-machines request failed: ${n.status}`);let r=await n.json().catch(()=>[]);return Array.isArray(r)?r.filter(e=>e&&typeof e.id==`string`&&typeof e.provider==`string`):[]}async function cn(e,t,n=fetch){let r=await n(`${L(e)}/account/hosted-machines/${encodeURIComponent(t)}`,{method:`DELETE`,headers:R(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`hosted machine teardown failed: ${r.status}`)}}async function z(e,t,n={},r=fetch){let i=await r(`${L(e)}${t}`,{...n,headers:R(e)}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`automation request failed: ${i.status}`);return a}function ln(e,t=fetch){return z(e,`/account/automations`,{},t)}function un(e,t,n=fetch){return z(e,`/account/automations`,{method:`POST`,body:JSON.stringify(t)},n)}function dn(e,t,n=fetch){return z(e,`/account/automations/${encodeURIComponent(t)}/webhook/rotate`,{method:`POST`},n)}function fn(e,t,n,r=fetch){return z(e,`/account/automations/${encodeURIComponent(t)}`,{method:`PUT`,body:JSON.stringify(n)},r)}function pn(e,t,n=fetch){return z(e,`/account/automations/simulate`,{method:`POST`,body:JSON.stringify(t)},n)}async function mn(e,t,n=fetch){let r=await n(`${L(e)}/account/automations/${encodeURIComponent(t)}`,{method:`DELETE`,headers:R(e)});if(!r.ok)throw Error(`delete automation failed: ${r.status}`)}function hn(e,t,n=fetch,r=crypto.randomUUID()){return z(e,`/account/automations/${encodeURIComponent(t)}/run`,{method:`POST`,body:JSON.stringify({sourceKey:r})},n)}function gn(e,t,n=fetch){return z(e,`/account/automation-runs`,{method:`POST`,body:JSON.stringify(t)},n)}function _n(e,t=50,n={},r=fetch){let i=new URLSearchParams({limit:String(t)});return n.summary&&i.set(`summary`,`1`),z(e,`/account/automation-runs?${i}`,{},r)}var vn=class extends Error{reason;status;constructor(e,t,n){super(e),this.reason=t,this.status=n,this.name=`RunFetchError`}};async function yn(e,t,n=fetch){let r;try{r=await n(`${L(e)}/account/automation-runs/${encodeURIComponent(t)}`,{headers:R(e)})}catch{throw new vn(`Could not reach the control plane`,`error`)}if(r.status===404)return null;if(r.status===401)throw new vn(`Unauthorized`,`unauthorized`,401);if(!r.ok)throw new vn(`automation run request failed: ${r.status}`,`error`,r.status);return await r.json()}async function bn(e,t,n,r=fetch){let i=await r(`${L(e)}/account/product-events`,{method:`POST`,headers:R(e),body:JSON.stringify({event:t,client:n})});if(!i.ok)throw Error(`product event request failed: ${i.status}`)}function xn(e,t,n=fetch){return z(e,`/account/automation-runs/${encodeURIComponent(t)}/cancel`,{method:`POST`},n).then(e=>e.run)}function Sn(e,t,n=fetch){return z(e,`/account/automation-runs/${encodeURIComponent(t)}/retry`,{method:`POST`},n).then(e=>e.run)}async function Cn(e,t=30,n=fetch){let r=await n(`${L(e)}/account/work-items?limit=${encodeURIComponent(String(t))}`,{headers:R(e)});if(!r.ok)throw Error(`work-items request failed: ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}async function wn(e,t,n,r=fetch){let i=await r(`${L(e)}/account/work-items/${encodeURIComponent(t)}/assign`,{method:`POST`,headers:R(e),body:JSON.stringify({node:n.node?.trim()||``,runtimeId:n.runtimeId?.trim()||``,model:n.model?.trim()||``,ephemeral:!!n.ephemeral})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`assign work item failed: ${i.status}`)}async function Tn(e,t,n=fetch){let r=await n(`${L(e)}/account/work-items/${encodeURIComponent(t)}`,{method:`DELETE`,headers:R(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`delete work item failed: ${r.status}`)}}async function En(e,t=fetch){let n=await t(`${L(e)}/account/work-items`,{method:`DELETE`,headers:R(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r?.error||`clear queue failed: ${n.status}`);return Number(r?.removed)||0}async function Dn(e,t=fetch){let n=await t(`${L(e)}/account/slack-hook`,{headers:R(e)});if(!n.ok)throw Error(`Slack integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function On(e,t,n=fetch){let r=await n(`${L(e)}/account/slack-hook`,{method:`POST`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`Connect Slack failed: ${r.status}`);return i.hook}async function kn(e,t=fetch){let n=await t(`${L(e)}/account/slack-hook`,{method:`DELETE`,headers:R(e)});if(!n.ok)throw Error(`Disconnect Slack failed: ${n.status}`)}async function An(e,t=fetch){let n=await t(`${L(e)}/account/linear-hook`,{headers:R(e)});if(!n.ok)throw Error(`Linear integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function jn(e,t={},n=fetch){let r=await n(`${L(e)}/account/linear-hook`,{method:`POST`,headers:R(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`Connect Linear failed: ${r.status}`);return i.hook}async function Mn(e,t=fetch){let n=await t(`${L(e)}/account/linear-hook`,{method:`DELETE`,headers:R(e)});if(!n.ok)throw Error(`Disconnect Linear failed: ${n.status}`)}async function Nn(e,t=fetch){let n=await t(`${L(e)}/devices`,{headers:R(e)});if(!n.ok)throw Error(`devices request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:[]}async function Pn(e,t,n=fetch){let r=await n(`${L(e)}/devices/${encodeURIComponent(t)}`,{method:`DELETE`,headers:R(e)});if(!r.ok)throw Error(`remove device failed: ${r.status}`)}async function Fn(e,t,n=fetch){await n(`${L(e)}/auth/logout`,{method:`POST`,headers:R(e),body:JSON.stringify(t?{devicePublicKeyB64:t}:{})})}function In(e){let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function Ln(e,t=fetch){let n=globalThis.navigator;if(!n?.serviceWorker||!(`PushManager`in globalThis)||!(`Notification`in globalThis))throw Error(`Push notifications are not supported on this device.`);let r=await t(`${L(e)}/api/push/vapid-public-key`,{headers:R(e)}),i=await r.json().catch(()=>({}));if(!r.ok||i?.enabled===!1||!i?.publicKey)throw Error(`Push notifications are not enabled for this account.`);if(await globalThis.Notification.requestPermission()!==`granted`)throw Error(`Notification permission was declined.`);let a=await(await n.serviceWorker.ready).pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:In(String(i.publicKey))});if(!(await t(`${L(e)}/api/push/subscribe`,{method:`POST`,headers:R(e),body:JSON.stringify({subscription:a})})).ok)throw Error(`Could not register for push notifications.`);return`Push notifications enabled.`}async function Rn(e,t=fetch){let n=await globalThis.navigator?.serviceWorker?.ready?.catch?.(()=>null),r=n?await n.pushManager.getSubscription():null,i=r?.endpoint||``;return r&&await r.unsubscribe().catch(()=>{}),i&&await t(`${L(e)}/api/push/subscribe`,{method:`DELETE`,headers:R(e),body:JSON.stringify({endpoint:i})}).catch(()=>{}),`Push notifications disabled on this device.`}async function zn(){let e=globalThis.navigator;if(!(e?.serviceWorker&&`PushManager`in globalThis&&`Notification`in globalThis))return{supported:!1,subscribed:!1,permission:`default`};let t=String(globalThis.Notification?.permission??`default`),n=await e.serviceWorker.ready.catch(()=>null);return{supported:!0,subscribed:!!(n&&await n.pushManager.getSubscription()),permission:t}}async function Bn(e,t=fetch){let n=await t(`${L(e)}/api/push/preferences`,{headers:R(e)});if(!n.ok)throw Error(`notification preferences request failed: ${n.status}`);return yt((await n.json().catch(()=>({})))?.preferences)}async function Vn(e,t,n=fetch){let r=await n(`${L(e)}/api/push/preferences`,{method:`PUT`,headers:R(e),body:JSON.stringify(t)});if(!r.ok)throw Error(`could not save notification preferences: ${r.status}`);return yt((await r.json().catch(()=>({})))?.preferences)}function Hn(e){return Math.max(5,Math.min(1440,Number(e)||60))}function Un(e,t=!1){return t?`teardown-failed`:e.milestones?.firstAgentEventAt?`working`:e.claimedAt||e.purpose===`queue-default`||e.purpose===`queue-item`?`claimed`:e.purpose===`ready-capacity`&&e.milestones?.credentialsReadyAt?`ready`:e.milestones?.nodeReadyAt&&!e.milestones?.credentialsReadyAt?`hydrating`:e.milestones?.nodeReadyAt?`node-ready`:`provisioning`}var B=`/data`,Wn=[`api.machines.dev`,`api.fly.io`],Gn=new TextEncoder;function Kn(e){let t;try{t=new URL(e).host}catch{throw Error(`Bad provider URL: ${e}`)}if(!Wn.includes(t))throw Error(`Refusing to send a token to non-provider host: ${t}`);return e}async function V(e,t){return Kn(t.url),await e(t)||{status:0,body:null}}function H(e){return{authorization:`Bearer ${String(e||``).trim()}`}}function U(e){return`'${String(e).replace(/'/g,`'\\''`)}'`}function qn(){try{return new Date().toISOString()}catch{return``}}function Jn(e){if(!e)return``;if(typeof e==`string`)return e;if(typeof e.message==`string`)return e.message;if(e.error&&typeof e.error==`object`){let t=e.error,n=typeof t.message==`string`?t.message:typeof t.code==`string`?t.code:``,r=t.details&&Array.isArray(t.details.fields)?t.details.fields:null;if(r?.length){let e=r.map(e=>`${e.name}: ${Array.isArray(e.messages)?e.messages.join(`, `):e.messages||``}`).filter(Boolean).join(`; `);e&&(n=n?`${n} (${e})`:e)}return n}return typeof e.error==`string`?e.error:Array.isArray(e.errors)&&e.errors.length?e.errors.map(e=>(typeof e==`string`?e:e?.message)||``).filter(Boolean).join(`; `):``}function W(e,t){let n=Jn(e?.body);return`Provider failed to ${t} (HTTP ${e?.status}${n?`: ${n}`:``})`}function Yn(e){return JSON.stringify({url:e.relayUrl,enrollmentToken:e.enrollmentToken,e2eKey:e.e2eKeyB64,controlPlaneUrl:e.controlPlaneUrl,clientBaseUrl:e.controlPlaneUrl})}function Xn(e){let t=!!e.provider,n=t&&e.sleepOnIdle;return[n?`export BIVY_DATA_DIR=${B}/bivy`:`export BIVY_DATA_DIR=/etc/bivy`,n?`export BIVY_WORKSPACE=${B}/workspace`:``,n?`export HOME=${B}/home`:``,e.repo?`export BIVY_REPO=${U(e.repo)}`:``,e.hostedTasks?`export BIVY_GITHUB_HOSTED_TASKS=1`:``,e.hostedCredentialCustody?`export BIVY_HOSTED_CREDENTIAL_CUSTODY=1`:``,e.hostedCredentialPublisher?`export BIVY_HOSTED_CREDENTIAL_PUBLISH=1`:``,e.nodeLabel?`export BIVY_NODE_LABEL=${U(e.nodeLabel)}`:``,e.githubToken?`export BIVY_GITHUB_TOKEN=${U(e.githubToken)}`:``,e.hostedMint?`export BIVY_HOSTED_MINT=1`:``,t?`export BIVY_EPHEMERAL=1`:``,t?`export BIVY_EPHEMERAL_PROVIDER=${U(e.provider)}`:``,t?`export BIVY_EPHEMERAL_TTL_MIN=${Hn(e.ttlMinutes)}`:``,t&&e.teardownOnAgentFinish?`export BIVY_TEARDOWN_ON_FINISH=1`:``,t&&e.restoreSessionId?`export BIVY_RESTORE=${U(e.restoreSessionId)}`:``,n?`export BIVY_EPHEMERAL_SLEEP=1`:``].filter(Boolean)}function Zn(e){return`#!/bin/bash
|
|
6
|
+
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$HOME/.local/bin:$PATH"
|
|
7
|
+
BIVY_CLI="$(readlink -f "$(command -v bivy)")"
|
|
8
|
+
BIVY_PACKAGE_DIR="$(dirname "$(dirname "$BIVY_CLI")")"
|
|
9
|
+
if [ -d "$BIVY_PACKAGE_DIR/node_modules/.bin" ]; then export PATH="$BIVY_PACKAGE_DIR/node_modules/.bin:$PATH"; fi
|
|
10
|
+
`+Xn(e).map(e=>`${e}\n`).join(``)+`exec bivy start
|
|
11
|
+
`}function Qn(e,t){return`curl --connect-timeout 2 --max-time 3 -fsS -X POST -H 'content-type: application/json' -H ${U(`authorization: Bearer ${e.enrollmentToken}`)} --data ${U(JSON.stringify({phase:t}))} ${U(`${e.controlPlaneUrl.replace(/\/$/,``)}/node/bootstrap-status`)} >/dev/null 2>&1 || true`}function $n(e){return e===`started`?`running`:e===`destroyed`?`gone`:e===`stopped`||e===`suspended`?`stopped`:`starting`}var er=`bivy_data`,tr=`personal`;async function nr(e,t,n){let r=String(n||``).trim();if(r)return r;let i=await V(e,{method:`POST`,url:`https://api.fly.io/graphql`,headers:{...H(t),"content-type":`application/json`},body:{query:`query { organizations { nodes { slug type } } }`}});if(i.status>=300)throw Error(W(i,`list organizations`));let a=Array.isArray(i.body?.data?.organizations?.nodes)?i.body.data.organizations.nodes:[];if(!a.length){let e=Jn(i.body);throw Error(`Fly token has no accessible organizations${e?`: ${e}`:``}`)}let o=a.find(e=>String(e?.type||``).toUpperCase()===`PERSONAL`&&e?.slug)||a.find(e=>e?.slug)||a[0];return String(o?.slug||tr)}var rr={"shared-1x-1gb":{cpus:1,memoryMb:1024,cpuKind:`shared`},"shared-1x-2gb":{cpus:1,memoryMb:2048,cpuKind:`shared`},"shared-2x-4gb":{cpus:2,memoryMb:4096,cpuKind:`shared`},"shared-4x-8gb":{cpus:4,memoryMb:8192,cpuKind:`shared`},"shared-8x-16gb":{cpus:8,memoryMb:16384,cpuKind:`shared`}};function ir(e){let t=e.installUrl||`https://bivy.sh/install.sh`,n=Hn(e.ttlMinutes)*60,r=e=>b(Gn.encode(e)),i=[`set -euo pipefail`,`export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$HOME/.local/bin:$PATH"`,`export DEBIAN_FRONTEND=noninteractive`,`mkdir -p /etc/bivy /workspace`,`chmod 700 /etc/bivy`,`chmod 600 /etc/bivy/relay.json /etc/bivy/start.sh`,`export BIVY_DATA_DIR=/etc/bivy`,`export BIVY_WORKSPACE=/workspace`,...e.sleepOnIdle?[`mkdir -p ${B}/bivy ${B}/workspace ${B}/home`,`chmod 700 ${B}/bivy`,`[ -f ${B}/bivy/relay.json ] || install -m 600 /etc/bivy/relay.json ${B}/bivy/relay.json`]:[],`trap ${U(Qn(e,`failed`))} ERR`,Qn(e,`booting`),`if ! command -v bivy >/dev/null 2>&1; then\n${Qn(e,`installing`)}\napt-get update -qq\napt-get install -y -qq curl ca-certificates\ncurl --connect-timeout 10 --max-time 120 -fsSL ${U(t)} | bash\nfi`,Qn(e,`starting`),`exec bash /etc/bivy/start.sh`].join(`
|
|
12
|
+
`);return{files:[{guest_path:`/etc/bivy/relay.json`,raw_value:r(Yn(e))},{guest_path:`/etc/bivy/start.sh`,raw_value:r(Zn(e))}],init:{exec:[`/usr/bin/timeout`,`--kill-after=10s`,String(n),`/bin/bash`,`-c`,i]}}}async function ar(e,t,n){if(!/^bivy-[a-z0-9-]+$/.test(n))return;let r=`https://api.machines.dev/v1/apps/${encodeURIComponent(n)}`,i=await V(e,{method:`GET`,url:`${r}/machines`,headers:H(t)});if(i.status===404)return;if(i.status>=300)throw Error(W(i,`check empty app`));if(!Array.isArray(i.body))throw Error(`Fly returned an invalid app inventory; keeping the app for cleanup retry`);if(i.body.length)return;let a=await V(e,{method:`GET`,url:`${r}/volumes`,headers:H(t)});for(let n of Array.isArray(a.body)?a.body:[]){if(!n?.id)continue;let i=await V(e,{method:`DELETE`,url:`${r}/volumes/${encodeURIComponent(n.id)}`,headers:H(t)});if(i.status>=300&&i.status!==404)throw Error(W(i,`delete volume`))}let o=await V(e,{method:`DELETE`,url:r,headers:H(t)});if(o.status>=300&&o.status!==404)throw Error(W(o,`delete empty app`))}async function or(e,t,n,r,i=20){let a=`https://api.machines.dev/v1/apps/${encodeURIComponent(n)}/volumes`,o=await V(e,{method:`GET`,url:a,headers:H(t)});if(o.status>=300)throw Error(W(o,`list volumes`));let s=(Array.isArray(o.body)?o.body:[]).find(e=>e?.name===er&&e?.id&&e?.state!==`destroyed`);if(s)return String(s.id);let c=await V(e,{method:`POST`,url:a,headers:{...H(t),"content-type":`application/json`},body:{name:er,region:r,size_gb:Math.max(1,Math.round(i)),encrypted:!0}});if(c.status>=300||!c.body?.id)throw Error(W(c,`create volume`));return String(c.body.id)}var sr={id:`fly`,name:`Fly.io`,currency:`USD`,regions:[{id:`iad`,label:`Ashburn, VA`},{id:`sjc`,label:`San Jose`},{id:`lhr`,label:`London`},{id:`fra`,label:`Frankfurt`},{id:`syd`,label:`Sydney`},{id:`nrt`,label:`Tokyo`}],defaultRegion:`iad`,sizes:[{id:`shared-1x-1gb`,label:`shared · 1 vCPU · 1 GB`,vcpus:1,memoryMiB:1024,architecture:`x86_64`,pricePerHour:.009,priceSource:`indicative`},{id:`shared-1x-2gb`,label:`shared · 1 vCPU · 2 GB`,vcpus:1,memoryMiB:2048,architecture:`x86_64`,pricePerHour:.0136,priceSource:`indicative`},{id:`shared-2x-4gb`,label:`shared · 2 vCPU · 4 GB`,vcpus:2,memoryMiB:4096,architecture:`x86_64`,pricePerHour:.0273,priceSource:`indicative`},{id:`shared-4x-8gb`,label:`shared · 4 vCPU · 8 GB`,vcpus:4,memoryMiB:8192,architecture:`x86_64`,pricePerHour:.0546,priceSource:`indicative`},{id:`shared-8x-16gb`,label:`shared · 8 vCPU · 16 GB`,vcpus:8,memoryMiB:16384,architecture:`x86_64`,pricePerHour:.1234,priceSource:`indicative`}],defaultSize:`shared-4x-8gb`,async validateToken({exec:e,token:t}){let n=await nr(e,t),r=await V(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(n)}`,headers:H(t)});if(r.status>=300)throw Error(W(r,`validate credential`))},async provision({exec:e,token:t,config:n,bootstrap:r}){if(!r)throw Error(`Fly requires a structured Bivy bootstrap; cloud-init is not supported by Fly Machines.`);let i=`bivy-${n.slug}`,a=await nr(e,t,n.org),o=rr[n.size]||rr[sr.defaultSize]||{cpus:1,memoryMb:2048,cpuKind:`shared`},s=await V(e,{method:`POST`,url:`https://api.machines.dev/v1/apps`,headers:{...H(t),"content-type":`application/json`},body:{app_name:i,org_slug:a}}),c=s.status===422&&/name has already been taken/i.test(Jn(s.body));if(s.status>=300&&s.status!==409&&!c)throw Error(W(s,`create app`));if(n.attemptId){let r=await V(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:H(t)});if(r.status>=300)throw Error(W(r,`check existing launch`));if(!Array.isArray(r.body))throw Error(`Fly returned an invalid machine inventory; refusing to risk a duplicate launch`);let a=r.body.find(e=>e?.config?.metadata?.[`bivy-attempt`]===String(n.attemptId));if(r.status<300&&a?.id)return{id:String(a.id),provider:`fly`,app:i,name:i,region:a.region||n.region||`iad`,status:$n(a.state),ip:null,createdAt:a.created_at||qn(),ttlMinutes:n.ttlMinutes};if(r.body.length)throw Error(`This Fly app already contains a machine from another launch. Reconnect or destroy it before rebuilding.`)}let l=ir(r),u=!!r.sleepOnIdle,d=u?await or(e,t,i,n.region||`iad`,n.persistentDiskGb):void 0,f=await V(e,{method:`POST`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:{...H(t),"content-type":`application/json`},body:{region:n.region||`iad`,config:{image:n.image||`ghcr.io/bivysh/bivy-ephemeral-runner@sha256:30705bdda88425646b0c5dc19fc0e95cc4a026ca9c09a4f904c15b3a21e246ac`,auto_destroy:!(r?.debugKeepMachine||u),restart:{policy:`no`},...d?{mounts:[{volume:d,path:B}]}:{},guest:{cpu_kind:o.cpuKind,cpus:Number(n.cpus)||o.cpus,memory_mb:Number(n.memoryMb)||o.memoryMb},metadata:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}},...l}}});if(f.status>=300)throw s.status<300&&f.status>=400&&f.status<500&&![408,409,429].includes(f.status)&&await ar(e,t,i),Error(W(f,`create machine`));let p=f.body;if(!p||!p.id)throw Error(`Fly did not return a machine`);return{id:String(p.id),provider:`fly`,app:i,name:i,region:n.region||`iad`,status:$n(p.state),ip:null,createdAt:qn(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await V(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}`,headers:H(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(W(r,`get machine`));return $n(r.body?.state)},async destroy({exec:e,token:t,machine:n}){let r=await V(e,{method:`DELETE`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}?force=true`,headers:H(t)});if(r.status>=300&&r.status!==404)throw Error(W(r,`delete machine`));await ar(e,t,n.app||``)},async wake({exec:e,token:t,machine:n}){let r=await V(e,{method:`POST`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}/start`,headers:H(t)});if(!(r.status<300)&&await sr.status({exec:e,token:t,machine:n})!==`running`)throw Error(W(r,`start machine`))},async cleanupAttempt({exec:e,token:t,nodeId:n,attemptId:r,ownershipTag:i}){if(!/^eph-(?:[a-f0-9]{16}|[a-f0-9]{32})$/.test(n))return!1;let a=`bivy-${n.replace(/^eph-/,``)}`,o=`https://api.machines.dev/v1/apps/${encodeURIComponent(a)}`,s=await V(e,{method:`GET`,url:`${o}/machines`,headers:H(t)});if(s.status!==404){if(s.status>=300||!Array.isArray(s.body))throw Error(`Cannot verify canceled Fly launch inventory`);if(s.body.some(e=>e?.config?.metadata?.[`bivy-attempt`]!==r||e?.config?.metadata?.[`bivy-account`]!==i))return!1;for(let n of s.body){if(!n?.id)return!1;let r=await V(e,{method:`DELETE`,url:`${o}/machines/${encodeURIComponent(n.id)}?force=true`,headers:H(t)});if(r.status>=300&&r.status!==404)return!1}let n=await V(e,{method:`DELETE`,url:o,headers:H(t)});if(n.status>=300&&n.status!==404)return!1}return(await V(e,{method:`GET`,url:o,headers:H(t)})).status===404},async discover({exec:e,token:t,ownershipTag:n}){let r=await nr(e,t),i=await V(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(r)}`,headers:H(t)});if(i.status>=300)throw Error(W(i,`list apps`));let a=Array.isArray(i.body?.apps)?i.body.apps:Array.isArray(i.body)?i.body:[],o=[];for(let r of a){let i=String(r?.name||``);if(!i.startsWith(`bivy-`))continue;let a=await V(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:H(t)});if(a.status>=300)continue;let s=Array.isArray(a.body)?a.body:[];for(let e of s){let t=e?.config?.metadata||{};t.bivy===`ephemeral`&&t[`bivy-account`]===n&&o.push({id:String(e.id),provider:`fly`,app:i,name:i,region:e.region||``,status:$n(e.state),ip:null,createdAt:typeof e.created_at==`string`?e.created_at:``,attemptId:typeof t[`bivy-attempt`]==`string`?t[`bivy-attempt`]:void 0})}}return o}};new Map([sr].map(e=>[e.id,e]));var cr=[{id:`fly`,name:`Fly.io`,computeClass:`byo-cloud`,tokenLabel:`Fly.io access token`,blurb:`Bivy creates a temporary Fly Machine, runs the session, then destroys it.`,steps:[`Open your Fly.io access tokens and sign in.`,`Click Create token — use a short-lived/deploy token if your account offers one.`,`Copy the token and paste it below. Revoke it after the session if you like.`],links:[{label:`Create a Fly.io token`,url:`https://fly.io/user/personal_access_tokens`},{label:`Fly Machines docs`,url:`https://fly.io/docs/machines/`}]}];function lr(e){let t=String(e||``).trim().toLowerCase();return cr.find(e=>e.id===t)||null}function ur(){try{return new Date().toISOString()}catch{return``}}function dr(){let e=new Map;return{async getAll(){return[...e.values()].map(e=>({...e}))},async put(t,n){e.set(t,{...n})},async delete(t){e.delete(t)}}}function fr(e,t,n,r){function i(){return new Promise((i,a)=>{let o=e.open(t,1);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(n)||o.result.createObjectStore(n,{keyPath:r})},o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)})}function a(e,t){return e.transaction(n,t).objectStore(n)}function o(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}return{async getAll(){let e=await i();try{return await o(a(e,`readonly`).getAll())||[]}finally{e.close()}},async put(e,t){let n=await i();try{await o(a(n,`readwrite`).put(t))}finally{n.close()}},async delete(e){let t=await i();try{await o(a(t,`readwrite`).delete(e))}finally{t.close()}}}}function pr(e,t){try{let n=globalThis.indexedDB;if(n)return fr(n,e===`provider-keys`?`bivy-ephemeral`:`bivy-ephemeral-${e}`,e,t)}catch{}return dr()}function mr(e=pr(`provider-keys`,`provider`)){return{async list(){let t;try{t=await e.getAll()}catch{t=[]}let n=new Map(t.map(e=>[e.provider,e]));return cr.map(e=>{let t=n.get(e.id);return{id:e.id,name:e.name,configured:!!(t&&t.token),updatedAt:t?t.updatedAt:null}})},async getToken(t){let n=lr(t);if(!n)return``;let r;try{r=await e.getAll()}catch{return``}let i=r.find(e=>e.provider===n.id);return i&&i.token?i.token:``},async setToken(t,n){let r=lr(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n||``).trim();if(!i)throw Error(`API token cannot be empty`);await e.put(r.id,{provider:r.id,token:i,updatedAt:ur()})},async remove(t){let n=lr(t);n&&await e.delete(n.id)}}}function hr(e=pr(`model-oauth`,`id`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>t(e||`default`)||`default`,r=(e,t)=>`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async entries(){return(await i()).filter(e=>e?.provider&&e?.refresh).map(e=>({provider:t(e.provider),label:n(e.label),access:String(e.access||``),refresh:String(e.refresh),expires:Number(e.expires)||0,...Number.isFinite(Number(e.refreshedAt))?{refreshedAt:Number(e.refreshedAt)}:{},...Number.isFinite(Number(e.updatedAt))?{updatedAt:Number(e.updatedAt)}:{}}))},async set(i){let a=t(i.provider),o=n(i.label);if(!a||!String(i.refresh||``).trim())throw Error(`A provider and refresh token are required`);await e.put(r(a,o),{...i,id:r(a,o),provider:a,label:o})},async remove(i,a=`default`){await e.delete(r(t(i),n(a)))}}}function gr(e=pr(`model-keys`,`provider`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>String(e||`default`).trim().toLowerCase()||`default`,r=(e,t)=>t==="default"?e:`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async list(){return(await i()).filter(e=>e&&e.provider).map(e=>({provider:String(e.provider),label:n(e.label),configured:!!e.key,updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`})).sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async entries(){return(await i()).filter(e=>e&&e.provider&&e.key).map(e=>({provider:String(e.provider),label:n(e.label),key:String(e.key),updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`}))},async get(e,r=`default`){let a=t(e),o=n(r);if(!a)return``;let s=(await i()).find(e=>e.provider===a&&n(e.label)===o);return s&&s.key?s.key:``},async set(i,a,o=`account`,s=`default`){let c=t(i),l=n(s);if(!c)throw Error(`Provider is required`);let u=String(a||``).trim();if(!u)throw Error(`API key cannot be empty`);if(o!==`account`&&o!==`device`)throw Error(`Credential scope must be account or device`);await e.put(r(c,l),{provider:c,label:l,key:u,scope:o,updatedAt:ur()})},async remove(i,a=`default`){let o=t(i);o&&await e.delete(r(o,n(a)))}}}function _r(e=pr(`pending-launches`,`id`)){return{async list(){try{return(await e.getAll()).filter(e=>e&&e.id&&e.config&&e.prompt).sort((e,t)=>String(e.createdAt).localeCompare(String(t.createdAt)))}catch{return[]}},async put(t){let{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u}=t;await e.put(n,{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u})},async remove(t){await e.delete(t)}}}var vr=`bivy`,G=`device-key`,yr=`x25519`;function br(){try{return typeof globalThis<`u`&&!!globalThis.indexedDB}catch{return!1}}var xr=4e3;function Sr(){return new Promise((e,t)=>{let n=!1,r=e=>{n||(n=!0,e())},i=setTimeout(()=>r(()=>t(Error(`indexedDB.open timed out`))),xr),a=indexedDB.open(vr,1);a.onupgradeneeded=()=>{a.result.objectStoreNames.contains(G)||a.result.createObjectStore(G)},a.onsuccess=()=>r(()=>{clearTimeout(i),e(a.result)}),a.onerror=()=>r(()=>{clearTimeout(i),t(a.error)}),a.onblocked=()=>r(()=>{clearTimeout(i),t(Error(`indexedDB.open blocked`))})})}function Cr(e,t){return new Promise((n,r)=>{let i;try{i=t(e)}catch(e){r(e);return}i.onsuccess=()=>n(i.result),i.onerror=e=>{e.preventDefault(),r(i.error)}})}async function wr(){if(!br())return;let e=await Sr();try{await Cr(e.transaction(G,`readwrite`).objectStore(G),e=>e.delete(yr))}finally{e.close()}}function Tr(){return br()?{async load(){let e=await Sr();try{let t=await Cr(e.transaction(G,`readonly`).objectStore(G),e=>e.get(yr));return t&&t.priv instanceof CryptoKey&&typeof t.pub==`string`?{priv:t.priv,pub:t.pub}:null}finally{e.close()}},async save(e,t){try{let n=globalThis.structuredClone;n&&n({priv:e,pub:t})}catch{throw Error(`IndexedDB cannot clone this device key`)}let n=await Sr();try{let r=n.transaction(G,`readwrite`);r.onerror=e=>e.preventDefault(),await Cr(r.objectStore(G),n=>n.put({priv:e,pub:t},yr)),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)});let i=await Cr(n.transaction(G,`readonly`).objectStore(G),e=>e.get(yr));if(!i||!(i.priv instanceof CryptoKey)||i.priv.extractable||i.pub!==t)throw Error(`IndexedDB did not preserve the non-extractable device key`)}finally{n.close()}}}:null}var Er=new WeakMap;function Dr(e,t){if(t)return Or(e,t);let n=Er.get(e);if(n)return n;let r=Or(e,Tr()??void 0);return Er.set(e,r),r.catch(()=>{Er.get(e)===r&&Er.delete(e)}),r}async function Or(e,t){let n=t??Tr();if(n)try{let t=await n.load();if(t)return t;let r=e.device();if(r){let t=await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!1,[`deriveBits`]);return await n.save(t,r.pub),e.clearDevice(),{priv:t,pub:r.pub}}let i=await crypto.subtle.generateKey({name:`X25519`},!1,[`deriveBits`]),a=S(new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)));return await n.save(i.privateKey,a),{priv:i.privateKey,pub:a}}catch{}let r=e.device();if(r)return{priv:await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!0,[`deriveBits`]),pub:r.pub};let i=await crypto.subtle.generateKey({name:`X25519`},!0,[`deriveBits`]),a=new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)),o=new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,i.privateKey)),s=S(a),c=S(o);return e.setDevice({pub:s,priv:c}),{priv:i.privateKey,pub:s}}async function kr(e,t){let n=await crypto.subtle.importKey(`raw`,C(t),{name:`X25519`},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:`X25519`,public:n},e,256))}async function Ar(e,t,n){let r=await kr(e,t),i=await crypto.subtle.importKey(`raw`,r,`HKDF`,!1,[`deriveBits`]),a=n===`rotate`?w.rotate:n===`device-vault`?w.deviceVault:w.pair,o=new TextEncoder().encode(a),s=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array,info:o},i,256)),c=n===`device-vault`?[`encrypt`,`decrypt`]:[`decrypt`];return crypto.subtle.importKey(`raw`,s,`AES-GCM`,!1,c)}async function jr(e,t){let n=await crypto.subtle.importKey(`raw`,C(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return S(new Uint8Array(await crypto.subtle.sign(`HMAC`,n,C(t))))}var Mr=class extends Error{constructor(){super(`Device vault changed concurrently`),this.name=`DeviceVaultConflictError`}},Nr=()=>({v:3,providerTokens:{},modelKeys:{},oauthCredentials:{}}),Pr=()=>({phase:`idle`,attemptedAt:null,succeededAt:null,pending:!1,failure:null}),Fr=e=>{let t=e?Date.parse(e):NaN;return Number.isFinite(t)?t:0};function Ir(e){if(e&&typeof e==`object`&&e.v===3){let t=e,n={};for(let[e,r]of Object.entries(t.modelKeys&&typeof t.modelKeys==`object`?t.modelKeys:{})){if(!r||typeof r!=`object`)continue;let t=r;n[e]=t.value?{...t,value:{provider:t.value.provider||e.split(`:`)[0]||e,label:t.value.label||e.split(`:`).slice(1).join(`:`)||`default`,key:t.value.key}}:t}return{v:3,providerTokens:t.providerTokens&&typeof t.providerTokens==`object`?t.providerTokens:{},modelKeys:n,oauthCredentials:t.oauthCredentials&&typeof t.oauthCredentials==`object`?t.oauthCredentials:{}}}let t=Nr(),n=Date.now();if(e&&typeof e==`object`&&e.v===2){let r=e;for(let[e,i]of Object.entries(r.providerTokens??{}))typeof i==`string`&&(t.providerTokens[e]={value:i,updatedAt:n});for(let[e,i]of Object.entries(r.modelKeys??{}))i&&typeof i.key==`string`&&(t.modelKeys[e]={value:{provider:e,label:`default`,key:i.key},updatedAt:Fr(i.updatedAt)||n})}else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e))typeof i==`string`&&(t.providerTokens[r]={value:i,updatedAt:n});return t}function Lr(e,t){return e?t?e.updatedAt===t.updatedAt?!!e.tombstone==!!t.tombstone?JSON.stringify(e.value)>=JSON.stringify(t.value)?e:t:e.tombstone?e:t:e.updatedAt>t.updatedAt?e:t:e:t}function Rr(e,t){let n=Nr();for(let r of new Set([...Object.keys(e.providerTokens),...Object.keys(t.providerTokens)]))n.providerTokens[r]=Lr(e.providerTokens[r],t.providerTokens[r]);for(let r of new Set([...Object.keys(e.modelKeys),...Object.keys(t.modelKeys)]))n.modelKeys[r]=Lr(e.modelKeys[r],t.modelKeys[r]);for(let r of new Set([...Object.keys(e.oauthCredentials),...Object.keys(t.oauthCredentials)]))n.oauthCredentials[r]=Lr(e.oauthCredentials[r],t.oauthCredentials[r]);return n}function K(e,t=`default`){let n=String(e||``).trim().toLowerCase(),r=String(t||`default`).trim().toLowerCase()||`default`;return r==="default"?n:`${n}:${r}`}function zr(e){let t=e.indexOf(`:`);return t<0?{provider:e,label:`default`}:{provider:e.slice(0,t),label:e.slice(t+1)||`default`}}function Br(){return crypto.getRandomValues(new Uint8Array(32))}function Vr(e){let t=e.randomKey??Br,n=e.now??Date.now,r=null,i=0,a=0,o=Nr(),s=null,c=0,l={},u={},d={},f={},p={},m={},h=Pr(),g=null,_=async()=>e.state?.save({clock:c,tokenVersions:l,modelVersions:u,oauthVersions:d,tokenTombstones:f,modelTombstones:p,oauthTombstones:m,sync:h}),v=()=>s??=(async()=>{let t=await e.state?.load();c=Math.max(t?.clock??0,n()),l={...t?.tokenVersions??{}},u={...t?.modelVersions??{}},d={...t?.oauthVersions??{}},f={...t?.tokenTombstones??{}},p={...t?.modelTombstones??{}},m={...t?.oauthTombstones??{}},h=t?.sync??Pr()})(),y=()=>c=Math.max(c+1,n()),S=async(e,t)=>D(await E(t),JSON.stringify(e)),C=async(e,t)=>Ir(JSON.parse(await O(await E(t),e))),w=async(e,t,n)=>D(await Ar(e.priv,t,`device-vault`),b(n)),T=async(e,t,n)=>x(await O(await Ar(e.priv,t,`device-vault`),n));async function ee(){let t=Nr();if(e.providerTokenSyncEnabled?.()!==!1)for(let n of await e.local.list()){let r=await e.local.getToken(n.id);r&&(t.providerTokens[n.id]={value:r,updatedAt:Math.max(Fr(n.updatedAt),l[n.id]??1)})}for(let[e,n]of Object.entries(f))t.providerTokens[e]=Lr(t.providerTokens[e],{value:null,updatedAt:n,tombstone:!0});if(e.modelKeys){for(let n of await e.modelKeys.entries())if(n.scope===`account`){let e=K(n.provider,n.label);t.modelKeys[e]={value:{provider:n.provider,label:n.label,key:n.key},updatedAt:Math.max(Fr(n.updatedAt),u[e]??1)}}}for(let[e,n]of Object.entries(p))t.modelKeys[e]=Lr(t.modelKeys[e],{value:null,updatedAt:n,tombstone:!0});if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let n of await e.oauthCredentials.entries()){let e=K(n.provider,n.label),r=Math.max(Number(n.refreshedAt)||0,Number(n.updatedAt)||0,d[e]??1);t.oauthCredentials[e]={value:n,updatedAt:r}}for(let[e,n]of Object.entries(m))t.oauthCredentials[e]=Lr(t.oauthCredentials[e],{value:null,updatedAt:n,tombstone:!0});return t}async function te(t){for(let[n,r]of Object.entries(t.providerTokens)){let t=(await e.local.list()).find(e=>e.id===n),i=Fr(t?.updatedAt);r.tombstone?(f[n]=Math.max(f[n]??0,r.updatedAt),i<=r.updatedAt&&await e.local.remove(n)):r.value&&(!t?.configured||i<r.updatedAt)&&(await e.local.setToken(n,r.value),l[n]=r.updatedAt,delete f[n])}if(e.modelKeys)for(let[n,r]of Object.entries(t.modelKeys)){let t=r.value?.provider??n,i=r.value?.label??`default`,a=(await e.modelKeys.list()).find(e=>e.provider===t&&e.label===i),o=Fr(a?.updatedAt);r.tombstone?(p[n]=Math.max(p[n]??0,r.updatedAt),o<=r.updatedAt&&await e.modelKeys.remove(t,i)):r.value&&(!a?.configured||o<r.updatedAt)&&(await e.modelKeys.set(t,r.value.key,`account`,i),u[n]=r.updatedAt,delete p[n])}if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let[n,r]of Object.entries(t.oauthCredentials)){let t=(await e.oauthCredentials.entries()).find(e=>K(e.provider,e.label)===n),i=Math.max(Number(t?.refreshedAt)||0,Number(t?.updatedAt)||0,d[n]??0);if(r.tombstone){if(m[n]=Math.max(m[n]??0,r.updatedAt),i<=r.updatedAt){let r=t??zr(n);await e.oauthCredentials.remove(r.provider,r.label)}}else r.value&&i<r.updatedAt&&(await e.oauthCredentials.set(r.value),d[n]=r.updatedAt,delete m[n])}}async function ne(){if(!e.enabled())return;await v();let s=await e.device(),c=await e.remote.get();a=c.generation??0;let l=c.keyGeneration??0;(!r||(c.wrappedKey?.generation??0)>i)&&c.wrappedKey&&(r=await T(s,c.wrappedKey.wrappedByPublicKeyB64,c.wrappedKey.wrappedKey),i=c.wrappedKey.generation??l),r&&c.vault&&(o=await C(c.vault,r)),r&&l>i&&(r=t(),i=l);let u=await ee(),d=Rr(o,u),f=Object.keys(d.providerTokens).length+Object.keys(d.modelKeys).length+Object.keys(d.oauthCredentials).length>0;if(!r){if(!c.vault&&f)r=t(),i=l;else{await e.remote.requestKey(),h={...h,phase:`pending`,pending:!0,failure:null},await _();return}}let p=JSON.stringify(d)!==JSON.stringify(o)||!c.vault||l>(c.wrappedKey?.generation??l);o=d,p&&(a=(await e.remote.putVault(await S(o,r),a,i))?.generation??a+1);let m=new Set([s.pub,...c.recipients??[],...c.requests]);for(let t of m)await e.remote.putWrapped(t,await w(s,t,r),s.pub,i);await te(o),h={phase:`synced`,attemptedAt:h.attemptedAt,succeededAt:new Date(n()).toISOString(),pending:!1,failure:null},await _()}async function k(){return g||(g=(async()=>{await v(),h={...h,phase:`pending`,attemptedAt:new Date(n()).toISOString(),pending:!0,failure:null},await _();try{for(let e=0;e<3;e++)try{await ne();return}catch(t){if(!(t instanceof Mr)||e===2)throw t}}catch(e){throw h={...h,phase:`failed`,pending:!0,failure:e instanceof Error?e.message:String(e)},await _(),e}})().finally(()=>{g=null}),g)}return{sync:k,getSyncState:()=>({...h}),async getToken(t){let n=await e.local.getToken(t);if(n)return n;e.enabled()&&!o.providerTokens[t]&&await k();let r=o.providerTokens[t];return r&&!r.tombstone?r.value??``:``},async setToken(t,n){await v(),await e.local.setToken(t,n),l[t]=y(),delete f[t],await _(),e.enabled()&&e.providerTokenSyncEnabled?.()!==!1&&await k()},async remove(t){await v(),await e.local.remove(t),f[t]=y(),await _(),e.enabled()&&await k()},async list(){let t=await e.local.list(),n=new Set(t.filter(e=>e.configured).map(e=>e.id)),r=[...t];if(e.providerTokenSyncEnabled?.()!==!1)for(let[e,t]of Object.entries(o.providerTokens))!t.tombstone&&t.value&&!n.has(e)&&r.push({id:e,name:e,configured:!0,updatedAt:new Date(t.updatedAt).toISOString()});return r},async listModelKeys(){let t=await e.modelKeys?.list()??[],n=new Set(t.filter(e=>e.configured).map(e=>K(e.provider,e.label)));for(let[e,r]of Object.entries(o.modelKeys))!r.tombstone&&r.value&&!n.has(e)&&t.push({provider:r.value.provider,label:r.value.label,configured:!0,updatedAt:new Date(r.updatedAt).toISOString(),scope:`account`});return t.sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async modelKeyEntries(){let t=await e.modelKeys?.entries()??[],n=new Map(t.map(e=>[K(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.modelKeys))!t.tombstone&&t.value&&!n.has(e)&&n.set(e,{provider:t.value.provider,label:t.value.label,key:t.value.key,updatedAt:new Date(t.updatedAt).toISOString(),scope:`account`});return[...n.values()]},async getModelKey(t){let n=K(t),r=await e.modelKeys?.get(t)??``;if(r)return r;e.enabled()&&!o.modelKeys[n]&&await k();let i=o.modelKeys[n];return i&&!i.tombstone?i.value?.key??``:``},async setModelKey(t,n,r=`account`,i=`default`){if(!e.modelKeys)throw Error(`Device model-key storage is unavailable`);await v();let a=K(t,i);await e.modelKeys.set(t,n,r,i),r===`device`?p[a]=y():(u[a]=y(),delete p[a]),await _(),e.enabled()&&await k()},async removeModelKey(t,n=`default`){await v();let r=K(t,n);await e.modelKeys?.remove(t,n),p[r]=y(),await _(),e.enabled()&&await k()},async importModelKeys(t){if(e.modelKeys){await v();for(let n of t){let t=n.label??`default`,r=K(n.provider,t);await e.modelKeys.set(n.provider,n.key,`account`,t),u[r]=y(),delete p[r]}await _(),e.enabled()&&await k()}},async oauthCredentialEntries(){if(e.oauthRecoveryEnabled?.()!==!0)return[];let t=await e.oauthCredentials?.entries()??[],n=new Map(t.map(e=>[K(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.oauthCredentials))if(!t.tombstone&&t.value){let r=n.get(e),i=Math.max(Number(r?.refreshedAt)||0,Number(r?.updatedAt)||0);(!r||i<t.updatedAt)&&n.set(e,t.value)}return[...n.values()]},async importOAuthCredentials(t){if(!e.oauthCredentials||e.oauthRecoveryEnabled?.()!==!0)return;await v();let n=await e.oauthCredentials.entries();for(let r of t){let t=K(r.provider,r.label),i=Math.max(Number(r.refreshedAt)||0,Number(r.updatedAt)||0),a=n.find(e=>K(e.provider,e.label)===t),o=Math.max(Number(a?.refreshedAt)||0,Number(a?.updatedAt)||0,d[t]??0);a&&i<=o||(await e.oauthCredentials.set(r),d[t]=i||y(),delete m[t])}await _(),e.enabled()&&await k()},async removeOAuthCredential(t,n=`default`,r){await v();let i=K(t,n),a=Number(r)||y();a<=(d[i]??0)||(await e.oauthCredentials?.remove(t,n),m[i]=Math.max(m[i]??0,a),await _(),e.enabled()&&await k())}}}var Hr=`bivy_local_token`,Ur=15e3,Wr=`This device isn't paired with this machine. Run 'bivy tailscale pair' there and open the link on this device.`,Gr=class{origin;tokenStore;fetchImpl;WS;bootstrap;pairCode;deviceName;requireToken;unpaired=!1;handlers;authPending=Promise.resolve();ws=null;connected=!1;backoff=1e3;closedByUs=!1;reconnectTimer=null;constructor(e){this.origin=e.origin??``,this.tokenStore=e.tokenStore??(typeof globalThis<`u`?globalThis.sessionStorage:void 0),this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.bootstrap=e.bootstrap??``,this.pairCode=e.pairCode??``,this.deviceName=e.deviceName??`Paired device`,this.requireToken=e.requireToken??!1,this.handlers=e.handlers}token(){return this.tokenStore?.getItem(Hr)||``}directHeaders(e){let t=this.token();return{"content-type":`application/json`,...t?{authorization:`Bearer ${t}`}:{},...e||{}}}async directApi(e,t={}){if(!e.startsWith(`/api/auth/`)&&(await this.authPending,this.unpaired))throw Error(Wr);let n=await this.fetchImpl(`${this.origin}${e}`,{...t,headers:{...this.directHeaders(),...t.headers||{}}}),r=await n.json().catch(()=>({}));if(!n.ok){let e=Error(r?.error||`Local request failed (${n.status})`);throw r&&typeof r==`object`&&Object.assign(e,r),e}return r}async bootstrapAuth(){if(this.pairCode){let e=this.pairCode;this.pairCode=``;try{let t=await this.directApi(`/api/auth/pair`,{method:`POST`,body:JSON.stringify({code:e,name:this.deviceName})});if(t?.token){this.tokenStore?.setItem(Hr,t.token);return}}catch(e){this.handlers.onError?.(e instanceof Error?e.message:String(e))}}if(!(this.token()||this.requireToken))try{let e=await this.directApi(`/api/auth/bootstrap`,{method:`POST`,body:JSON.stringify({name:`Local Remote UI`,bootstrap:this.bootstrap})});e?.token&&this.tokenStore?.setItem(Hr,e.token)}catch(e){console.warn(`local bootstrap failed`,e)}}notPaired(){this.unpaired=!0,this.connected=!1,this.setStatus(`offline`),this.handlers.onError?.(Wr)}setStatus(e){this.handlers.onStatus(e)}emit(e){this.handlers.onEvent(e)}emitMerged(e,t,n){this.emit({...n||{},...t||{},type:e})}async connect(){this.closedByUs=!1,this.setStatus(`connecting`),this.authPending=this.bootstrapAuth(),await this.authPending;let e=typeof location<`u`&&location.protocol===`https:`?`wss:`:`ws:`,t=typeof location<`u`?location.host:this.origin.replace(/^https?:\/\//,``),n=this.token(),r=`${e}//${t}/ws${n?`?access_token=${encodeURIComponent(n)}`:``}`,i=new this.WS(r);this.ws=i;let a=()=>i===this.ws;i.onopen=()=>{a()&&(this.connected=!0,this.backoff=1e3,this.setStatus(`online`),this.send({kind:`sessions.list`}),this.send({kind:`models.list`}),this.send({kind:`runtimes.list`}),this.send({kind:`terminal.list`}),this.send({kind:`terminal.multiplexers`}))},i.onmessage=e=>{if(a())try{this.emit(JSON.parse(String(e.data)))}catch{}},i.onclose=e=>{if(a()&&!this.closedByUs){if(this.requireToken&&e?.code===1008&&e.reason===`Unauthorized`){this.tokenStore?.setItem(Hr,``),this.notPaired();return}this.connected=!1,this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.closedByUs||this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,Ur)}},i.onerror=()=>{}}close(){if(this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){let e=this.ws;this.ws=null,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}async send(e){try{switch(e.kind){case`ping`:this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e));break;case`history`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.have==null?{}:{have:String(e.have)},...e.haveToken?{haveToken:String(e.haveToken)}:{}});this.emit(await this.directApi(`/api/session/history?${t}`));break}case`session.replay`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},afterSeq:String(e.afterSeq??0)});this.emit(await this.directApi(`/api/session/replay?${t}`));break}case`sessions.list`:this.emit({type:`sessions.list`,sessions:await this.directApi(`/api/sessions`)});break;case`session.open`:{let t=await this.directApi(`/api/sessions/open`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,path:e.path,agent:e.agent,runtimeId:e.runtimeId})});this.emit({type:`session.history`,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:t.messages||[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.new`:{let t=await this.directApi(`/api/session`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`session.history`,requestId:e.requestId,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/sessions/discover`);this.emit({type:`session.discover.result`,requestId:t,sessions:e?.sessions??[]})}catch(e){this.emit({type:`session.discover.error`,requestId:t,error:e?.message||String(e)})}break}case`apps.list`:case`apps.publish`:case`apps.offers`:case`apps.adopt`:case`apps.open`:case`apps.logs`:case`apps.showMe`:case`apps.mute`:case`apps.reviewMode`:case`apps.annotate`:case`apps.clearNotes`:case`apps.agentNotes`:case`apps.share`:case`apps.unshare`:case`apps.revoke`:case`apps.remove`:case`artifacts.list`:case`files.list`:case`files.read`:case`access.get`:case`tailnet.machines`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/${e.kind.replace(`.`,`/`)}`,{method:`POST`,body:JSON.stringify(e)});if(typeof n.error==`string`)throw Error(n.error);this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`session.presence.get`:case`session.presence.draft`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/session/presence/${e.kind.slice(17)}`,{method:`POST`,body:JSON.stringify(e)});this.emit({...n,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`attachment.fetch`:{let t=String(e.requestId??``),n=String(e.hash??``);try{let e=await this.fetchImpl(`${this.origin}/api/attachment/${encodeURIComponent(n)}`,{headers:this.directHeaders()});if(!e.ok)throw Error(`Attachment fetch failed (${e.status})`);let r=e.headers.get(`content-type`)||`application/octet-stream`,i=new Uint8Array(await e.arrayBuffer()),a=``,o=32768;for(let e=0;e<i.length;e+=o)a+=String.fromCharCode(...i.subarray(e,e+o));this.emit({type:`attachment.data`,requestId:t,hash:n,mimeType:r,data:btoa(a)})}catch(e){this.emit({type:`attachment.error`,requestId:t,hash:n,error:e?.message||String(e)})}break}case`session.import`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/sessions/import`,{method:`POST`,body:JSON.stringify({runtimeId:e.runtimeId,ref:e.ref,acceptDisclosure:e.acceptDisclosure})});this.emit({type:`session.import.result`,requestId:t,sessionId:n.sessionId,runtimeId:n.runtimeId,mode:n.mode,seedPrompt:n.seedPrompt})}catch(e){let n=e;this.emit({type:`session.import.error`,requestId:t,error:String(n?.message??e),needsDisclosure:n?.needsDisclosure,disclosure:n?.disclosure})}break}case`session.delete`:await this.directApi(`/api/sessions/delete`,{method:`POST`,body:JSON.stringify({id:e.sessionId,path:e.path})});break;case`session.rename`:await this.directApi(`/api/sessions/rename`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name})});break;case`session.pr.refresh`:this.emitMerged(`session.pr_result`,await this.directApi(`/api/session/pr/refresh`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),{sessionId:String(e.sessionId??``)});break;case`sessions.pr.refresh_all`:this.emitMerged(`sessions.pr_refresh_result`,await this.directApi(`/api/sessions/pr/refresh`,{method:`POST`}));break;case`prompt`:await this.directApi(`/api/session/prompt`,{method:`POST`,body:JSON.stringify(e)});break;case`abort`:await this.directApi(`/api/session/abort`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});break;case`session.turn_attention.resolve`:await this.directApi(`/api/session/turn-attention`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,action:e.action})});break;case`session.limit_retry`:await this.directApi(`/api/session/limit-retry`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,enabled:e.enabled})});break;case`session.command.invoke`:await this.directApi(`/api/session/command`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,name:e.name,args:e.args})});break;case`session.pause`:await this.directApi(`/api/session/pause`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.paused`,sessionId:String(e.sessionId??``)});break;case`session.resume`:await this.directApi(`/api/session/resume`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})}),this.emit({type:`session.resumed`,sessionId:String(e.sessionId??``)});break;case`session.checkpoints`:{let t=await this.directApi(`/api/session/checkpoints`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId})});this.emit({type:`session.checkpoints`,sessionId:String(e.sessionId??``),checkpoints:t?.checkpoints??[]});break}case`session.rewind`:await this.directApi(`/api/session/rewind`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,checkpointId:e.checkpointId})}),this.emit({type:`session.rewound`,sessionId:String(e.sessionId??``),checkpointId:String(e.checkpointId??``)});break;case`session.question.answer`:await this.directApi(`/api/session/question/answer`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,requestId:e.requestId,answers:e.answers,cancelled:e.cancelled})});break;case`models.list`:this.emitMerged(`models.list`,await this.directApi(`/api/models?${new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.runtimeId?{runtimeId:String(e.runtimeId)}:{}})}`));break;case`models.prefetch`:await this.directApi(`/api/models/prefetch`,{method:`POST`,body:JSON.stringify({runtimeIds:e.runtimeIds})});break;case`model.select`:await this.directApi(`/api/models/select`,{method:`POST`,body:JSON.stringify(e)});break;case`thinking.set_level`:await this.directApi(`/api/thinking/set-level`,{method:`POST`,body:JSON.stringify(e)});break;case`node.stats`:{let t=new URLSearchParams(e.sessionId?{sessionId:String(e.sessionId)}:{});this.emit({type:`node.stats`,stats:await this.directApi(`/api/node/stats?${t}`)});break}case`capabilities.get`:this.emit({type:`capabilities`,capabilities:await this.directApi(`/api/capabilities`)});break;case`runtimes.list`:this.emitMerged(`runtimes.list`,await this.directApi(`/api/runtimes`));break;case`runtime.select`:this.emitMerged(`runtime.updated`,await this.directApi(`/api/runtimes/select`,{method:`POST`,body:JSON.stringify({id:e.id})}));break;case`runtime.install`:this.emitMerged(`runtime.install.done`,await this.directApi(`/api/runtimes/install`,{method:`POST`,body:JSON.stringify({id:e.id})}),{id:String(e.id??``)});break;case`providers.list`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers`));break;case`provider.auth.get`:this.emitMerged(`provider.auth`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`));break;case`provider.apiKey`:{let t=String(e.requestId??``);try{this.emitMerged(`providers.list`,await this.directApi(`/api/auth/api-key`,{method:`POST`,body:JSON.stringify({provider:e.provider,key:e.key})})),this.emit({type:`provider.apiKey.ok`,requestId:t})}catch(e){this.emit({type:`provider.apiKey.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.remove`:this.emitMerged(`providers.list`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}));break;case`credentials.list`:this.emitMerged(`credentials.records`,await this.directApi(`/api/auth/credentials`));break;case`credentials.native.preview`:case`credentials.native.import`:{let t=String(e.requestId??``),n=e.kind===`credentials.native.preview`?`native-preview`:`native-import`;try{let r=await this.directApi(`/api/auth/credentials/${n}`,{method:`POST`,body:JSON.stringify(e)});if(typeof r.error==`string`)throw Error(r.error);this.emit({...r,type:`${e.kind}.ok`,requestId:t})}catch(n){this.emit({type:`${e.kind}.error`,requestId:t,error:n instanceof Error?n.message:String(n)})}break}case`credentials.account.export`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials/account-export`,{method:`POST`,body:JSON.stringify({includeOAuth:e.includeOAuth===!0})});this.emit({type:`credentials.account.export`,requestId:t,...n})}catch(e){this.emit({type:`credentials.account.export.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.account.import`:{let t=String(e.requestId??``);try{await this.directApi(`/api/auth/credentials/account-import`,{method:`POST`,body:JSON.stringify({oauthEntries:e.oauthEntries})}),this.emit({type:`credentials.account.import.ok`,requestId:t})}catch(e){this.emit({type:`credentials.account.import.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/credentials`,{method:`POST`,body:JSON.stringify(e)});this.emitMerged(`credentials.records`,n),this.emitMerged(`providers.list`,n),this.emit({type:`credential.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.remove`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}`,{method:`DELETE`});this.emitMerged(`credentials.records`,i),this.emitMerged(`providers.list`,i),this.emit({type:`credential.remove.ok`,requestId:t})}catch(e){this.emit({type:`credential.remove.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.sync.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/availability`,{method:`POST`,body:JSON.stringify({sync:e.sync})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.sync.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.sync.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.unattended.set`:{let t=String(e.requestId??``);try{let n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`)),i=await this.directApi(`/api/auth/credentials/${n}/${r}/unattended`,{method:`POST`,body:JSON.stringify({unattended:e.unattended===!0})});this.emitMerged(`credentials.records`,i),this.emit({type:`credential.unattended.set.ok`,requestId:t})}catch(e){this.emit({type:`credential.unattended.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credential.test`:{let t=String(e.requestId??``),n=encodeURIComponent(String(e.provider??``)),r=encodeURIComponent(String(e.label??`default`));try{let e=await this.directApi(`/api/auth/credentials/${n}/${r}/test`,{method:`POST`,body:`{}`});this.emitMerged(`credentials.records`,e),this.emit({type:`credential.test.result`,requestId:t,...e})}catch(n){this.emit({type:`credential.test.result`,requestId:t,provider:e.provider,label:e.label,ok:!1,at:Date.now(),reason:`network_error`,error:n instanceof Error?n.message:String(n)})}break}case`credentials.presets.get`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`));break;case`credentials.presets.setMapping`:{let t=String(e.requestId??``);try{this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments`,{method:`POST`,body:JSON.stringify({preset:e.preset,provider:e.provider,label:e.label})})),this.emit({type:`credentials.presets.setMapping.ok`,requestId:t})}catch(e){this.emit({type:`credentials.presets.setMapping.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`credentials.presets.setActive`:this.emitMerged(`credentials.presets`,await this.directApi(`/api/auth/credential-assignments/active`,{method:`POST`,body:JSON.stringify({active:e.active})}));break;case`models.custom.list`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom`));break;case`models.custom.presets`:this.emitMerged(`models.custom.presets`,await this.directApi(`/api/models/catalog`));break;case`models.custom.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/models/discover`,{method:`POST`,body:`{}`});this.emit({type:`models.custom.discover.ok`,requestId:t,...e})}catch(e){this.emit({type:`models.custom.discover.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.verify`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/verify`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`models.custom.verify.ok`,requestId:t,...n})}catch(e){this.emit({type:`models.custom.verify.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.save`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/models/custom`,{method:`POST`,body:JSON.stringify(e.spec??e)});this.emitMerged(`models.custom.list`,n),this.emit({type:`models.custom.save.ok`,requestId:t,provider:n.provider})}catch(e){this.emit({type:`models.custom.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`models.custom.remove`:this.emitMerged(`models.custom.list`,await this.directApi(`/api/models/custom/${encodeURIComponent(String(e.id??e.provider??``))}`,{method:`DELETE`}));break;case`rulesets.list`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`));break;case`rulesets.save`:{let t=String(e.requestId??``);try{this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets`,{method:`POST`,body:JSON.stringify(e)})),this.emit({type:`rulesets.save.ok`,requestId:t})}catch(e){this.emit({type:`rulesets.save.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`rulesets.remove`:this.emitMerged(`rulesets.list`,await this.directApi(`/api/rulesets/${encodeURIComponent(String(e.name??``))}`,{method:`DELETE`}));break;case`activation.readiness`:this.emitMerged(`activation.readiness`,await this.directApi(`/api/activation/readiness`));break;case`repos.list`:this.emitMerged(`repos.list`,await this.directApi(`/api/repos`));break;case`branches.list`:this.emitMerged(`branches.list`,await this.directApi(`/api/repos/branches?repo=${encodeURIComponent(String(e.repo||``))}`));break;case`workspaces.list`:this.emitMerged(`workspaces.list`,await this.directApi(`/api/workspaces`));break;case`node.settings.get`:this.emit({type:`node.settings`,requestId:String(e.requestId??``),settings:await this.directApi(`/api/node/settings`)});break;case`node.settings.set`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/node/settings`,{method:`POST`,body:JSON.stringify(e.settings??e)});this.emit({type:`node.settings`,requestId:t,settings:n?.settings??n})}catch(e){this.emit({type:`node.settings.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.reset`:this.emitMerged(`provider.oauth.reset`,await this.directApi(`/api/auth/providers/${encodeURIComponent(String(e.provider||``))}`,{method:`DELETE`}),{provider:String(e.provider??``)});break;case`provider.oauth.start`:this.emitMerged(`provider.oauth.started`,await this.directApi(`/api/auth/oauth/start`,{method:`POST`,body:JSON.stringify({provider:e.provider,label:e.label})}),{provider:String(e.provider??``)});break;case`provider.oauth.open_on_node`:{let t=String(e.requestId??``);try{let n=await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/open-on-node`,{method:`POST`,body:`{}`});this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,...n})}catch(e){this.emit({type:`provider.oauth.open_on_node.result`,requestId:t,opened:!1,error:e instanceof Error?e.message:String(e)})}break}case`provider.oauth.code`:await this.directApi(`/api/auth/oauth/${encodeURIComponent(String(e.id))}/manual-code`,{method:`POST`,body:JSON.stringify({code:e.code})});break;case`github.app.manifest.start`:try{this.emitMerged(`github.app.manifest.ready`,await this.directApi(`/api/github/app/manifest/start`,{method:`POST`,body:JSON.stringify({origin:e.origin,org:e.org})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.manifest.code`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/manifest/complete`,{method:`POST`,body:JSON.stringify({code:e.code,state:e.state})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.connect-existing`:try{this.emitMerged(`github.app.manifest.done`,await this.directApi(`/api/github/app/connect-existing`,{method:`POST`,body:JSON.stringify({appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel})}),{requestId:String(e.requestId??``)})}catch(t){this.emit({type:`github.app.manifest.error`,requestId:String(e.requestId??``),error:t instanceof Error?t.message:String(t)})}break;case`github.app.disconnect`:await this.directApi(`/api/github/app/disconnect`,{method:`POST`,body:JSON.stringify({appId:e.appId})}),this.emit({type:`github.app.disconnected`,requestId:String(e.requestId??``),ok:!0});break;case`github.connect.start`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/start`,{method:`POST`}));break;case`github.connect.poll`:this.emitMerged(`github.connect.status`,await this.directApi(`/api/github/connect/poll`));break;case`approval`:await this.directApi(`/api/approvals/${encodeURIComponent(String(e.id))}/${e.approved?`approve`:`reject`}`,{method:`POST`,body:`{}`});break;case`stt.config.get`:this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`));break;case`stt.config.set`:{let t=String(e.requestId??``);try{this.emitMerged(`stt.config`,await this.directApi(`/api/stt/config`,{method:`POST`,body:JSON.stringify({provider:e.provider,setKey:e.setKey,removeKey:e.removeKey})})),this.emit({type:`stt.config.set.ok`,requestId:t})}catch(e){this.emit({type:`stt.config.set.error`,requestId:t,error:e instanceof Error?e.message:String(e)})}break}case`transcribe`:this.emitMerged(`transcription`,await this.directApi(`/api/transcribe`,{method:`POST`,body:JSON.stringify({audio:e.audio,mimeType:e.mimeType,provider:e.provider,language:e.language})}),{requestId:String(e.requestId??``)});break;case`synthesize`:this.emitMerged(`speech.audio`,await this.directApi(`/api/speech`,{method:`POST`,body:JSON.stringify({text:e.text,voice:e.voice,instructions:e.instructions})}),{requestId:String(e.requestId??``)});break;case`node.update`:try{await this.directApi(`/api/node/update`,{method:`POST`,body:`{}`}),this.emit({type:`node.update.result`,ok:!0})}catch(e){this.emit({type:`node.update.result`,ok:!1,error:e?.message||String(e)})}break;default:/^(terminal|session\.fork)\./.test(String(e.kind||``))&&this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e))}}catch(e){this.handlers.onError?.(e?.message||String(e))}}},Kr=8388608,qr=class{deps;queue=[];queuedBytes=0;pending;timer;generation=0;constructor(e){this.deps=e}accept(e){if(e.type===`transfer.part`){this.part(e);return}if(this.pending||this.queue.length){if(this.queuedBytes+=new TextEncoder().encode(JSON.stringify(e)).length,this.queuedBytes>Kr||this.queue.length>=4096){this.reset(),this.deps.fault(`Transcript delivery fell behind. Reconnecting to synchronize again.`);return}this.queue.push(e);return}this.deliver(e)}deliver(e){if(e.code!==`transfer_required`){this.deps.emit(e);return}let t=e.transfer;if(!t||!/^[a-f0-9]{48}$/.test(t.id)||!/^[a-f0-9]{64}$/.test(t.key)||!/^[a-f0-9]{24}$/.test(t.iv)||!Number.isSafeInteger(t.bytes)||t.bytes<=0||t.bytes>67108864||t.pageBytes!==393216){this.deps.emit({type:`session.error`,code:`delivery_invalid`,sessionId:e.sessionId,requestId:e.requestId,error:`Invalid large-response transfer. Update the app and retry.`});return}this.pending={offer:t,envelope:e,bytes:new Uint8Array(t.bytes),offset:0,requestId:``,retries:0},this.request()}request(){let e=this.pending;e&&(e.requestId=`transfer-${crypto.randomUUID()}`,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.pending===e&&(++e.retries<=2?this.request():this.fail(`Large-response delivery timed out. Retry to synchronize.`))},this.deps.timeoutMs??1e4),this.deps.send({kind:`transfer.read`,transferId:e.offer.id,offset:e.offset,requestId:e.requestId}).catch(()=>{this.pending===e&&this.fail(`Could not request the next response page. Retry to synchronize.`)}))}async part(e){let t=this.pending;if(t&&e.requestId===t.requestId&&e.transferId===t.offer.id&&e.offset===t.offset){if(clearTimeout(this.timer),typeof e.error==`string`){this.fail(e.error);return}try{if(typeof e.data!=`string`||e.data.length>524288)throw Error(`Invalid response page.`);let n=x(e.data);if(n.length!==Math.min(393216,t.offer.bytes-t.offset))throw Error(`Incomplete response page.`);if(t.bytes.set(n,t.offset),t.offset+=n.length,t.retries=0,t.offset<t.offer.bytes){this.request();return}t.requestId=``;let r=this.generation,i=e=>Uint8Array.from(e.match(/../g),e=>parseInt(e,16)),a=await crypto.subtle.importKey(`raw`,i(t.offer.key),`AES-GCM`,!1,[`decrypt`]),o;try{o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i(t.offer.iv)},a,t.bytes)}catch{throw Error(`Response integrity check failed.`)}if(r!==this.generation||this.pending!==t)return;let s=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(o));if(!s||typeof s.type!=`string`||s.code===`transfer_required`||s.type===`transfer.part`)throw Error(`Invalid response envelope.`);this.pending=void 0,this.deps.emit(s),this.drain()}catch(e){this.pending===t&&this.fail(`${e.message} Retry to synchronize.`)}}}fail(e){let t=this.pending?.envelope;this.reset(),this.deps.emit({type:`session.error`,code:`delivery_failed`,sessionId:t?.sessionId,requestId:t?.requestId,error:e}),this.deps.fault(e)}drain(){for(;!this.pending&&this.queue.length;){let e=this.queue.shift();this.queuedBytes-=new TextEncoder().encode(JSON.stringify(e)).length,this.deliver(e)}}reset(){clearTimeout(this.timer),this.pending=void 0,this.queue=[],this.queuedBytes=0,this.generation++}},Jr=15e3,Yr=15e3,Xr=4,Zr=3;function Qr(){return b(crypto.getRandomValues(new Uint8Array(12)))}function $r(e){return/device limit|another account|isn't authorized|not authorized|forbidden/i.test(e)}var ei=class{store;handlers;fetchImpl;WS;pairingOnly;ws=null;connected=!1;initialBackoff;backoff;closedByUs=!1;reconnectTimer=null;pairSent=!1;pairAttempts=0;connectFailures=0;hasReachedNode=!1;curKey=null;devicePromise=null;sendQueue=[];reassemble=k({onReject:e=>{this.handlers.onError?.(e),/limit/.test(e)?this.close():this.ws?.close()}});acceptFrame=ee();transfers;receiveChain=Promise.resolve();decryptBytes=0;constructor(e){this.store=e.store,this.pairingOnly=e.pairingOnly??!1,this.handlers=e.handlers,this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.initialBackoff=e.initialBackoffMs??1e3,this.backoff=this.initialBackoff,this.transfers=new qr({send:e=>this.send(e),emit:e=>this.handlers.onEvent(e),fault:e=>{this.handlers.onError?.(e),this.ws?.close()}})}cpBase(){return(this.store.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}reportRemoteReconnect(){if(!this.store.s)return;let e=typeof navigator<`u`&&/Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);this.fetchImpl(`${this.cpBase()}/account/product-events`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({event:`remote_reconnect`,client:e?`mobile`:`desktop`})}).catch(()=>{})}setStatus(e){this.handlers.onStatus(e)}device(){return this.devicePromise||=Dr(this.store).catch(e=>{throw this.devicePromise=null,e}),this.devicePromise}async keyFor(e){let t=this.store.keys()[e];return t?E(C(t)):null}canConnect(){let e=this.store.cur;return e?!!(this.curKey||this.store.keys()[e]||this.store.s||this.store.nodePubs()[e]&&this.store.pairSecrets()[e]):!1}soloCreds(){let e=this.store.solo()[this.store.cur];return e&&e.room&&e.roomToken?e:null}async mintClientTicket(){let e=await this.fetchImpl(`${this.cpBase()}/client/relay-ticket`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})});if(!e.ok)throw Error(`ticket request failed: ${e.status}`);let t=await e.json();if(!t?.ticket)throw Error(`no ticket`);return{ticket:t.ticket,relayUrl:typeof t.relayUrl==`string`?t.relayUrl:null}}async connect(){if(this.closedByUs=!1,this.setStatus(`connecting`),this.curKey=await this.keyFor(this.store.cur),this.closedByUs)return;let e=this.soloCreds(),t=``,n=null;if(!e)try{({ticket:t,relayUrl:n}=await this.mintClientTicket())}catch(e){this.connectFailures+=1,this.connectFailures>=Xr&&this.handlers.onError?.(e?.message||`ticket mint failed`),this.scheduleReconnect();return}if(this.closedByUs)return;this.pairSent=!1;let r=this.store.cur,i=(n||this.store.relay).replace(/\/$/,``),a=e?`${i}/client?room=${encodeURIComponent(e.room)}&roomToken=${encodeURIComponent(e.roomToken)}`:`${i}/client?ticket=${encodeURIComponent(t)}&nodeId=${encodeURIComponent(r)}`,o=new this.WS(a);this.ws=o;let s=()=>o===this.ws&&r===this.store.cur;o.onmessage=async e=>{if(!s())return;let t;try{t=JSON.parse(String(e.data))}catch{return}if(t.t===`ready`||t.t===`peer.online`){let e=o;this.hasReachedNode&&!e._productReconnectReported&&(e._productReconnectReported=!0,this.reportRemoteReconnect()),this.hasReachedNode=!0,this.connected=!0,this.backoff=this.initialBackoff,this.connectFailures=0,this.setStatus(this.curKey?`online`:`pairing`),await this.onLinkReady()}else if(t.t===`peer.offline`)this.setStatus(`reconnecting`);else if(t.t===`pair`&&typeof t.p==`string`)await this.handlePairFrame(t.p);else if(t.t===`error`)this.handlers.onError?.(t.error||`relay error`);else if(t.t===`run.updated`&&typeof t.id==`string`)this.handlers.onEvent({type:`run.updated`,runId:t.id,revision:typeof t.revision==`string`?t.revision:void 0});else if(t.t===`frame`&&typeof t.p==`string`){if(!this.curKey)return;let e=this.reassemble(t);if(e===null)return;if(this.decryptBytes+e.length>33554432){this.handlers.onError?.(`Response decoding fell behind. Reconnecting to synchronize.`),o.close();return}this.decryptBytes+=e.length;let n=this.curKey;this.receiveChain=this.receiveChain.then(async()=>{if(!s()||o.readyState!==1)return;let t=JSON.parse(await O(n,e));s()&&o.readyState===1&&this.acceptFrame(t)&&this.transfers.accept(t.data)}).catch(()=>{s()&&o.readyState===1&&(this.handlers.onError?.(`Could not decode the machine response. Reconnecting to synchronize.`),o.close())}).finally(()=>{this.decryptBytes-=e.length})}},o.onclose=()=>{s()&&!this.closedByUs&&(this.connected=!1,this.transfers.reset(),this.reassemble.reset(),this.scheduleReconnect())},o.onerror=()=>{}}scheduleReconnect(){this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.canConnect()&&!this.closedByUs&&this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,Jr)}shouldResync(){let e=this.ws;if(!e)return!1;let t=Date.now();return e._resyncAt!==void 0&&t-e._resyncAt<Yr?!1:(e._resyncAt=t,!0)}async onLinkReady(){if(this.curKey){if(this.pairingOnly||(this.flush(),!this.shouldResync()))return;this.store.sessions(),await this.send({kind:`sessions.list`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}else{this.setStatus(`linking`);let e=this.store.cur;this.store.nodePubs()[e]&&this.store.pairSecrets()[e]?await this.sendPairHello():await this.sendAccountPair()}}async sendPairHello(){if(this.pairSent)return;let e=this.store.cur,t=this.store.nodePubs()[e],n=this.store.pairSecrets()[e];if(!t||!n)return;let r=await this.device(),i=await jr(n,r.pub);this.pairSent=!0,this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.hello`,devicePublicKeyB64:r.pub,proofB64:i,label:ti()})}))}async sendAccountPair(){if(this.pairSent||!this.store.s)return;let e=await this.device();this.pairSent=!0;try{let t=await this.fetchImpl(`${this.cpBase()}/client/pair-grant`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})}),n=await t.json().catch(()=>({}));if(!t.ok||!n?.grant)throw Error(`Could not create pairing grant`);this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.account`,sessionToken:n.grant,devicePublicKeyB64:e.pub,label:ti()})}))}catch(e){this.pairSent=!1,this.handlers.onError?.(e?.message||`Could not pair this device`),this.setStatus(`reconnecting`)}}async handlePairFrame(e){let t;try{t=JSON.parse(e)}catch{return}let n=this.store.cur,r=this.store.nodePubs()[n];!r&&typeof t.nodePublicKeyB64==`string`&&(this.store.addNodePub(n,t.nodePublicKeyB64),r=t.nodePublicKeyB64);let i=await this.device();if(t.k===`pair.welcome`&&typeof t.wrapped==`string`&&r&&!this.curKey)try{let e=x(await O(await Ar(i.priv,r,`pair`),t.wrapped));if(this.storeRoomKey(n,e),this.store.clearPairSecret(n),this.curKey=await this.keyFor(n),this.pairAttempts=0,this.setStatus(`online`),this.pairingOnly)return;this.flush(),await this.send({kind:`sessions.list`}),await this.send({kind:`history`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}catch{this.setStatus(`reconnecting`)}else if(t.k===`key.rotate`&&Array.isArray(t.deliveries)&&r){let e=await Ar(i.priv,r,`rotate`);for(let r of t.deliveries)try{this.storeRoomKey(n,x(await O(e,r.wrapped))),this.curKey=await this.keyFor(n);break}catch{}}else t.k===`pair.error`&&this.onPairRejected(typeof t.error==`string`?t.error:``)}onPairRejected(e){if($r(e)){this.handlers.onError?.(e),this.close();return}if(this.pairAttempts+=1,this.pairAttempts>=Zr){this.handlers.onError?.(e||`Couldn't link this device — the node rejected it. Make sure the node is online and you're signed in to the right account, then try again.`),this.close();return}this.handlers.onError?.(e?`${e} — retrying…`:`Device link was rejected — retrying…`),this.pairSent=!1;let t=this.ws;this.ws=null,this.connected=!1;try{t?.close()}catch{}this.scheduleReconnect()}storeRoomKey(e,t){this.store.addKey(e,S(t))}rawSend(e){this.connected&&this.ws?.readyState===1?this.ws.send(e):this.sendQueue.push(e)}flush(){for(;this.sendQueue.length&&this.ws?.readyState===1;){let e=this.sendQueue.shift();e!==void 0&&this.ws.send(e)}}async send(e){if(!this.curKey)return;let t={v:1,ts:Date.now(),nonce:Qr(),data:e},n=await D(this.curKey,JSON.stringify(t));if(n.length>33554432){let t=`This request is too large to send. Reduce the attachments and retry.`;this.handlers.onError?.(t),this.handlers.onEvent({type:`session.error`,code:`delivery_too_large`,sessionId:typeof e.sessionId==`string`?e.sessionId:void 0,requestId:e.requestId,error:t});return}for(let e of ne(n,Qr))this.rawSend(e)}close(){if(this.transfers.reset(),this.reassemble.reset(),this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){this.transfers.reset(),this.reassemble.reset();let e=this.ws;this.ws=null,this.connected=!1,this.pairSent=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}};function ti(){return globalThis.navigator?.platform||`Device`}var ni=Object.freeze({repo:null,branch:null,sandbox:null,acknowledgeReducedProtections:!1,ephemeralConfig:null});function ri(e,t){switch(t.type){case`select-repository`:return e.repo===t.repo?{...e}:{...e,repo:t.repo,branch:null};case`select-branch`:return{...e,branch:t.branch};case`select-sandbox`:return{...e,sandbox:t.sandbox};case`acknowledge-reduced-protections`:return{...e,acknowledgeReducedProtections:t.acknowledged};case`select-ephemeral-config`:return{...e,ephemeralConfig:t.config};case`reset`:return{...ni}}}var ii=512,ai=class{nextSeq=0;held=new Map;maxHeld;constructor(e={}){this.maxHeld=Math.max(1,e.maxHeld??ii)}baseline(e){let t=(Number.isFinite(e)?Math.max(0,Math.floor(e)):0)+1;t>this.nextSeq&&(this.nextSeq=t);for(let e of[...this.held.keys()])e<this.nextSeq&&this.held.delete(e)}accept(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{ready:[t]};let n=Math.floor(e);if(this.nextSeq===0)return this.nextSeq=n+1,{ready:[t]};if(n<this.nextSeq)return{ready:[]};if(n>this.nextSeq)return this.held.set(n,t),this.held.size>this.maxHeld?{ready:[],overflow:!0}:{ready:[],gapFrom:this.nextSeq-1};let r=[t];for(this.nextSeq+=1;this.held.has(this.nextSeq);)r.push(this.held.get(this.nextSeq)),this.held.delete(this.nextSeq),this.nextSeq+=1;return{ready:r}}reset(){this.nextSeq=0,this.held.clear()}get expected(){return this.nextSeq}get heldCount(){return this.held.size}};function oi(e,t){if(t.type===`node.updated`)return typeof t.name!=`string`||!t.name||!e.currentNodeId?{handled:!0,value:e}:{handled:!0,value:{...e,nodes:e.nodes.map(n=>n.id===e.currentNodeId?{...n,name:t.name}:n)}};if(t.type===`node.update`){let n=typeof t.current==`string`?t.current:``,r=typeof t.latest==`string`?t.latest:``;return{handled:!0,value:n&&r?{...e,nodeUpdate:{current:n,latest:r}}:{...e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1}}}return t.type===`node.update.result`?t.ok===!1?{handled:!0,value:{...e,nodeUpdating:!1,nodeUpdateAcknowledged:!1},error:typeof t.error==`string`?t.error:`Couldn't start the update on this node.`}:{handled:!0,value:{...e,nodeUpdateAcknowledged:!0}}:{handled:!1,value:e}}function si(e,t){let n=String(t.sessionId||``);return t.type===`session.paused`?!n||e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:[...e.pausedSessionIds,n]}}:t.type===`session.resumed`?!n||!e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:e.pausedSessionIds.filter(e=>e!==n)}}:{handled:!1,value:e}}function ci(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.termId==`string`?t:void 0}function li(e,t,n){if(t.type===`terminal.list`){let n=Array.isArray(t.terminals)?t.terminals.map(ci).filter(e=>!!e):[];return{handled:!0,value:{...e,runTerminals:n}}}if(t.type===`terminal.created`){let n=ci(t.terminal);return n?{handled:!0,value:{...e,runTerminals:[n,...e.runTerminals.filter(e=>e.termId!==n.termId)]}}:{handled:!0,value:e}}if(t.type===`terminal.activity`){let r=String(t.termId||``);if(!r)return{handled:!0,value:e};let i=Number(t.at)||n;return{handled:!0,value:{...e,runTerminals:e.runTerminals.map(e=>e.termId===r?{...e,lastActivityAt:i}:e)}}}if(t.type===`terminal.closed`||t.type===`terminal.exit`){let n=String(t.termId||``);return n?{handled:!0,value:{...e,runTerminals:e.runTerminals.filter(e=>e.termId!==n)}}:{handled:!0,value:e}}if(t.type===`terminal.tui`){let n=String(t.sessionId||``);if(!n)return{handled:!0,value:e};let r=!!t.active;return r===e.tuiSessions.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,tuiSessions:r?[...e.tuiSessions,n]:e.tuiSessions.filter(e=>e!==n)}}}return{handled:!1,value:e}}function ui(e){switch(e.type){case`repos.list`:return{handled:!0,catalogs:{repos:Array.isArray(e.repos)?e.repos:[],reposAuthed:e.authed!==!1,reposError:e.error||null,reposReason:e.reason===`gh-unauthed`||e.reason===`no-token`?e.reason:null,reposLoading:!1}};case`branches.list`:return{handled:!0,catalogs:{branches:Array.isArray(e.branches)?e.branches:[],branchesRepo:typeof e.repo==`string`&&e.repo?e.repo:null,branchesDefault:typeof e.defaultBranch==`string`?e.defaultBranch:null,branchesError:e.error||null,branchesLoading:!1}};case`credentials.records`:return{handled:!0,settings:{credentialRecords:Array.isArray(e.records)?e.records:[]}};case`credentials.presets`:return{handled:!0,settings:{credentialPresets:e.presets??{}}};case`models.custom.list`:return Array.isArray(e.providers)?{handled:!0,settings:{localModels:e.providers}}:{handled:!0};case`models.custom.presets`:return Array.isArray(e.presets)?{handled:!0,settings:{localModelPresets:e.presets}}:{handled:!0};case`rulesets.list`:return Array.isArray(e.rulesets)?{handled:!0,settings:{rulesets:e.rulesets}}:{handled:!0};case`stt.config`:return Array.isArray(e.providers)&&typeof e.provider==`string`?{handled:!0,settings:{sttConfig:{provider:e.provider,providers:e.providers}}}:{handled:!0};case`node.settings`:return e.settings&&typeof e.settings==`object`?{handled:!0,settings:{nodeSettings:e.settings}}:{handled:!0};default:return{handled:!1}}}function di(e,t){if(t.type===`sessions.pr_refresh_result`)return{handled:!0,value:{...e,prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}}};let n=e.githubApp||{phase:`idle`};return t.type===`github.app.manifest.ready`?{handled:!0,value:{...e,githubApp:{...n,phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}}}:t.type===`github.app.manifest.done`?{handled:!0,value:{...e,githubApp:{...n,phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}}}:t.type===`github.app.manifest.error`?{handled:!0,value:{...e,githubApp:{...n,phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}}}:{handled:!1,value:e}}function fi(e){return/^\/[a-zA-Z]/.test(e.trimStart())}function pi(e){return!!(e&&typeof e==`object`&&typeof e.name==`string`&&e.name.startsWith(`/`)&&e.name.length>=2)}function mi(e){let t=e.trim();if(!fi(t))return null;let n=/^\/(\S+)\s*([\s\S]*)$/.exec(t);if(!n||!n[1])return null;let r=(n[2]??``).trim();return{name:`/${n[1].toLowerCase()}`,args:r}}function hi(e,t=[]){let n=t.filter(pi),r=n.length>0,i=n.find(t=>t.name.toLowerCase()===e.name.toLowerCase());return i?{kind:`agent`,command:i,args:e.args}:{kind:`unknown`,name:e.name,hasCatalog:r}}function gi(e,t=[]){let n=e.trimStart().toLowerCase();if(!n.startsWith(`/`)||/\s/.test(n))return[];let r=t.filter(pi);return n===`/`?r:r.filter(e=>e.name.toLowerCase().startsWith(n)||e.aliases?.some(e=>e.toLowerCase().startsWith(n)))}function _i(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!pi(r)||n.has(r.name))continue;n.add(r.name);let e={name:r.name};typeof r.description==`string`&&r.description&&(e.description=r.description),(r.mode===`protocol`||r.mode===`prompt`)&&(e.mode=r.mode),t.push(e)}return t}function vi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].name!==t[n].name||e[n].description!==t[n].description||e[n].mode!==t[n].mode)return!1;return!0}function yi(e,t){let n=[];if(Array.isArray(e))for(let t of e){let e=typeof t?.url==`string`?t.url:``;if(!e)continue;let r=t?.state===`merged`||t?.state===`closed`?t.state:`open`;n.push({url:e,state:r,number:typeof t?.number==`number`?t.number:void 0,title:typeof t?.title==`string`?t.title:void 0})}return n.length===0&&typeof t==`string`&&t&&n.push({url:t,state:`open`}),n}function bi(e){if(e&&e.length!==0)return e.find(e=>e.state===`open`)??e[0]}var xi=[`read-only`,`workspace-write`,`danger-full-access`];function Si(e){let t=String(e??``).trim().toLowerCase().replace(/_/g,`-`);return xi.includes(t)?t:void 0}function Ci(e){let t=String(e??``).trim().toLowerCase();return[`never`,`risky`,`always`,`autonomous`].includes(t)?t:void 0}function wi(e){let t=String(e??``).trim().toLowerCase();return[`trusted_workstation`,`isolated_customer_cloud`,`restricted`].includes(t)?t:void 0}var Ti=[`guaranteed`,`degraded`,`unavailable`];function Ei(e){return!!e&&typeof e==`object`&&Ti.includes(e.state)}function Di(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion===`session-contract.v1`&&typeof t.resolvedAt==`string`&&typeof t.preview==`boolean`&&t.agent&&typeof t.agent==`object`&&typeof t.agent.id==`string`&&Ei(t.executionMode)&&Ei(t.auth)&&Ei(t.resume)&&Ei(t.toolInterception)&&Ei(t.sandbox)&&Array.isArray(t.degradedReasons)&&typeof t.requiresAcknowledgement==`boolean`)return t}function Oi(e){return typeof e==`string`&&e.startsWith(`repo:`)?e.slice(5):null}function ki(e){return typeof e==`string`&&(e.startsWith(`issue:`)||e.startsWith(`queue:`))}function Ai(e){if(typeof e!=`string`||!e.startsWith(`issue:`))return null;let t=e.slice(6),n=t.lastIndexOf(`#`);if(n===-1)return null;let r=t.slice(0,n),i=Number(t.slice(n+1));return!r||!Number.isFinite(i)?null:{repo:r,issueNumber:i}}function ji(e){let t=e?.source,n=Oi(t),r=e?.githubIssueUrl||null;!r&&typeof t==`string`&&t.startsWith(`github:issue`)&&(r=t.split(`:`).slice(1).join(`:`)||null);let i=yi(e?.prs,e?.prUrl);return{issueUrl:r,prUrl:(bi(i)?.state===`open`?bi(i)?.url:null)??e?.prUrl??null,branch:e?.branch||null,repo:n,prs:i}}function Mi(e){return ji({source:e.source,branch:e.branch,prUrl:e.prUrl,prs:e.prs})}function Ni(e){if(!e||typeof e!=`object`)return null;let t=typeof e.costUsd==`number`,n=e.tokens&&typeof e.tokens.total==`number`,r=e.plan&&Array.isArray(e.plan.windows)&&e.plan.windows.length;return!t&&!n&&!r?null:e}function Pi(e){if(!e||typeof e!=`object`)return null;let t=e.memory?.node&&typeof e.memory.node.total==`number`,n=e.cpu?.node&&typeof e.cpu.node.usedPct==`number`,r=e.storage?.node&&typeof e.storage.node.total==`number`;return!t&&!n&&!r?null:e}function Fi(e){return!e||typeof e!=`object`||!e.os||typeof e.os.platform!=`string`||typeof e.generatedAt!=`string`?null:e}function Ii(e){if(!Array.isArray(e)||!e.length)return null;for(let t of e){if(typeof t?.question!=`string`||typeof t?.header!=`string`||!Array.isArray(t.options)||t.options.length===1)return null;for(let e of t.options)if(typeof e?.label!=`string`)return null}return e}function Li(e,t=[]){if(!Array.isArray(e))return[];let n=new Map(t.map(e=>[e.sessionId,e])),r=new Map;for(let t of e){let e=String(t?.sessionId||t?.id||``);if(!e||r.has(e))continue;let i=n.get(e),a=Ri(t?.sessionState);r.set(e,{sessionId:e,path:t?.path||t?.sessionFile||void 0,workspace:t?.workspace||t?.bivySession?.workspace||void 0,worktree:t?.worktree||t?.bivySession?.worktree||t?.bivySession?.workspaceContext?.worktree||void 0,name:String(t?.name||`Untitled session`),source:t?.source,bivyCreated:t?.bivyCreated===!0,forkedFrom:t?.forkedFrom||void 0,delegatedFrom:t?.delegatedFrom&&typeof t.delegatedFrom.sessionId==`string`?t.delegatedFrom:void 0,nodeId:t?.nodeId||void 0,runtimeId:t?.runtimeId,agentName:t?.agentName,updatedAt:t?.updatedAt||t?.modified,needsAction:a?.agent===`awaiting-input`||!!t?.needsAction,status:Bi(t?.status,!!t?.needsAction,!!t?.isStreaming,a),sessionState:a,branch:t?.branch||void 0,rebuildable:t?.rebuildable?!0:void 0,sandbox:Si(t?.sandbox??t?.bivySession?.sandbox),approvalMode:Ci(t?.approvalMode??t?.bivySession?.approvalMode),ephemeral:(t?.ephemeral??t?.bivySession?.ephemeral)===!0||void 0,executionProfile:wi(t?.executionProfile??t?.bivySession?.executionProfile),contract:Di(t?.contract??t?.bivySession?.contract),auditHealth:t?.auditHealth??t?.bivySession?.auditHealth,eventLogHealth:t?.eventLogHealth??t?.bivySession?.eventLogHealth,prUrl:t?.prUrl||void 0,prs:yi(t?.prs,t?.prUrl),attention:Array.isArray(t?.attention)?t.attention:i?.attention,lastSeenAt:i?.lastSeenAt,finishedAt:i?.finishedAt,failedAt:i?.failedAt,launchProgress:i?.launchProgress})}return[...r.values()]}function Ri(e){if(!e||typeof e!=`object`)return;let t=e;if((t.transport===`reachable`||t.transport===`unreachable`)&&(t.process===`alive`||t.process===`exited`||t.process===`none`)&&(t.agent===`idle`||t.agent===`working`||t.agent===`waiting`||t.agent===`awaiting-input`)&&(t.workspace===`clean`||t.workspace===`dirty`||t.workspace===`checkpointing`)&&(t.displayStatus===`idle`||t.displayStatus===`working`||t.displayStatus===`needs_attention`||t.displayStatus===`failed`))return t}function zi(e){return e?.displayStatus===`needs_attention`?`needs_action`:e?.displayStatus}function Bi(e,t,n,r){return e===`saved`?`saved`:zi(r)||(t||e===`needs_action`?`needs_action`:e===`working`||n?`working`:e===`failed`?`failed`:`idle`)}function Vi(e){return Array.isArray(e)?e.map(e=>({id:String(e?.id||e?.model||``),label:e?.label||e?.name,...e})):[]}function Hi(e){let t=Array.isArray(e?.availableThinkingLevels)&&e.availableThinkingLevels.length?e.availableThinkingLevels.map(String):[`off`];return{supportsThinking:!!e?.supportsThinking,thinkingLevel:String(e?.thinkingLevel||`off`),availableThinkingLevels:t}}function Ui(e,t){return!e||!t?!1:e.id===t.id&&e.provider===t.provider}function Wi(e){return e?String(e.displayName||e.name||e.id||``):``}function Gi(e){return Ii(e)??void 0}function Ki(e,t){return e.approvals.some(e=>e.sessionId===t)||e.questions.some(e=>e.sessionId===t)||e.turnAttentions.some(e=>e.sessionId===t)}function qi(e,t,n){let r=t;switch(t.type){case`approval.created`:{let i=r.approval||t;return i?.id?{handled:!0,value:{...e,approvals:[...e.approvals.filter(e=>e.id!==i.id),i]},...i.sessionId?{row:{sessionId:i.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}:{handled:!0,value:e}}case`approval.resolved`:case`approval.removed`:{let t=String(r.id||r.approvalId||``),n=e.approvals.find(e=>e.id===t),i={...e,approvals:e.approvals.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!Ki(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.question`:{let t=String(r.requestId||``),i=Gi(r.questions);if(!t||!i)return{handled:!0,value:e};let a={id:t,...r.sessionId?{sessionId:String(r.sessionId)}:{},questions:i,createdAt:Number(r.createdAt)||n};return{handled:!0,value:{...e,questions:[...e.questions.filter(e=>e.id!==t),a]},...a.sessionId?{row:{sessionId:a.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}}case`session.question.resolved`:{let t=String(r.requestId||r.id||``),n=e.questions.find(e=>e.id===t),i={...e,questions:e.questions.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!Ki(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.turn_attention`:{let t=String(r.sessionId||``),i=r.trigger===`wedged`||r.trigger===`stalled`?r.trigger:void 0;if(!t||!i)return{handled:!0,value:e};let a={sessionId:t,trigger:i,idleMs:Math.max(0,Number(r.idleMs)||0),at:Number(r.at)||n,message:String(r.message||`This turn may be stuck. Stop it or keep waiting?`)};return{handled:!0,value:{...e,turnAttentions:[...e.turnAttentions.filter(e=>e.sessionId!==t),a]},row:{sessionId:t,status:`needs_action`,needsAction:!0,updatedAt:n}}}case`session.turn_attention.resolved`:{let t=String(r.sessionId||``);if(!t)return{handled:!0,value:e};let n={...e,turnAttentions:e.turnAttentions.filter(e=>e.sessionId!==t)};return{handled:!0,value:n,...Ki(n,t)?{}:{row:{sessionId:t,status:`working`,needsAction:!1}}}}default:return{handled:!1,value:e}}}function q(e,t){return!!t&&t!==e}function Ji(e){return(Array.isArray(e.actions)?e.actions:[e.action]).filter(e=>typeof e==`string`&&e.length>0)}function Yi(e,t,n){let r=t,i=String(r.sessionId||``);switch(t.type){case`session.state`:{let t=Ri(r.state??r.sessionState);return!i||!t?{handled:!0,commands:[]}:{handled:!0,patch:i===e.activeSessionId?{working:t.agent===`working`,...t.agent===`working`?{}:{workingLabel:``}}:void 0,commands:[{kind:`row`,sessionId:i,patch:{sessionState:t,status:zi(t),needsAction:t.displayStatus===`needs_attention`}}]}}case`session.renamed`:{let t=[];return r.name&&i&&t.push({kind:`rename`,sessionId:i,name:String(r.name)}),r.branch&&i&&t.push({kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}),{handled:!0,patch:!i||i===e.activeSessionId?{...r.name?{activeTitle:String(r.name)}:{},...r.branch?{github:{...e.github,branch:String(r.branch)}}:{}}:void 0,commands:t}}case`session.branch_renamed`:return{handled:!0,patch:(!i||i===e.activeSessionId)&&r.branch?{github:{...e.github,branch:String(r.branch)}}:void 0,commands:r.branch&&i?[{kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}]:[]};case`session.error`:case`session.errored`:{if(q(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=r.error&&typeof r.error==`object`?r.error:null,n=t?.kind===`model_auth`&&typeof t.provider==`string`,i=n?`No credentials for ${t.provider}`:je(String(r.error||r.errorMessage||`error`)),a={kind:`entry`,role:`error`,text:i,...n?{actions:[`connect-provider:${t.provider}`]}:{}};return{handled:!0,patch:{...String(r.code||``).startsWith(`delivery_`)?{}:{working:!1},opening:!1},commands:r.sessionId?[a]:[{kind:`global-error`,message:i}]}}case`session.closed`:return{handled:!0,patch:i===e.activeSessionId?{working:!1,workingLabel:``,opening:!1}:void 0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`saved`,needsAction:!1}}]:[]};case`session.failed`:return{handled:!0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`failed`,needsAction:!1,failedAt:Number(r.failedAt)||n,updatedAt:n}}]:[]};case`session.notice`:{if(!r.message||i&&i!==e.activeSessionId)return{handled:!0,commands:[]};let t=Ji(r);return{handled:!0,commands:[{kind:`entry`,role:`system`,text:String(r.message),...t.length?{actions:t}:{}}]}}case`session.cloning`:return{handled:!0,patch:!i||i===e.activeSessionId?{working:!0,workingLabel:`Cloning ${r.repo||`repo`}…`}:void 0,commands:[]};case`session.auth_required`:return{handled:!0,commands:!q(e.activeSessionId,r.sessionId)&&r.provider?[{kind:`model-auth`,provider:String(r.provider),reason:String(r.reason||``)}]:[]};case`session.usage`:return{handled:!0,patch:q(e.activeSessionId,r.sessionId)?void 0:{usage:Ni(r.usage)},commands:[]};case`session.warning`:return{handled:!0,commands:!q(e.activeSessionId,r.sessionId)&&r.warning?[{kind:`entry`,role:`system`,text:String(r.warning)}]:[]};case`session.changes`:{if(q(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=Array.isArray(r.changes)?r.changes:[];if(!t.length)return{handled:!0,patch:{changes:null},commands:[]};let i={before:r.before?String(r.before):void 0,after:String(r.after??``),files:t};return{handled:!0,patch:{changes:i,changesHistory:[...e.changesHistory,{...i,id:e.newChangeId??`change-${e.changesHistory.length+1}`,at:n}]},commands:[]}}case`session.rewound`:return q(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{changes:null},commands:[{kind:`entry`,role:`system`,text:`Rewound the workspace to an earlier checkpoint.`}]};case`session.checkpoints`:return q(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{checkpoints:Array.isArray(r.checkpoints)?r.checkpoints.map(e=>({id:String(e.id??``),label:String(e.label??`checkpoint`),createdAt:Number(e.createdAt??0)})).filter(e=>e.id):[]},commands:[]};default:return{handled:!1,commands:[]}}}var Xi=e=>{let t=e;return!!t&&typeof t.viewId==`string`&&typeof t.view==`string`&&[`requests`,`data`,`logs`].includes(t.backend)&&typeof t.summary==`string`&&t.summary.length<=300&&(t.detail===void 0||typeof t.detail==`string`&&t.detail.length<=300)&&[`ok`,`warn`,`danger`,`neutral`].includes(t.tone)&&(t.item===void 0||typeof t.item==`string`)},Zi=e=>{let t=e;return!!t&&typeof t.hash==`string`&&/^[0-9a-f]{64}$/.test(t.hash)&&[t.size,t.width,t.height].every(e=>typeof e==`number`&&e>=0)};function Qi(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&(t.trigger===`present`||t.trigger===`run`||t.trigger===`asked`||t.trigger===`notes`)&&typeof t.at==`number`&&(t.shot===void 0||Zi(t.shot))&&(t.before===void 0||Zi(t.before))&&(t.note===void 0||typeof t.note==`string`)&&(t.notes===void 0||Number.isInteger(t.notes)&&t.notes>=0)&&(t.evidence===void 0||Array.isArray(t.evidence)&&t.evidence.length<=12&&t.evidence.every(Xi))&&(t.try===void 0||Array.isArray(t.try)&&t.try.length<=6&&t.try.every(e=>!!e&&typeof e.id==`string`&&/^[a-z0-9][a-z0-9-]{0,63}$/.test(e.id)&&typeof e.name==`string`&&e.name.length<=80))}var $i=[`open`,`changed`,`gone`,`done`];function ea(e){if(!e||typeof e!=`object`)return!1;let t=e,n=(e,t)=>!!e&&typeof e==`object`&&t.every(t=>typeof e[t]==`number`);return typeof t.id==`string`&&typeof t.sessionId==`string`&&typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.viewId==`string`&&typeof t.name==`string`&&typeof t.view==`string`&&typeof t.path==`string`&&typeof t.words==`string`&&typeof t.at==`number`&&(t.number===void 0||Number.isInteger(t.number)&&t.number>=1)&&Array.isArray(t.selectors)&&t.selectors.every(e=>typeof e==`string`)&&n(t.region,[`x`,`y`,`width`,`height`])&&n(t.viewport,[`width`,`height`])&&$i.includes(t.state)&&(t.shot===void 0||Zi(t.shot))}function ta(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.appId==`string`&&/^[a-f0-9]{32}$/.test(t.appId)&&typeof t.sessionId==`string`&&t.sessionId.length>0&&typeof t.name==`string`&&t.name.length<=100}var na=[{id:`1h`,label:`1 hour`,ms:36e5},{id:`1d`,label:`1 day`,ms:864e5},{id:`7d`,label:`7 days`,ms:6048e5}];function ra(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.urgent===void 0||typeof t.urgent==`boolean`)}function ia(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.status==`string`&&typeof t.task==`string`&&[t.agent,t.machine,t.nodeId,t.group,t.childSessionId,t.answer,t.branch,t.prUrl,t.failure].every(e=>e===void 0||typeof e==`string`)}function aa(e){return!!e&&e.type===`bivy_attachment`&&!!e.ref&&typeof e.ref.hash==`string`&&(e.ref.kind===`image`||e.ref.kind===`file`)}function oa(e,t){return{kind:e.kind,name:e.name,size:e.size,mimeType:e.mimeType,hash:e.hash,...t?.createdAt===void 0?{}:{createdAt:t.createdAt},...t?.artifact?{artifact:!0}:{}}}var sa=0,J=()=>`e${Date.now().toString(36)}-${(sa++).toString(36)}`;function ca(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`text`||t===`output_text`||!t&&typeof e?.text==`string`}function la(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`thinking`||t===`reasoning`}var ua=/^\s*(?:\[Request interrupted by user|<(?:task-notification|system-reminder)[\s>/])/;function da(e){return ua.test(e)}function fa(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.filter(ca).map(e=>String(e?.text??e?.content??``)).join(`
|
|
13
|
+
`);if(e&&typeof e==`object`){let t=e.text??e.content??e.output??e.result;if(typeof t==`string`)return t;if(t!==void 0)return fa(t);try{return JSON.stringify(e)}catch{return String(e)}}return e==null?``:String(e)}function pa(e){return Array.isArray(e)?e.filter(la).map(e=>String(e?.text??e?.thinking??e?.reasoning??``)).join(`
|
|
14
|
+
`):``}function ma(e){if(Array.isArray(e)){let t=e.filter(ca).map(e=>String(e?.text??e?.content??``)).join(`
|
|
15
|
+
`);if(t)return ga(t);try{return JSON.stringify(e)}catch{return String(e)}}return ga(fa(e))}var ha=[{header:/^\[Subagent hand-back\][^\n]*The report follows:\n/,indent:` `},{header:/^<task\b[^>\n]*>\s*<task_result>\n?/,footer:/\n?<\/task_result>\s*<\/task>\s*$/,indent:``}];function ga(e){for(let t of ha){let n=t.header.exec(e);if(!n)continue;let r=e.slice(n[0].length),i=t.footer?r.replace(t.footer,``):r;return t.indent?i.split(`
|
|
16
|
+
`).map(e=>e.startsWith(t.indent)?e.slice(t.indent.length):e).join(`
|
|
17
|
+
`):i}return e}function _a(e,t,n=J){if(!Array.isArray(e))return[];let r=[];for(let i of e)if(Ce(i)){let e=ke(i)||t||``;r.push({callId:Oe(i)||n(),name:Te(i),input:Ee(i),status:`running`,detail:j(i),...e?{parentToolUseId:e}:{}})}else if(we(i)){let e=Oe(i),t=ma(i?.content),n=j(i),a=(i?.isError||i?.is_error)&&n?{...n,result:{...n.result??{},isError:!0}}:i?.isError||i?.is_error?{kind:`unknown`,result:{isError:!0}}:n;r.push({callId:e,name:Te(i),input:{},status:`done`,result:t,...a?{detail:a}:{}})}return r}function va(e){return{callId:String(e?.toolCallId||e?.toolUseId||e?.tool_use_id||e?.id||``),name:String(e?.toolName||e?.name||`tool`).toLowerCase(),input:{},status:`done`,result:ma(e?.content),detail:e?.isError||e?.is_error?j(e)??{kind:`unknown`,result:{isError:!0}}:j(e)}}function ya(e){let t=new Map;function n(e){if(!e||typeof e!=`object`)return;if(aa(e)){t.set(e.ref.hash,oa(e.ref));return}if(Array.isArray(e)){e.forEach(n);return}let r=e;r.content&&n(r.content)}return n(e),[...t.values()]}function ba(e){let t=[],n=new Set,r=-1,i=0,a=()=>`h${r}.${i++}`;for(let o of e||[]){r++,i=0;let e=String(o?.role||`assistant`).toLowerCase(),s=o?.content,c=fa(s);if(e===`user`){if(Array.isArray(s)){for(let e of s)if(we(e))for(let n of _a([e],void 0,a))Ca(t,n,a)}let e=ya(s);(c&&!da(c)||e.length)&&t.push({id:a(),role:`user`,text:c,...e.length?{attachments:e}:{}})}else if(e===`system`)c&&!da(c)&&t.push({id:a(),role:`system`,text:c});else if(e===`toolresult`||e===`tool_result`){let e=va(o);e&&Ca(t,e,a)}else{let e=ke(o),n=e=>{let n=e.trim();n&&t.push(Me(n)?{id:a(),role:`error`,text:je(n)}:{id:a(),role:`assistant`,text:n})},r=e=>{let n=e.trim();n&&t.push({id:a(),role:`thinking`,text:n})};if(typeof s==`string`||!Array.isArray(s))n(c);else{let i=[],c=[],l=()=>{n(i.join(`
|
|
18
|
+
`)),i=[]},u=()=>{r(c.join(`
|
|
19
|
+
`)),c=[]},d=()=>{l(),u()};for(let n of s)if(Ce(n)||we(n)){d();for(let r of _a([n],e,a))Ca(t,r,a)}else if(n?.type===`bivy_app`&&ta(n.app))d(),t.push({id:`app-${n.app.appId}`,role:`assistant`,text:``,app:n.app});else if(n?.type===`bivy_notice`&&ra(n.notice))d(),t.push({id:n.notice.id,role:`assistant`,text:``,notice:n.notice});else if(n?.type===`bivy_delegation`&&ia(n.delegation))d(),t.push({id:`delegation-${n.delegation.id}`,role:`assistant`,text:``,delegation:n.delegation});else if(n?.type===`bivy_app_review`&&Qi(n.review))d(),t.push({id:n.review.id,role:`assistant`,text:``,review:n.review});else if(n?.type===`bivy_app_pin`&&ea(n.pin))d(),t.push({id:n.pin.id,role:`assistant`,text:``,pin:n.pin});else if(aa(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:[{...oa(n.ref,{createdAt:e,artifact:n.artifact}),description:typeof n.caption==`string`?n.caption:void 0}]})}else ca(n)?(u(),i.push(String(n?.text??n?.content??``))):la(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=ya(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 xa(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,`
|
|
20
|
+
`).replace(/\n{3,}/g,`
|
|
21
|
+
|
|
22
|
+
`).trim()}function Sa(e,t){return e&&typeof e==`object`&&!Array.isArray(e)&&t&&typeof t==`object`&&!Array.isArray(t)?{...e,...t}:t??e}function Ca(e,t,n=J){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`?Sa(r.tool.input,t.input):r.tool.input}:e.push({id:n(),role:`assistant`,text:``,tool:t})}function wa(e=!0){return{assistantId:null,thinkingId:null,finalized:e,thinkingText:``,sawThinking:!1,pendingText:``,committedText:``,committedThinking:``}}function Ta(e){return{...e,transcript:[...e.transcript],draft:{...e.draft}}}function Ea(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 Da(e,t){let n={id:Ea(e.transcript),...t};return e.transcript.push(n),n}function Oa(e,t,n){e.transcript=e.transcript.map(e=>e.id===t?{...e,...n}:e)}function ka(e,t){e.transcript=e.transcript.filter(e=>e.id!==t)}function Aa(e,t){e.working=!0,e.workingLabel=t}function ja(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?Oa(e,s,{text:n,html:o,streaming:!r}):(s=Da(e,{role:i,text:n,html:o,streaming:!r}).id,e.draft[a]=s),r&&(e.draft[a]=null)}function Ma(e){e.draft.assistantId&&Oa(e,e.draft.assistantId,{streaming:!1}),e.draft.thinkingId&&Oa(e,e.draft.thinkingId,{streaming:!1}),e.draft.assistantId=null,e.draft.thinkingId=null}function Na(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,ja(e,`thinking`,n,!0))}function Pa(e){return(e.pendingText.startsWith(e.committedText)?e.pendingText.slice(e.committedText.length):e.pendingText).trim()}function Fa(e){let t=Pa(e.draft);t&&(e.draft.committedText=e.draft.pendingText,Me(t)?(e.draft.assistantId&&(ka(e,e.draft.assistantId),e.draft.assistantId=null),Da(e,{role:`error`,text:je(t)})):ja(e,`assistant`,t,!0))}function Ia(e){let t=Pa(e.draft);t&&ja(e,`assistant`,t,!1)}function La(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 Ra(e,t,n){if(t)n.thinkingText=t;else{let t=La(e);t.kind===`delta`?n.thinkingText+=t.text:t.kind===`full`&&(n.thinkingText=t.text)}return n.thinkingText.trim()}function za(e,t){return e&&t&&typeof e==`object`&&typeof t==`object`&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t??e}function Ba(e,t){let n=t.callId?e.transcript.findIndex(e=>e.tool?.callId===t.callId):-1;if(n<0){Da(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`?za(i.input,t.input):i.input}}}function Va(e){e.transcript=e.transcript.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function Ha(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}`:Ea(t)}function Ua(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 Wa(e,t){return e.some(e=>e.attachments?.some(e=>e.hash===t))}function Ga(e,t,n){let r=xe(t);if(!r)return{handled:!1,value:e,commands:[]};let i=Ta(e),a=[];switch(r){case`agent_start`:case`turn_start`:i.draft.finalized=!1,Aa(i,r===`agent_start`?`Planning…`:`Thinking…`);break;case`message_start`:t.message?.role===`assistant`&&(i.draft.finalized&&(i.draft=wa(!1)),Aa(i,`Drafting response…`));break;case`app_published`:{let e=t.app;if(!ta(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(!ia(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:(Na(i),Fa(i),i.transcript.push(n));break}case`notice`:{let e=t.notice;if(!ra(e)||i.transcript.some(t=>t.notice?.id===e.id))break;Na(i),Fa(i),i.transcript.push({id:e.id,role:`assistant`,text:``,notice:e});break}case`app_review`:{let e=t.review;if(!Qi(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(!ea(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(Wa(i.transcript,r.hash))break;let o=typeof t.caption==`string`?t.caption:``;Da(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=fa(n.content).trim();if(a&&(i.draft.pendingText=a),Ra(t,pa(n.content).trim(),i.draft)&&!a&&(i.draft.sawThinking=!0),r===`message_end`||r===`message_boundary`)Na(i),Fa(i),i.draft.finalized=!0;else{let e=a?`Drafting response…`:`Thinking…`;(!i.working||i.workingLabel!==e)&&Aa(i,e),Ia(i)}for(let e of _a(n.content))Ba(i,e);break}case`start`:Na(i),Fa(i),Ma(i),Ba(i,{callId:Ha(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Aa(i,Ua(t,i.transcript));break;case`update`:Ba(i,{callId:Ha(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Aa(i,Ua(t,i.transcript));break;case`result`:Ba(i,{callId:Ha(t,i.transcript),name:Te(t),input:{},status:`done`,result:ma(t.result),detail:j(t)});break;case`turn_end`:Aa(i,`Planning next step…`);break;case`agent_end`:Ma(i),Va(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=ya(t.result??t.message??t.output).filter(e=>!Wa(i.transcript,e.hash));e.length&&(Da(i,{role:`assistant`,text:``,attachments:e}),a.push({kind:`remember-agent-attachments`}))}return{handled:!0,value:i,commands:a}}function Y(e,t=!1){return{queue:e,changed:!1,accepted:t}}function Ka(e,t){switch(t.type){case`enqueue`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...Y(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{...Y(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 Y(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{...Y(e),edit:{ok:!1,reason:`not_found`}};let r=e[n];if(r.status!==`queued`)return{...Y(e),edit:{ok:!1,reason:`not_queued`}};if(r.version!==t.expectedVersion)return{...Y(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`?Y(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?Y(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 Y(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 Y(e);let r=Math.max(0,Math.min(t.toIndex,e.length-1));if(r===n)return Y(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 Y(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}:Y(e);case`revert-to-queued`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`sending`)return Y(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}:Y(e);case`clear`:return e.length?{queue:[],changed:!0,accepted:!0}:Y(e,!0)}}function qa(e){return e.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function Ja(e){return e===`openai-codex`?`openai`:e}var Ya=[`status`,`signedIn`,`nodes`,`currentNodeId`,`nodeUpdate`,`nodeUpdating`,`nodeUpdateAcknowledged`],Xa=[`sessions`,`runTerminals`,`tuiSessions`,`pausedSessionIds`,`commandsBySession`,`followupsBySession`],Za=[`activeSessionId`,`activeRuntimeId`,`activeTitle`,`github`,`transcript`,`working`,`workingLabel`,`opening`,`approvals`,`questions`,`turnAttentions`,`usage`,`changes`,`changesHistory`,`checkpoints`],Qa=[`models`,`modelsRuntimeId`,`currentModelId`,`currentModel`,`thinking`,`runtimes`,`currentAgentName`,`selectedAgentId`,`installingRuntimeId`,`repos`,`reposAuthed`,`reposError`,`reposLoading`,`reposReason`,`githubConnect`,`branches`,`branchesRepo`,`branchesDefault`,`branchesError`,`branchesLoading`,`providers`,`activationReadiness`],$a=[`nodeSettings`,`providerAuth`,`credentialRecords`,`credentialPresets`,`localModels`,`localModelPresets`,`rulesets`,`sttConfig`,`nodeStats`,`capabilities`],eo=[`forkProgress`,`oauth`,`needsModelAuth`,`githubApp`,`prResult`,`prRefreshAllResult`,`error`,`notice`];function to(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 no(){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:{...ni}}}function ro(e=!0){return wa(e)}function io(e){return e.role===`assistant`&&!e.tool&&!!e.attachments?.length}function ao(e){return e.tool?`tool:${e.tool.callId}`:`${e.role}:${e.text}`}function oo(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?so(e,0,r):e.length;if(!t.after)return so(e,n,r);for(let i=r-1;i>=n;i--){let n=e[i];if(!io(n)&&ao(n)===t.after)return so(e,i+1,r)}return r}function so(e,t,n){for(;t<n&&io(e[t]);)t++;return t}var co=class e{state=no();listeners=new Set;notifyPending=!1;notifyHandle=null;draft=ro();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 ai;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(ba(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 ba(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=ro(),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||Wi(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?Mi(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=to(this.state.connection,e,Ya),n=to(this.state.sessionIndex,e,Xa),r=to(this.state.activeSession,e,Za),i=to(this.state.catalogs,e,Qa),a=to(this.state.settings,e,$a),o=to(this.state.presentation,e,eo);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=_i((t&&typeof t==`object`?t:void 0)?.commands);if(vi(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=Ka(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(Li(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(Li(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=ro(),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:ri(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:J(),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=ri(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:ri(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=Wi(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=>Ui(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:Ui(t,e)}))})}setSelectedAgentLocal(e){let t={selectedAgentId:e,currentAgentName:Wi(this.state.catalogs.runtimes.find(t=>t.id===e))||this.state.catalogs.currentAgentName,draft:ri(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=ro(),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:ri(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:J(),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=oi(this.state.connection,e);if(n.handled){this.setValues({connection:n.value,...n.error?{presentation:{...this.state.presentation,error:n.error}}:{}});return}let r=si(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=li({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=ui(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=di(this.state.presentation,e);if(o.handled){this.setValues({presentation:o.value});return}let s=qi({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=Yi({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:J()}:{}},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:J(),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=Ri(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:zi(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:J(),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=Vi(t.models),i=t.current?Vi([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=>Ui(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=>Ui(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:Hi(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?Vi([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:Ui(e,n)}))});return}case`thinking.updated`:{let t=e;t.thinking&&this.set({thinking:Hi(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:Wi(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=Ja(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!==`notice`){let e=i===`agent_end`,r=Ri(t.state??t.sessionState);this.updateSessionRow(n,{status:zi(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=Pi(e.stats);t&&this.set({nodeStats:t});return}case`capabilities`:{let t=Fi(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=Ga({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=Ri(e.sessionState??e.bivySession?.state),l=!(c?c.agent===`working`:e.isStreaming),u=this.withCachedAttachments(l?qa(ba(a)):ba(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=ro(),this.deferredHistory=null;let f=Ri(e.sessionState??e.bivySession?.state);t&&f&&this.updateSessionRow(t,{sessionState:f,status:zi(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:ji(e),transcript:this.withPendingUserEntries(d),working:f?f.agent===`working`:!!e.isStreaming,opening:!1,usage:Ni(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(!io(a)){i=ao(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=oo(i,e);i=[...i.slice(0,t),{id:J(),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=yi(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 lo(e,t){return e>0||t}function uo(e){let t=e?.streamingBehaviors;return Array.isArray(t)&&t.includes(`steer`)}function fo(e){return e.find(e=>e.status===`queued`)}var po=`t`;function mo(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(po,{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(po,e)}catch{return r(null)}let o=t(a.objectStore(po));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 ho(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 go=`bivy-attachments-v1`,_o=67108864,vo=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(go)).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>_o)return;let a=await caches.open(go),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<=_o)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(go)}catch{}}},yo=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<=_o){for(;this.bytes+n>_o&&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()}},bo=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()}},xo=15e3,So=()=>Error(`The machine is not reachable.`),Co=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,So())},xo),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,So())}),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 wo(){return window.navigation}var To=0,Eo=[],Do=[],Oo,ko=[];function Ao(){if(!(Oo||Eo.some(e=>e.closing)))for(let e of ko.splice(0))e()}function jo(e){ko.push(e),setTimeout(Ao,0)}function Mo(){if(Oo)return;let e=Eo.at(-1);if(e?.closing){Oo=e;let t=wo();e.returnKey&&t?t.traverseTo(e.returnKey):history.back();return}for(let e of Do.splice(0))e.disposed||(e.returnKey=wo()?.currentEntry?.key,history.pushState({...history.state,__bivyModal:e.id},``,location.href),Eo.push(e));Eo.at(-1)?.closing?Mo():Ao()}typeof window<`u`&&window.addEventListener(`popstate`,e=>{let t=Eo.at(-1);if(t&&e.state?.__bivyModal===t.id){e.stopImmediatePropagation(),Oo=void 0,queueMicrotask(Mo);return}let n=Eo.pop();Oo=void 0,n&&(e.stopImmediatePropagation(),n.disposed||n.onBack(),queueMicrotask(Mo))});function No(e){let t={id:++To,onBack:e,closing:!1,disposed:!1};return queueMicrotask(()=>{t.disposed||(Do.push(t),Mo())}),{close(){t.closing||(t.closing=!0,Mo())},dispose(){t.disposed=!0,t.closing=!0,Mo()}}}var Po=[`appearance`,`notifications`,`import`,`providers`,`models`,`instructions`,`voice`,`share`,`github`,`linear`,`slack`,`queue`,`webhooks`,`rulesets`,`nodes`,`account`,`link`];function Fo(e){return Po.includes(e)}var Io=[`runs`,`rulesets`];function Lo(e){return e===`queue`?`runs`:Io.includes(e)?e:null}var Ro=/^\/(artifacts|apps)\/?$/,zo=/^\/sessions\/([^/]+)\/?$/,Bo=/^\/settings(?:\/([^/]+))?\/?$/,Vo=/^\/automations(?:\/([^/]+))?\/?$/;function Ho(e=location.pathname){let t=zo.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=Bo.exec(e);if(r){let e=r[1]?decodeURIComponent(r[1]):``;return{kind:`settings`,view:Fo(e)?e:null}}let i=Vo.exec(e);if(i)return{kind:`automations`,section:Lo(i[1]?decodeURIComponent(i[1]):``)};let a=Ro.exec(e);return a?{kind:`library`,view:a[1]}:{kind:`root`}}function Uo(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 X(e,t={}){let n=Uo(e);n!==location.pathname+location.search+location.hash&&(t.replace?history.replaceState(null,``,n):history.pushState(null,``,n))}function Wo(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 Go(e,t,n=globalThis.__BIVY_RUNTIME_CONFIG__){return!n||typeof n!=`object`||!(e in n)?t:n[e]===!0}var Ko=Go(`ephemeralMachinesEnabled`,{BASE_URL:`/`,DEV:!1,EPHEMERAL_MACHINES_ENABLED:``,MODE:`production`,PROD:!0,SSR:!1}.EPHEMERAL_MACHINES_ENABLED===`1`),qo=`bivy.pwa.first-success`,Jo=`bivy.product-metric.first_useful_response`,Yo=`bivy.pwa.install-dismissed`,Xo=new Set,Zo=null,Qo=!1,$o=!1,es=0;function ts(){try{return localStorage.getItem(qo)===`1`||localStorage.getItem(Jo)===`1`}catch{return!1}}function ns(){return typeof window>`u`?!1:window.matchMedia?.(`(display-mode: standalone)`).matches===!0||navigator.standalone===!0}function rs(){try{return localStorage.getItem(Yo)===`1`}catch{return!1}}$o=typeof window<`u`&&rs();function is(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 as(){return typeof navigator>`u`?null:is(navigator.userAgent,navigator.platform,navigator.maxTouchPoints,ns())}var Z={updateAvailable:!1,installChoice:null,standalone:ns(),shellCached:!1,firstSuccess:typeof window<`u`&&ts(),hasDraft:!1,pendingAttachments:0,readingAttachments:!1,turnActive:!1,locallyQueuedPrompts:0,queuedFollowups:0};function Q(e){let t={...Z,...e};Object.keys(t).every(e=>t[e]===Z[e])||(Z=t,Xo.forEach(e=>e()))}function os(){let e=ns();Q({standalone:e,installChoice:e||Qo||$o||!Z.firstSuccess?null:Zo?`native`:as()})}async function ss(){try{Q({shellCached:!!(await navigator.serviceWorker?.getRegistration())?.active})}catch{Q({shellCached:!1})}}function cs(){let e=e=>{e.preventDefault(),Zo=e,os()},t=()=>{Zo=null,Qo=!0,os()},n=()=>{ss()},r=window.matchMedia?.(`(display-mode: standalone)`);return window.addEventListener(`beforeinstallprompt`,e),window.addEventListener(`appinstalled`,t),navigator.serviceWorker?.addEventListener(`controllerchange`,n),r?.addEventListener?.(`change`,os),os(),ss(),()=>{window.removeEventListener(`beforeinstallprompt`,e),window.removeEventListener(`appinstalled`,t),navigator.serviceWorker?.removeEventListener(`controllerchange`,n),r?.removeEventListener?.(`change`,os)}}function ls(e){return Xo.add(e),()=>Xo.delete(e)}function us(){return Z}function ds(e){Q({updateAvailable:e})}function fs(e){Q(e)}function ps(e){Q({turnActive:e})}function ms(){es+=1,Q({locallyQueuedPrompts:es})}function hs(){es=0,Q({locallyQueuedPrompts:0})}function gs(e){Q({queuedFollowups:Math.max(0,Math.floor(e))})}function _s(){try{localStorage.setItem(qo,`1`)}catch{}Q({firstSuccess:!0}),os()}function vs(){$o=!0,Zo=null;try{localStorage.setItem(Yo,`1`)}catch{}Q({installChoice:null})}async function ys(){let e=Zo;if(!e||Z.standalone||!Z.firstSuccess)return`unavailable`;Zo=null,Q({installChoice:null});try{return await e.prompt(),(await e.userChoice).outcome}catch{return`unavailable`}}function bs(e=Z){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 xs(e=Z){return e.updateAvailable&&bs(e).length===0}var Ss="On that machine, run `bivy status` (or `bivy restart`).";function Cs(e,t,n=Z,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. ${Ss}`}: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. ${Ss}`}:e===`offline`?{kind:`offline-page`,label:`Offline`,detail:`${i} is unreachable. Your draft is kept on this device. ${Ss}`}:{kind:`live-control`,label:`Live control`,detail:`${i} is connected. Prompts send now and transcript changes sync live.`}}var ws=66e4,Ts=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}:{}},ws),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}:{}},ws)}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})})}},Es=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}},Ds=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)}},Os=class{deps;constructor(e){this.deps=e}listConfigs(){return this.deps.listConfigs()}async reprovision(e,t){try{let n=this.deps.correlations().find(n=>n.nodeId===e||n.sessionId===t);if(n?.computeSource!==`managed`)throw Error(`This session's machine can't be rebuilt.`);if(!n.setupId)throw Error(`This cloud 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)}catch(e){this.deps.reportError(e instanceof Error?e:Error(String(e)))}}isCurrentNodeResumable(){if(this.deps.direct())return!1;let e=this.deps.currentNodeId();return!e||this.deps.correlations().find(t=>t.nodeId===e)?.computeSource!==`managed`?!1:!this.deps.nodes().some(t=>t.id===e)}},ks=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)}},As=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 lo(t,this.store.getState().activeSession.working)}supportsSteering(){let e=this.store.getState(),t=e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId;return uo(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=fo(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}:{}})}},js=`bivy.device.id`,Ms=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android.*Mobile/,`Android phone`],[/Android/,`Android tablet`],[/CrOS/,`Chromebook`],[/Macintosh|Mac OS X/,`Mac`],[/Windows/,`Windows PC`],[/Linux/,`Linux`]];function Ns(e,t=0){let n=Ms.find(([t])=>t.test(e))?.[1]??`Browser`;return n===`Mac`&&t>1?`iPad`:n}var Ps;function Fs(){if(Ps)return Ps;let e=``;try{e=localStorage.getItem(js)??``}catch{}if(!e){e=`web:${crypto.randomUUID()}`;try{localStorage.setItem(js,e)}catch{}}return Ps={id:e,label:Ns(navigator.userAgent,navigator.maxTouchPoints)},Ps}var Is=class extends Error{disclosure;constructor(e){super(e),this.disclosure=e,this.name=`NeedsDisclosureError`}};function $(){return`r-${crypto.randomUUID()}`}function Ls(){return crypto.randomUUID()}var Rs=/^(localhost|127\.0\.0\.1|\[?::1\]?)$/,zs=`bivy-room-v1`,Bs=24e4;function Vs(e=gt(r())){return n?!1:Go(`directNode`,!1)||new URLSearchParams(location.search).has(`local`)?!0:Rs.test(location.hostname)&&!e.s&&!location.hash.includes(`payload=`)}var Hs=new class e{store=new co;local=gt(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=[];terminalListeners=new Set;pendingTranscriptions=new Map;pendingSpeech=new Map;pendingAcks=new Map;transcriptCache=mo({maxSessions:50});attachmentLoader=new yo;attachmentDiskCache=new vo;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 As(this.store,{send:e=>this.send(e),createClientMessageId:Ls,now:Date.now,persistBackstop:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},cancelBackstop:e=>this.cancelScheduledFollowup(e)}),this.nodeCoordinator=new Es({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 Ts({reportForkProgress:e=>this.store.setForkProgress({status:`working`,message:e}),send:e=>{this.sendToCurrentNode(e)},sendRequest:e=>{this.sendToCurrentNode(e)},createRequestId:$,createClientMessageId:Ls,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()}${Uo({kind:`session`,id:e})}`,refreshAccountSessions:()=>{this.refreshAccountSessions()},launchManagedDestination:async(e,t)=>{let n=await Pt(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:()=>X({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=Ho();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:()=>Ko?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(),X({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 Ds({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 Os({listConfigs:()=>Xt(this.local),direct:()=>this.direct,currentNodeId:()=>this.local.cur,nodes:()=>this.store.getState().connection.nodes,correlations:()=>this.ephemeralCorrelations,restoreManagedMachine:e=>Ft(this.local,e),connectToNode:(e,t)=>this.connectToNode(e,t),reportError:e=>this.store.setError(e.message)}),this.accountCoordinator=new ks({local:this.local,sendGithubDisconnect:({appId:e,hookId:t})=>this.send({kind:`github.app.disconnect`,requestId:$(),appId:e||void 0,hookId:t||void 0}),refreshNodes:()=>this.refreshNodes(),api:{fetchMe:Bt,fetchGithubApp:Gt,fetchGithubQueue:Cn,fetchAutomationRuns:_n,cancelAutomationRun:xn,disconnectGithubApp:Kt,removeNode:Ut,enablePush:Ln,disablePush:Rn,pushStatus:zn,getNotificationPreferences:Bn,setNotificationPreferences:Vn,createOneOffRun:gn,setGithubAppDefaultNode:qt,setGithubAppTriggerAccess:Jt,assignWorkItem:wn,deleteWorkItem:Tn,clearWorkQueue:En},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.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&&bt(this.local,location.hash)&&history.replaceState(null,``,location.pathname+location.search)}catch{}this.seedDraftDefaults(),this.detectGithubAppReturn(),this.direct=Vs(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=Ho(),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=Go(`directNode`,!1);return this.direct?new Gr({bootstrap:new URLSearchParams(location.search).get(`bootstrap`)||``,...t?{tokenStore:r(),pairCode:this.directPairCode,deviceName:Fs().label,requireToken:!0}:{},handlers:e}):new ei({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)}bn(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&&(_s(),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 Tt(this.local)}centralGithubApp(){return Et(this.local)}createCentralGithubInstall(e=`/`){return Dt(this.local,e)}managedAutomationTarget(){return Ot(this.local)}async managedCredentialReady(){return(await kt(this.local)).ready}async waitForManagedCredential(e=2e4,t=-1){let n=Date.now()+e;for(;Date.now()<n;){let e=await kt(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 Nt(this.local)}createNodeClaim(){return It(this.local)}listNodeClaims(){return Lt(this.local)}revokeNodeClaim(e){return Rt(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(Ho(),{navigate:!1})}),t(e=>{let t=Wo(e,d());t&&(history.replaceState(null,``,t.path),this.pendingRoute=Ho(),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:Fs(),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=$();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 Dr(this.local)).pub}catch{}try{await Fn(this.local,e)}catch{}try{await wr()}catch{}await this.attachmentDiskCache.clear(),this.local.clear(),await m(),this.store.setSignedIn(!1),location.assign(`/`)}listDevices(){return Nn(this.local)}isCurrentDevice(e){return!!e&&this.local.device()?.pub===e}removeDevice(e){return Pn(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:Fs()}:e)}updateNode(){ho(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=$();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 fileCommand(e,t,n){if(this.store.getState().connection.status!==`online`)throw Error(`Connect to the machine to browse its files.`);return this.awaitAck({kind:e,sessionId:t,path:n},3e4)}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 Co(this.local,(e,t)=>new ei({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 Is(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=Ls();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),X({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 zt(this.local);this.sessionTitleKeys??=new bo(this.local,(e,t)=>new ei({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,X({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},X({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&&X({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.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);if(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…`),n.computeSource!==`managed`)throw Error(`This machine profile is no longer supported.`);let o=Pt(this.local,n.id,{runtimeId:i,requestId:e}),[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 At&&r.code===`managed_credentials_required`?(this.store.updateLaunchCheckpoint(e,`capacity`,`waiting`),this.store.updateLaunchCheckpoint(e,`account`,`failed`,r.message,r.code)):r instanceof At&&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 At?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 kt(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&&X({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 ei({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},X({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…`],[Bs,`Still offline after ${Math.round(Bs/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 Tt(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 sn(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)){tn(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)){nn(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;let n=this.store.cachedModelsFor(e)??[];if(n.length){this.runtimeModelWaiters.delete(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(),X({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=$();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=$();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:$(),origin:d(),org:e||void 0})}githubAppManifestCode(e,t){this.store.setGithubAppPhase(`completing`),this.send({kind:`github.app.manifest.code`,requestId:$(),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 en(this.local,e)}fetchMe(){return this.accountCoordinator.fetchMe()}deleteAccount(){return Vt(this.local)}invokeAccountExtensionAction(e){return u()?Ht(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=gr();deviceOAuthCredentials=hr();ephemeralKeys=Vr({local:mr(),modelKeys:this.ephemeralModelKeys,oauthCredentials:this.deviceOAuthCredentials,oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled(),remote:this.deviceVaultRemote(),device:()=>Dr(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{}}}});pendingLaunchStore=_r();managedCredentialSetupNodes=new Set;managedCredentialGrantInFlight=!1;managedCredentialReturnSessionId=null;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)}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 Dr(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 Dr(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 Mr;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 Dr(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})`)}}}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}}}dismissModelAuthPrompt(){this.store.setNeedsModelAuth(null)}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{}}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})}}listEphemeralConfigs(){return this.ephemeralCoordinator.listConfigs()}getQueueRouting(){return Qt(this.local)}setQueueRouting(e){return $t(this.local,e)}setHostedProvisioning(e){return on(this.local,e)}listHostedMachines(){return sn(this.local)}destroyHostedMachine(e){return cn(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||!bt(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;X({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 un(this.local,{name:`Follow-up`,templateCiphertext:`${zs}:${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&&mn(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 fn(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 ln(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(),X({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||bn(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||bn(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||bn(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}},Us=g();function Ws({tone:e,variant:t=`outline`,upper:n=!1,className:r=``,children:i,...a}){return(0,Us.jsx)(`span`,{className:`badge${n?` upper`:``}${r?` ${r}`:``}`,"data-tone":e,"data-variant":t,...a,children:i})}function Gs(){return(0,y.useSyncExternalStore)(Hs.store.subscribe,Hs.store.getState)}export{Gt as $,Ai as A,vt as B,Ho as C,O as Ct,Ja as D,No as E,v as Et,gi as F,un as G,xn as H,mi as I,kn as J,mn as K,hi as L,bi as M,Oi as N,xa as O,fi as P,ln as Q,lr as R,X as S,E as St,jo as T,C as Tt,jn as U,vn as V,On as W,yn as X,Tt as Y,_n as Z,ds as _,Qe as _t,Fs as a,wt as at,Ko as b,Ae as bt,Cs as c,dn as ct,cs as d,Ct as dt,an as et,ms as f,St as ft,ps as g,rt as gt,gs as h,at as ht,Hs as i,yt as it,ki as j,na as k,vs as l,hn as lt,fs as m,pt as mt,Ws as n,Dn as nt,xs as o,bn as ot,ys as p,fn as pt,Mn as q,Is as r,xt as rt,hs as s,Sn as st,Gs as t,An as tt,us as u,pn as ut,ls as v,Fe as vt,Uo as w,D as wt,Go as x,ye as xt,bs as y,Ne as yt,Un as z};
|