@bivy/bivy 0.20.9-staging.2 → 0.20.9-staging.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +12 -14
- package/dist/agents/pi/integration.js +1 -1
- package/dist/apps/remote-preview.js +3 -0
- package/dist/apps/service.js +6 -1
- package/dist/apps/styles.css +40 -102
- package/dist/automation-reseal.js +30 -0
- package/dist/certification/generated.js +1 -1
- package/dist/device-registry.js +27 -0
- package/dist/ephemeral-teardown.js +11 -1
- package/dist/exec.js +4 -1
- package/dist/runtime/model-catalog.js +16 -0
- package/dist/server.js +73 -62
- package/dist/session/event-log.js +98 -41
- package/dist/session/inline-image-fetch.js +24 -33
- package/dist/session/message-components.js +323 -0
- package/dist/session/run-terminal.js +9 -7
- package/dist/session/session-tokens.js +1 -1
- package/dist/session/transcript-persistence.js +106 -11
- package/package.json +6 -6
- package/web/assets/AutomationsView-Cobo4Kep.js +51 -0
- package/web/assets/{ChangesCard-DcSRy5g_.js → ChangesCard-Bo6E8C_y.js} +3 -3
- package/web/assets/LibraryView-BTeMc6BO.js +2 -0
- package/web/assets/{ProviderConnect-cpGwBMrU.js → ProviderConnect-CsidS7kq.js} +1 -1
- package/web/assets/SessionList-B7IbeXSa.js +1 -0
- package/web/assets/Settings-BQRQsQ36.js +10 -0
- package/web/assets/{Sheet-D-5t3lJ0.js → Sheet-C0BIPbMr.js} +1 -1
- package/web/assets/{Terminal-CjMjKB1f.js → Terminal-BTRgonB5.js} +1 -1
- package/web/assets/{VoiceSettings-xv6rjaY2.js → VoiceSettings-UZ1SA0lQ.js} +1 -1
- package/web/assets/{abnfDiagram-VCTEODGH-BLT3MLyK.js → abnfDiagram-VCTEODGH-CJoWsvVk.js} +1 -1
- package/web/assets/architecture-7GRP2DOG-CuzcodTO.js +1 -0
- package/web/assets/{architectureDiagram-5GKGNRK7-BGinLETW.js → architectureDiagram-5GKGNRK7-_qpa4O1v.js} +1 -1
- package/web/assets/{blockDiagram-I7D4REHJ-BNiY2HLB.js → blockDiagram-I7D4REHJ-DmLgwSr-.js} +1 -1
- package/web/assets/{c4Diagram-7LVT6UL2-46aGfRMd.js → c4Diagram-7LVT6UL2-DeZuOOSk.js} +1 -1
- package/web/assets/channel-B0OL-aPd.js +1 -0
- package/web/assets/{chunk-4HAMMTFA-CRzer-vm.js → chunk-4HAMMTFA-Cr6O6lBG.js} +1 -1
- package/web/assets/{chunk-75Z2AOVW-MFkgf2Ar.js → chunk-75Z2AOVW-gSgNIYMY.js} +1 -1
- package/web/assets/{chunk-DU6HZSFF-Bpze6ID8.js → chunk-DU6HZSFF-BacnRf2Y.js} +1 -1
- package/web/assets/{chunk-F27PBJKO-Dq3OmNXG.js → chunk-F27PBJKO-DRrpfF1z.js} +1 -1
- package/web/assets/{chunk-GMAD6QVW-umDWdG9g.js → chunk-GMAD6QVW-DXCi6v6B.js} +1 -1
- package/web/assets/{chunk-GVQU2GXP-DuT1Awt9.js → chunk-GVQU2GXP-Yd74hIeT.js} +1 -1
- package/web/assets/{chunk-IMKFNOWR-CpFFccVb.js → chunk-IMKFNOWR-D5xz0-QC.js} +1 -1
- package/web/assets/{chunk-L3NEJ4N5-0jRWrASa.js → chunk-L3NEJ4N5-BrS0CGPM.js} +1 -1
- package/web/assets/{chunk-OSK3NFVY-CBErW4-p.js → chunk-OSK3NFVY-C6d1DSJe.js} +1 -1
- package/web/assets/{chunk-P2QGCYS3-BPMii7LM.js → chunk-P2QGCYS3-BrKgIngm.js} +1 -1
- package/web/assets/{chunk-POPQ4Y6H-CHTRMb_C.js → chunk-POPQ4Y6H-Bkwx5BZs.js} +1 -1
- package/web/assets/{chunk-PWAF6VOD-BOcNKrmu.js → chunk-PWAF6VOD-AeCCeE0F.js} +1 -1
- package/web/assets/{chunk-SHT3W25Y-Dvb-oEDN.js → chunk-SHT3W25Y-01NYjozy.js} +1 -1
- package/web/assets/{chunk-SVP7TREG-B4AQIUTK.js → chunk-SVP7TREG-CCh7wXAI.js} +1 -1
- package/web/assets/{chunk-TICWLB2K-CWzLTsHW.js → chunk-TICWLB2K-CcWKqwdM.js} +1 -1
- package/web/assets/classDiagram-ZZMXUADV-D8dSdFQt.js +1 -0
- package/web/assets/classDiagram-v2-VYDZK3BY-D8dSdFQt.js +1 -0
- package/web/assets/{cynefin-OW5HDTMX-BPkKT48j.js → cynefin-OW5HDTMX-CYYc_tBE.js} +1 -1
- package/web/assets/{cynefinDiagram-5FMLGOSQ-Ck2qLmpR.js → cynefinDiagram-5FMLGOSQ-Dnz7OfxK.js} +1 -1
- package/web/assets/{dagre-GXQ25YYZ-BPKEs_49.js → dagre-GXQ25YYZ-di5CyaMt.js} +1 -1
- package/web/assets/{diagram-S7CK7UJ4-ou-L5HdJ.js → diagram-S7CK7UJ4-BVC93OLB.js} +1 -1
- package/web/assets/{diagram-UQ7AKVKN-DihVn6fF.js → diagram-UQ7AKVKN-D7pXHAvQ.js} +1 -1
- package/web/assets/{diagram-VSXAHHWV-BkLtxbP7.js → diagram-VSXAHHWV-d0zW-IUz.js} +1 -1
- package/web/assets/{diagram-VX7I27RA-BZ-Z-CwP.js → diagram-VX7I27RA-BRlMo9oa.js} +1 -1
- package/web/assets/{diagram-Z3DM3KII-BQN-bGqD.js → diagram-Z3DM3KII-BmfntB1i.js} +1 -1
- package/web/assets/{ebnfDiagram-PWID7BFC-aKK1a_it.js → ebnfDiagram-PWID7BFC-BxUYvqsz.js} +1 -1
- package/web/assets/{erDiagram-RLTQ6QDP-BGsXtJl-.js → erDiagram-RLTQ6QDP-CbUl1Cqa.js} +1 -1
- package/web/assets/eventmodeling-NTZA5JFV-sTVSUyNU.js +1 -0
- package/web/assets/flowDiagram-HODETNUW-Beo3zBEU.js +1 -0
- package/web/assets/{ganttDiagram-EL5Y4UJY-lrYuyNAe.js → ganttDiagram-EL5Y4UJY-CkpR0avQ.js} +1 -1
- package/web/assets/{gitGraph-4MIJSDKK-raj_IxZ8.js → gitGraph-4MIJSDKK-CmbJxSaM.js} +1 -1
- package/web/assets/{gitGraphDiagram-WWUBYQGX-DzqRGXuk.js → gitGraphDiagram-WWUBYQGX-iyO408KF.js} +1 -1
- package/web/assets/index-B4HaCD-n.css +1 -0
- package/web/assets/{index-B6GPr2Pt.js → index-fdEPLcPs.js} +2 -2
- package/web/assets/{info-A6RAGUB7-DJVi9SAN.js → info-A6RAGUB7--6JCM0xX.js} +1 -1
- package/web/assets/{infoDiagram-27XIBGKW-B2HrGywP.js → infoDiagram-27XIBGKW-Dchx6QcB.js} +1 -1
- package/web/assets/{ishikawaDiagram-5VMMS53U-CczIkvWw.js → ishikawaDiagram-5VMMS53U-DOY3izUi.js} +1 -1
- package/web/assets/{journeyDiagram-3NMN7TZE-D-h-kwep.js → journeyDiagram-3NMN7TZE-oqZgC9oJ.js} +1 -1
- package/web/assets/{kanban-definition-UXKFOSKX-GClrFWfH.js → kanban-definition-UXKFOSKX-HCRC0D9X.js} +1 -1
- package/web/assets/{line-pweWV0oc.js → line-qcY2eok7.js} +1 -1
- package/web/assets/{mermaid-parser.core-C1vHZCtC.js → mermaid-parser.core-Bullp1xl.js} +3 -3
- package/web/assets/{mermaid.core-Df8DJ7AE.js → mermaid.core-FBmsAtMC.js} +4 -4
- package/web/assets/{mindmap-definition-YA3MSWOX-BpqA307n.js → mindmap-definition-YA3MSWOX-CfgOAkVQ.js} +1 -1
- package/web/assets/mount-IY4-2elJ.js +31 -0
- package/web/assets/{packet-AYTQ26CC-afE6T0Hc.js → packet-AYTQ26CC-COAmiopo.js} +1 -1
- package/web/assets/{pegDiagram-XKGWAZYB-AAEw7Khy.js → pegDiagram-XKGWAZYB-BYafVbeG.js} +1 -1
- package/web/assets/{pie-WAS4IAKB-vtwSUVVK.js → pie-WAS4IAKB-ZYe346n6.js} +1 -1
- package/web/assets/{pieDiagram-E7YTZNPT-CDg0SkhS.js → pieDiagram-E7YTZNPT-DnRbaA7i.js} +1 -1
- package/web/assets/{quadrantDiagram-AXDQQJYC-_o0rOR26.js → quadrantDiagram-AXDQQJYC-B2uxyKLd.js} +1 -1
- package/web/assets/{radar-RG4KPBEZ-_Tf7tpz8.js → radar-RG4KPBEZ-DwFlqYgB.js} +1 -1
- package/web/assets/{railroad-74A4TZTK-DM_a0HtL.js → railroad-74A4TZTK-DBv5jh9o.js} +1 -1
- package/web/assets/railroad-abnf-HS5TGJTU-VQxaaUVU.js +1 -0
- package/web/assets/railroad-ebnf-LZEXJU2U-DWKO1s90.js +1 -0
- package/web/assets/railroad-peg-WCYAUIDC-DvViPquF.js +1 -0
- package/web/assets/{railroadDiagram-O6MQD6OU-BpQZeQ-f.js → railroadDiagram-O6MQD6OU-CIUFwDWd.js} +1 -1
- package/web/assets/{requirementDiagram-BXWQKSXE-DC4US4K_.js → requirementDiagram-BXWQKSXE-BXwDlf9Q.js} +1 -1
- package/web/assets/{sankeyDiagram-P5KCCOFB-BUJ9KIqV.js → sankeyDiagram-P5KCCOFB-DTiRcy5E.js} +1 -1
- package/web/assets/{sequenceDiagram-WJ2MYXX4-By7D5XFY.js → sequenceDiagram-WJ2MYXX4-DFPRDr4a.js} +1 -1
- package/web/assets/settingsRoute-3489vHS0.js +1 -0
- package/web/assets/{stateDiagram-D77RDMKH-D0BA3EeM.js → stateDiagram-D77RDMKH-CFQ-4xlY.js} +1 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-DIIQkE2r.js +1 -0
- package/web/assets/{swimlanes-42K2YHIH-BNUI3ghm.js → swimlanes-42K2YHIH-Bke6VXs0.js} +1 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-Drds9YUy.js +8 -0
- package/web/assets/{timeline-definition-24CTP7MA-DVzeoz4F.js → timeline-definition-24CTP7MA-Cs2-dpWN.js} +1 -1
- package/web/assets/{treeView-Q6P3EWNA-CnvdZw-U.js → treeView-Q6P3EWNA-Dr8vsD3U.js} +1 -1
- package/web/assets/{treemap-WGGIJYW6-Ax_RXzPk.js → treemap-WGGIJYW6-DbvC3nsA.js} +1 -1
- package/web/assets/useStore-BDEjghiw.js +23 -0
- package/web/assets/{vennDiagram-4TSXK5OY-CNauH8S4.js → vennDiagram-4TSXK5OY-CdUoLWPo.js} +1 -1
- package/web/assets/{wardley-WFR3VGLG-q8WnmSMu.js → wardley-WFR3VGLG-BL7j6fb-.js} +1 -1
- package/web/assets/{wardleyDiagram-VM6X3IG4-DKOY4P11.js → wardleyDiagram-VM6X3IG4-BEVYmHWI.js} +1 -1
- package/web/assets/{xychartDiagram-S5SC5T6Z-m8KaPfml.js → xychartDiagram-S5SC5T6Z-C9zn_1JB.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-DEild20v.js +0 -51
- package/web/assets/LibraryView-Cu0tU0gU.js +0 -2
- package/web/assets/Settings-BoTU83-i.js +0 -10
- package/web/assets/architecture-7GRP2DOG-s28sMQ0-.js +0 -1
- package/web/assets/channel-CPSM7rj7.js +0 -1
- package/web/assets/classDiagram-ZZMXUADV-CZ-So67n.js +0 -1
- package/web/assets/classDiagram-v2-VYDZK3BY-CZ-So67n.js +0 -1
- package/web/assets/eventmodeling-NTZA5JFV-Dd2mk6iz.js +0 -1
- package/web/assets/flowDiagram-HODETNUW-D7f1jYIL.js +0 -1
- package/web/assets/index-D76QD5dl.css +0 -1
- package/web/assets/mount-ISRAcaLu.js +0 -33
- package/web/assets/railroad-abnf-HS5TGJTU-BzFZIgti.js +0 -1
- package/web/assets/railroad-ebnf-LZEXJU2U-BkKCtTE4.js +0 -1
- package/web/assets/railroad-peg-WCYAUIDC-CuXWl9dG.js +0 -1
- package/web/assets/settingsRoute-DSj-6Pdo.js +0 -1
- package/web/assets/stateDiagram-v2-MP3YSRHH-2_bDqGCB.js +0 -1
- package/web/assets/swimlanesDiagram-VR7AAH4N-SmXx3nAj.js +0 -8
- package/web/assets/useStore-BznE40dl.js +0 -29
|
@@ -1,29 +0,0 @@
|
|
|
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-B6GPr2Pt.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 gt(e,t,n){try{return JSON.parse(e.getItem(t)||JSON.stringify(n))}catch{return n}}function _t(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 gt(e,`bivy_keys`,{})},addKey(t,n){let r=this.keys();r[t]=n,e.setItem(`bivy_keys`,JSON.stringify(r))},nodePubs(){return gt(e,`bivy_nodepubs`,{})},addNodePub(t,n){let r=this.nodePubs();r[t]=n,e.setItem(`bivy_nodepubs`,JSON.stringify(r))},pairSecrets(){return gt(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 gt(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 gt(e,`bivy_device`,null)},setDevice(t){e.setItem(`bivy_device`,JSON.stringify(t))},clearDevice(){try{e.removeItem(`bivy_device`)}catch{}},sessions(){return gt(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 gt(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 vt=[`question_asked`,`agent_notice`,`approval_requested`,`agent_waiting`,`session_done`,`session_error`,`terminal_bell`,`automation_blocked`,`app_notes`],yt=[{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 sent you a message 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 bt(e){let t={};for(let n of vt){let r=e&&typeof e==`object`?e[n]:void 0;t[n]=typeof r!=`boolean`||r}return t}function xt(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 St(){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 Ct(e,t=fetch){let n=await t(`${I(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 wt(e,t,n=fetch){let r=await n(`${I(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 Tt(e,t,n,r=fetch){let i=await r(`${I(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 I(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}async function Et(e,t=fetch){let n=await t(`${I(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 Dt(e,t=fetch){let n=await t(`${I(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 Ot(e,t=`/`,n=fetch){let r=await n(`${I(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 kt(e,t=fetch){let n=await t(`${I(e)}/account/managed-automation-target`,{method:`POST`,headers:L(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 At(e,t=fetch){let n=await t(`${I(e)}/account/managed-credential-status`,{headers:L(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 jt=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 Mt(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 jt(e.reason||e.error||n,t,e.code,r)}function Nt(e,t){t.machine?.nodeId&&t.roomKey&&e.addKey(t.machine.nodeId,t.roomKey)}async function Pt(e,t=fetch){let n=await t(`${I(e)}/account/onboarding/managed-defaults`,{method:`POST`,headers:L(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.reason||r.error||`managed session setup failed: ${n.status}`);return Qt(r.config)}async function Ft(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(`${I(e)}/account/managed-machines`,{method:`POST`,headers:L(e),body:JSON.stringify({configId:t,...i?{runtimeId:i}:{},...a?{requestId:a}:{}})}),s=await o.json().catch(()=>({}));if(!o.ok||!s.machine)throw Mt(s,o.status,`managed Machine launch failed: ${o.status}`);return Nt(e,s),s.machine}async function It(e,t,n=fetch){let r=await n(`${I(e)}/account/managed-machines/restore`,{method:`POST`,headers:L(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok||!i.machine)throw Mt(i,r.status,`managed Machine restore failed: ${r.status}`);return Nt(e,i),i.machine}async function Lt(e,t=fetch){let n=await t(`${I(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 Rt(e,t=fetch){let n=await t(`${I(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 zt(e,t,n=fetch){let r=await n(`${I(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 Bt(e,t=fetch){let n=await t(`${I(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 L(e){return{authorization:`Bearer ${e.s}`,"content-type":`application/json`}}async function Vt(e,t=fetch){let n=await t(`${I(e)}/me`,{headers:L(e)});if(!n.ok)throw Error(`account request failed: ${n.status}`);return await n.json()}async function Ht(e,t=fetch){let n=await t(`${I(e)}/account`,{method:`DELETE`,headers:L(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`account deletion failed: ${n.status}`)}async function Ut(e,t,n=fetch){let r=await n(`${I(e)}/account/extension/actions/${encodeURIComponent(t)}`,{method:`POST`,headers:L(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 Wt(e,t,n=fetch){let r=await n(`${I(e)}/nodes/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok)throw Error(`remove node failed: ${r.status}`)}function Gt(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 Kt(e,t=fetch){let n=await t(`${I(e)}/account/github-app`,{headers:L(e)});if(!n.ok)throw Error(`github-app request failed: ${n.status}`);return Gt(await n.json())}async function qt(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(`${I(e)}/account/github-app${a}`,{method:`DELETE`,headers:L(e)});if(!o.ok)throw Error(`disconnect failed: ${o.status}`)}async function Jt(e,t,n,r=fetch){let i=await r(`${I(e)}/account/github-app/default-node`,{method:`POST`,headers:L(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 Yt(e,t,n,r=fetch){let i=await r(`${I(e)}/account/github-app/trigger-access`,{method:`POST`,headers:L(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`}async function Xt(e,t=fetch){let n=await t(`${I(e)}/account/ephemeral-default`,{headers:L(e)});if(!n.ok)throw Error(`ephemeral-default request failed: ${n.status}`);let r=await n.json().catch(()=>({}));return{enabled:!!r?.enabled,provider:r?.provider,region:r?.region,size:r?.size,ttlMinutes:r?.ttlMinutes}}async function Zt(e,t,n=fetch){let r=await n(`${I(e)}/account/ephemeral-default`,{method:`PUT`,headers:L(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set ephemeral default failed: ${r.status}`);return{enabled:!!i?.enabled,provider:i?.provider,region:i?.region,size:i?.size,ttlMinutes:i?.ttlMinutes}}function Qt(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 $t(e,t=fetch){let n=await t(`${I(e)}/account/ephemeral-configs`,{headers:L(e)});if(!n.ok)throw Error(`ephemeral-configs request failed: ${n.status}`);let r=await n.json().catch(()=>[]);return Array.isArray(r)?r.map(Qt).filter(e=>e.id):[]}async function en(e,t,n=fetch){let r=await n(`${I(e)}/account/ephemeral-configs`,{method:`POST`,headers:L(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`create ephemeral config failed: ${r.status}`);return Qt(i)}async function tn(e,t,n,r=fetch){let i=await r(`${I(e)}/account/ephemeral-configs/${encodeURIComponent(t)}`,{method:`PUT`,headers:L(e),body:JSON.stringify(n)}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`update ephemeral config failed: ${i.status}`);return Qt(a)}async function nn(e,t,n=fetch){let r=await n(`${I(e)}/account/ephemeral-configs/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`delete ephemeral config failed: ${r.status}`)}}function rn(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 an(e,t=fetch){let n=await t(`${I(e)}/account/queue-routing`,{headers:L(e)});if(!n.ok)throw Error(`queue-routing request failed: ${n.status}`);return rn(await n.json().catch(()=>({})))}async function on(e,t,n=fetch){let r=await n(`${I(e)}/account/queue-routing`,{method:`PUT`,headers:L(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set queue routing failed: ${r.status}`);return rn(i)}async function sn(e,t,n=fetch){let r=await n(`${I(e)}/account/hosted-github-app/connect`,{method:`POST`,headers:L(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 cn(e,t=fetch){let n=await t(`${I(e)}/account/hosted-github-repositories`,{headers:L(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 ln(e,t,n=fetch){let[r,i]=t.split(`/`);if(!r||!i)throw Error(`Repository must be owner/name`);let a=await n(`${I(e)}/account/hosted-github-repositories/${encodeURIComponent(r)}/${encodeURIComponent(i)}/branches`,{headers:L(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:[]}async function un(e,t,n,r,i=fetch){let a=await i(`${I(e)}/account/hosted-provisioning/validate-provider`,{method:`POST`,headers:L(e),body:JSON.stringify({provider:t,token:n,region:r})}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o?.error||`provider credential validation failed: ${a.status}`)}function dn(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 fn(e,t=fetch){let n=await t(`${I(e)}/account/hosted-provisioning`,{headers:L(e)});if(!n.ok)throw Error(`hosted-provisioning request failed: ${n.status}`);return dn(await n.json().catch(()=>({})))}async function pn(e,t,n=fetch){let r=await n(`${I(e)}/account/hosted-provisioning`,{method:`PUT`,headers:L(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set hosted provisioning failed: ${r.status}`);return dn(i)}async function mn(e,t=fetch){let n=await t(`${I(e)}/account/hosted-provisioning/rotate`,{method:`POST`,headers:L(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r?.error||`rotate hosted credentials failed: ${n.status}`);return dn(r)}async function hn(e,t=fetch){let n=await t(`${I(e)}/account/hosted-audit`,{headers:L(e)});if(!n.ok)throw Error(`hosted-audit request failed: ${n.status}`);let r=await n.json().catch(()=>[]);return Array.isArray(r)?r:[]}async function gn(e,t=fetch){let n=await t(`${I(e)}/account/hosted-machines`,{headers:L(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 _n(e,t,n=fetch){let r=await n(`${I(e)}/account/hosted-machines/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`hosted machine teardown failed: ${r.status}`)}}async function vn(e,t=!1,n=fetch){let r=await n(`${I(e)}/account/hosted-provision-now`,{method:`POST`,headers:L(e),body:JSON.stringify({execute:t})}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`hosted provision failed: ${r.status}`);return i}async function R(e,t,n={},r=fetch){let i=await r(`${I(e)}${t}`,{...n,headers:L(e)}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`automation request failed: ${i.status}`);return a}function yn(e,t=fetch){return R(e,`/account/automations`,{},t)}function bn(e,t,n=fetch){return R(e,`/account/automations`,{method:`POST`,body:JSON.stringify(t)},n)}function xn(e,t,n=fetch){return R(e,`/account/automations/${encodeURIComponent(t)}/webhook/rotate`,{method:`POST`},n)}function Sn(e,t,n,r=fetch){return R(e,`/account/automations/${encodeURIComponent(t)}`,{method:`PUT`,body:JSON.stringify(n)},r)}function Cn(e,t,n=fetch){return R(e,`/account/automations/simulate`,{method:`POST`,body:JSON.stringify(t)},n)}async function wn(e,t,n=fetch){let r=await n(`${I(e)}/account/automations/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok)throw Error(`delete automation failed: ${r.status}`)}function Tn(e,t,n=fetch,r=crypto.randomUUID()){return R(e,`/account/automations/${encodeURIComponent(t)}/run`,{method:`POST`,body:JSON.stringify({sourceKey:r})},n)}function En(e,t,n=fetch){return R(e,`/account/automation-runs`,{method:`POST`,body:JSON.stringify(t)},n)}function Dn(e,t=50,n={},r=fetch){let i=new URLSearchParams({limit:String(t)});return n.summary&&i.set(`summary`,`1`),R(e,`/account/automation-runs?${i}`,{},r)}var On=class extends Error{reason;status;constructor(e,t,n){super(e),this.reason=t,this.status=n,this.name=`RunFetchError`}};async function kn(e,t,n=fetch){let r;try{r=await n(`${I(e)}/account/automation-runs/${encodeURIComponent(t)}`,{headers:L(e)})}catch{throw new On(`Could not reach the control plane`,`error`)}if(r.status===404)return null;if(r.status===401)throw new On(`Unauthorized`,`unauthorized`,401);if(!r.ok)throw new On(`automation run request failed: ${r.status}`,`error`,r.status);return await r.json()}async function An(e,t,n,r=fetch){let i=await r(`${I(e)}/account/product-events`,{method:`POST`,headers:L(e),body:JSON.stringify({event:t,client:n})});if(!i.ok)throw Error(`product event request failed: ${i.status}`)}function jn(e,t,n=fetch){return R(e,`/account/automation-runs/${encodeURIComponent(t)}/cancel`,{method:`POST`},n).then(e=>e.run)}function Mn(e,t,n=fetch){return R(e,`/account/automation-runs/${encodeURIComponent(t)}/retry`,{method:`POST`},n).then(e=>e.run)}async function Nn(e,t=30,n=fetch){let r=await n(`${I(e)}/account/work-items?limit=${encodeURIComponent(String(t))}`,{headers:L(e)});if(!r.ok)throw Error(`work-items request failed: ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}async function Pn(e,t,n,r=fetch){let i=await r(`${I(e)}/account/work-items/${encodeURIComponent(t)}/assign`,{method:`POST`,headers:L(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 Fn(e,t,n=fetch){let r=await n(`${I(e)}/account/work-items/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`delete work item failed: ${r.status}`)}}async function In(e,t=fetch){let n=await t(`${I(e)}/account/work-items`,{method:`DELETE`,headers:L(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 Ln(e,t=fetch){let n=await t(`${I(e)}/account/slack-hook`,{headers:L(e)});if(!n.ok)throw Error(`Slack integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function Rn(e,t,n=fetch){let r=await n(`${I(e)}/account/slack-hook`,{method:`POST`,headers:L(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 zn(e,t=fetch){let n=await t(`${I(e)}/account/slack-hook`,{method:`DELETE`,headers:L(e)});if(!n.ok)throw Error(`Disconnect Slack failed: ${n.status}`)}async function Bn(e,t=fetch){let n=await t(`${I(e)}/account/linear-hook`,{headers:L(e)});if(!n.ok)throw Error(`Linear integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function Vn(e,t={},n=fetch){let r=await n(`${I(e)}/account/linear-hook`,{method:`POST`,headers:L(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 Hn(e,t=fetch){let n=await t(`${I(e)}/account/linear-hook`,{method:`DELETE`,headers:L(e)});if(!n.ok)throw Error(`Disconnect Linear failed: ${n.status}`)}async function Un(e,t=fetch){let n=await t(`${I(e)}/devices`,{headers:L(e)});if(!n.ok)throw Error(`devices request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:[]}async function Wn(e,t,n=fetch){let r=await n(`${I(e)}/devices/${encodeURIComponent(t)}`,{method:`DELETE`,headers:L(e)});if(!r.ok)throw Error(`remove device failed: ${r.status}`)}async function Gn(e,t,n=fetch){await n(`${I(e)}/auth/logout`,{method:`POST`,headers:L(e),body:JSON.stringify(t?{devicePublicKeyB64:t}:{})})}function Kn(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 qn(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(`${I(e)}/api/push/vapid-public-key`,{headers:L(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:Kn(String(i.publicKey))});if(!(await t(`${I(e)}/api/push/subscribe`,{method:`POST`,headers:L(e),body:JSON.stringify({subscription:a})})).ok)throw Error(`Could not register for push notifications.`);return`Push notifications enabled.`}async function Jn(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(`${I(e)}/api/push/subscribe`,{method:`DELETE`,headers:L(e),body:JSON.stringify({endpoint:i})}).catch(()=>{}),`Push notifications disabled on this device.`}async function Yn(){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 Xn(e,t=fetch){let n=await t(`${I(e)}/api/push/preferences`,{headers:L(e)});if(!n.ok)throw Error(`notification preferences request failed: ${n.status}`);return bt((await n.json().catch(()=>({})))?.preferences)}async function Zn(e,t,n=fetch){let r=await n(`${I(e)}/api/push/preferences`,{method:`PUT`,headers:L(e),body:JSON.stringify(t)});if(!r.ok)throw Error(`could not save notification preferences: ${r.status}`);return bt((await r.json().catch(()=>({})))?.preferences)}function Qn(e){return Math.max(5,Math.min(1440,Number(e)||60))}function $n(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`}function er(e){return e===`EUR`?`€`:`$`}function tr(e,t=`USD`){let n=er(t),r=e<.1?4:2;return`${n}${e.toFixed(r)}`}function nr(e,t,n=`USD`){let r=e?.pricePerHour;if(!r||r<=0)return``;let i=`≈ ${tr(r,n)}/hr`;return!t||t<=0?i:`${i} · up to ${tr(r*(Qn(t)/60),n)} before it self-destructs`}function rr(e,t,n,r){let i=e?.pricePerHour,a=Date.parse(t);if(!i||i<=0||!Number.isFinite(a))return null;let o=Qn(n);return{accrued:i*(Math.max(0,Math.min(r-a,o*6e4))/36e5),maximum:i*o/60}}var ir=[`api.hetzner.cloud`,`api.machines.dev`,`api.fly.io`,`ec2.us-east-1.amazonaws.com`,`ec2.us-west-2.amazonaws.com`,`ec2.eu-west-1.amazonaws.com`,`ec2.eu-central-1.amazonaws.com`,`ec2.ap-southeast-1.amazonaws.com`,`ec2.ap-northeast-1.amazonaws.com`,`ssm.us-east-1.amazonaws.com`,`ssm.us-west-2.amazonaws.com`,`ssm.eu-west-1.amazonaws.com`,`ssm.eu-central-1.amazonaws.com`,`ssm.ap-southeast-1.amazonaws.com`,`ssm.ap-northeast-1.amazonaws.com`],ar=new TextEncoder;function or(e){let t;try{t=new URL(e).host}catch{throw Error(`Bad provider URL: ${e}`)}if(!ir.includes(t))throw Error(`Refusing to send a token to non-provider host: ${t}`);return e}async function z(e,t){return or(t.url),await e(t)||{status:0,body:null}}function B(e){return{authorization:`Bearer ${String(e||``).trim()}`}}function V(e){return`'${String(e).replace(/'/g,`'\\''`)}'`}function sr(){try{return new Date().toISOString()}catch{return``}}function cr(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 H(e,t){let n=cr(e?.body);return`Provider failed to ${t} (HTTP ${e?.status}${n?`: ${n}`:``})`}function lr(e,t,n){let r=e.get(t);if(r)return r;let i=n().catch(n=>{throw e.delete(t),n});return e.set(t,i),i}function ur(e,t){return e.split(`
|
|
6
|
-
`).map(e=>t+e).join(`
|
|
7
|
-
`)}function dr(e){return JSON.stringify({url:e.relayUrl,enrollmentToken:e.enrollmentToken,e2eKey:e.e2eKeyB64,controlPlaneUrl:e.controlPlaneUrl,clientBaseUrl:e.controlPlaneUrl})}function fr(e){let t=!!e.provider;return[`export BIVY_DATA_DIR=/etc/bivy`,e.repo?`export BIVY_REPO=${V(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=${V(e.nodeLabel)}`:``,e.githubToken?`export BIVY_GITHUB_TOKEN=${V(e.githubToken)}`:``,e.hostedMint?`export BIVY_HOSTED_MINT=1`:``,t?`export BIVY_EPHEMERAL=1`:``,t?`export BIVY_EPHEMERAL_PROVIDER=${V(e.provider)}`:``,t?`export BIVY_EPHEMERAL_TTL_MIN=${Qn(e.ttlMinutes)}`:``,t&&e.teardownOnAgentFinish?`export BIVY_TEARDOWN_ON_FINISH=1`:``,t&&e.restoreSessionId?`export BIVY_RESTORE=${V(e.restoreSessionId)}`:``].filter(Boolean)}function pr(e){return`#!/bin/bash
|
|
8
|
-
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$HOME/.local/bin:$PATH"
|
|
9
|
-
BIVY_CLI="$(readlink -f "$(command -v bivy)")"
|
|
10
|
-
BIVY_PACKAGE_DIR="$(dirname "$(dirname "$BIVY_CLI")")"
|
|
11
|
-
if [ -d "$BIVY_PACKAGE_DIR/node_modules/.bin" ]; then export PATH="$BIVY_PACKAGE_DIR/node_modules/.bin:$PATH"; fi
|
|
12
|
-
`+fr(e).map(e=>`${e}\n`).join(``)+`exec bivy start
|
|
13
|
-
`}function mr(e,t){return`curl --connect-timeout 2 --max-time 3 -fsS -X POST -H 'content-type: application/json' -H ${V(`authorization: Bearer ${e.enrollmentToken}`)} --data ${V(JSON.stringify({phase:t}))} ${V(`${e.controlPlaneUrl.replace(/\/$/,``)}/node/bootstrap-status`)} >/dev/null 2>&1 || true`}function hr(e){let t=dr(e),n=Qn(e.ttlMinutes),r=e.installUrl||`https://bivy.sh/install.sh`,i=pr(e),a=t=>mr(e,t),o=`systemd-run --on-active=${n}m --timer-property=AccuracySec=1s --unit=bivy-ttl shutdown -h now || (echo 'shutdown -h now' | at now + ${n} minutes) || setsid bash -c 'sleep ${n*60}; shutdown -h now' </dev/null >/var/log/bivy-ttl.log 2>&1 &`;return[`#cloud-config`,`write_files:`,` - path: /etc/bivy/relay.json`,` permissions: '0600'`,` content: |`,ur(t,` `),` - path: /etc/bivy/start.sh`,` permissions: '0755'`,` content: |`,ur(i,` `),`runcmd:`,` - [ bash, -lc, ${JSON.stringify(o)} ]`,` - [ bash, -lc, ${JSON.stringify(a(`booting`))} ]`,` - [ bash, -lc, ${JSON.stringify(`set -euo pipefail; ${a(`installing`)}; mkdir -p /etc/bivy && export BIVY_DATA_DIR=/etc/bivy && (command -v bivy >/dev/null 2>&1 || curl --connect-timeout 10 --max-time 120 -fsSL ${V(r)} | bash) || { ${a(`failed`)}; exit 1; }`)} ]`,` - [ bash, -lc, ${JSON.stringify(a(`starting`))} ]`,` - [ bash, -lc, "systemd-run --unit=bivy --collect --property=Restart=on-failure /etc/bivy/start.sh || setsid bash /etc/bivy/start.sh </dev/null >/var/log/bivy.log 2>&1 &" ]`].join(`
|
|
14
|
-
`)+`
|
|
15
|
-
`}function gr(e){let t=String(e||``).split(`:`),n=(t[0]||``).trim(),r=(t[1]||``).trim(),i=t.length>2&&t.slice(2).join(`:`).trim()||void 0;if(!n||!r)throw Error("AWS token must be `accessKeyId:secretAccessKey` (optionally `:sessionToken`)");return{accessKeyId:n,secretAccessKey:r,sessionToken:i}}function _r(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function vr(e){let t=typeof e==`string`?ar.encode(e):e;return _r(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function yr(e,t){let n=await crypto.subtle.importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return new Uint8Array(await crypto.subtle.sign(`HMAC`,n,ar.encode(t)))}function br(e){return encodeURIComponent(e).replace(/[!*'()]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase())}function xr(){try{return new Date().toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}catch{return`19700101T000000Z`}}async function Sr(e){let t=e.amzDate||xr(),n=t.slice(0,8),r={};for(let[t,n]of Object.entries(e.headers))r[t.toLowerCase()]=n;r.host=e.host,r[`x-amz-date`]=t,e.creds.sessionToken&&(r[`x-amz-security-token`]=e.creds.sessionToken);let i=Object.keys(r).sort(),a=i.map(e=>`${e}:${String(r[e]).trim()}\n`).join(``),o=i.join(`;`),s=await vr(e.body),c=[e.method.toUpperCase(),e.path||`/`,``,a,o,s].join(`
|
|
16
|
-
`),l=`${n}/${e.region}/${e.service}/aws4_request`,u=[`AWS4-HMAC-SHA256`,t,l,await vr(c)].join(`
|
|
17
|
-
`),d=_r(await yr(await yr(await yr(await yr(await yr(ar.encode(`AWS4${e.creds.secretAccessKey}`),n),e.region),e.service),`aws4_request`),u));return{...r,authorization:`AWS4-HMAC-SHA256 Credential=${e.creds.accessKeyId}/${l}, SignedHeaders=${o}, Signature=${d}`}}var Cr={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`};function wr(e){return e.replace(/&(#x?[0-9a-fA-F]+|[a-z]+);/gi,(e,t)=>{if(t[0]===`#`){let n=t[1]===`x`||t[1]===`X`?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isFinite(n)?String.fromCodePoint(n):e}return Cr[t.toLowerCase()]??e})}function Tr(e){let t=0,n=e.length,r=e=>e===` `||e===` `||e===`
|
|
18
|
-
`||e===`\r`;function i(){for(;t<n&&r(e.charAt(t));)t++}function a(){for(;;){if(i(),e.startsWith(`<?`,t)){let r=e.indexOf(`?>`,t);t=r<0?n:r+2;continue}if(e.startsWith(`<!--`,t)){let r=e.indexOf(`-->`,t);t=r<0?n:r+3;continue}if(e.startsWith(`<!`,t)){let r=e.indexOf(`>`,t);t=r<0?n:r+1;continue}break}}function o(){let i=t;for(;t<n&&!r(e.charAt(t))&&e.charAt(t)!==`>`&&e.charAt(t)!==`/`&&e.charAt(t)!==`=`;)t++;return e.slice(i,t)}function s(){for(;;){if(i(),t>=n||e.charAt(t)===`>`||e.charAt(t)===`/`)return;if(o(),i(),e.charAt(t)===`=`){t++,i();let a=e.charAt(t);if(a===`"`||a===`'`){t++;let r=e.indexOf(a,t);t=r<0?n:r+1}else for(;t<n&&!r(e.charAt(t))&&e.charAt(t)!==`>`;)t++}}}function c(){t++;let r=o();s(),i();let a={tag:r,children:[],text:``};if(e.charAt(t)===`/`)return t+=2,a;t++;let l=``;for(;t<n;){if(e.startsWith(`</`,t)){let r=e.indexOf(`>`,t);t=r<0?n:r+1;break}if(e.startsWith(`<!--`,t)){let r=e.indexOf(`-->`,t);t=r<0?n:r+3;continue}if(e.charAt(t)===`<`){a.children.push(c());continue}let r=t;for(;t<n&&e.charAt(t)!==`<`;)t++;l+=e.slice(r,t)}return a.text=wr(l).trim(),a}return a(),t>=n||e.charAt(t)!==`<`?{tag:``,children:[],text:``}:c()}function U(e,t){return e?.children.find(e=>e.tag===t)}function Er(e,t){return e?e.children.filter(e=>e.tag===t):[]}function Dr(e,t){if(e){if(e.tag===t)return e;for(let n of e.children){let e=Dr(n,t);if(e)return e}}}function Or(e){return Object.entries(e).filter(e=>e[1]!==void 0).map(([e,t])=>`${br(e)}=${br(t)}`).join(`&`)}function kr(e){return`ec2.${e}.amazonaws.com`}function Ar(e){return`ssm.${e}.amazonaws.com`}async function jr(e,t,n,r,i,a){let o=kr(n),s=Or({Action:r,Version:`2016-11-15`,...i}),c=await Sr({method:`POST`,host:o,path:`/`,region:n,service:`ec2`,headers:{"content-type":`application/x-www-form-urlencoded; charset=UTF-8`},body:s,creds:t}),l=await z(e,{method:`POST`,url:`https://${o}/`,headers:c,body:s}),u=typeof l.body==`string`&&l.body.trim()?Tr(l.body):{tag:``,children:[],text:``};if(l.status>=300){let e=Dr(u,`Code`)?.text,t=Dr(u,`Message`)?.text;throw Error(`AWS failed to ${a} (HTTP ${l.status}${e?`: ${e}`:``}${t?` — ${t}`:``})`)}return u}async function Mr(e,t,n,r){let i=Ar(n),a=JSON.stringify({Name:r}),o=await Sr({method:`POST`,host:i,path:`/`,region:n,service:`ssm`,headers:{"content-type":`application/x-amz-json-1.1`,"x-amz-target":`AmazonSSM.GetParameter`},body:a,creds:t}),s=await z(e,{method:`POST`,url:`https://${i}/`,headers:o,body:a});if(s.status>=300){let e=cr(s.body)||(s.body&&typeof s.body==`object`?String(s.body.__type??``):``);throw Error(`AWS failed to resolve the Ubuntu AMI (HTTP ${s.status}${e?`: ${e}`:``})`)}let c=s.body&&typeof s.body==`object`?s.body?.Parameter?.Value:void 0;if(!c)throw Error(`AWS SSM did not return an AMI id`);return String(c)}var Nr=`/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id`,Pr=new Map;function Fr(e,t,n){return lr(Pr,n,()=>Mr(e,t,n,Nr))}function Ir(e){switch(e){case`running`:return`running`;case`pending`:return`starting`;case`stopping`:case`stopped`:case`shutting-down`:return`stopped`;case`terminated`:return`gone`;default:return`starting`}}var Lr=[{id:`us-east-1`,label:`US East (N. Virginia)`},{id:`us-west-2`,label:`US West (Oregon)`},{id:`eu-west-1`,label:`Europe (Ireland)`},{id:`eu-central-1`,label:`Europe (Frankfurt)`},{id:`ap-southeast-1`,label:`Asia Pacific (Singapore)`},{id:`ap-northeast-1`,label:`Asia Pacific (Tokyo)`}],Rr=40,W=(e,t,n,r,i)=>({id:e,label:t,vcpus:n,memoryMiB:r*1024,diskGiB:Rr,architecture:`x86_64`,pricePerHour:i,priceSource:`indicative`}),zr=[W(`t3.micro`,`t3.micro · 2 vCPU · 1 GB`,2,1,.0104),W(`t3.small`,`t3.small · 2 vCPU · 2 GB`,2,2,.0208),W(`t3.medium`,`t3.medium · 2 vCPU · 4 GB`,2,4,.0416),W(`t3.large`,`t3.large · 2 vCPU · 8 GB`,2,8,.0832),W(`t3.xlarge`,`t3.xlarge · 4 vCPU · 16 GB`,4,16,.1664),W(`t3.2xlarge`,`t3.2xlarge · 8 vCPU · 32 GB`,8,32,.3328),W(`m7i.xlarge`,`m7i.xlarge · 4 vCPU · 16 GB`,4,16,.2016),W(`m7i.2xlarge`,`m7i.2xlarge · 8 vCPU · 32 GB`,8,32,.4032),W(`r7i.2xlarge`,`r7i.2xlarge · 8 vCPU · 64 GB`,8,64,.5292),W(`r7i.4xlarge`,`r7i.4xlarge · 16 vCPU · 128 GB`,16,128,1.0584)],Br={id:`aws`,name:`AWS EC2`,currency:`USD`,regions:Lr,defaultRegion:`us-east-1`,sizes:zr,defaultSize:`m7i.xlarge`,async validateToken({exec:e,token:t,region:n}){await jr(e,gr(t),n||Br.defaultRegion,`DescribeInstances`,{MaxResults:`5`},`validate credential`)},async listSizes({exec:e,token:t,region:n}){let r=gr(t),i=n||Br.defaultRegion,a={};zr.forEach((e,t)=>{a[`InstanceType.${t+1}`]=e.id});let o;try{o=await jr(e,r,i,`DescribeInstanceTypes`,a,`list instance types`)}catch{return zr}let s;try{let t={LocationType:`region`};zr.forEach((e,n)=>{t[`Filter.1.Value.${n+1}`]=e.id}),t[`Filter.1.Name`]=`instance-type`;let n=await jr(e,r,i,`DescribeInstanceTypeOfferings`,t,`list instance offerings`);s=new Set(Er(U(n,`instanceTypeOfferingSet`),`item`).map(e=>U(e,`instanceType`)?.text||``).filter(Boolean))}catch{}let c=Er(U(o,`instanceTypeSet`),`item`).map(e=>{let t=U(e,`instanceType`)?.text||``,n=U(U(e,`vCpuInfo`),`defaultVCpus`)?.text,r=U(U(e,`memoryInfo`),`sizeInMiB`)?.text,i=r?Math.round(Number(r)/1024):void 0,a=zr.find(e=>e.id===t);return!t||s&&!s.has(t)?null:{...a,id:t,label:`${t} · ${n??`?`} vCPU · ${i??`?`} GB`,vcpus:n?Number(n):a?.vcpus,memoryMiB:r?Number(r):a?.memoryMiB}}).filter(e=>!!e);return c.length?c:zr},async provision({exec:e,token:t,config:n,userData:r}){let i=gr(t),a=n.region||Br.defaultRegion,o=`bivy-${n.slug}`,s=U(U(await jr(e,i,a,`RunInstances`,{ImageId:n.image?String(n.image):await Fr(e,i,a),InstanceType:n.size||Br.defaultSize,MinCount:`1`,MaxCount:`1`,UserData:b(ar.encode(r)),InstanceInitiatedShutdownBehavior:`terminate`,"BlockDeviceMapping.1.DeviceName":`/dev/sda1`,"BlockDeviceMapping.1.Ebs.VolumeSize":String(Rr),"BlockDeviceMapping.1.Ebs.VolumeType":`gp3`,"BlockDeviceMapping.1.Ebs.DeleteOnTermination":`true`,...n.attemptId?{ClientToken:String(n.attemptId)}:{},"TagSpecification.1.ResourceType":`instance`,"TagSpecification.1.Tag.1.Key":`Name`,"TagSpecification.1.Tag.1.Value":o,"TagSpecification.1.Tag.2.Key":`bivy`,"TagSpecification.1.Tag.2.Value":`ephemeral`,...n.attemptId?{"TagSpecification.1.Tag.3.Key":`bivy-attempt`,"TagSpecification.1.Tag.3.Value":String(n.attemptId)}:{},...n.ownershipTag?{"TagSpecification.1.Tag.4.Key":`bivy-account`,"TagSpecification.1.Tag.4.Value":String(n.ownershipTag)}:{}},`launch instance`),`instancesSet`),`item`),c=U(s,`instanceId`)?.text;if(!c)throw Error(`AWS did not return an instance id`);let l=U(U(s,`instanceState`),`name`)?.text,u=U(s,`ipAddress`)?.text||Dr(U(s,`networkInterfaceSet`),`publicIp`)?.text||null;return{id:c,provider:`aws`,name:o,region:a,status:Ir(l),ip:u||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=gr(t),i;try{i=await jr(e,r,n.region,`DescribeInstances`,{"InstanceId.1":n.id},`get instance`)}catch(e){if(String(e.message||``).includes(`InvalidInstanceID.NotFound`))return`gone`;throw e}let a=U(Dr(i,`instancesSet`),`item`);return a?Ir(U(U(a,`instanceState`),`name`)?.text):`gone`},async destroy({exec:e,token:t,machine:n}){let r=gr(t);try{await jr(e,r,n.region,`TerminateInstances`,{"InstanceId.1":n.id},`terminate instance`)}catch(e){if(!String(e.message||``).includes(`InvalidInstanceID.NotFound`))throw e}},async discover({exec:e,token:t,ownershipTag:n}){let r=gr(t),i=[];for(let t of Lr.map(e=>e.id)){let a;try{a=await jr(e,r,t,`DescribeInstances`,{"Filter.1.Name":`tag:bivy-account`,"Filter.1.Value.1":n,"Filter.2.Name":`instance-state-name`,"Filter.2.Value.1":`pending`,"Filter.2.Value.2":`running`,"Filter.2.Value.3":`stopping`,"Filter.2.Value.4":`stopped`},`list instances`)}catch{continue}for(let e of Er(U(a,`reservationSet`),`item`))for(let n of Er(U(e,`instancesSet`),`item`)){let e=U(n,`instanceId`)?.text;if(!e)continue;let r=U(U(n,`instanceState`),`name`)?.text,a=Er(U(n,`tagSet`),`item`).find(e=>U(e,`key`)?.text===`bivy-attempt`);i.push({id:e,provider:`aws`,name:e,region:t,status:Ir(r),ip:U(n,`ipAddress`)?.text||null,createdAt:U(n,`launchTime`)?.text||``,attemptId:a?U(a,`value`)?.text:void 0})}}return i}};function Vr(e){return e===`started`?`running`:e===`destroyed`?`gone`:e===`stopped`?`stopped`:`starting`}var Hr=`personal`;async function Ur(e,t,n){let r=String(n||``).trim();if(r)return r;let i=await z(e,{method:`POST`,url:`https://api.fly.io/graphql`,headers:{...B(t),"content-type":`application/json`},body:{query:`query { organizations { nodes { slug type } } }`}});if(i.status>=300)throw Error(H(i,`list organizations`));let a=Array.isArray(i.body?.data?.organizations?.nodes)?i.body.data.organizations.nodes:[];if(!a.length){let e=cr(i.body);throw Error(`Fly token has no accessible organizations${e?`: ${e}`:``}`)}let o=a.find(e=>String(e?.type||``).toUpperCase()===`PERSONAL`&&e?.slug)||a.find(e=>e?.slug)||a[0];return String(o?.slug||Hr)}var Wr={"shared-1x-1gb":{cpus:1,memoryMb:1024,cpuKind:`shared`},"shared-1x-2gb":{cpus:1,memoryMb:2048,cpuKind:`shared`},"shared-2x-4gb":{cpus:2,memoryMb:4096,cpuKind:`shared`},"shared-4x-8gb":{cpus:4,memoryMb:8192,cpuKind:`shared`},"shared-8x-16gb":{cpus:8,memoryMb:16384,cpuKind:`shared`}};function Gr(e){let t=e.installUrl||`https://bivy.sh/install.sh`,n=Qn(e.ttlMinutes)*60,r=e=>b(ar.encode(e)),i=[`set -euo pipefail`,`export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$HOME/.local/bin:$PATH"`,`export DEBIAN_FRONTEND=noninteractive`,`mkdir -p /etc/bivy /workspace`,`chmod 700 /etc/bivy`,`chmod 600 /etc/bivy/relay.json /etc/bivy/start.sh`,`export BIVY_DATA_DIR=/etc/bivy`,`export BIVY_WORKSPACE=/workspace`,`trap ${V(mr(e,`failed`))} ERR`,mr(e,`booting`),`if ! command -v bivy >/dev/null 2>&1; then\n${mr(e,`installing`)}\napt-get update -qq\napt-get install -y -qq curl ca-certificates\ncurl --connect-timeout 10 --max-time 120 -fsSL ${V(t)} | bash\nfi`,mr(e,`starting`),`exec bash /etc/bivy/start.sh`].join(`
|
|
19
|
-
`);return{files:[{guest_path:`/etc/bivy/relay.json`,raw_value:r(dr(e))},{guest_path:`/etc/bivy/start.sh`,raw_value:r(pr(e))}],init:{exec:[`/usr/bin/timeout`,`--kill-after=10s`,String(n),`/bin/bash`,`-c`,i]}}}async function Kr(e,t,n){if(!/^bivy-[a-z0-9-]+$/.test(n))return;let r=`https://api.machines.dev/v1/apps/${encodeURIComponent(n)}`,i=await z(e,{method:`GET`,url:`${r}/machines`,headers:B(t)});if(i.status===404)return;if(i.status>=300)throw Error(H(i,`check empty app`));if(!Array.isArray(i.body))throw Error(`Fly returned an invalid app inventory; keeping the app for cleanup retry`);if(i.body.length)return;let a=await z(e,{method:`DELETE`,url:r,headers:B(t)});if(a.status>=300&&a.status!==404)throw Error(H(a,`delete empty app`))}var qr={id:`fly`,name:`Fly.io`,currency:`USD`,regions:[{id:`iad`,label:`Ashburn, VA`},{id:`sjc`,label:`San Jose`},{id:`lhr`,label:`London`},{id:`fra`,label:`Frankfurt`},{id:`syd`,label:`Sydney`},{id:`nrt`,label:`Tokyo`}],defaultRegion:`iad`,sizes:[{id:`shared-1x-1gb`,label:`shared · 1 vCPU · 1 GB`,vcpus:1,memoryMiB:1024,architecture:`x86_64`,pricePerHour:.009,priceSource:`indicative`},{id:`shared-1x-2gb`,label:`shared · 1 vCPU · 2 GB`,vcpus:1,memoryMiB:2048,architecture:`x86_64`,pricePerHour:.0136,priceSource:`indicative`},{id:`shared-2x-4gb`,label:`shared · 2 vCPU · 4 GB`,vcpus:2,memoryMiB:4096,architecture:`x86_64`,pricePerHour:.0273,priceSource:`indicative`},{id:`shared-4x-8gb`,label:`shared · 4 vCPU · 8 GB`,vcpus:4,memoryMiB:8192,architecture:`x86_64`,pricePerHour:.0546,priceSource:`indicative`},{id:`shared-8x-16gb`,label:`shared · 8 vCPU · 16 GB`,vcpus:8,memoryMiB:16384,architecture:`x86_64`,pricePerHour:.1234,priceSource:`indicative`}],defaultSize:`shared-4x-8gb`,async validateToken({exec:e,token:t}){let n=await Ur(e,t),r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(n)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`validate credential`))},async provision({exec:e,token:t,config:n,bootstrap:r}){if(!r)throw Error(`Fly requires a structured Bivy bootstrap; cloud-init is not supported by Fly Machines.`);let i=`bivy-${n.slug}`,a=await Ur(e,t,n.org),o=Wr[n.size]||Wr[qr.defaultSize]||{cpus:1,memoryMb:2048,cpuKind:`shared`},s=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps`,headers:{...B(t),"content-type":`application/json`},body:{app_name:i,org_slug:a}}),c=s.status===422&&/name has already been taken/i.test(cr(s.body));if(s.status>=300&&s.status!==409&&!c)throw Error(H(s,`create app`));if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(r.status>=300)throw Error(H(r,`check existing launch`));if(!Array.isArray(r.body))throw Error(`Fly returned an invalid machine inventory; refusing to risk a duplicate launch`);let a=r.body.find(e=>e?.config?.metadata?.[`bivy-attempt`]===String(n.attemptId));if(r.status<300&&a?.id)return{id:String(a.id),provider:`fly`,app:i,name:i,region:a.region||n.region||`iad`,status:Vr(a.state),ip:null,createdAt:a.created_at||sr(),ttlMinutes:n.ttlMinutes};if(r.body.length)throw Error(`This Fly app already contains a machine from another launch. Reconnect or destroy it before rebuilding.`)}let l=Gr(r),u=await z(e,{method:`POST`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:{...B(t),"content-type":`application/json`},body:{region:n.region||`iad`,config:{image:n.image||`ghcr.io/bivysh/bivy-ephemeral-runner@sha256:30705bdda88425646b0c5dc19fc0e95cc4a026ca9c09a4f904c15b3a21e246ac`,auto_destroy:!r?.debugKeepMachine,restart:{policy:`no`},guest:{cpu_kind:o.cpuKind,cpus:Number(n.cpus)||o.cpus,memory_mb:Number(n.memoryMb)||o.memoryMb},metadata:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}},...l}}});if(u.status>=300)throw s.status<300&&u.status>=400&&u.status<500&&![408,409,429].includes(u.status)&&await Kr(e,t,i),Error(H(u,`create machine`));let d=u.body;if(!d||!d.id)throw Error(`Fly did not return a machine`);return{id:String(d.id),provider:`fly`,app:i,name:i,region:n.region||`iad`,status:Vr(d.state),ip:null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get machine`));return Vr(r.body?.state)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(n.app||``)}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete machine`));await Kr(e,t,n.app||``)},async cleanupAttempt({exec:e,token:t,nodeId:n,attemptId:r,ownershipTag:i}){if(!/^eph-(?:[a-f0-9]{16}|[a-f0-9]{32})$/.test(n))return!1;let a=`bivy-${n.replace(/^eph-/,``)}`,o=`https://api.machines.dev/v1/apps/${encodeURIComponent(a)}`,s=await z(e,{method:`GET`,url:`${o}/machines`,headers:B(t)});if(s.status!==404){if(s.status>=300||!Array.isArray(s.body))throw Error(`Cannot verify canceled Fly launch inventory`);if(s.body.some(e=>e?.config?.metadata?.[`bivy-attempt`]!==r||e?.config?.metadata?.[`bivy-account`]!==i))return!1;for(let n of s.body){if(!n?.id)return!1;let r=await z(e,{method:`DELETE`,url:`${o}/machines/${encodeURIComponent(n.id)}?force=true`,headers:B(t)});if(r.status>=300&&r.status!==404)return!1}let n=await z(e,{method:`DELETE`,url:o,headers:B(t)});if(n.status>=300&&n.status!==404)return!1}return(await z(e,{method:`GET`,url:o,headers:B(t)})).status===404},async discover({exec:e,token:t,ownershipTag:n}){let r=await Ur(e,t),i=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps?org_slug=${encodeURIComponent(r)}`,headers:B(t)});if(i.status>=300)throw Error(H(i,`list apps`));let a=Array.isArray(i.body?.apps)?i.body.apps:Array.isArray(i.body)?i.body:[],o=[];for(let r of a){let i=String(r?.name||``);if(!i.startsWith(`bivy-`))continue;let a=await z(e,{method:`GET`,url:`https://api.machines.dev/v1/apps/${encodeURIComponent(i)}/machines`,headers:B(t)});if(a.status>=300)continue;let s=Array.isArray(a.body)?a.body:[];for(let e of s){let t=e?.config?.metadata||{};t.bivy===`ephemeral`&&t[`bivy-account`]===n&&o.push({id:String(e.id),provider:`fly`,app:i,name:i,region:e.region||``,status:Vr(e.state),ip:null,createdAt:typeof e.created_at==`string`?e.created_at:``,attemptId:typeof t[`bivy-attempt`]==`string`?t[`bivy-attempt`]:void 0})}}return o}};function Jr(e){return e===`running`?`running`:e===`off`||e===`stopping`?`stopped`:`starting`}function Yr(e){let t=Array.isArray(e?.prices)?e.prices:[];for(let e of t){let t=Number(e?.price_hourly?.gross);if(Number.isFinite(t)&&t>0)return t}}var Xr=new Map,Zr=new Map;function Qr(e,t){return lr(Xr,t,async()=>{let n=[],r=`https://api.hetzner.cloud/v1/server_types?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list server types`));let a=Array.isArray(i.body?.server_types)?i.body.server_types:[];for(let e of a){if(e.deprecation)continue;let t=e.architecture===`arm`?`Arm64`:`x86`;n.push({typeId:Number(e.id),id:String(e.name),label:`${e.name} · ${e.cores} vCPU · ${e.memory} GB · ${e.disk} GB (${t})`,cores:Number(e.cores)||0,memory:Number(e.memory)||0,disk:Number(e.disk)||0,architecture:e.architecture===`arm`?`arm64`:`x86_64`,pricePerHour:Yr(e)})}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/server_types?per_page=50&page=${o}`:null}return n})}function $r(e,t){return lr(Zr,t,async()=>{let n=new Map,r=`https://api.hetzner.cloud/v1/datacenters?per_page=50`;for(let i=0;r&&i<10;i++){let i=await z(e,{method:`GET`,url:r,headers:B(t)});if(i.status>=300)throw Error(H(i,`list datacenters`));let a=Array.isArray(i.body?.datacenters)?i.body.datacenters:[];for(let e of a){let t=e?.location?.name;if(!t)continue;let r=n.get(t)??new Set,i=Array.isArray(e?.server_types?.available)?e.server_types.available:[];for(let e of i)r.add(Number(e));n.set(t,r)}let o=i.body?.meta?.pagination?.next_page;r=o?`https://api.hetzner.cloud/v1/datacenters?per_page=50&page=${o}`:null}return n})}var ei={id:`hetzner`,name:`Hetzner Cloud`,currency:`EUR`,regions:[{id:`nbg1`,label:`Nuremberg`},{id:`fsn1`,label:`Falkenstein`},{id:`hel1`,label:`Helsinki`},{id:`ash`,label:`Ashburn, VA`},{id:`hil`,label:`Hillsboro, OR`}],defaultRegion:`nbg1`,sizes:[{id:`cpx11`,label:`cpx11 · 2 vCPU · 2 GB · 40 GB (AMD x86)`,vcpus:2,memoryMiB:2048,diskGiB:40,architecture:`x86_64`,pricePerHour:.007,priceSource:`indicative`},{id:`cpx21`,label:`cpx21 · 3 vCPU · 4 GB · 80 GB (AMD x86)`,vcpus:3,memoryMiB:4096,diskGiB:80,architecture:`x86_64`,pricePerHour:.013,priceSource:`indicative`},{id:`cpx31`,label:`cpx31 · 4 vCPU · 8 GB · 160 GB (AMD x86)`,vcpus:4,memoryMiB:8192,diskGiB:160,architecture:`x86_64`,pricePerHour:.026,priceSource:`indicative`},{id:`cpx41`,label:`cpx41 · 8 vCPU · 16 GB · 240 GB (AMD x86)`,vcpus:8,memoryMiB:16384,diskGiB:240,architecture:`x86_64`,pricePerHour:.049,priceSource:`indicative`},{id:`cpx51`,label:`cpx51 · 16 vCPU · 32 GB · 360 GB (AMD x86)`,vcpus:16,memoryMiB:32768,diskGiB:360,architecture:`x86_64`,pricePerHour:.099,priceSource:`indicative`},{id:`cax11`,label:`cax11 · 2 vCPU · 4 GB · 40 GB (Arm64)`,vcpus:2,memoryMiB:4096,diskGiB:40,architecture:`arm64`,pricePerHour:.006,priceSource:`indicative`},{id:`cax21`,label:`cax21 · 4 vCPU · 8 GB · 80 GB (Arm64)`,vcpus:4,memoryMiB:8192,diskGiB:80,architecture:`arm64`,pricePerHour:.012,priceSource:`indicative`},{id:`cax31`,label:`cax31 · 8 vCPU · 16 GB · 160 GB (Arm64)`,vcpus:8,memoryMiB:16384,diskGiB:160,architecture:`arm64`,pricePerHour:.024,priceSource:`indicative`},{id:`cax41`,label:`cax41 · 16 vCPU · 32 GB · 320 GB (Arm64)`,vcpus:16,memoryMiB:32768,diskGiB:320,architecture:`arm64`,pricePerHour:.048,priceSource:`indicative`}],defaultSize:`cpx31`,guestCanEnsureDeletion:!1,async validateToken({exec:e,token:t}){let n=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?per_page=1`,headers:B(t)});if(n.status>=300)throw Error(H(n,`validate credential`))},async listSizes({exec:e,token:t,region:n}){let r=await Qr(e,t),i=r;if(n)try{let a=(await $r(e,t)).get(n),o=a?r.filter(e=>a.has(e.typeId)):r;o.length&&(i=o)}catch{}return[...i].sort((e,t)=>e.cores-t.cores||e.memory-t.memory||e.id.localeCompare(t.id)).map(({id:e,label:t,cores:n,memory:r,disk:i,architecture:a,pricePerHour:o})=>({id:e,label:t,vcpus:n,memoryMiB:r*1024,diskGiB:i,architecture:a,pricePerHour:o,priceSource:o?`live`:void 0}))},async provision({exec:e,token:t,config:n,userData:r}){let i=`bivy-${n.slug}`;if(n.attemptId){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-attempt=${n.attemptId}`)}`,headers:B(t)});if(r.status<300&&Array.isArray(r.body?.servers)&&r.body.servers[0]){let e=r.body.servers[0];return{id:String(e.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}}}let a=await z(e,{method:`POST`,url:`https://api.hetzner.cloud/v1/servers`,headers:{...B(t),"content-type":`application/json`},body:{name:i,server_type:n.size||ei.defaultSize,image:n.image||`ubuntu-24.04`,location:n.region||`nbg1`,user_data:r,start_after_create:!0,labels:{bivy:`ephemeral`,...n.attemptId?{"bivy-attempt":String(n.attemptId)}:{},...n.ownershipTag?{"bivy-account":String(n.ownershipTag)}:{}}}});if(a.status>=300)throw Error(H(a,`create server`));let o=a.body&&a.body.server;if(!o)throw Error(`Hetzner did not return a server`);return{id:String(o.id),provider:`hetzner`,name:i,region:n.region||`nbg1`,status:Jr(o.status),ip:o.public_net?.ipv4?.ip||null,createdAt:sr(),ttlMinutes:n.ttlMinutes}},async status({exec:e,token:t,machine:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status===404)return`gone`;if(r.status>=300)throw Error(H(r,`get server`));return Jr(r.body?.server?.status)},async destroy({exec:e,token:t,machine:n}){let r=await z(e,{method:`DELETE`,url:`https://api.hetzner.cloud/v1/servers/${encodeURIComponent(n.id)}`,headers:B(t)});if(r.status>=300&&r.status!==404)throw Error(H(r,`delete server`))},async discover({exec:e,token:t,ownershipTag:n}){let r=await z(e,{method:`GET`,url:`https://api.hetzner.cloud/v1/servers?label_selector=${encodeURIComponent(`bivy-account=${n}`)}`,headers:B(t)});if(r.status>=300)throw Error(H(r,`list servers`));return(Array.isArray(r.body?.servers)?r.body.servers:[]).map(e=>({id:String(e.id),provider:`hetzner`,name:String(e.name||``),region:e.datacenter?.location?.name||``,status:Jr(e.status),ip:e.public_net?.ipv4?.ip||null,createdAt:typeof e.created==`string`?e.created:``,attemptId:typeof e.labels?.[`bivy-attempt`]==`string`?e.labels[`bivy-attempt`]:void 0}))}},ti=new Map([ei,qr,Br].map(e=>[e.id,e]));function ni(e){return ti.get(String(e||``).trim().toLowerCase())||null}async function ri(e,t,n,r){let i=ni(e);if(!i)throw Error(`Unknown provider: ${e}`);let a=String(t||``).trim();if(!a)throw Error(`${i.name} token is required`);if(!i.validateToken)throw Error(`${i.name} credential validation is not available`);await i.validateToken({exec:n,token:a,region:r||i.defaultRegion})}function ii(e,t,n,r=Date.now()){return rr(e,t,n,r)}function ai(e){return e.replace(/^eph-/,``)}function oi(e){let t=e.region||e.defaultRegion,n=e.size||e.defaultSize,r=ai(e.nodeId),i=String(e.name||``).trim();return{attemptId:e.attemptId,nodeId:e.nodeId,requestedAt:e.requestedAt,provider:e.provider,region:t,size:n,providerConfig:{slug:r,region:t,size:n,image:e.image,ttlMinutes:e.ttlMinutes,attemptId:e.attemptId,ownershipTag:e.ownershipTag},machineFacts:{...i?{name:i}:{},...e.setupId?{setupId:e.setupId}:{},...e.repo?{repo:e.repo}:{},...e.teardownOnAgentFinish?{teardownOnAgentFinish:!0}:{},...e.workItemId?{workItemId:e.workItemId}:{},...e.purpose?{purpose:e.purpose}:{}}}}function si(e,t,n){return{...e,...t.machineFacts,attemptId:t.attemptId,nodeId:t.nodeId,size:t.size,milestones:{...e.milestones??{},requestedAt:t.requestedAt,providerAcceptedAt:n}}}function ci(e){let t=e.nodeId.replace(/^eph-/,``);return{bootstrap:{relayUrl:e.relayUrl,controlPlaneUrl:e.controlPlaneUrl,enrollmentToken:e.enrollmentToken,e2eKeyB64:e.roomKeyB64,ttlMinutes:e.ttlMinutes,repo:e.repo,hostedTasks:e.hostedTasks,hostedCredentialCustody:e.hostedCredentialCustody,hostedCredentialPublisher:e.hostedCredentialPublisher,nodeLabel:e.hostedTasks?t:void 0,githubToken:e.githubToken,hostedMint:e.hostedMint,provider:e.provider,teardownOnAgentFinish:e.teardownOnAgentFinish,debugKeepMachine:e.debugKeepMachine,restoreSessionId:e.restoreSessionId}}}var li=[{id:`fly`,name:`Fly.io`,computeClass:`byo-cloud`,tokenLabel:`Fly.io access token`,blurb:`Bivy creates a temporary Fly Machine, runs the session, then destroys it.`,steps:[`Open your Fly.io access tokens and sign in.`,`Click Create token — use a short-lived/deploy token if your account offers one.`,`Copy the token and paste it below. Revoke it after the session if you like.`],links:[{label:`Create a Fly.io token`,url:`https://fly.io/user/personal_access_tokens`},{label:`Fly Machines docs`,url:`https://fly.io/docs/machines/`}]},{id:`hetzner`,name:`Hetzner Cloud`,computeClass:`byo-cloud`,tokenLabel:`Hetzner Cloud API token`,blurb:`Bivy manages Hetzner servers from start to deletion so billing always stops, even when your devices are offline.`,steps:[`Open the Hetzner Cloud Console and select or create a project for Bivy's runners.`,`Go to Security → API Tokens and click Generate API token.`,`Choose Read & Write, then copy the token and paste it below.`],links:[{label:`Hetzner Cloud Console`,url:`https://console.hetzner.cloud/projects`},{label:`API token docs`,url:`https://docs.hetzner.com/cloud/api/getting-started/generating-api-token/`}],hostedOnly:!0},{id:`aws`,name:`AWS EC2`,computeClass:`byo-cloud`,tokenLabel:`Access key — paste as accessKeyId:secretAccessKey`,blurb:`Bivy launches a temporary EC2 instance, runs the session, then terminates it.`,steps:[`Create (or reuse) an IAM user scoped to a minimal EC2 policy — see the Bivy docs link below for a copy-pasteable policy.`,`On that user, open Security credentials → Access keys → Create access key.`,`Paste both values below as accessKeyId:secretAccessKey (append :sessionToken if you're using temporary STS credentials).`],links:[{label:`IAM access keys`,url:`https://console.aws.amazon.com/iam/home#/security_credentials`},{label:`EC2 console`,url:`https://console.aws.amazon.com/ec2/home`},{label:`Minimal IAM policy (Bivy docs)`,url:`https://github.com/bivysh/bivy/blob/main/docs/ephemeral-sessions.md#aws-ec2`}]}];function G(e){let t=String(e||``).trim().toLowerCase();return li.find(e=>e.id===t)||null}function ui(e){return{id:e.machineId||e.nodeId,provider:e.provider,name:e.nodeId,region:e.region||``,status:`gone`,ip:null,createdAt:``,ttlMinutes:e.ttlMinutes,app:e.app,nodeId:e.nodeId,setupId:e.setupId,repo:e.repo,computeSource:e.computeSource}}function di(e){let t=e.ephemeral;return!t?.provider||!t.machineId?null:{id:t.machineId,provider:t.provider,name:e.name||t.machineId,region:t.region||``,status:`stopped`,ip:null,createdAt:``,app:t.app,nodeId:e.id}}function fi(){try{return new Date().toISOString()}catch{return``}}function pi(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function mi(){let e=new Map;return{async getAll(){return[...e.values()].map(e=>({...e}))},async put(t,n){e.set(t,{...n})},async delete(t){e.delete(t)}}}function hi(e,t,n,r){function i(){return new Promise((i,a)=>{let o=e.open(t,1);o.onupgradeneeded=()=>{o.result.objectStoreNames.contains(n)||o.result.createObjectStore(n,{keyPath:r})},o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)})}function a(e,t){return e.transaction(n,t).objectStore(n)}function o(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}return{async getAll(){let e=await i();try{return await o(a(e,`readonly`).getAll())||[]}finally{e.close()}},async put(e,t){let n=await i();try{await o(a(n,`readwrite`).put(t))}finally{n.close()}},async delete(e){let t=await i();try{await o(a(t,`readwrite`).delete(e))}finally{t.close()}}}}function K(e,t){try{let n=globalThis.indexedDB;if(n)return hi(n,e===`provider-keys`?`bivy-ephemeral`:`bivy-ephemeral-${e}`,e,t)}catch{}return mi()}function gi(e=K(`provider-keys`,`provider`)){return{async list(){let t;try{t=await e.getAll()}catch{t=[]}let n=new Map(t.map(e=>[e.provider,e]));return li.map(e=>{let t=n.get(e.id);return{id:e.id,name:e.name,configured:!!(t&&t.token),updatedAt:t?t.updatedAt:null}})},async getToken(t){let n=G(t);if(!n)return``;let r;try{r=await e.getAll()}catch{return``}let i=r.find(e=>e.provider===n.id);return i&&i.token?i.token:``},async setToken(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n||``).trim();if(!i)throw Error(`API token cannot be empty`);await e.put(r.id,{provider:r.id,token:i,updatedAt:fi()})},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function _i(e=K(`model-oauth`,`id`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>t(e||`default`)||`default`,r=(e,t)=>`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async entries(){return(await i()).filter(e=>e?.provider&&e?.refresh).map(e=>({provider:t(e.provider),label:n(e.label),access:String(e.access||``),refresh:String(e.refresh),expires:Number(e.expires)||0,...Number.isFinite(Number(e.refreshedAt))?{refreshedAt:Number(e.refreshedAt)}:{},...Number.isFinite(Number(e.updatedAt))?{updatedAt:Number(e.updatedAt)}:{}}))},async set(i){let a=t(i.provider),o=n(i.label);if(!a||!String(i.refresh||``).trim())throw Error(`A provider and refresh token are required`);await e.put(r(a,o),{...i,id:r(a,o),provider:a,label:o})},async remove(i,a=`default`){await e.delete(r(t(i),n(a)))}}}function vi(e=K(`model-keys`,`provider`)){let t=e=>String(e||``).trim().toLowerCase(),n=e=>String(e||`default`).trim().toLowerCase()||`default`,r=(e,t)=>t==="default"?e:`${e}:${t}`,i=async()=>{try{return await e.getAll()}catch{return[]}};return{async list(){return(await i()).filter(e=>e&&e.provider).map(e=>({provider:String(e.provider),label:n(e.label),configured:!!e.key,updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`})).sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async entries(){return(await i()).filter(e=>e&&e.provider&&e.key).map(e=>({provider:String(e.provider),label:n(e.label),key:String(e.key),updatedAt:e.updatedAt??null,scope:e.scope===`device`?`device`:`account`}))},async get(e,r=`default`){let a=t(e),o=n(r);if(!a)return``;let s=(await i()).find(e=>e.provider===a&&n(e.label)===o);return s&&s.key?s.key:``},async set(i,a,o=`account`,s=`default`){let c=t(i),l=n(s);if(!c)throw Error(`Provider is required`);let u=String(a||``).trim();if(!u)throw Error(`API key cannot be empty`);if(o!==`account`&&o!==`device`)throw Error(`Credential scope must be account or device`);await e.put(r(c,l),{provider:c,label:l,key:u,scope:o,updatedAt:fi()})},async remove(i,a=`default`){let o=t(i);o&&await e.delete(r(o,n(a)))}}}var yi=`github-task-token`;function bi(e=K(`github-task-token`,`id`)){return{async get(){let t;try{t=await e.getAll()}catch{return``}let n=t.find(e=>e.id===yi);return n&&n.token?n.token:``},async set(t){let n=String(t||``).trim();if(!n)throw Error(`GitHub token cannot be empty`);await e.put(yi,{id:yi,token:n,updatedAt:fi()})},async remove(){await e.delete(yi)}}}var xi={region:null,size:null,ttlMinutes:null,repo:null,teardownOnAgentFinish:!1};function Si(e=K(`provider-prefs`,`provider`)){let t=async t=>{let n=G(t);if(!n)return{...xi};let r;try{r=await e.getAll()}catch{return{...xi}}let i=r.find(e=>e.provider===n.id);return i?{region:i.region??null,size:i.size??null,ttlMinutes:typeof i.ttlMinutes==`number`?i.ttlMinutes:null,repo:i.repo??null,teardownOnAgentFinish:i.teardownOnAgentFinish===!0}:{...xi}};return{get:t,async set(n,r){let i=G(n);if(!i)throw Error(`Unknown ephemeral provider: ${n}`);let a={...await t(i.id),...r};return await e.put(i.id,{provider:i.id,...a,updatedAt:fi()}),a},async remove(t){let n=G(t);n&&await e.delete(n.id)}}}function Ci(){try{return`setup-`+pi(8)}catch{return`setup-${Math.random().toString(16).slice(2)}`}}function wi(e=K(`setups`,`id`)){let t=async()=>{try{return(await e.getAll()).filter(e=>e&&e.id&&G(e.provider)).sort((e,t)=>String(e.name).localeCompare(String(t.name)))}catch{return[]}};return{async list(e){let n=await t();if(!e)return n;let r=G(e);return r?n.filter(e=>e.provider===r.id):[]},async get(e){return(await t()).find(t=>t.id===e)??null},async create(t,n){let r=G(t);if(!r)throw Error(`Unknown ephemeral provider: ${t}`);let i=String(n.name||``).trim();if(!i)throw Error(`Setup name is required`);let a=fi(),o={id:Ci(),provider:r.id,name:i,...xi,region:n.region??null,size:n.size??null,ttlMinutes:n.ttlMinutes??null,repo:n.repo??null,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,createdAt:a,updatedAt:a};return await e.put(o.id,o),o},async update(n,r){let i=(await t()).find(e=>e.id===n);if(!i)throw Error(`Ephemeral setup not found`);let a={...i,...r,id:i.id,provider:i.provider,updatedAt:fi()};if(a.name=String(a.name||``).trim(),!a.name)throw Error(`Setup name is required`);return await e.put(n,a),a},async remove(t){await e.delete(t)}}}function Ti(e=K(`pending-launches`,`id`)){return{async list(){try{return(await e.getAll()).filter(e=>e&&e.id&&e.config&&e.prompt).sort((e,t)=>String(e.createdAt).localeCompare(String(t.createdAt)))}catch{return[]}},async put(t){let{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u}=t;await e.put(n,{id:n,config:r,prompt:i,followups:a,logs:o,phase:s,machine:c,createdAt:l,updatedAt:u})},async remove(t){await e.delete(t)}}}function Ei(e=K(`machines`,`id`)){return{async list(){try{return(await e.getAll()).sort((e,t)=>String(t.createdAt).localeCompare(String(e.createdAt)))}catch{return[]}},async add(t){if(!t||!t.id)throw Error(`Machine record needs an id`);return await e.put(t.id,t),t},async update(t,n){let r=(await e.getAll().catch(()=>[])).find(e=>e.id===t);if(!r)return null;let i={...r,...n};return await e.put(t,i),i},async remove(t){await e.delete(t)}}}function Di(){try{return new Date().toISOString()}catch{return``}}function Oi(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}function ki(e,t=fetch){return async n=>{let r=await t(`${Oi(e)}/api/ephemeral/exec`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.s}`},body:JSON.stringify(n)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`exec relay failed (${r.status})`);return{status:i.status??r.status,body:i.body}}}function Ai(e){return[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function ji(e,t,n){let r=ni(e);if(!r)return[];if(!r.listSizes)return r.sizes;let i=await t.keys.getToken(e).catch(()=>``);if(!i)return r.sizes;try{let e=await r.listSizes({exec:t.exec,token:i,region:n});return e.length?e:r.sizes}catch{return r.sizes}}async function Mi(e,t){if(e.computeSource===`managed`&&!e.externalTeardownGuaranteed)throw Error(`Bivy hosted machines must be launched by the control plane, not with a device-held cloud token.`);if(t.enrollment?.token&&!e.reuseNodeId)throw Error(`Saved enrollment requires the original node identity`);let n=Di(),r=t.fetchImpl??fetch,i=ni(e.provider);if(!i)throw Error(`Unknown provider: ${e.provider}`);let a=t=>{try{e.onProgress?.(t)}catch{}};a(`Preparing ${i.name} launch…`);let o=await t.keys.getToken(e.provider);if(!o)throw Error(`Add a ${i.name} token first.`);if(i.guestCanEnsureDeletion===!1&&!e.externalTeardownGuaranteed)throw Error(`${i.name} requires hosted provisioning: powering off its guest does not delete the billable server, so a device-only launch is unsafe.`);let s=e.attemptId||Ai(16),c=e.reuseNodeId||`eph-`+Ai(8);await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`requested`});let l=JSON.stringify({nodeId:c,name:e.name||`Ephemeral ${i.name}`});a(`Enrolling a secure Bivy node…`);let u=async()=>{let e=await r(`${Oi(t.store)}/nodes/enroll`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${t.store.s}`},body:l});return{res:e,data:await e.json().catch(()=>({}))}},d=t.enrollment?.token;if(!d){let{res:t,data:n}=await u();if(!t.ok||typeof n?.enrollmentToken!=`string`||!n.enrollmentToken){let t=n?.error||`Could not enroll the machine`;throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:t}),Error(t)}d=n.enrollmentToken}await t.enrollment?.persist(c,d),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`enrolled`}),a(`Node enrolled. Building its secure bootstrap…`);let f=e.reuseRoomKeyB64?C(e.reuseRoomKeyB64):crypto.getRandomValues(new Uint8Array(32));t.store.addKey(c,S(f)),await t.persistRoomKey?.(c,S(f));let p=oi({...e,attemptId:s,nodeId:c,requestedAt:n,defaultRegion:i.defaultRegion,defaultSize:i.defaultSize}),m=ci({...e,provider:p.provider,nodeId:p.nodeId,enrollmentToken:d,roomKeyB64:b(f),relayUrl:t.store.relay,controlPlaneUrl:Oi(t.store)}),h=hr(m.bootstrap);a(`Creating the machine in ${p.region} (${p.size})…`);let g;try{g=await i.provision({exec:t.exec,token:o,userData:h,bootstrap:m.bootstrap,config:p.providerConfig})}catch(t){throw await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`failed`,error:String(t?.message||t).slice(0,500)}),t}let _={...g,...p.machineFacts,attemptId:s};return await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`provider-accepted`,machine:_}),a(`Machine created. Starting Bivy and connecting securely…`),g=si(_,p,Di()),await t.machines.add(g),await e.onLifecycle?.({attemptId:s,nodeId:c,phase:`tracked`,machine:g}),g}async function Ni(e,t){let n=t.fetchImpl??fetch,r=ni(e.provider);if(r){let n=await t.keys.getToken(e.provider);if(!n)throw Error(`Add the ${r.name} token on this device to destroy this machine.`);try{await r.destroy({exec:t.exec,token:n,machine:e})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Couldn't destroy this machine at ${r.name}: ${t}. It's still listed — try again in a moment.`)}}t.providerOnly||(await t.machines.remove(e.id),e.nodeId&&await n(`${Oi(t.store)}/nodes/${encodeURIComponent(e.nodeId)}`,{method:`DELETE`,headers:{authorization:`Bearer ${t.store.s}`}}).catch(()=>{}))}var Pi=`bivy`,q=`device-key`,Fi=`x25519`;function Ii(){try{return typeof globalThis<`u`&&!!globalThis.indexedDB}catch{return!1}}var Li=4e3;function Ri(){return new Promise((e,t)=>{let n=!1,r=e=>{n||(n=!0,e())},i=setTimeout(()=>r(()=>t(Error(`indexedDB.open timed out`))),Li),a=indexedDB.open(Pi,1);a.onupgradeneeded=()=>{a.result.objectStoreNames.contains(q)||a.result.createObjectStore(q)},a.onsuccess=()=>r(()=>{clearTimeout(i),e(a.result)}),a.onerror=()=>r(()=>{clearTimeout(i),t(a.error)}),a.onblocked=()=>r(()=>{clearTimeout(i),t(Error(`indexedDB.open blocked`))})})}function zi(e,t){return new Promise((n,r)=>{let i;try{i=t(e)}catch(e){r(e);return}i.onsuccess=()=>n(i.result),i.onerror=e=>{e.preventDefault(),r(i.error)}})}async function Bi(){if(!Ii())return;let e=await Ri();try{await zi(e.transaction(q,`readwrite`).objectStore(q),e=>e.delete(Fi))}finally{e.close()}}function Vi(){return Ii()?{async load(){let e=await Ri();try{let t=await zi(e.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));return t&&t.priv instanceof CryptoKey&&typeof t.pub==`string`?{priv:t.priv,pub:t.pub}:null}finally{e.close()}},async save(e,t){try{let n=globalThis.structuredClone;n&&n({priv:e,pub:t})}catch{throw Error(`IndexedDB cannot clone this device key`)}let n=await Ri();try{let r=n.transaction(q,`readwrite`);r.onerror=e=>e.preventDefault(),await zi(r.objectStore(q),n=>n.put({priv:e,pub:t},Fi)),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)});let i=await zi(n.transaction(q,`readonly`).objectStore(q),e=>e.get(Fi));if(!i||!(i.priv instanceof CryptoKey)||i.priv.extractable||i.pub!==t)throw Error(`IndexedDB did not preserve the non-extractable device key`)}finally{n.close()}}}:null}var Hi=new WeakMap;function Ui(e,t){if(t)return Wi(e,t);let n=Hi.get(e);if(n)return n;let r=Wi(e,Vi()??void 0);return Hi.set(e,r),r.catch(()=>{Hi.get(e)===r&&Hi.delete(e)}),r}async function Wi(e,t){let n=t??Vi();if(n)try{let t=await n.load();if(t)return t;let r=e.device();if(r){let t=await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!1,[`deriveBits`]);return await n.save(t,r.pub),e.clearDevice(),{priv:t,pub:r.pub}}let i=await crypto.subtle.generateKey({name:`X25519`},!1,[`deriveBits`]),a=S(new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)));return await n.save(i.privateKey,a),{priv:i.privateKey,pub:a}}catch{}let r=e.device();if(r)return{priv:await crypto.subtle.importKey(`pkcs8`,C(r.priv),{name:`X25519`},!0,[`deriveBits`]),pub:r.pub};let i=await crypto.subtle.generateKey({name:`X25519`},!0,[`deriveBits`]),a=new Uint8Array(await crypto.subtle.exportKey(`raw`,i.publicKey)),o=new Uint8Array(await crypto.subtle.exportKey(`pkcs8`,i.privateKey)),s=S(a),c=S(o);return e.setDevice({pub:s,priv:c}),{priv:i.privateKey,pub:s}}async function Gi(e,t){let n=await crypto.subtle.importKey(`raw`,C(t),{name:`X25519`},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:`X25519`,public:n},e,256))}async function Ki(e,t,n){let r=await Gi(e,t),i=await crypto.subtle.importKey(`raw`,r,`HKDF`,!1,[`deriveBits`]),a=n===`rotate`?w.rotate:n===`device-vault`?w.deviceVault:w.pair,o=new TextEncoder().encode(a),s=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:new Uint8Array,info:o},i,256)),c=n===`device-vault`?[`encrypt`,`decrypt`]:[`decrypt`];return crypto.subtle.importKey(`raw`,s,`AES-GCM`,!1,c)}async function qi(e,t){let n=await crypto.subtle.importKey(`raw`,C(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return S(new Uint8Array(await crypto.subtle.sign(`HMAC`,n,C(t))))}var Ji=class extends Error{constructor(){super(`Device vault changed concurrently`),this.name=`DeviceVaultConflictError`}},Yi=()=>({v:3,providerTokens:{},modelKeys:{},oauthCredentials:{}}),Xi=()=>({phase:`idle`,attemptedAt:null,succeededAt:null,pending:!1,failure:null}),Zi=e=>{let t=e?Date.parse(e):NaN;return Number.isFinite(t)?t:0};function Qi(e){if(e&&typeof e==`object`&&e.v===3){let t=e,n={};for(let[e,r]of Object.entries(t.modelKeys&&typeof t.modelKeys==`object`?t.modelKeys:{})){if(!r||typeof r!=`object`)continue;let t=r;n[e]=t.value?{...t,value:{provider:t.value.provider||e.split(`:`)[0]||e,label:t.value.label||e.split(`:`).slice(1).join(`:`)||`default`,key:t.value.key}}:t}return{v:3,providerTokens:t.providerTokens&&typeof t.providerTokens==`object`?t.providerTokens:{},modelKeys:n,oauthCredentials:t.oauthCredentials&&typeof t.oauthCredentials==`object`?t.oauthCredentials:{}}}let t=Yi(),n=Date.now();if(e&&typeof e==`object`&&e.v===2){let r=e;for(let[e,i]of Object.entries(r.providerTokens??{}))typeof i==`string`&&(t.providerTokens[e]={value:i,updatedAt:n});for(let[e,i]of Object.entries(r.modelKeys??{}))i&&typeof i.key==`string`&&(t.modelKeys[e]={value:{provider:e,label:`default`,key:i.key},updatedAt:Zi(i.updatedAt)||n})}else if(e&&typeof e==`object`)for(let[r,i]of Object.entries(e))typeof i==`string`&&(t.providerTokens[r]={value:i,updatedAt:n});return t}function $i(e,t){return e?t?e.updatedAt===t.updatedAt?!!e.tombstone==!!t.tombstone?JSON.stringify(e.value)>=JSON.stringify(t.value)?e:t:e.tombstone?e:t:e.updatedAt>t.updatedAt?e:t:e:t}function ea(e,t){let n=Yi();for(let r of new Set([...Object.keys(e.providerTokens),...Object.keys(t.providerTokens)]))n.providerTokens[r]=$i(e.providerTokens[r],t.providerTokens[r]);for(let r of new Set([...Object.keys(e.modelKeys),...Object.keys(t.modelKeys)]))n.modelKeys[r]=$i(e.modelKeys[r],t.modelKeys[r]);for(let r of new Set([...Object.keys(e.oauthCredentials),...Object.keys(t.oauthCredentials)]))n.oauthCredentials[r]=$i(e.oauthCredentials[r],t.oauthCredentials[r]);return n}function J(e,t=`default`){let n=String(e||``).trim().toLowerCase(),r=String(t||`default`).trim().toLowerCase()||`default`;return r==="default"?n:`${n}:${r}`}function ta(e){let t=e.indexOf(`:`);return t<0?{provider:e,label:`default`}:{provider:e.slice(0,t),label:e.slice(t+1)||`default`}}function na(){return crypto.getRandomValues(new Uint8Array(32))}function ra(e){let t=e.randomKey??na,n=e.now??Date.now,r=null,i=0,a=0,o=Yi(),s=null,c=0,l={},u={},d={},f={},p={},m={},h=Xi(),g=null,_=async()=>e.state?.save({clock:c,tokenVersions:l,modelVersions:u,oauthVersions:d,tokenTombstones:f,modelTombstones:p,oauthTombstones:m,sync:h}),v=()=>s??=(async()=>{let t=await e.state?.load();c=Math.max(t?.clock??0,n()),l={...t?.tokenVersions??{}},u={...t?.modelVersions??{}},d={...t?.oauthVersions??{}},f={...t?.tokenTombstones??{}},p={...t?.modelTombstones??{}},m={...t?.oauthTombstones??{}},h=t?.sync??Xi()})(),y=()=>c=Math.max(c+1,n()),S=async(e,t)=>D(await E(t),JSON.stringify(e)),C=async(e,t)=>Qi(JSON.parse(await O(await E(t),e))),w=async(e,t,n)=>D(await Ki(e.priv,t,`device-vault`),b(n)),T=async(e,t,n)=>x(await O(await Ki(e.priv,t,`device-vault`),n));async function ee(){let t=Yi();if(e.providerTokenSyncEnabled?.()!==!1)for(let n of await e.local.list()){let r=await e.local.getToken(n.id);r&&(t.providerTokens[n.id]={value:r,updatedAt:Math.max(Zi(n.updatedAt),l[n.id]??1)})}for(let[e,n]of Object.entries(f))t.providerTokens[e]=$i(t.providerTokens[e],{value:null,updatedAt:n,tombstone:!0});if(e.modelKeys){for(let n of await e.modelKeys.entries())if(n.scope===`account`){let e=J(n.provider,n.label);t.modelKeys[e]={value:{provider:n.provider,label:n.label,key:n.key},updatedAt:Math.max(Zi(n.updatedAt),u[e]??1)}}}for(let[e,n]of Object.entries(p))t.modelKeys[e]=$i(t.modelKeys[e],{value:null,updatedAt:n,tombstone:!0});if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let n of await e.oauthCredentials.entries()){let e=J(n.provider,n.label),r=Math.max(Number(n.refreshedAt)||0,Number(n.updatedAt)||0,d[e]??1);t.oauthCredentials[e]={value:n,updatedAt:r}}for(let[e,n]of Object.entries(m))t.oauthCredentials[e]=$i(t.oauthCredentials[e],{value:null,updatedAt:n,tombstone:!0});return t}async function te(t){for(let[n,r]of Object.entries(t.providerTokens)){let t=(await e.local.list()).find(e=>e.id===n),i=Zi(t?.updatedAt);r.tombstone?(f[n]=Math.max(f[n]??0,r.updatedAt),i<=r.updatedAt&&await e.local.remove(n)):r.value&&(!t?.configured||i<r.updatedAt)&&(await e.local.setToken(n,r.value),l[n]=r.updatedAt,delete f[n])}if(e.modelKeys)for(let[n,r]of Object.entries(t.modelKeys)){let t=r.value?.provider??n,i=r.value?.label??`default`,a=(await e.modelKeys.list()).find(e=>e.provider===t&&e.label===i),o=Zi(a?.updatedAt);r.tombstone?(p[n]=Math.max(p[n]??0,r.updatedAt),o<=r.updatedAt&&await e.modelKeys.remove(t,i)):r.value&&(!a?.configured||o<r.updatedAt)&&(await e.modelKeys.set(t,r.value.key,`account`,i),u[n]=r.updatedAt,delete p[n])}if(e.oauthCredentials&&e.oauthRecoveryEnabled?.()===!0)for(let[n,r]of Object.entries(t.oauthCredentials)){let t=(await e.oauthCredentials.entries()).find(e=>J(e.provider,e.label)===n),i=Math.max(Number(t?.refreshedAt)||0,Number(t?.updatedAt)||0,d[n]??0);if(r.tombstone){if(m[n]=Math.max(m[n]??0,r.updatedAt),i<=r.updatedAt){let r=t??ta(n);await e.oauthCredentials.remove(r.provider,r.label)}}else r.value&&i<r.updatedAt&&(await e.oauthCredentials.set(r.value),d[n]=r.updatedAt,delete m[n])}}async function ne(){if(!e.enabled())return;await v();let s=await e.device(),c=await e.remote.get();a=c.generation??0;let l=c.keyGeneration??0;(!r||(c.wrappedKey?.generation??0)>i)&&c.wrappedKey&&(r=await T(s,c.wrappedKey.wrappedByPublicKeyB64,c.wrappedKey.wrappedKey),i=c.wrappedKey.generation??l),r&&c.vault&&(o=await C(c.vault,r)),r&&l>i&&(r=t(),i=l);let u=await ee(),d=ea(o,u),f=Object.keys(d.providerTokens).length+Object.keys(d.modelKeys).length+Object.keys(d.oauthCredentials).length>0;if(!r){if(!c.vault&&f)r=t(),i=l;else{await e.remote.requestKey(),h={...h,phase:`pending`,pending:!0,failure:null},await _();return}}let p=JSON.stringify(d)!==JSON.stringify(o)||!c.vault||l>(c.wrappedKey?.generation??l);o=d,p&&(a=(await e.remote.putVault(await S(o,r),a,i))?.generation??a+1);let m=new Set([s.pub,...c.recipients??[],...c.requests]);for(let t of m)await e.remote.putWrapped(t,await w(s,t,r),s.pub,i);await te(o),h={phase:`synced`,attemptedAt:h.attemptedAt,succeededAt:new Date(n()).toISOString(),pending:!1,failure:null},await _()}async function k(){return g||(g=(async()=>{await v(),h={...h,phase:`pending`,attemptedAt:new Date(n()).toISOString(),pending:!0,failure:null},await _();try{for(let e=0;e<3;e++)try{await ne();return}catch(t){if(!(t instanceof Ji)||e===2)throw t}}catch(e){throw h={...h,phase:`failed`,pending:!0,failure:e instanceof Error?e.message:String(e)},await _(),e}})().finally(()=>{g=null}),g)}return{sync:k,getSyncState:()=>({...h}),async getToken(t){let n=await e.local.getToken(t);if(n)return n;e.enabled()&&!o.providerTokens[t]&&await k();let r=o.providerTokens[t];return r&&!r.tombstone?r.value??``:``},async setToken(t,n){await v(),await e.local.setToken(t,n),l[t]=y(),delete f[t],await _(),e.enabled()&&e.providerTokenSyncEnabled?.()!==!1&&await k()},async remove(t){await v(),await e.local.remove(t),f[t]=y(),await _(),e.enabled()&&await k()},async list(){let t=await e.local.list(),n=new Set(t.filter(e=>e.configured).map(e=>e.id)),r=[...t];if(e.providerTokenSyncEnabled?.()!==!1)for(let[e,t]of Object.entries(o.providerTokens))!t.tombstone&&t.value&&!n.has(e)&&r.push({id:e,name:e,configured:!0,updatedAt:new Date(t.updatedAt).toISOString()});return r},async listModelKeys(){let t=await e.modelKeys?.list()??[],n=new Set(t.filter(e=>e.configured).map(e=>J(e.provider,e.label)));for(let[e,r]of Object.entries(o.modelKeys))!r.tombstone&&r.value&&!n.has(e)&&t.push({provider:r.value.provider,label:r.value.label,configured:!0,updatedAt:new Date(r.updatedAt).toISOString(),scope:`account`});return t.sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))},async modelKeyEntries(){let t=await e.modelKeys?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.modelKeys))!t.tombstone&&t.value&&!n.has(e)&&n.set(e,{provider:t.value.provider,label:t.value.label,key:t.value.key,updatedAt:new Date(t.updatedAt).toISOString(),scope:`account`});return[...n.values()]},async getModelKey(t){let n=J(t),r=await e.modelKeys?.get(t)??``;if(r)return r;e.enabled()&&!o.modelKeys[n]&&await k();let i=o.modelKeys[n];return i&&!i.tombstone?i.value?.key??``:``},async setModelKey(t,n,r=`account`,i=`default`){if(!e.modelKeys)throw Error(`Device model-key storage is unavailable`);await v();let a=J(t,i);await e.modelKeys.set(t,n,r,i),r===`device`?p[a]=y():(u[a]=y(),delete p[a]),await _(),e.enabled()&&await k()},async removeModelKey(t,n=`default`){await v();let r=J(t,n);await e.modelKeys?.remove(t,n),p[r]=y(),await _(),e.enabled()&&await k()},async importModelKeys(t){if(e.modelKeys){await v();for(let n of t){let t=n.label??`default`,r=J(n.provider,t);await e.modelKeys.set(n.provider,n.key,`account`,t),u[r]=y(),delete p[r]}await _(),e.enabled()&&await k()}},async oauthCredentialEntries(){if(e.oauthRecoveryEnabled?.()!==!0)return[];let t=await e.oauthCredentials?.entries()??[],n=new Map(t.map(e=>[J(e.provider,e.label),e]));for(let[e,t]of Object.entries(o.oauthCredentials))if(!t.tombstone&&t.value){let r=n.get(e),i=Math.max(Number(r?.refreshedAt)||0,Number(r?.updatedAt)||0);(!r||i<t.updatedAt)&&n.set(e,t.value)}return[...n.values()]},async importOAuthCredentials(t){if(!e.oauthCredentials||e.oauthRecoveryEnabled?.()!==!0)return;await v();let n=await e.oauthCredentials.entries();for(let r of t){let t=J(r.provider,r.label),i=Math.max(Number(r.refreshedAt)||0,Number(r.updatedAt)||0),a=n.find(e=>J(e.provider,e.label)===t),o=Math.max(Number(a?.refreshedAt)||0,Number(a?.updatedAt)||0,d[t]??0);a&&i<=o||(await e.oauthCredentials.set(r),d[t]=i||y(),delete m[t])}await _(),e.enabled()&&await k()},async removeOAuthCredential(t,n=`default`,r){await v();let i=J(t,n),a=Number(r)||y();a<=(d[i]??0)||(await e.oauthCredentials?.remove(t,n),m[i]=Math.max(m[i]??0,a),await _(),e.enabled()&&await k())}}}var ia=`bivy_local_token`,aa=15e3,oa=`This device isn't paired with this machine. Run 'bivy tailscale pair' there and open the link on this device.`,sa=class{origin;tokenStore;fetchImpl;WS;bootstrap;pairCode;deviceName;requireToken;unpaired=!1;handlers;authPending=Promise.resolve();ws=null;connected=!1;backoff=1e3;closedByUs=!1;reconnectTimer=null;constructor(e){this.origin=e.origin??``,this.tokenStore=e.tokenStore??(typeof globalThis<`u`?globalThis.sessionStorage:void 0),this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.bootstrap=e.bootstrap??``,this.pairCode=e.pairCode??``,this.deviceName=e.deviceName??`Paired device`,this.requireToken=e.requireToken??!1,this.handlers=e.handlers}token(){return this.tokenStore?.getItem(ia)||``}directHeaders(e){let t=this.token();return{"content-type":`application/json`,...t?{authorization:`Bearer ${t}`}:{},...e||{}}}async directApi(e,t={}){if(!e.startsWith(`/api/auth/`)&&(await this.authPending,this.unpaired))throw Error(oa);let n=await this.fetchImpl(`${this.origin}${e}`,{...t,headers:{...this.directHeaders(),...t.headers||{}}}),r=await n.json().catch(()=>({}));if(!n.ok){let e=Error(r?.error||`Local request failed (${n.status})`);throw r&&typeof r==`object`&&Object.assign(e,r),e}return r}async bootstrapAuth(){if(this.pairCode){let e=this.pairCode;this.pairCode=``;try{let t=await this.directApi(`/api/auth/pair`,{method:`POST`,body:JSON.stringify({code:e,name:this.deviceName})});if(t?.token){this.tokenStore?.setItem(ia,t.token);return}}catch(e){this.handlers.onError?.(e instanceof Error?e.message:String(e))}}if(!(this.token()||this.requireToken))try{let e=await this.directApi(`/api/auth/bootstrap`,{method:`POST`,body:JSON.stringify({name:`Local Remote UI`,bootstrap:this.bootstrap})});e?.token&&this.tokenStore?.setItem(ia,e.token)}catch(e){console.warn(`local bootstrap failed`,e)}}notPaired(){this.unpaired=!0,this.connected=!1,this.setStatus(`offline`),this.handlers.onError?.(oa)}setStatus(e){this.handlers.onStatus(e)}emit(e){this.handlers.onEvent(e)}emitMerged(e,t,n){this.emit({...n||{},...t||{},type:e})}async connect(){this.closedByUs=!1,this.setStatus(`connecting`),this.authPending=this.bootstrapAuth(),await this.authPending;let e=typeof location<`u`&&location.protocol===`https:`?`wss:`:`ws:`,t=typeof location<`u`?location.host:this.origin.replace(/^https?:\/\//,``),n=this.token(),r=`${e}//${t}/ws${n?`?access_token=${encodeURIComponent(n)}`:``}`,i=new this.WS(r);this.ws=i;let a=()=>i===this.ws;i.onopen=()=>{a()&&(this.connected=!0,this.backoff=1e3,this.setStatus(`online`),this.send({kind:`sessions.list`}),this.send({kind:`models.list`}),this.send({kind:`runtimes.list`}),this.send({kind:`terminal.list`}),this.send({kind:`terminal.multiplexers`}))},i.onmessage=e=>{if(a())try{this.emit(JSON.parse(String(e.data)))}catch{}},i.onclose=e=>{if(a()&&!this.closedByUs){if(this.requireToken&&e?.code===1008&&e.reason===`Unauthorized`){this.tokenStore?.setItem(ia,``),this.notPaired();return}this.connected=!1,this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.closedByUs||this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,aa)}},i.onerror=()=>{}}close(){if(this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){let e=this.ws;this.ws=null,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}async send(e){try{switch(e.kind){case`ping`:this.connected&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e));break;case`history`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},...e.have==null?{}:{have:String(e.have)},...e.haveToken?{haveToken:String(e.haveToken)}:{}});this.emit(await this.directApi(`/api/session/history?${t}`));break}case`session.replay`:{let t=new URLSearchParams({...e.sessionId?{sessionId:String(e.sessionId)}:{},afterSeq:String(e.afterSeq??0)});this.emit(await this.directApi(`/api/session/replay?${t}`));break}case`sessions.list`:this.emit({type:`sessions.list`,sessions:await this.directApi(`/api/sessions`)});break;case`session.open`:{let t=await this.directApi(`/api/sessions/open`,{method:`POST`,body:JSON.stringify({sessionId:e.sessionId,path:e.path,agent:e.agent,runtimeId:e.runtimeId})});this.emit({type:`session.history`,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:t.messages||[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.new`:{let t=await this.directApi(`/api/session`,{method:`POST`,body:JSON.stringify(e)});this.emit({type:`session.history`,requestId:e.requestId,sessionId:t.id,sessionFile:t.sessionFile,workspace:t.workspace,source:t.source,runtimeId:t.runtimeId,agentName:t.agentName,name:t.name,messages:[],sessionState:t.sessionState??t.bivySession?.state,branch:t.branch,prUrl:t.prUrl});break}case`session.discover`:{let t=String(e.requestId??``);try{let e=await this.directApi(`/api/sessions/discover`);this.emit({type:`session.discover.result`,requestId:t,sessions:e?.sessions??[]})}catch(e){this.emit({type:`session.discover.error`,requestId:t,error:e?.message||String(e)})}break}case`apps.list`:case`apps.publish`:case`apps.offers`:case`apps.adopt`:case`apps.open`:case`apps.logs`:case`apps.showMe`:case`apps.mute`:case`apps.reviewMode`:case`apps.annotate`:case`apps.clearNotes`:case`apps.agentNotes`:case`apps.share`:case`apps.unshare`:case`apps.revoke`:case`apps.remove`:case`artifacts.list`:case`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))}}},ca=8388608,la=class{deps;queue=[];queuedBytes=0;pending;timer;generation=0;constructor(e){this.deps=e}accept(e){if(e.type===`transfer.part`){this.part(e);return}if(this.pending||this.queue.length){if(this.queuedBytes+=new TextEncoder().encode(JSON.stringify(e)).length,this.queuedBytes>ca||this.queue.length>=4096){this.reset(),this.deps.fault(`Transcript delivery fell behind. Reconnecting to synchronize again.`);return}this.queue.push(e);return}this.deliver(e)}deliver(e){if(e.code!==`transfer_required`){this.deps.emit(e);return}let t=e.transfer;if(!t||!/^[a-f0-9]{48}$/.test(t.id)||!/^[a-f0-9]{64}$/.test(t.key)||!/^[a-f0-9]{24}$/.test(t.iv)||!Number.isSafeInteger(t.bytes)||t.bytes<=0||t.bytes>67108864||t.pageBytes!==393216){this.deps.emit({type:`session.error`,code:`delivery_invalid`,sessionId:e.sessionId,requestId:e.requestId,error:`Invalid large-response transfer. Update the app and retry.`});return}this.pending={offer:t,envelope:e,bytes:new Uint8Array(t.bytes),offset:0,requestId:``,retries:0},this.request()}request(){let e=this.pending;e&&(e.requestId=`transfer-${crypto.randomUUID()}`,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.pending===e&&(++e.retries<=2?this.request():this.fail(`Large-response delivery timed out. Retry to synchronize.`))},this.deps.timeoutMs??1e4),this.deps.send({kind:`transfer.read`,transferId:e.offer.id,offset:e.offset,requestId:e.requestId}).catch(()=>{this.pending===e&&this.fail(`Could not request the next response page. Retry to synchronize.`)}))}async part(e){let t=this.pending;if(t&&e.requestId===t.requestId&&e.transferId===t.offer.id&&e.offset===t.offset){if(clearTimeout(this.timer),typeof e.error==`string`){this.fail(e.error);return}try{if(typeof e.data!=`string`||e.data.length>524288)throw Error(`Invalid response page.`);let n=x(e.data);if(n.length!==Math.min(393216,t.offer.bytes-t.offset))throw Error(`Incomplete response page.`);if(t.bytes.set(n,t.offset),t.offset+=n.length,t.retries=0,t.offset<t.offer.bytes){this.request();return}t.requestId=``;let r=this.generation,i=e=>Uint8Array.from(e.match(/../g),e=>parseInt(e,16)),a=await crypto.subtle.importKey(`raw`,i(t.offer.key),`AES-GCM`,!1,[`decrypt`]),o;try{o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i(t.offer.iv)},a,t.bytes)}catch{throw Error(`Response integrity check failed.`)}if(r!==this.generation||this.pending!==t)return;let s=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(o));if(!s||typeof s.type!=`string`||s.code===`transfer_required`||s.type===`transfer.part`)throw Error(`Invalid response envelope.`);this.pending=void 0,this.deps.emit(s),this.drain()}catch(e){this.pending===t&&this.fail(`${e.message} Retry to synchronize.`)}}}fail(e){let t=this.pending?.envelope;this.reset(),this.deps.emit({type:`session.error`,code:`delivery_failed`,sessionId:t?.sessionId,requestId:t?.requestId,error:e}),this.deps.fault(e)}drain(){for(;!this.pending&&this.queue.length;){let e=this.queue.shift();this.queuedBytes-=new TextEncoder().encode(JSON.stringify(e)).length,this.deliver(e)}}reset(){clearTimeout(this.timer),this.pending=void 0,this.queue=[],this.queuedBytes=0,this.generation++}},ua=15e3,da=15e3,fa=4,pa=3;function ma(){return b(crypto.getRandomValues(new Uint8Array(12)))}function ha(e){return/device limit|another account|isn't authorized|not authorized|forbidden/i.test(e)}var ga=class{store;handlers;fetchImpl;WS;pairingOnly;ws=null;connected=!1;initialBackoff;backoff;closedByUs=!1;reconnectTimer=null;pairSent=!1;pairAttempts=0;connectFailures=0;hasReachedNode=!1;curKey=null;devicePromise=null;sendQueue=[];reassemble=k({onReject:e=>{this.handlers.onError?.(e),/limit/.test(e)?this.close():this.ws?.close()}});acceptFrame=ee();transfers;receiveChain=Promise.resolve();decryptBytes=0;constructor(e){this.store=e.store,this.pairingOnly=e.pairingOnly??!1,this.handlers=e.handlers,this.fetchImpl=e.fetchImpl??globalThis.fetch?.bind(globalThis),this.WS=e.webSocketImpl??globalThis.WebSocket,this.initialBackoff=e.initialBackoffMs??1e3,this.backoff=this.initialBackoff,this.transfers=new la({send:e=>this.send(e),emit:e=>this.handlers.onEvent(e),fault:e=>{this.handlers.onError?.(e),this.ws?.close()}})}cpBase(){return(this.store.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}reportRemoteReconnect(){if(!this.store.s)return;let e=typeof navigator<`u`&&/Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);this.fetchImpl(`${this.cpBase()}/account/product-events`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({event:`remote_reconnect`,client:e?`mobile`:`desktop`})}).catch(()=>{})}setStatus(e){this.handlers.onStatus(e)}device(){return this.devicePromise||=Ui(this.store).catch(e=>{throw this.devicePromise=null,e}),this.devicePromise}async keyFor(e){let t=this.store.keys()[e];return t?E(C(t)):null}canConnect(){let e=this.store.cur;return e?!!(this.curKey||this.store.keys()[e]||this.store.s||this.store.nodePubs()[e]&&this.store.pairSecrets()[e]):!1}soloCreds(){let e=this.store.solo()[this.store.cur];return e&&e.room&&e.roomToken?e:null}async mintClientTicket(){let e=await this.fetchImpl(`${this.cpBase()}/client/relay-ticket`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})});if(!e.ok)throw Error(`ticket request failed: ${e.status}`);let t=await e.json();if(!t?.ticket)throw Error(`no ticket`);return{ticket:t.ticket,relayUrl:typeof t.relayUrl==`string`?t.relayUrl:null}}async connect(){if(this.closedByUs=!1,this.setStatus(`connecting`),this.curKey=await this.keyFor(this.store.cur),this.closedByUs)return;let e=this.soloCreds(),t=``,n=null;if(!e)try{({ticket:t,relayUrl:n}=await this.mintClientTicket())}catch(e){this.connectFailures+=1,this.connectFailures>=fa&&this.handlers.onError?.(e?.message||`ticket mint failed`),this.scheduleReconnect();return}if(this.closedByUs)return;this.pairSent=!1;let r=this.store.cur,i=(n||this.store.relay).replace(/\/$/,``),a=e?`${i}/client?room=${encodeURIComponent(e.room)}&roomToken=${encodeURIComponent(e.roomToken)}`:`${i}/client?ticket=${encodeURIComponent(t)}&nodeId=${encodeURIComponent(r)}`,o=new this.WS(a);this.ws=o;let s=()=>o===this.ws&&r===this.store.cur;o.onmessage=async e=>{if(!s())return;let t;try{t=JSON.parse(String(e.data))}catch{return}if(t.t===`ready`||t.t===`peer.online`){let e=o;this.hasReachedNode&&!e._productReconnectReported&&(e._productReconnectReported=!0,this.reportRemoteReconnect()),this.hasReachedNode=!0,this.connected=!0,this.backoff=this.initialBackoff,this.connectFailures=0,this.setStatus(this.curKey?`online`:`pairing`),await this.onLinkReady()}else if(t.t===`peer.offline`)this.setStatus(`reconnecting`);else if(t.t===`pair`&&typeof t.p==`string`)await this.handlePairFrame(t.p);else if(t.t===`error`)this.handlers.onError?.(t.error||`relay error`);else if(t.t===`run.updated`&&typeof t.id==`string`)this.handlers.onEvent({type:`run.updated`,runId:t.id,revision:typeof t.revision==`string`?t.revision:void 0});else if(t.t===`frame`&&typeof t.p==`string`){if(!this.curKey)return;let e=this.reassemble(t);if(e===null)return;if(this.decryptBytes+e.length>33554432){this.handlers.onError?.(`Response decoding fell behind. Reconnecting to synchronize.`),o.close();return}this.decryptBytes+=e.length;let n=this.curKey;this.receiveChain=this.receiveChain.then(async()=>{if(!s()||o.readyState!==1)return;let t=JSON.parse(await O(n,e));s()&&o.readyState===1&&this.acceptFrame(t)&&this.transfers.accept(t.data)}).catch(()=>{s()&&o.readyState===1&&(this.handlers.onError?.(`Could not decode the machine response. Reconnecting to synchronize.`),o.close())}).finally(()=>{this.decryptBytes-=e.length})}},o.onclose=()=>{s()&&!this.closedByUs&&(this.connected=!1,this.transfers.reset(),this.reassemble.reset(),this.scheduleReconnect())},o.onerror=()=>{}}scheduleReconnect(){this.setStatus(`reconnecting`),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.canConnect()&&!this.closedByUs&&this.connect()},this.backoff),this.backoff=Math.min(this.backoff*2,ua)}shouldResync(){let e=this.ws;if(!e)return!1;let t=Date.now();return e._resyncAt!==void 0&&t-e._resyncAt<da?!1:(e._resyncAt=t,!0)}async onLinkReady(){if(this.curKey){if(this.pairingOnly||(this.flush(),!this.shouldResync()))return;this.store.sessions(),await this.send({kind:`sessions.list`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}else{this.setStatus(`linking`);let e=this.store.cur;this.store.nodePubs()[e]&&this.store.pairSecrets()[e]?await this.sendPairHello():await this.sendAccountPair()}}async sendPairHello(){if(this.pairSent)return;let e=this.store.cur,t=this.store.nodePubs()[e],n=this.store.pairSecrets()[e];if(!t||!n)return;let r=await this.device(),i=await qi(n,r.pub);this.pairSent=!0,this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.hello`,devicePublicKeyB64:r.pub,proofB64:i,label:_a()})}))}async sendAccountPair(){if(this.pairSent||!this.store.s)return;let e=await this.device();this.pairSent=!0;try{let t=await this.fetchImpl(`${this.cpBase()}/client/pair-grant`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${this.store.s}`},body:JSON.stringify({nodeId:this.store.cur})}),n=await t.json().catch(()=>({}));if(!t.ok||!n?.grant)throw Error(`Could not create pairing grant`);this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.account`,sessionToken:n.grant,devicePublicKeyB64:e.pub,label:_a()})}))}catch(e){this.pairSent=!1,this.handlers.onError?.(e?.message||`Could not pair this device`),this.setStatus(`reconnecting`)}}async handlePairFrame(e){let t;try{t=JSON.parse(e)}catch{return}let n=this.store.cur,r=this.store.nodePubs()[n];!r&&typeof t.nodePublicKeyB64==`string`&&(this.store.addNodePub(n,t.nodePublicKeyB64),r=t.nodePublicKeyB64);let i=await this.device();if(t.k===`pair.welcome`&&typeof t.wrapped==`string`&&r&&!this.curKey)try{let e=x(await O(await Ki(i.priv,r,`pair`),t.wrapped));if(this.storeRoomKey(n,e),this.store.clearPairSecret(n),this.curKey=await this.keyFor(n),this.pairAttempts=0,this.setStatus(`online`),this.pairingOnly)return;this.flush(),await this.send({kind:`sessions.list`}),await this.send({kind:`history`}),await this.send({kind:`models.list`}),await this.send({kind:`runtimes.list`}),await this.send({kind:`terminal.list`}),await this.send({kind:`terminal.multiplexers`})}catch{this.setStatus(`reconnecting`)}else if(t.k===`key.rotate`&&Array.isArray(t.deliveries)&&r){let e=await Ki(i.priv,r,`rotate`);for(let r of t.deliveries)try{this.storeRoomKey(n,x(await O(e,r.wrapped))),this.curKey=await this.keyFor(n);break}catch{}}else t.k===`pair.error`&&this.onPairRejected(typeof t.error==`string`?t.error:``)}onPairRejected(e){if(ha(e)){this.handlers.onError?.(e),this.close();return}if(this.pairAttempts+=1,this.pairAttempts>=pa){this.handlers.onError?.(e||`Couldn't link this device — the node rejected it. Make sure the node is online and you're signed in to the right account, then try again.`),this.close();return}this.handlers.onError?.(e?`${e} — retrying…`:`Device link was rejected — retrying…`),this.pairSent=!1;let t=this.ws;this.ws=null,this.connected=!1;try{t?.close()}catch{}this.scheduleReconnect()}storeRoomKey(e,t){this.store.addKey(e,S(t))}rawSend(e){this.connected&&this.ws?.readyState===1?this.ws.send(e):this.sendQueue.push(e)}flush(){for(;this.sendQueue.length&&this.ws?.readyState===1;){let e=this.sendQueue.shift();e!==void 0&&this.ws.send(e)}}async send(e){if(!this.curKey)return;let t={v:1,ts:Date.now(),nonce:ma(),data:e},n=await D(this.curKey,JSON.stringify(t));if(n.length>33554432){let t=`This request is too large to send. Reduce the attachments and retry.`;this.handlers.onError?.(t),this.handlers.onEvent({type:`session.error`,code:`delivery_too_large`,sessionId:typeof e.sessionId==`string`?e.sessionId:void 0,requestId:e.requestId,error:t});return}for(let e of ne(n,ma))this.rawSend(e)}close(){if(this.transfers.reset(),this.reassemble.reset(),this.closedByUs=!0,this.connected=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.ws)try{this.ws.close()}catch{}this.ws=null,this.setStatus(`offline`)}reconnect(){this.transfers.reset(),this.reassemble.reset();let e=this.ws;this.ws=null,this.connected=!1,this.pairSent=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null);try{e?.close()}catch{}this.connect()}};function _a(){return globalThis.navigator?.platform||`Device`}var va=Object.freeze({repo:null,branch:null,sandbox:null,acknowledgeReducedProtections:!1,ephemeralConfig:null});function ya(e,t){switch(t.type){case`select-repository`:return e.repo===t.repo?{...e}:{...e,repo:t.repo,branch:null};case`select-branch`:return{...e,branch:t.branch};case`select-sandbox`:return{...e,sandbox:t.sandbox};case`acknowledge-reduced-protections`:return{...e,acknowledgeReducedProtections:t.acknowledged};case`select-ephemeral-config`:return{...e,ephemeralConfig:t.config};case`reset`:return{...va}}}var ba=512,xa=class{nextSeq=0;held=new Map;maxHeld;constructor(e={}){this.maxHeld=Math.max(1,e.maxHeld??ba)}baseline(e){let t=(Number.isFinite(e)?Math.max(0,Math.floor(e)):0)+1;t>this.nextSeq&&(this.nextSeq=t);for(let e of[...this.held.keys()])e<this.nextSeq&&this.held.delete(e)}accept(e,t){if(typeof e!=`number`||!Number.isFinite(e))return{ready:[t]};let n=Math.floor(e);if(this.nextSeq===0)return this.nextSeq=n+1,{ready:[t]};if(n<this.nextSeq)return{ready:[]};if(n>this.nextSeq)return this.held.set(n,t),this.held.size>this.maxHeld?{ready:[],overflow:!0}:{ready:[],gapFrom:this.nextSeq-1};let r=[t];for(this.nextSeq+=1;this.held.has(this.nextSeq);)r.push(this.held.get(this.nextSeq)),this.held.delete(this.nextSeq),this.nextSeq+=1;return{ready:r}}reset(){this.nextSeq=0,this.held.clear()}get expected(){return this.nextSeq}get heldCount(){return this.held.size}};function Sa(e,t){if(t.type===`node.updated`)return typeof t.name!=`string`||!t.name||!e.currentNodeId?{handled:!0,value:e}:{handled:!0,value:{...e,nodes:e.nodes.map(n=>n.id===e.currentNodeId?{...n,name:t.name}:n)}};if(t.type===`node.update`){let n=typeof t.current==`string`?t.current:``,r=typeof t.latest==`string`?t.latest:``;return{handled:!0,value:n&&r?{...e,nodeUpdate:{current:n,latest:r}}:{...e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1}}}return t.type===`node.update.result`?t.ok===!1?{handled:!0,value:{...e,nodeUpdating:!1,nodeUpdateAcknowledged:!1},error:typeof t.error==`string`?t.error:`Couldn't start the update on this node.`}:{handled:!0,value:{...e,nodeUpdateAcknowledged:!0}}:{handled:!1,value:e}}function Ca(e,t){let n=String(t.sessionId||``);return t.type===`session.paused`?!n||e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:[...e.pausedSessionIds,n]}}:t.type===`session.resumed`?!n||!e.pausedSessionIds.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,pausedSessionIds:e.pausedSessionIds.filter(e=>e!==n)}}:{handled:!1,value:e}}function wa(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.termId==`string`?t:void 0}function Ta(e,t,n){if(t.type===`terminal.list`){let n=Array.isArray(t.terminals)?t.terminals.map(wa).filter(e=>!!e):[];return{handled:!0,value:{...e,runTerminals:n}}}if(t.type===`terminal.created`){let n=wa(t.terminal);return n?{handled:!0,value:{...e,runTerminals:[n,...e.runTerminals.filter(e=>e.termId!==n.termId)]}}:{handled:!0,value:e}}if(t.type===`terminal.activity`){let r=String(t.termId||``);if(!r)return{handled:!0,value:e};let i=Number(t.at)||n;return{handled:!0,value:{...e,runTerminals:e.runTerminals.map(e=>e.termId===r?{...e,lastActivityAt:i}:e)}}}if(t.type===`terminal.closed`||t.type===`terminal.exit`){let n=String(t.termId||``);return n?{handled:!0,value:{...e,runTerminals:e.runTerminals.filter(e=>e.termId!==n)}}:{handled:!0,value:e}}if(t.type===`terminal.tui`){let n=String(t.sessionId||``);if(!n)return{handled:!0,value:e};let r=!!t.active;return r===e.tuiSessions.includes(n)?{handled:!0,value:e}:{handled:!0,value:{...e,tuiSessions:r?[...e.tuiSessions,n]:e.tuiSessions.filter(e=>e!==n)}}}return{handled:!1,value:e}}function Ea(e){switch(e.type){case`repos.list`:return{handled:!0,catalogs:{repos:Array.isArray(e.repos)?e.repos:[],reposAuthed:e.authed!==!1,reposError:e.error||null,reposReason:e.reason===`gh-unauthed`||e.reason===`no-token`?e.reason:null,reposLoading:!1}};case`branches.list`:return{handled:!0,catalogs:{branches:Array.isArray(e.branches)?e.branches:[],branchesRepo:typeof e.repo==`string`&&e.repo?e.repo:null,branchesDefault:typeof e.defaultBranch==`string`?e.defaultBranch:null,branchesError:e.error||null,branchesLoading:!1}};case`credentials.records`:return{handled:!0,settings:{credentialRecords:Array.isArray(e.records)?e.records:[]}};case`credentials.presets`:return{handled:!0,settings:{credentialPresets:e.presets??{}}};case`models.custom.list`:return Array.isArray(e.providers)?{handled:!0,settings:{localModels:e.providers}}:{handled:!0};case`models.custom.presets`:return Array.isArray(e.presets)?{handled:!0,settings:{localModelPresets:e.presets}}:{handled:!0};case`rulesets.list`:return Array.isArray(e.rulesets)?{handled:!0,settings:{rulesets:e.rulesets}}:{handled:!0};case`stt.config`:return Array.isArray(e.providers)&&typeof e.provider==`string`?{handled:!0,settings:{sttConfig:{provider:e.provider,providers:e.providers}}}:{handled:!0};case`node.settings`:return e.settings&&typeof e.settings==`object`?{handled:!0,settings:{nodeSettings:e.settings}}:{handled:!0};default:return{handled:!1}}}function Da(e,t){if(t.type===`sessions.pr_refresh_result`)return{handled:!0,value:{...e,prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}}};let n=e.githubApp||{phase:`idle`};return t.type===`github.app.manifest.ready`?{handled:!0,value:{...e,githubApp:{...n,phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}}}:t.type===`github.app.manifest.done`?{handled:!0,value:{...e,githubApp:{...n,phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}}}:t.type===`github.app.manifest.error`?{handled:!0,value:{...e,githubApp:{...n,phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}}}:{handled:!1,value:e}}function Oa(e){return/^\/[a-zA-Z]/.test(e.trimStart())}function ka(e){return!!(e&&typeof e==`object`&&typeof e.name==`string`&&e.name.startsWith(`/`)&&e.name.length>=2)}function Aa(e){let t=e.trim();if(!Oa(t))return null;let n=/^\/(\S+)\s*([\s\S]*)$/.exec(t);if(!n||!n[1])return null;let r=(n[2]??``).trim();return{name:`/${n[1].toLowerCase()}`,args:r}}function ja(e,t=[]){let n=t.filter(ka),r=n.length>0,i=n.find(t=>t.name.toLowerCase()===e.name.toLowerCase());return i?{kind:`agent`,command:i,args:e.args}:{kind:`unknown`,name:e.name,hasCatalog:r}}function Ma(e,t=[]){let n=e.trimStart().toLowerCase();if(!n.startsWith(`/`)||/\s/.test(n))return[];let r=t.filter(ka);return n===`/`?r:r.filter(e=>e.name.toLowerCase().startsWith(n)||e.aliases?.some(e=>e.toLowerCase().startsWith(n)))}function Na(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!ka(r)||n.has(r.name))continue;n.add(r.name);let e={name:r.name};typeof r.description==`string`&&r.description&&(e.description=r.description),(r.mode===`protocol`||r.mode===`prompt`)&&(e.mode=r.mode),t.push(e)}return t}function Pa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].name!==t[n].name||e[n].description!==t[n].description||e[n].mode!==t[n].mode)return!1;return!0}function Fa(e,t){let n=[];if(Array.isArray(e))for(let t of e){let e=typeof t?.url==`string`?t.url:``;if(!e)continue;let r=t?.state===`merged`||t?.state===`closed`?t.state:`open`;n.push({url:e,state:r,number:typeof t?.number==`number`?t.number:void 0,title:typeof t?.title==`string`?t.title:void 0})}return n.length===0&&typeof t==`string`&&t&&n.push({url:t,state:`open`}),n}function Ia(e){if(e&&e.length!==0)return e.find(e=>e.state===`open`)??e[0]}var La=[`read-only`,`workspace-write`,`danger-full-access`];function Ra(e){let t=String(e??``).trim().toLowerCase().replace(/_/g,`-`);return La.includes(t)?t:void 0}function za(e){let t=String(e??``).trim().toLowerCase();return[`never`,`risky`,`always`,`autonomous`].includes(t)?t:void 0}function Ba(e){let t=String(e??``).trim().toLowerCase();return[`trusted_workstation`,`isolated_customer_cloud`,`restricted`].includes(t)?t:void 0}var Va=[`guaranteed`,`degraded`,`unavailable`];function Ha(e){return!!e&&typeof e==`object`&&Va.includes(e.state)}function Ua(e){if(!e||typeof e!=`object`)return;let t=e;if(t.schemaVersion===`session-contract.v1`&&typeof t.resolvedAt==`string`&&typeof t.preview==`boolean`&&t.agent&&typeof t.agent==`object`&&typeof t.agent.id==`string`&&Ha(t.executionMode)&&Ha(t.auth)&&Ha(t.resume)&&Ha(t.toolInterception)&&Ha(t.sandbox)&&Array.isArray(t.degradedReasons)&&typeof t.requiresAcknowledgement==`boolean`)return t}function Wa(e){return typeof e==`string`&&e.startsWith(`repo:`)?e.slice(5):null}function Ga(e){return typeof e==`string`&&(e.startsWith(`issue:`)||e.startsWith(`queue:`))}function Ka(e){if(typeof e!=`string`||!e.startsWith(`issue:`))return null;let t=e.slice(6),n=t.lastIndexOf(`#`);if(n===-1)return null;let r=t.slice(0,n),i=Number(t.slice(n+1));return!r||!Number.isFinite(i)?null:{repo:r,issueNumber:i}}function qa(e){let t=e?.source,n=Wa(t),r=e?.githubIssueUrl||null;!r&&typeof t==`string`&&t.startsWith(`github:issue`)&&(r=t.split(`:`).slice(1).join(`:`)||null);let i=Fa(e?.prs,e?.prUrl);return{issueUrl:r,prUrl:(Ia(i)?.state===`open`?Ia(i)?.url:null)??e?.prUrl??null,branch:e?.branch||null,repo:n,prs:i}}function Ja(e){return qa({source:e.source,branch:e.branch,prUrl:e.prUrl,prs:e.prs})}function Ya(e){if(!e||typeof e!=`object`)return null;let t=typeof e.costUsd==`number`,n=e.tokens&&typeof e.tokens.total==`number`,r=e.plan&&Array.isArray(e.plan.windows)&&e.plan.windows.length;return!t&&!n&&!r?null:e}function Xa(e){if(!e||typeof e!=`object`)return null;let t=e.memory?.node&&typeof e.memory.node.total==`number`,n=e.cpu?.node&&typeof e.cpu.node.usedPct==`number`,r=e.storage?.node&&typeof e.storage.node.total==`number`;return!t&&!n&&!r?null:e}function Za(e){return!e||typeof e!=`object`||!e.os||typeof e.os.platform!=`string`||typeof e.generatedAt!=`string`?null:e}function Qa(e){if(!Array.isArray(e)||!e.length)return null;for(let t of e){if(typeof t?.question!=`string`||typeof t?.header!=`string`||!Array.isArray(t.options)||t.options.length===1)return null;for(let e of t.options)if(typeof e?.label!=`string`)return null}return e}function $a(e,t=[]){if(!Array.isArray(e))return[];let n=new Map(t.map(e=>[e.sessionId,e])),r=new Map;for(let t of e){let e=String(t?.sessionId||t?.id||``);if(!e||r.has(e))continue;let i=n.get(e),a=eo(t?.sessionState);r.set(e,{sessionId:e,path:t?.path||t?.sessionFile||void 0,workspace:t?.workspace||t?.bivySession?.workspace||void 0,worktree:t?.worktree||t?.bivySession?.worktree||t?.bivySession?.workspaceContext?.worktree||void 0,name:String(t?.name||`Untitled session`),source:t?.source,bivyCreated:t?.bivyCreated===!0,forkedFrom:t?.forkedFrom||void 0,delegatedFrom:t?.delegatedFrom&&typeof t.delegatedFrom.sessionId==`string`?t.delegatedFrom:void 0,nodeId:t?.nodeId||void 0,runtimeId:t?.runtimeId,agentName:t?.agentName,updatedAt:t?.updatedAt||t?.modified,needsAction:a?.agent===`awaiting-input`||!!t?.needsAction,status:no(t?.status,!!t?.needsAction,!!t?.isStreaming,a),sessionState:a,branch:t?.branch||void 0,rebuildable:t?.rebuildable?!0:void 0,sandbox:Ra(t?.sandbox??t?.bivySession?.sandbox),approvalMode:za(t?.approvalMode??t?.bivySession?.approvalMode),ephemeral:(t?.ephemeral??t?.bivySession?.ephemeral)===!0||void 0,executionProfile:Ba(t?.executionProfile??t?.bivySession?.executionProfile),contract:Ua(t?.contract??t?.bivySession?.contract),auditHealth:t?.auditHealth??t?.bivySession?.auditHealth,eventLogHealth:t?.eventLogHealth??t?.bivySession?.eventLogHealth,prUrl:t?.prUrl||void 0,prs:Fa(t?.prs,t?.prUrl),attention:Array.isArray(t?.attention)?t.attention:i?.attention,lastSeenAt:i?.lastSeenAt,finishedAt:i?.finishedAt,failedAt:i?.failedAt,launchProgress:i?.launchProgress})}return[...r.values()]}function eo(e){if(!e||typeof e!=`object`)return;let t=e;if((t.transport===`reachable`||t.transport===`unreachable`)&&(t.process===`alive`||t.process===`exited`||t.process===`none`)&&(t.agent===`idle`||t.agent===`working`||t.agent===`waiting`||t.agent===`awaiting-input`)&&(t.workspace===`clean`||t.workspace===`dirty`||t.workspace===`checkpointing`)&&(t.displayStatus===`idle`||t.displayStatus===`working`||t.displayStatus===`needs_attention`||t.displayStatus===`failed`))return t}function to(e){return e?.displayStatus===`needs_attention`?`needs_action`:e?.displayStatus}function no(e,t,n,r){return e===`saved`?`saved`:to(r)||(t||e===`needs_action`?`needs_action`:e===`working`||n?`working`:e===`failed`?`failed`:`idle`)}function ro(e){return Array.isArray(e)?e.map(e=>({id:String(e?.id||e?.model||``),label:e?.label||e?.name,...e})):[]}function io(e){let t=Array.isArray(e?.availableThinkingLevels)&&e.availableThinkingLevels.length?e.availableThinkingLevels.map(String):[`off`];return{supportsThinking:!!e?.supportsThinking,thinkingLevel:String(e?.thinkingLevel||`off`),availableThinkingLevels:t}}function ao(e,t){return!e||!t?!1:e.id===t.id&&e.provider===t.provider}function oo(e){return e?String(e.displayName||e.name||e.id||``):``}function so(e){return Qa(e)??void 0}function co(e,t){return e.approvals.some(e=>e.sessionId===t)||e.questions.some(e=>e.sessionId===t)||e.turnAttentions.some(e=>e.sessionId===t)}function lo(e,t,n){let r=t;switch(t.type){case`approval.created`:{let i=r.approval||t;return i?.id?{handled:!0,value:{...e,approvals:[...e.approvals.filter(e=>e.id!==i.id),i]},...i.sessionId?{row:{sessionId:i.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}:{handled:!0,value:e}}case`approval.resolved`:case`approval.removed`:{let t=String(r.id||r.approvalId||``),n=e.approvals.find(e=>e.id===t),i={...e,approvals:e.approvals.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.question`:{let t=String(r.requestId||``),i=so(r.questions);if(!t||!i)return{handled:!0,value:e};let a={id:t,...r.sessionId?{sessionId:String(r.sessionId)}:{},questions:i,createdAt:Number(r.createdAt)||n};return{handled:!0,value:{...e,questions:[...e.questions.filter(e=>e.id!==t),a]},...a.sessionId?{row:{sessionId:a.sessionId,status:`needs_action`,needsAction:!0,updatedAt:n}}:{}}}case`session.question.resolved`:{let t=String(r.requestId||r.id||``),n=e.questions.find(e=>e.id===t),i={...e,questions:e.questions.filter(e=>e.id!==t)},a=n?.sessionId;return{handled:!0,value:i,...a&&!co(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.turn_attention`:{let t=String(r.sessionId||``),i=r.trigger===`wedged`||r.trigger===`stalled`?r.trigger:void 0;if(!t||!i)return{handled:!0,value:e};let a={sessionId:t,trigger:i,idleMs:Math.max(0,Number(r.idleMs)||0),at:Number(r.at)||n,message:String(r.message||`This turn may be stuck. Stop it or keep waiting?`)};return{handled:!0,value:{...e,turnAttentions:[...e.turnAttentions.filter(e=>e.sessionId!==t),a]},row:{sessionId:t,status:`needs_action`,needsAction:!0,updatedAt:n}}}case`session.turn_attention.resolved`:{let t=String(r.sessionId||``);if(!t)return{handled:!0,value:e};let n={...e,turnAttentions:e.turnAttentions.filter(e=>e.sessionId!==t)};return{handled:!0,value:n,...co(n,t)?{}:{row:{sessionId:t,status:`working`,needsAction:!1}}}}default:return{handled:!1,value:e}}}function uo(e,t){return!!t&&t!==e}function fo(e){return(Array.isArray(e.actions)?e.actions:[e.action]).filter(e=>typeof e==`string`&&e.length>0)}function po(e,t,n){let r=t,i=String(r.sessionId||``);switch(t.type){case`session.state`:{let t=eo(r.state??r.sessionState);return!i||!t?{handled:!0,commands:[]}:{handled:!0,patch:i===e.activeSessionId?{working:t.agent===`working`,...t.agent===`working`?{}:{workingLabel:``}}:void 0,commands:[{kind:`row`,sessionId:i,patch:{sessionState:t,status:to(t),needsAction:t.displayStatus===`needs_attention`}}]}}case`session.renamed`:{let t=[];return r.name&&i&&t.push({kind:`rename`,sessionId:i,name:String(r.name)}),r.branch&&i&&t.push({kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}),{handled:!0,patch:!i||i===e.activeSessionId?{...r.name?{activeTitle:String(r.name)}:{},...r.branch?{github:{...e.github,branch:String(r.branch)}}:{}}:void 0,commands:t}}case`session.branch_renamed`:return{handled:!0,patch:(!i||i===e.activeSessionId)&&r.branch?{github:{...e.github,branch:String(r.branch)}}:void 0,commands:r.branch&&i?[{kind:`row`,sessionId:i,patch:{branch:String(r.branch)}}]:[]};case`session.error`:case`session.errored`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=r.error&&typeof r.error==`object`?r.error:null,n=t?.kind===`model_auth`&&typeof t.provider==`string`,i=n?`No credentials for ${t.provider}`:je(String(r.error||r.errorMessage||`error`)),a={kind:`entry`,role:`error`,text:i,...n?{actions:[`connect-provider:${t.provider}`]}:{}};return{handled:!0,patch:{...String(r.code||``).startsWith(`delivery_`)?{}:{working:!1},opening:!1},commands:r.sessionId?[a]:[{kind:`global-error`,message:i}]}}case`session.closed`:return{handled:!0,patch:i===e.activeSessionId?{working:!1,workingLabel:``,opening:!1}:void 0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`saved`,needsAction:!1}}]:[]};case`session.failed`:return{handled:!0,commands:i?[{kind:`row`,sessionId:i,patch:{status:`failed`,needsAction:!1,failedAt:Number(r.failedAt)||n,updatedAt:n}}]:[]};case`session.notice`:{if(!r.message||i&&i!==e.activeSessionId)return{handled:!0,commands:[]};let t=fo(r);return{handled:!0,commands:[{kind:`entry`,role:`system`,text:String(r.message),...t.length?{actions:t}:{}}]}}case`session.cloning`:return{handled:!0,patch:!i||i===e.activeSessionId?{working:!0,workingLabel:`Cloning ${r.repo||`repo`}…`}:void 0,commands:[]};case`session.auth_required`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.provider?[{kind:`model-auth`,provider:String(r.provider),reason:String(r.reason||``)}]:[]};case`session.usage`:return{handled:!0,patch:uo(e.activeSessionId,r.sessionId)?void 0:{usage:Ya(r.usage)},commands:[]};case`session.warning`:return{handled:!0,commands:!uo(e.activeSessionId,r.sessionId)&&r.warning?[{kind:`entry`,role:`system`,text:String(r.warning)}]:[]};case`session.changes`:{if(uo(e.activeSessionId,r.sessionId))return{handled:!0,commands:[]};let t=Array.isArray(r.changes)?r.changes:[];if(!t.length)return{handled:!0,patch:{changes:null},commands:[]};let i={before:r.before?String(r.before):void 0,after:String(r.after??``),files:t};return{handled:!0,patch:{changes:i,changesHistory:[...e.changesHistory,{...i,id:e.newChangeId??`change-${e.changesHistory.length+1}`,at:n}]},commands:[]}}case`session.rewound`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{changes:null},commands:[{kind:`entry`,role:`system`,text:`Rewound the workspace to an earlier checkpoint.`}]};case`session.checkpoints`:return uo(e.activeSessionId,r.sessionId)?{handled:!0,commands:[]}:{handled:!0,patch:{checkpoints:Array.isArray(r.checkpoints)?r.checkpoints.map(e=>({id:String(e.id??``),label:String(e.label??`checkpoint`),createdAt:Number(e.createdAt??0)})).filter(e=>e.id):[]},commands:[]};default:return{handled:!1,commands:[]}}}var mo=e=>{let t=e;return!!t&&typeof t.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`)},ho=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 go(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||ho(t.shot))&&(t.before===void 0||ho(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(mo))&&(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 _o=[`open`,`changed`,`gone`,`done`];function vo(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`])&&_o.includes(t.state)&&(t.shot===void 0||ho(t.shot))}function yo(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 bo=[{id:`1h`,label:`1 hour`,ms:36e5},{id:`1d`,label:`1 day`,ms:864e5},{id:`7d`,label:`7 days`,ms:6048e5}],xo=[`here`,`subagents`,`new`],So=e=>e===void 0||xo.includes(e);function Co(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.text==`string`&&t.text.length>0&&(t.title===void 0||typeof t.title==`string`)&&So(t.run)}function wo(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 To(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 Eo(e){return!!e&&e.type===`bivy_attachment`&&!!e.ref&&typeof e.ref.hash==`string`&&(e.ref.kind===`image`||e.ref.kind===`file`)}function Do(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 Oo=0,Y=()=>`e${Date.now().toString(36)}-${(Oo++).toString(36)}`;function ko(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`text`||t===`output_text`||!t&&typeof e?.text==`string`}function Ao(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`thinking`||t===`reasoning`}var jo=/^\s*(?:\[Request interrupted by user|<(?:task-notification|system-reminder)[\s>/])/;function Mo(e){return jo.test(e)}function No(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.filter(ko).map(e=>String(e?.text??e?.content??``)).join(`
|
|
20
|
-
`);if(e&&typeof e==`object`){let t=e.text??e.content??e.output??e.result;if(typeof t==`string`)return t;if(t!==void 0)return No(t);try{return JSON.stringify(e)}catch{return String(e)}}return e==null?``:String(e)}function Po(e){return Array.isArray(e)?e.filter(Ao).map(e=>String(e?.text??e?.thinking??e?.reasoning??``)).join(`
|
|
21
|
-
`):``}function Fo(e){if(Array.isArray(e)){let t=e.filter(ko).map(e=>String(e?.text??e?.content??``)).join(`
|
|
22
|
-
`);if(t)return Lo(t);try{return JSON.stringify(e)}catch{return String(e)}}return Lo(No(e))}var Io=[{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 Lo(e){for(let t of Io){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(`
|
|
23
|
-
`).map(e=>e.startsWith(t.indent)?e.slice(t.indent.length):e).join(`
|
|
24
|
-
`):i}return e}function Ro(e,t,n=Y){if(!Array.isArray(e))return[];let r=[];for(let i of e)if(Ce(i)){let e=ke(i)||t||``;r.push({callId:Oe(i)||n(),name:Te(i),input:Ee(i),status:`running`,detail:j(i),...e?{parentToolUseId:e}:{}})}else if(we(i)){let e=Oe(i),t=Fo(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 zo(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:Fo(e?.content),detail:e?.isError||e?.is_error?j(e)??{kind:`unknown`,result:{isError:!0}}:j(e)}}function Bo(e){let t=new Map;function n(e){if(!e||typeof e!=`object`)return;if(Eo(e)){t.set(e.ref.hash,Do(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 Vo(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=No(s);if(e===`user`){if(Array.isArray(s)){for(let e of s)if(we(e))for(let n of Ro([e],void 0,a))Wo(t,n,a)}let e=Bo(s);(c&&!Mo(c)||e.length)&&t.push({id:a(),role:`user`,text:c,...e.length?{attachments:e}:{}})}else if(e===`system`)c&&!Mo(c)&&t.push({id:a(),role:`system`,text:c});else if(e===`toolresult`||e===`tool_result`){let e=zo(o);e&&Wo(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(`
|
|
25
|
-
`)),i=[]},u=()=>{r(c.join(`
|
|
26
|
-
`)),c=[]},d=()=>{l(),u()};for(let n of s)if(Ce(n)||we(n)){d();for(let r of Ro([n],e,a))Wo(t,r,a)}else if(n?.type===`bivy_app`&&yo(n.app))d(),t.push({id:`app-${n.app.appId}`,role:`assistant`,text:``,app:n.app});else if(n?.type===`bivy_suggestion`&&Co(n.suggestion))d(),t.push({id:n.suggestion.id,role:`assistant`,text:``,suggestion:n.suggestion});else if(n?.type===`bivy_notice`&&wo(n.notice))d(),t.push({id:n.notice.id,role:`assistant`,text:``,notice:n.notice});else if(n?.type===`bivy_delegation`&&To(n.delegation))d(),t.push({id:`delegation-${n.delegation.id}`,role:`assistant`,text:``,delegation:n.delegation});else if(n?.type===`bivy_app_review`&&go(n.review))d(),t.push({id:n.review.id,role:`assistant`,text:``,review:n.review});else if(n?.type===`bivy_app_pin`&&vo(n.pin))d(),t.push({id:n.pin.id,role:`assistant`,text:``,pin:n.pin});else if(Eo(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:[{...Do(n.ref,{createdAt:e,artifact:n.artifact}),description:typeof n.caption==`string`?n.caption:void 0}]})}else ko(n)?(u(),i.push(String(n?.text??n?.content??``))):Ao(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=Bo(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 Ho(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,`
|
|
27
|
-
`).replace(/\n{3,}/g,`
|
|
28
|
-
|
|
29
|
-
`).trim()}function Uo(e,t){return e&&typeof e==`object`&&!Array.isArray(e)&&t&&typeof t==`object`&&!Array.isArray(t)?{...e,...t}:t??e}function Wo(e,t,n=Y){let r=t.callId?e.find(e=>e.tool&&e.tool.callId===t.callId):[...e].reverse().find(e=>e.tool&&e.tool.status===`running`&&(t.name===`tool`||e.tool.name===t.name));r&&r.tool?r.tool={...r.tool,status:t.status,result:t.result??r.tool.result,detail:t.detail??r.tool.detail,parentToolUseId:t.parentToolUseId??r.tool.parentToolUseId,name:t.status===`done`&&t.name===`tool`?r.tool.name:t.name,input:t.status===`running`?Uo(r.tool.input,t.input):r.tool.input}:e.push({id:n(),role:`assistant`,text:``,tool:t})}function Go(e=!0){return{assistantId:null,thinkingId:null,finalized:e,thinkingText:``,sawThinking:!1,pendingText:``,committedText:``,committedThinking:``}}function Ko(e){return{...e,transcript:[...e.transcript],draft:{...e.draft}}}function qo(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 Jo(e,t){let n={id:qo(e.transcript),...t};return e.transcript.push(n),n}function Yo(e,t,n){e.transcript=e.transcript.map(e=>e.id===t?{...e,...n}:e)}function Xo(e,t){e.transcript=e.transcript.filter(e=>e.id!==t)}function Zo(e,t){e.working=!0,e.workingLabel=t}function Qo(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?Yo(e,s,{text:n,html:o,streaming:!r}):(s=Jo(e,{role:i,text:n,html:o,streaming:!r}).id,e.draft[a]=s),r&&(e.draft[a]=null)}function $o(e){e.draft.assistantId&&Yo(e,e.draft.assistantId,{streaming:!1}),e.draft.thinkingId&&Yo(e,e.draft.thinkingId,{streaming:!1}),e.draft.assistantId=null,e.draft.thinkingId=null}function es(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,Qo(e,`thinking`,n,!0))}function ts(e){return(e.pendingText.startsWith(e.committedText)?e.pendingText.slice(e.committedText.length):e.pendingText).trim()}function ns(e){let t=ts(e.draft);t&&(e.draft.committedText=e.draft.pendingText,Me(t)?(e.draft.assistantId&&(Xo(e,e.draft.assistantId),e.draft.assistantId=null),Jo(e,{role:`error`,text:je(t)})):Qo(e,`assistant`,t,!0))}function rs(e){let t=ts(e.draft);t&&Qo(e,`assistant`,t,!1)}function is(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 as(e,t,n){if(t)n.thinkingText=t;else{let t=is(e);t.kind===`delta`?n.thinkingText+=t.text:t.kind===`full`&&(n.thinkingText=t.text)}return n.thinkingText.trim()}function os(e,t){return e&&t&&typeof e==`object`&&typeof t==`object`&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t??e}function ss(e,t){let n=t.callId?e.transcript.findIndex(e=>e.tool?.callId===t.callId):-1;if(n<0){Jo(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`?os(i.input,t.input):i.input}}}function cs(e){e.transcript=e.transcript.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function ls(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}`:qo(t)}function us(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 ds(e,t){return e.some(e=>e.attachments?.some(e=>e.hash===t))}function fs(e,t,n){let r=xe(t);if(!r)return{handled:!1,value:e,commands:[]};let i=Ko(e),a=[];switch(r){case`agent_start`:case`turn_start`:i.draft.finalized=!1,Zo(i,r===`agent_start`?`Planning…`:`Thinking…`);break;case`message_start`:t.message?.role===`assistant`&&(i.draft.finalized&&(i.draft=Go(!1)),Zo(i,`Drafting response…`));break;case`app_published`:{let e=t.app;if(!yo(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(!To(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:(es(i),ns(i),i.transcript.push(n));break}case`suggestion`:{let e=t.suggestion;if(!Co(e)||i.transcript.some(t=>t.suggestion?.id===e.id))break;i.transcript.push({id:e.id,role:`assistant`,text:``,suggestion:e});break}case`notice`:{let e=t.notice;if(!wo(e)||i.transcript.some(t=>t.notice?.id===e.id))break;es(i),ns(i),i.transcript.push({id:e.id,role:`assistant`,text:``,notice:e});break}case`app_review`:{let e=t.review;if(!go(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(!vo(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(ds(i.transcript,r.hash))break;let o=typeof t.caption==`string`?t.caption:``;Jo(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=No(n.content).trim();if(a&&(i.draft.pendingText=a),as(t,Po(n.content).trim(),i.draft)&&!a&&(i.draft.sawThinking=!0),r===`message_end`||r===`message_boundary`)es(i),ns(i),i.draft.finalized=!0;else{let e=a?`Drafting response…`:`Thinking…`;(!i.working||i.workingLabel!==e)&&Zo(i,e),rs(i)}for(let e of Ro(n.content))ss(i,e);break}case`start`:es(i),ns(i),$o(i),ss(i,{callId:ls(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Zo(i,us(t,i.transcript));break;case`update`:ss(i,{callId:ls(t,i.transcript),name:Te(t),input:Ee(t),status:`running`,detail:j(t),...ke(t)?{parentToolUseId:ke(t)}:{}}),Zo(i,us(t,i.transcript));break;case`result`:ss(i,{callId:ls(t,i.transcript),name:Te(t),input:{},status:`done`,result:Fo(t.result),detail:j(t)});break;case`turn_end`:Zo(i,`Planning next step…`);break;case`agent_end`:$o(i),cs(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=Bo(t.result??t.message??t.output).filter(e=>!ds(i.transcript,e.hash));e.length&&(Jo(i,{role:`assistant`,text:``,attachments:e}),a.push({kind:`remember-agent-attachments`}))}return{handled:!0,value:i,commands:a}}function X(e,t=!1){return{queue:e,changed:!1,accepted:t}}function ps(e,t){switch(t.type){case`enqueue`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`queued`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`schedule`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...X(e,!0),item:n};let r={...t.item,status:`scheduled`,createdAt:t.now,updatedAt:t.now,version:1};return{queue:[...e,r],changed:!0,accepted:!0,item:r}}case`attach-automation`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAutomationId:t.automationId},{queue:r,changed:!0,accepted:!0}}case`edit`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return{...X(e),edit:{ok:!1,reason:`not_found`}};let r=e[n];if(r.status!==`queued`)return{...X(e),edit:{ok:!1,reason:`not_queued`}};if(r.version!==t.expectedVersion)return{...X(e),edit:{ok:!1,reason:`stale`}};let i={...r,...t.patch,version:r.version+1,updatedAt:t.now,scheduledAutomationId:void 0},a=e.slice();return a[n]=i,{queue:a,changed:!0,accepted:!0,item:i,edit:{ok:!0,item:i}}}case`remove`:{let n=e.find(e=>e.id===t.id);return!n||n.status!==`queued`&&n.status!==`scheduled`?X(e):{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}}case`prune-scheduled`:{let n=e.filter(e=>e.status!==`scheduled`||(e.scheduledAutomationId?t.keepIds.includes(e.scheduledAutomationId):!1));return n.length===e.length?X(e):{queue:n,changed:!0,accepted:!0}}case`reschedule`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`scheduled`)return X(e);let r=e.slice();return r[n]={...e[n],scheduledAt:t.scheduledAt,updatedAt:t.now,version:e[n].version+1},{queue:r,changed:!0,accepted:!0}}case`reorder`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`queued`)return X(e);let r=Math.max(0,Math.min(t.toIndex,e.length-1));if(r===n)return X(e,!0);let i=e.slice(),[a]=i.splice(n,1);return i.splice(r,0,a),{queue:i,changed:!0,accepted:!0}}case`mark-sending`:{let n=e.findIndex(e=>e.id===t.id);if(n<0)return X(e);let r={...e[n],status:`sending`,updatedAt:t.now},i=e.slice();return i[n]=r,{queue:i,changed:!0,accepted:!0,item:r}}case`confirm-sent`:return e.some(e=>e.id===t.id)?{queue:e.filter(e=>e.id!==t.id),changed:!0,accepted:!0}:X(e);case`revert-to-queued`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`sending`)return X(e);let r={...e[n],status:`queued`,updatedAt:t.now};return{queue:[r,...e.filter(e=>e.id!==t.id)],changed:!0,accepted:!0,item:r}}case`settle-sending`:return e.some(e=>e.status===`sending`)?{queue:e.filter(e=>e.status!==`sending`),changed:!0,accepted:!0}:X(e);case`clear`:return e.length?{queue:[],changed:!0,accepted:!0}:X(e,!0)}}function ms(e){return e.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function hs(e){return e===`openai-codex`?`openai`:e}var gs=[`status`,`signedIn`,`nodes`,`currentNodeId`,`nodeUpdate`,`nodeUpdating`,`nodeUpdateAcknowledged`],_s=[`sessions`,`runTerminals`,`tuiSessions`,`pausedSessionIds`,`commandsBySession`,`followupsBySession`],vs=[`activeSessionId`,`activeRuntimeId`,`activeTitle`,`github`,`transcript`,`working`,`workingLabel`,`opening`,`approvals`,`questions`,`turnAttentions`,`usage`,`changes`,`changesHistory`,`checkpoints`],ys=[`models`,`modelsRuntimeId`,`currentModelId`,`currentModel`,`thinking`,`runtimes`,`currentAgentName`,`selectedAgentId`,`installingRuntimeId`,`repos`,`reposAuthed`,`reposError`,`reposLoading`,`reposReason`,`githubConnect`,`branches`,`branchesRepo`,`branchesDefault`,`branchesError`,`branchesLoading`,`providers`,`activationReadiness`],bs=[`nodeSettings`,`providerAuth`,`credentialRecords`,`credentialPresets`,`localModels`,`localModelPresets`,`rulesets`,`sttConfig`,`nodeStats`,`capabilities`],xs=[`forkProgress`,`oauth`,`needsModelAuth`,`githubApp`,`prResult`,`prRefreshAllResult`,`error`,`notice`];function Ss(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 Cs(){return{connection:{status:`offline`,signedIn:!1,nodes:[],currentNodeId:null,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1},sessionIndex:{sessions:[],runTerminals:[],tuiSessions:[],pausedSessionIds:[],commandsBySession:{},followupsBySession:{}},activeSession:{activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[]},catalogs:{models:[],modelsRuntimeId:null,currentModelId:null,currentModel:null,thinking:{supportsThinking:!1,thinkingLevel:`off`,availableThinkingLevels:[`off`]},runtimes:[],currentAgentName:`Agent`,selectedAgentId:null,installingRuntimeId:null,repos:[],reposAuthed:!0,reposError:null,reposLoading:!1,reposReason:null,githubConnect:{status:`idle`},branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,providers:[],activationReadiness:null},settings:{nodeSettings:null,providerAuth:null,credentialRecords:[],credentialPresets:null,localModels:[],localModelPresets:[],rulesets:[],sttConfig:null,nodeStats:null,capabilities:null},presentation:{oauth:null,needsModelAuth:null,githubApp:null,prResult:null,prRefreshAllResult:null,error:null,errorActions:[],notice:null,forkProgress:null},draft:{...va}}}function ws(e=!0){return Go(e)}function Ts(e){return e.role===`assistant`&&!e.tool&&!!e.attachments?.length}function Es(e){return e.tool?`tool:${e.tool.callId}`:`${e.role}:${e.text}`}function Ds(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?Os(e,0,r):e.length;if(!t.after)return Os(e,n,r);for(let i=r-1;i>=n;i--){let n=e[i];if(!Ts(n)&&Es(n)===t.after)return Os(e,i+1,r)}return r}function Os(e,t,n){for(;t<n&&Ts(e[t]);)t++;return t}var ks=class e{state=Cs();listeners=new Set;notifyPending=!1;notifyHandle=null;draft=ws();knownAgentAttachmentsBySession=new Map;draftModel=null;modelsByRuntime=new Map;cachedModelsFor(e){return this.modelsByRuntime.get(e)?.models}pending=new Map;usersBeforePending=0;attachmentsByText=new Map;static ATTACHMENTS_CACHE_MAX=100;inlineImagesByUrl=new Map;transcriptCache=new Map;static CACHE_MAX=30;recentlyDeleted=new Map;historyRaw=new Map;deferredHistory=null;awaitingOpenHistory=!1;onHistoryPersist;requestReplay;seqReassembler=new xa;seqSessionId;seqEpoch;trackSeqStream(e,t){let n=typeof t==`string`?t:void 0;(this.seqSessionId!==e||this.seqEpoch!==n)&&(this.seqReassembler.reset(),this.seqSessionId=e,this.seqEpoch=n)}requestFreshHistory;onSessionSettled;onSessionCreatedElsewhere;getState=()=>this.state;setGithubAppPhase(e,t={}){this.set({githubApp:{...this.state.presentation.githubApp||{phase:`idle`},phase:e,...t}})}setGithubConnect(e){this.set({githubConnect:e})}getHistoryCursor(e){let t=this.historyRaw.get(e);return t&&t.count>0&&t.historyHash?{have:t.count,haveToken:t.historyHash}:{}}seedHistory(e,t,n,r){if(!e||!r||!Array.isArray(t))return;this.historyRaw.set(e,{messages:t,count:n,historyHash:r});let i=this.withInlineImageRefs(this.withCachedAttachments(Vo(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 Vo(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=ws(),this.deferredHistory=null,this.awaitingOpenHistory=!0,this.pending.clear(),this.usersBeforePending=0;let t=this.transcriptCache.get(e),n=this.state.sessionIndex.sessions.find(t=>t.sessionId===e);this.set({activeSessionId:e,activeRuntimeId:n?.runtimeId??null,currentAgentName:n?.agentName||oo(this.state.catalogs.runtimes.find(e=>e.id===n?.runtimeId))||``,currentModel:null,currentModelId:null,models:[],modelsRuntimeId:n?.runtimeId??null,sessions:n?this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,lastSeenAt:Date.now()}:t):this.state.sessionIndex.sessions,...n?.name?{activeTitle:n.name}:{},github:n?Ja(n):{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:t??[],working:!1,workingLabel:``,opening:!t||t.length===0,usage:null,changes:null,changesHistory:[],checkpoints:[]})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));set(e){let t=Ss(this.state.connection,e,gs),n=Ss(this.state.sessionIndex,e,_s),r=Ss(this.state.activeSession,e,vs),i=Ss(this.state.catalogs,e,ys),a=Ss(this.state.settings,e,bs),o=Ss(this.state.presentation,e,xs);this.setValues({connection:t,sessionIndex:n,activeSession:r,catalogs:i,settings:a,presentation:o,draft:e.draft??this.state.draft})}setValues(e){if(this.state={...this.state,...e},this.state.activeSession.working){this.scheduleNotify();return}this.flushNotify()}scheduleNotify(){if(this.notifyPending)return;this.notifyPending=!0;let e=()=>{this.notifyPending=!1,this.notifyHandle=null;for(let e of this.listeners)e()};this.notifyHandle=typeof globalThis.requestAnimationFrame==`function`?globalThis.requestAnimationFrame(e):setTimeout(e,16)}flushNotify(){if(!this.notifyPending){for(let e of this.listeners)e();return}let e=this.notifyHandle;this.notifyPending=!1,this.notifyHandle=null,e!==null&&(typeof globalThis.cancelAnimationFrame==`function`&&typeof e==`number`?globalThis.cancelAnimationFrame(e):clearTimeout(e));for(let e of this.listeners)e()}mergeRuntimeCapabilities(e,t){let n=e?String(e):``;if(!n||!t||typeof t!=`object`)return;let r=this.state.catalogs.runtimes.findIndex(e=>e.id===n),i=r>=0?this.state.catalogs.runtimes[r]:void 0;if(!i)return;let a=i.capabilities||{},o={...t};delete o.commands;let s={...a,...o};if(JSON.stringify(s)===JSON.stringify(a))return;let c=this.state.catalogs.runtimes.slice();c[r]={...i,capabilities:s},this.set({runtimes:c})}setSessionCommands(e,t){let n=e?String(e):``;if(!n)return;let r=Na((t&&typeof t==`object`?t:void 0)?.commands);if(Pa(this.state.sessionIndex.commandsBySession[n]??[],r))return;let i={...this.state.sessionIndex.commandsBySession};r.length?i[n]=r:delete i[n],this.set({commandsBySession:i})}dropSessionCommands(e){if(!(e in this.state.sessionIndex.commandsBySession))return;let t={...this.state.sessionIndex.commandsBySession};delete t[e],this.set({commandsBySession:t})}getFollowups(e){return this.state.sessionIndex.followupsBySession[e]??[]}setFollowupsFor(e,t){let n={...this.state.sessionIndex.followupsBySession};t.length?n[e]=[...t]:delete n[e],this.set({followupsBySession:n})}transitionFollowups(e,t){let n=ps(this.getFollowups(e),t);return n.changed&&this.setFollowupsFor(e,n.queue),n}enqueueFollowup(e,t,n){return this.transitionFollowups(e,{type:`enqueue`,item:t,now:n}).item}enqueueScheduledFollowup(e,t,n){return this.transitionFollowups(e,{type:`schedule`,item:t,now:n}).item}attachFollowupAutomation(e,t,n){return this.transitionFollowups(e,{type:`attach-automation`,id:t,automationId:n}).accepted===!0}editFollowup(e,t,n,r,i){return this.transitionFollowups(e,{type:`edit`,id:t,patch:n,expectedVersion:r,now:i}).edit}removeFollowup(e,t){return this.transitionFollowups(e,{type:`remove`,id:t}).accepted===!0}pruneScheduledFollowups(e,t){this.transitionFollowups(e,{type:`prune-scheduled`,keepIds:[...t]})}rescheduleFollowup(e,t,n,r){return this.transitionFollowups(e,{type:`reschedule`,id:t,scheduledAt:n,now:r}).accepted===!0}reorderFollowup(e,t,n){return this.transitionFollowups(e,{type:`reorder`,id:t,toIndex:n}).accepted===!0}markFollowupSending(e,t,n){return this.transitionFollowups(e,{type:`mark-sending`,id:t,now:n}).item}confirmFollowupSent(e,t){this.transitionFollowups(e,{type:`confirm-sent`,id:t})}revertFollowupToQueued(e,t,n){this.transitionFollowups(e,{type:`revert-to-queued`,id:t,now:n})}settleSendingFollowups(e){this.transitionFollowups(e,{type:`settle-sending`})}dropFollowups(e){e in this.state.sessionIndex.followupsBySession&&this.transitionFollowups(e,{type:`clear`})}clearActivationReadiness(){this.set({activationReadiness:null})}setStatus(e){if(e===this.state.connection.status)return;let t=this.state.connection.currentNodeId;this.set({status:e,...t&&e===`online`?{nodes:this.state.connection.nodes.map(e=>e.id===t?{...e,online:!0}:e)}:{}})}setSignedIn(e){e!==this.state.connection.signedIn&&this.set({signedIn:e})}setNodes(e){let t=this.state.connection.currentNodeId;this.set({nodes:t&&this.state.connection.status===`online`?e.map(e=>e.id===t?{...e,online:!0}:e):e})}setSessions(e){let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions)),n=new Set(t.map(e=>e.sessionId)),r=[...this.state.sessionIndex.sessions.filter(e=>!n.has(e.sessionId)&&(e.pendingLaunch||!(!e.launchProgress||e.launchProgress.firstResponseAt))),...t],i=this.state.activeSession.activeSessionId,a=i?r.find(e=>e.sessionId===i):void 0,o=!!(a&&a.status!==`working`&&a.sessionState?.agent!==`working`);this.set({sessions:i?r.map(e=>e.sessionId===i?{...e,lastSeenAt:Date.now()}:e):r,...o?{working:!1,workingLabel:``}:{}})}seedSessions(e){if(this.state.sessionIndex.sessions.length>0)return;let t=this.withoutRecentlyDeleted($a(e,this.state.sessionIndex.sessions));t.length!==0&&this.set({sessions:t})}setCurrentNode(e){e!==this.state.connection.currentNodeId&&this.set({currentNodeId:e,nodeUpdate:null,nodeUpdating:!1,nodeUpdateAcknowledged:!1})}resetSession(){this.draft=ws(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],usage:null,changes:null,changesHistory:[],checkpoints:[],commandsBySession:{},followupsBySession:{},error:null,notice:null,needsModelAuth:null,draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null}),nodeSettings:null})}setForkProgress(e){this.set({forkProgress:e})}setError(e,t=[]){this.set({error:e,errorActions:e?t:[]})}setNotice(e){this.set({notice:e})}setNodeUpdating(e){this.set({nodeUpdating:e,nodeUpdateAcknowledged:!1})}setNeedsModelAuth(e){this.set({needsModelAuth:e})}pushSystemMessage(e){this.pushEntry({id:Y(),role:`system`,text:e})}clearPrResult(){this.state.presentation.prResult&&this.set({prResult:null})}clearPrRefreshAllResult(){this.state.presentation.prRefreshAllResult&&this.set({prRefreshAllResult:null})}setReposLoading(e){this.set({reposLoading:e})}updateSessionDraft(e){let t=ya(this.state.draft,e);return this.set({draft:t}),t}setDraftEphemeralConfig(e){this.updateSessionDraft({type:`select-ephemeral-config`,config:e})}setDraftRepo(e){this.updateSessionDraft({type:`select-repository`,repo:e})}setBranchesLoading(e){this.set({branchesLoading:e})}clearBranches(){this.set({branches:[],branchesRepo:null,branchesDefault:null,branchesError:null,branchesLoading:!1,draft:ya(this.state.draft,{type:`select-branch`,branch:null})})}setDraftBranch(e){this.updateSessionDraft({type:`select-branch`,branch:e})}setDraftSandbox(e){this.updateSessionDraft({type:`select-sandbox`,sandbox:e})}setDraftAcknowledgeReducedProtections(e){this.updateSessionDraft({type:`acknowledge-reduced-protections`,acknowledged:e})}setDraftModel(e){this.draftModel=e}seedDraftAgentModel(e,t){if(this.state.activeSession.activeSessionId)return;let n={},r=e=>String(e.status||`available`)===`available`,i=e?this.state.catalogs.runtimes.find(t=>t.id===e&&r(t)):void 0,a=this.state.catalogs.runtimes.find(e=>e.current&&r(e)),o=i||a;if(o){let e=oo(o);n.selectedAgentId=o.id,e&&(n.currentAgentName=e)}if(!o||this.state.catalogs.modelsRuntimeId==null||this.state.catalogs.modelsRuntimeId===o.id){let e=t?this.state.catalogs.models.find(e=>ao(e,t)):void 0,r=this.state.catalogs.models.find(e=>e.current),i=e||r;i&&(n.currentModel=i,n.currentModelId=i.id)}else n.models=[],n.modelsRuntimeId=null,n.currentModel=null,n.currentModelId=null;Object.keys(n).length&&this.set(n)}setCurrentModelLocal(e){this.set({currentModel:e,currentModelId:e.id,models:this.state.catalogs.models.map(t=>({...t,current:ao(t,e)}))})}setSelectedAgentLocal(e){let t={selectedAgentId:e,currentAgentName:oo(this.state.catalogs.runtimes.find(t=>t.id===e))||this.state.catalogs.currentAgentName,draft:ya(this.state.draft,{type:`acknowledge-reduced-protections`,acknowledged:!1})};if(this.state.catalogs.modelsRuntimeId!=null&&this.state.catalogs.modelsRuntimeId!==e){let n=this.modelsByRuntime.get(e);n?(t.models=n.models,t.modelsRuntimeId=e,t.currentModel=n.currentModel,t.currentModelId=n.currentModel?.id??null):(t.models=[],t.modelsRuntimeId=null,t.currentModel=null,t.currentModelId=null)}this.set(t)}setInstalling(e){this.set({installingRuntimeId:e})}setThinkingLevel(e){this.set({thinking:{...this.state.catalogs.thinking,thinkingLevel:e}})}resetActiveSession(){this.draft=ws(),this.pending.clear(),this.usersBeforePending=0,this.set({activeSessionId:null,activeRuntimeId:null,activeTitle:`New session`,github:{issueUrl:null,prUrl:null,branch:null,repo:null,prs:[]},transcript:[],working:!1,workingLabel:``,opening:!1,approvals:[],questions:[],turnAttentions:[],selectedAgentId:null,currentAgentName:``,usage:null,changes:null,changesHistory:[],checkpoints:[],draft:ya(this.state.draft,{type:`select-ephemeral-config`,config:null})})}persistPendingSession(e,t,n=!0,r,i=Date.now()){if(this.isSessionDeleted(e))return;let a=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),o={...a,sessionId:e,name:t.trim()||a?.name||`New session`,status:a?.status===`failed`?`failed`:`working`,pendingLaunch:!0,pendingNodeName:r||a?.pendingNodeName,launchProgress:a?.launchProgress??{startedAt:i,checkpoints:{account:{state:`active`,at:i}}},updatedAt:a?.updatedAt||Date.now()};this.set({...n?{activeSessionId:e,activeTitle:o.name}:{},sessions:[o,...this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)]})}retryPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>{if(t.sessionId!==e)return t;let n=t.launchProgress?Object.fromEntries(Object.entries(t.launchProgress.checkpoints).map(([e,t])=>[e,t?.state===`failed`?{state:`active`,at:Date.now()}:t])):void 0;return{...t,status:`working`,updatedAt:Date.now(),launchProgress:t.launchProgress?{...t.launchProgress,failedAt:void 0,checkpoints:n??{}}:void 0}})})}dismissPendingSession(e){this.recentlyDeleted.set(e,Date.now()),this.set({activeSessionId:this.state.activeSession.activeSessionId===e?null:this.state.activeSession.activeSessionId,sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}updateLaunchCheckpoint(e,t,n,r,i){let a=Date.now();this.set({sessions:this.state.sessionIndex.sessions.map(o=>o.sessionId===e&&o.launchProgress?{...o,launchProgress:{...o.launchProgress,...n===`failed`?{failedAt:a}:{},checkpoints:{...Object.fromEntries(Object.entries(o.launchProgress.checkpoints).map(([e,t])=>[e,n===`failed`&&t?.state===`active`?{...t,state:`waiting`}:t])),[t]:{state:n,at:a,...r?{error:r}:{},...i?{errorCode:i}:{}}}}}:o)})}setLaunchModelChoice(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress?{...n,needsAction:!(!t||t.loading||t.selecting),launchProgress:{...n.launchProgress,modelChoice:t}}:n)})}markLaunchFirstResponse(e,t=Date.now()){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e&&n.launchProgress&&!n.launchProgress.firstResponseAt?{...n,launchProgress:{...n.launchProgress,firstResponseAt:t,failedAt:void 0,checkpoints:{...n.launchProgress.checkpoints,agent:{state:`done`,at:t}}}}:n)})}bindPendingSessionNode(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,nodeId:t}:n)})}completePendingSession(e,t,n){if(this.isSessionDeleted(e)||this.isSessionDeleted(t))return;let r=this.state.sessionIndex.sessions.find(t=>t.sessionId===e),i={...r,sessionId:t,nodeId:n,name:r?.name||`New session`,status:`working`,pendingLaunch:!1,pendingNodeName:void 0,updatedAt:Date.now()};this.set({activeSessionId:this.state.activeSession.activeSessionId===e?t:this.state.activeSession.activeSessionId,sessions:[i,...this.state.sessionIndex.sessions.filter(n=>n.sessionId!==e&&n.sessionId!==t)]})}failPendingSession(e){this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e?{...t,status:`failed`,launchProgress:t.launchProgress?{...t.launchProgress,failedAt:t.launchProgress.failedAt??Date.now()}:void 0}:t)})}setActiveTitle(e){this.set({activeTitle:e})}renameSessionLocal(e,t){this.set({sessions:this.state.sessionIndex.sessions.map(n=>n.sessionId===e?{...n,name:t}:n)})}seedDeletedSessionTombstones(e){if(e&&typeof e==`object`){for(let[t,n]of Object.entries(e)){let e=Number(n);t&&Number.isFinite(e)&&this.recentlyDeleted.set(t,e)}this.set({sessions:this.withoutRecentlyDeleted(this.state.sessionIndex.sessions)})}}deletedSessionTombstones(){return Object.fromEntries(this.recentlyDeleted)}removeSessionLocal(e){this.recentlyDeleted.set(e,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(t=>t.sessionId!==e)})}isSessionDeleted(e){return this.recentlyDeleted.has(e)}withoutRecentlyDeleted(e){return this.recentlyDeleted.size===0?e:e.filter(e=>!this.isSessionDeleted(e.sessionId))}upsertSession(e){if(!e.sessionId||this.isSessionDeleted(e.sessionId))return;let t=this.state.sessionIndex.sessions.find(t=>t.sessionId===e.sessionId);if(t){let n={...t,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))};this.set({sessions:this.state.sessionIndex.sessions.map(t=>t.sessionId===e.sessionId?n:t)})}else this.set({sessions:[e,...this.state.sessionIndex.sessions]})}addUserMessage(e,t,n){let r={id:Y(),role:`user`,text:e,html:ye(e),...n&&n.length?{attachments:n}:{}};t&&(this.pending.size===0&&(this.usersBeforePending=this.state.activeSession.transcript.reduce((e,t)=>t.role===`user`?e+1:e,0)),this.pending.set(t,{entry:r,confirmed:!1})),n&&n.length&&this.rememberAttachments(e,n),this.set({transcript:[...this.state.activeSession.transcript,r]}),this.state.activeSession.activeSessionId&&this.updateSessionRow(this.state.activeSession.activeSessionId,{updatedAt:Date.now()})}apply(e){let t=String(e.type||``),n=Sa(this.state.connection,e);if(n.handled){this.setValues({connection:n.value,...n.error?{presentation:{...this.state.presentation,error:n.error}}:{}});return}let r=Ca(this.state.sessionIndex,e);if(r.handled){r.value!==this.state.sessionIndex&&this.setValues({sessionIndex:{...this.state.sessionIndex,pausedSessionIds:[...r.value.pausedSessionIds]}});return}let i=Ta({runTerminals:this.state.sessionIndex.runTerminals,tuiSessions:this.state.sessionIndex.tuiSessions},e,Date.now());if(i.handled){this.set({runTerminals:[...i.value.runTerminals],tuiSessions:[...i.value.tuiSessions]});return}let a=Ea(e);if(a.handled){(a.catalogs||a.settings)&&this.setValues({...a.catalogs?{catalogs:{...this.state.catalogs,...a.catalogs}}:{},...a.settings?{settings:{...this.state.settings,...a.settings}}:{}});return}let o=Da(this.state.presentation,e);if(o.handled){this.setValues({presentation:o.value});return}let s=lo({approvals:this.state.activeSession.approvals,questions:this.state.activeSession.questions,turnAttentions:this.state.activeSession.turnAttentions},e,Date.now());if(s.handled){this.set({approvals:s.value.approvals,questions:s.value.questions,turnAttentions:s.value.turnAttentions}),s.row&&this.updateSessionRow(s.row.sessionId,s.row);return}let c=po({activeSessionId:this.state.activeSession.activeSessionId,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel,opening:this.state.activeSession.opening,usage:this.state.activeSession.usage,changes:this.state.activeSession.changes,changesHistory:this.state.activeSession.changesHistory,checkpoints:this.state.activeSession.checkpoints,activeTitle:this.state.activeSession.activeTitle,github:this.state.activeSession.github,...t===`session.changes`?{newChangeId:Y()}:{}},e,Date.now());if(c.handled){c.patch&&this.set(c.patch);for(let e of c.commands)e.kind===`row`?this.updateSessionRow(e.sessionId,e.patch):e.kind===`entry`?this.pushEntry({id:Y(),role:e.role,text:e.text,...e.actions?.length?{actions:e.actions}:{}}):e.kind===`model-auth`&&this.state.connection.currentNodeId?this.setNeedsModelAuth({nodeId:this.state.connection.currentNodeId,provider:e.provider,reason:e.reason}):e.kind===`rename`?this.renameSessionLocal(e.sessionId,e.name):e.kind===`global-error`?this.set({error:e.message}):e.kind===`reset-active`&&this.resetActiveSession();return}this.applyStatefulEvent(e,t)}applyStatefulEvent(e,t){switch(t){case`sessions.list`:this.setSessions(e.sessions);return;case`session.created`:{let t=e,n=String(t.sessionId||t.id||``);if(n){let e=this.state.sessionIndex.sessions.find(e=>e.sessionId===n),r=eo(t.sessionState??t.bivySession?.state);this.upsertSession({sessionId:n,path:t.sessionFile||t.path,workspace:t.workspace||t.bivySession?.workspace,worktree:t.worktree||t.bivySession?.worktree||t.bivySession?.workspaceContext?.worktree,branch:t.branch||t.bivySession?.branch,name:t.name||(e?void 0:`Untitled session`),source:t.source,bivyCreated:t.bivyCreated===!0,nodeId:t.nodeId,runtimeId:t.runtimeId,agentName:t.agentName,updatedAt:t.updatedAt||t.modified||(e?void 0:Date.now()),status:to(r)??`idle`,sessionState:r,needsAction:r?.displayStatus===`needs_attention`})}this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),n&&this.setSessionCommands(n,t.capabilities),this.onSessionCreatedElsewhere?.();return}case`session.capabilities`:{let t=e;this.mergeRuntimeCapabilities(t.runtimeId,t.capabilities),this.setSessionCommands(t.sessionId,t.capabilities);return}case`session.deleted`:{let t=e,n=String(t.sessionId||``),r=t.sessionFile;n&&this.recentlyDeleted.set(n,Date.now()),this.set({sessions:this.state.sessionIndex.sessions.filter(e=>e.sessionId!==n&&(!r||e.path!==r))}),n&&this.dropSessionCommands(n),n&&this.dropFollowups(n),n&&this.knownAgentAttachmentsBySession.delete(n),n&&n===this.state.activeSession.activeSessionId&&this.resetActiveSession();return}case`session.history`:{let t=e,n=t.sessionId||this.state.activeSession.activeSessionId;if(n&&n===this.state.activeSession.activeSessionId&&this.state.activeSession.working&&!this.draft.finalized&&!this.awaitingOpenHistory){this.deferredHistory=t;return}this.applyHistory(t,n);return}case`session.user_message`:{let t=e,n=t.clientMessageId?this.pending.get(t.clientMessageId):void 0,r=!(!n||n.confirmed);if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId||t.sessionId&&!this.state.activeSession.activeSessionId&&!r||(this.state.activeSession.changes&&this.set({changes:null}),t.retry&&!r))return;if(r&&n){n.entry.attachments?.length&&t.text&&this.rememberAttachments(String(t.text),n.entry.attachments),n.confirmed=!0,t.text&&(n.confirmedText=String(t.text)),n.reconciled&&this.retirePending(t.clientMessageId);return}let i=String(t.text||``);this.pushEntry({id:Y(),role:`user`,text:i,html:ye(i)}),t.sessionId&&this.updateSessionRow(t.sessionId,{updatedAt:Date.now()});return}case`models.list`:{let t=e,n=t.runtimeId==null?null:String(t.runtimeId),r=ro(t.models),i=t.current?ro([t.current])[0]:null;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId){n&&n!==this.state.activeSession.activeRuntimeId&&this.modelsByRuntime.set(n,{models:r,currentModel:i});return}let a=r.filter(e=>e.configured!==!1),o=!this.state.activeSession.activeSessionId&&this.draftModel?a.find(e=>ao(e,this.draftModel)):void 0,s;if(o)s=o;else if(i)s=i;else if(a.length===0)s=null;else{let e=a.find(e=>e.current),t=a.find(e=>ao(e,this.state.catalogs.currentModel));s=e??t??a[0]}n&&this.modelsByRuntime.set(n,{models:r,currentModel:s});let c=this.state.activeSession.activeSessionId?this.state.activeSession.activeRuntimeId:this.state.catalogs.selectedAgentId;if(n&&c&&n!==c)return;this.set({models:r,modelsRuntimeId:n,currentModel:s,currentModelId:s?.id??null,...t.thinking?{thinking:io(t.thinking)}:{}});return}case`model.updated`:{let t=e;if(t.sessionId&&this.state.activeSession.activeSessionId&&t.sessionId!==this.state.activeSession.activeSessionId)return;let n=t.model?ro([t.model])[0]:this.state.catalogs.currentModel;this.set({currentModel:n,currentModelId:n?.id??this.state.catalogs.currentModelId,models:this.state.catalogs.models.map(e=>({...e,current:ao(e,n)}))});return}case`thinking.updated`:{let t=e;t.thinking&&this.set({thinking:io(t.thinking)});return}case`runtimes.list`:case`runtime.updated`:{let t=e,n=t.runtimes||this.state.catalogs.runtimes,r=t.current||n.find(e=>e.id===(this.state.catalogs.selectedAgentId||t.activeAgent)),i=(this.state.activeSession.activeSessionId?void 0:n.find(e=>e.id===this.state.catalogs.selectedAgentId))?.id||r?.id||t.activeAgent||this.state.catalogs.selectedAgentId,a=this.state.activeSession.activeSessionId?n.find(e=>e.id===this.state.activeSession.activeRuntimeId):n.find(e=>e.id===i)||r;this.set({runtimes:n,selectedAgentId:i,currentAgentName:oo(a)||this.state.catalogs.currentAgentName,...t.type===`runtime.updated`?{installingRuntimeId:null}:{}});return}case`runtime.install.done`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null});return}case`runtime.install.error`:{let t=e;this.set({runtimes:t.runtimes||this.state.catalogs.runtimes,installingRuntimeId:null,error:String(t.error||`Install failed`)});return}case`activation.readiness`:{let t=e;t.credential&&t.repository&&this.set({activationReadiness:{credential:t.credential,repository:t.repository}});return}case`github.connect.status`:{let t=e,n=[`waiting`,`connected`,`expired`,`denied`,`error`,`unconfigured`,`idle`].includes(t.status)?t.status:`idle`;this.set({githubConnect:{status:n,userCode:typeof t.userCode==`string`?t.userCode:void 0,verificationUri:typeof t.verificationUri==`string`?t.verificationUri:void 0,intervalMs:typeof t.intervalMs==`number`?t.intervalMs:void 0,error:typeof t.error==`string`?t.error:void 0}});return}case`providers.list`:{let t=e,n=Array.isArray(t.providers)?t.providers:[];this.set({providers:n});let r=this.state.presentation.needsModelAuth;if(r){let e=hs(r.provider);n.some(t=>(t.id===r.provider||t.id===e)&&t.configured)&&this.set({needsModelAuth:null})}return}case`provider.auth`:this.set({providerAuth:e});return;case`provider.oauth.reset`:{let t=e;Array.isArray(t.providers)&&this.set({providers:t.providers}),this.set({oauth:null});return}case`provider.oauth.started`:{let t=e;this.set({oauth:{id:String(t.id||``),provider:t.provider,authUrl:t.authUrl,instructions:t.instructions,deviceCode:t.deviceCode||null,usesCallbackServer:t.usesCallbackServer,canOpenOnNode:t.canOpenOnNode===!0,nodeName:typeof t.nodeName==`string`?t.nodeName:void 0,status:t.error?void 0:`Waiting for sign-in…`,error:t.error}});return}case`auth.oauth.progress`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,status:String(t.message||``)}});return}case`auth.oauth.done`:{let t=e;(!this.state.presentation.oauth||this.state.presentation.oauth.id===t.id)&&this.set({oauth:null});return}case`auth.oauth.error`:{let t=e;this.state.presentation.oauth&&this.state.presentation.oauth.id===t.id&&this.set({oauth:{...this.state.presentation.oauth,error:String(t.error||`sign-in failed`),status:void 0}});return}case`github.app.manifest.ready`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`submitting`,action:typeof t.action==`string`?t.action:void 0,manifest:t.manifest&&typeof t.manifest==`object`?t.manifest:void 0,state:typeof t.state==`string`?t.state:void 0,error:void 0}});return}case`github.app.manifest.done`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`done`,installUrl:typeof t.installUrl==`string`?t.installUrl:void 0,error:void 0,returning:!1}});return}case`github.app.manifest.error`:{let t=e;this.set({githubApp:{...this.getState().presentation.githubApp||{phase:`idle`},phase:`error`,error:typeof t.error==`string`?t.error:`GitHub App setup failed.`,returning:!1}});return}case`session.event`:{let t=e,n=t.sessionId,r=t.event||{},i=be(r?.type);if(n&&i!==`user_question`&&i!==`user_question_resolved`&&i!==`app_published`&&i!==`app_review`&&i!==`app_pin`&&i!==`suggestion`&&i!==`notice`){let e=i===`agent_end`,r=eo(t.state??t.sessionState);this.updateSessionRow(n,{status:to(r)??(e?`idle`:`working`),sessionState:r,needsAction:r?r.agent===`awaiting-input`:!1,...e?{updatedAt:Date.now(),finishedAt:Date.now()}:{}})}if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId||n&&!this.state.activeSession.activeSessionId)return;if(r&&r.type){let e=n&&!r.sessionId?{...r,sessionId:n}:r,i=t.seq;if(typeof i==`number`&&n){this.trackSeqStream(n,t.epoch);let r=this.seqReassembler.accept(i,e);for(let e of r.ready)this.apply(e);r.overflow?this.requestFreshHistory?.():r.gapFrom!==void 0&&this.requestReplay?.(n,r.gapFrom)}else this.apply(e)}return}case`session.replay`:{let t=e,n=t.sessionId;if(n&&this.state.activeSession.activeSessionId&&n!==this.state.activeSession.activeSessionId)return;if(t.mode===`reset`){this.requestFreshHistory?.();return}let r=Array.isArray(t.events)?t.events:[];for(let e of r)this.apply(e);return}case`node.stats`:{let t=Xa(e.stats);t&&this.set({nodeStats:t});return}case`capabilities`:{let t=Za(e.capabilities);t&&this.set({capabilities:t});return}case`session.pr_result`:{let t=e,n=t.prUrl||t.url||null;this.set({prResult:{sessionId:t.sessionId,url:n||void 0,error:t.ok===!1?String(t.error||`Could not open pull request`):void 0}}),t.ok!==!1&&(n||Array.isArray(t.prs))&&this.applyPrUpdate(String(t.sessionId||``),n,t.prs);return}case`session.pr_opened`:{let t=e;this.applyPrUpdate(String(t.sessionId||``),t.prUrl||null,t.prs);return}case`sessions.pr_refresh_result`:{let t=e;this.set({prRefreshAllResult:{scanned:Number(t.scanned)||0,changed:Number(t.changed)||0,error:t.ok===!1?String(t.error||`Could not refresh GitHub status`):void 0}});return}default:{let t=fs({transcript:this.state.activeSession.transcript,draft:this.draft,working:this.state.activeSession.working,workingLabel:this.state.activeSession.workingLabel},e,Date.now());if(!t.handled)return;this.draft=t.value.draft,this.set({transcript:t.value.transcript,working:t.value.working,workingLabel:t.value.workingLabel});for(let e of t.commands)e.kind===`cache-inline-image`?this.inlineImagesByUrl.set(e.url,e.ref):e.kind===`remember-agent-attachments`?this.rememberAgentAttachments(this.state.activeSession.activeSessionId,this.state.activeSession.transcript):e.kind===`turn-settled`&&(this.drainDeferredHistory(),this.onSessionSettled?.())}}}applyHistory(e,t){Array.isArray(e.attachmentRefs)&&this.foldAttachmentRefs(e.attachmentRefs),Array.isArray(e.inlineImageRefs)&&this.foldInlineImageRefs(e.inlineImageRefs);let n=Array.isArray(e.messages)?e.messages:[],r=t?this.historyRaw.get(t):void 0,i=e.mode===`append`&&r&&(e.baseCount===void 0||e.baseCount===r.count);if(e.mode===`append`&&!i){t&&this.historyRaw.delete(t),t&&t===this.state.activeSession.activeSessionId&&this.requestFreshHistory?.();return}let a=i?r.messages.concat(n):n,o=typeof e.count==`number`?e.count:a.length,s=typeof e.historyHash==`string`?e.historyHash:``;t&&(this.historyRaw.set(t,{messages:a,count:o,historyHash:s}),s&&this.onHistoryPersist?.(t,a,o,s));let c=eo(e.sessionState??e.bivySession?.state),l=!(c?c.agent===`working`:e.isStreaming),u=this.withCachedAttachments(l?ms(Vo(a)):Vo(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=ws(),this.deferredHistory=null;let f=eo(e.sessionState??e.bivySession?.state);t&&f&&this.updateSessionRow(t,{sessionState:f,status:to(f),needsAction:f.agent===`awaiting-input`}),this.awaitingOpenHistory=!1,this.set({activeSessionId:t,activeRuntimeId:e.runtimeId?String(e.runtimeId):this.state.activeSession.activeRuntimeId,activeTitle:e.name||this.state.activeSession.activeTitle,currentAgentName:e.agentName||this.state.catalogs.currentAgentName,github:qa(e),transcript:this.withPendingUserEntries(d),working:f?f.agent===`working`:!!e.isStreaming,opening:!1,usage:Ya(e.usage)}),t&&typeof e.headSeq==`number`&&(this.trackSeqStream(t,e.streamEpoch),this.seqReassembler.baseline(e.headSeq))}markStreamInterrupted(){this.deferredHistory=null,this.state.activeSession.opening&&this.set({opening:!1}),!this.draft.finalized&&(this.finishDrafts(),this.draft.finalized=!0)}drainDeferredHistory(){let e=this.deferredHistory;e&&(this.deferredHistory=null,this.requestFreshHistory?this.requestFreshHistory():this.applyHistory(e,e.sessionId||this.state.activeSession.activeSessionId))}pushEntry(e){this.set({transcript:[...this.state.activeSession.transcript,e]})}rememberAgentAttachments(e,t){if(!e)return;let n=this.knownAgentAttachmentsBySession.get(e),r=0,i=``;for(let a of t){if(a.role===`user`){r+=1,i=``;continue}if(!Ts(a)){i=Es(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=Ds(i,e);i=[...i.slice(0,t),{id:Y(),role:`assistant`,text:e.caption,attachments:[e.attachment]},...i.slice(t)]}return i}updateSessionRow(e,t){if(!e)return;let n=!1,r=this.state.sessionIndex.sessions.map(r=>{if(r.sessionId!==e)return r;let i={...r,...t};return e===this.state.activeSession.activeSessionId&&(i.lastSeenAt=Date.now()),(i.status!==r.status||i.needsAction!==r.needsAction||JSON.stringify(i.sessionState)!==JSON.stringify(r.sessionState)||i.branch!==r.branch||i.prUrl!==r.prUrl||JSON.stringify(i.prs)!==JSON.stringify(r.prs)||i.updatedAt!==r.updatedAt||i.lastSeenAt!==r.lastSeenAt||i.finishedAt!==r.finishedAt||i.failedAt!==r.failedAt)&&(n=!0),i});n&&this.set({sessions:r})}applyPrUpdate(e,t,n){let r=Fa(n,t);if(r.length===0)return;let i=r.find(e=>e.state===`open`)?.url??null;e&&this.updateSessionRow(e,{prUrl:i??void 0,prs:r}),(!e||e===this.state.activeSession.activeSessionId)&&this.set({github:{...this.state.activeSession.github,prUrl:i,prs:r}})}finishDrafts(){let e=new Set([this.draft.assistantId,this.draft.thinkingId].filter(Boolean));e.size&&this.set({transcript:this.state.activeSession.transcript.map(t=>e.has(t.id)?{...t,streaming:!1}:t)}),this.draft.assistantId=null,this.draft.thinkingId=null}};function As(e,t){return e>0||t}function js(e){let t=e?.streamingBehaviors;return Array.isArray(t)&&t.includes(`steer`)}function Ms(e){return e.find(e=>e.status===`queued`)}var Ns=`t`;function Ps(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(Ns,{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(Ns,e)}catch{return r(null)}let o=t(a.objectStore(Ns));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 Fs(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 Is=`bivy-attachments-v1`,Ls=67108864,Rs=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(Is)).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>Ls)return;let a=await caches.open(Is),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<=Ls)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(Is)}catch{}}},zs=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<=Ls){for(;this.bytes+n>Ls&&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()}},Bs=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()}},Vs=15e3,Hs=()=>Error(`The machine is not reachable.`),Us=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,Hs())},Vs),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,Hs())}),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 Ws(){return window.navigation}var Gs=0,Ks=[],qs=[],Js,Ys=[];function Xs(){if(!(Js||Ks.some(e=>e.closing)))for(let e of Ys.splice(0))e()}function Zs(e){Ys.push(e),setTimeout(Xs,0)}function Qs(){if(Js)return;let e=Ks.at(-1);if(e?.closing){Js=e;let t=Ws();e.returnKey&&t?t.traverseTo(e.returnKey):history.back();return}for(let e of qs.splice(0))e.disposed||(e.returnKey=Ws()?.currentEntry?.key,history.pushState({...history.state,__bivyModal:e.id},``,location.href),Ks.push(e));Ks.at(-1)?.closing?Qs():Xs()}typeof window<`u`&&window.addEventListener(`popstate`,e=>{let t=Ks.at(-1);if(t&&e.state?.__bivyModal===t.id){e.stopImmediatePropagation(),Js=void 0,queueMicrotask(Qs);return}let n=Ks.pop();Js=void 0,n&&(e.stopImmediatePropagation(),n.disposed||n.onBack(),queueMicrotask(Qs))});function $s(e){let t={id:++Gs,onBack:e,closing:!1,disposed:!1};return queueMicrotask(()=>{t.disposed||(qs.push(t),Qs())}),{close(){t.closing||(t.closing=!0,Qs())},dispose(){t.disposed=!0,t.closing=!0,Qs()}}}var ec=[`appearance`,`notifications`,`import`,`providers`,`models`,`instructions`,`voice`,`share`,`github`,`linear`,`slack`,`queue`,`webhooks`,`rulesets`,`nodes`,`ephemeral`,`account`,`link`];function tc(e){return ec.includes(e)}var nc=[`runs`,`rulesets`];function rc(e){return e===`queue`?`runs`:nc.includes(e)?e:null}var ic=/^\/(artifacts|apps)\/?$/,ac=/^\/sessions\/([^/]+)\/?$/,oc=/^\/settings(?:\/([^/]+))?\/?$/,sc=/^\/automations(?:\/([^/]+))?\/?$/;function cc(e=location.pathname){let t=ac.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=oc.exec(e);if(r){let e=r[1]?decodeURIComponent(r[1]):``;return{kind:`settings`,view:tc(e)?e:null}}let i=sc.exec(e);if(i)return{kind:`automations`,section:rc(i[1]?decodeURIComponent(i[1]):``)};let a=ic.exec(e);return a?{kind:`library`,view:a[1]}:{kind:`root`}}function lc(e){return(e.kind===`session`?`/sessions/${encodeURIComponent(e.id)}`:e.kind===`run`?$e(e.id):e.kind===`new`?`/sessions/new`:e.kind===`settings`?e.view?`/settings/${e.view}`:`/settings`:e.kind===`automations`?e.section?`/automations/${e.section}`:`/automations`:e.kind===`library`?`/${e.view}`:`/`)+location.search+location.hash}function Z(e,t={}){let n=lc(e);n!==location.pathname+location.search+location.hash&&(t.replace?history.replaceState(null,``,n):history.pushState(null,``,n))}function uc(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 dc(e,t,n=globalThis.__BIVY_RUNTIME_CONFIG__){return!n||typeof n!=`object`||!(e in n)?t:n[e]===!0}var fc={BASE_URL:`/`,DEV:!1,EPHEMERAL_MACHINES_ENABLED:``,MODE:`production`,PROD:!0,SSR:!1},pc=dc(`ephemeralMachinesEnabled`,fc.EPHEMERAL_MACHINES_ENABLED===`1`),mc=fc.VITE_BIVY_KEEP_FAILED_EPHEMERAL===`1`,hc=`bivy.cloudMachines.enabled`,gc=`bivy:cloud-machines-changed`;function _c(){try{return typeof localStorage<`u`&&localStorage.getItem(hc)===`1`}catch{return!1}}function vc(e){if(typeof window>`u`)return()=>{};let t=t=>{t.key===hc&&e()};return window.addEventListener(`storage`,t),window.addEventListener(gc,e),()=>{window.removeEventListener(`storage`,t),window.removeEventListener(gc,e)}}function yc(){return _c()}function bc(e){try{e?localStorage.setItem(hc,`1`):localStorage.removeItem(hc)}catch{}typeof window<`u`&&window.dispatchEvent(new Event(gc))}function xc(){return(0,y.useSyncExternalStore)(vc,_c,()=>!1)}var Sc=`bivy.pwa.first-success`,Cc=`bivy.product-metric.first_useful_response`,wc=`bivy.pwa.install-dismissed`,Tc=new Set,Ec=null,Dc=!1,Oc=!1,kc=0;function Ac(){try{return localStorage.getItem(Sc)===`1`||localStorage.getItem(Cc)===`1`}catch{return!1}}function jc(){return typeof window>`u`?!1:window.matchMedia?.(`(display-mode: standalone)`).matches===!0||navigator.standalone===!0}function Mc(){try{return localStorage.getItem(wc)===`1`}catch{return!1}}Oc=typeof window<`u`&&Mc();function Nc(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 Pc(){return typeof navigator>`u`?null:Nc(navigator.userAgent,navigator.platform,navigator.maxTouchPoints,jc())}var Q={updateAvailable:!1,installChoice:null,standalone:jc(),shellCached:!1,firstSuccess:typeof window<`u`&&Ac(),hasDraft:!1,pendingAttachments:0,readingAttachments:!1,turnActive:!1,locallyQueuedPrompts:0,queuedFollowups:0};function $(e){let t={...Q,...e};Object.keys(t).every(e=>t[e]===Q[e])||(Q=t,Tc.forEach(e=>e()))}function Fc(){let e=jc();$({standalone:e,installChoice:e||Dc||Oc||!Q.firstSuccess?null:Ec?`native`:Pc()})}async function Ic(){try{$({shellCached:!!(await navigator.serviceWorker?.getRegistration())?.active})}catch{$({shellCached:!1})}}function Lc(){let e=e=>{e.preventDefault(),Ec=e,Fc()},t=()=>{Ec=null,Dc=!0,Fc()},n=()=>{Ic()},r=window.matchMedia?.(`(display-mode: standalone)`);return window.addEventListener(`beforeinstallprompt`,e),window.addEventListener(`appinstalled`,t),navigator.serviceWorker?.addEventListener(`controllerchange`,n),r?.addEventListener?.(`change`,Fc),Fc(),Ic(),()=>{window.removeEventListener(`beforeinstallprompt`,e),window.removeEventListener(`appinstalled`,t),navigator.serviceWorker?.removeEventListener(`controllerchange`,n),r?.removeEventListener?.(`change`,Fc)}}function Rc(e){return Tc.add(e),()=>Tc.delete(e)}function zc(){return Q}function Bc(e){$({updateAvailable:e})}function Vc(e){$(e)}function Hc(e){$({turnActive:e})}function Uc(){kc+=1,$({locallyQueuedPrompts:kc})}function Wc(){kc=0,$({locallyQueuedPrompts:0})}function Gc(e){$({queuedFollowups:Math.max(0,Math.floor(e))})}function Kc(){try{localStorage.setItem(Sc,`1`)}catch{}$({firstSuccess:!0}),Fc()}function qc(){Oc=!0,Ec=null;try{localStorage.setItem(wc,`1`)}catch{}$({installChoice:null})}async function Jc(){let e=Ec;if(!e||Q.standalone||!Q.firstSuccess)return`unavailable`;Ec=null,$({installChoice:null});try{return await e.prompt(),(await e.userChoice).outcome}catch{return`unavailable`}}function Yc(e=Q){let t=[];return e.turnActive&&t.push(`the active turn finishes`),e.readingAttachments&&t.push(`file reading finishes`),e.hasDraft&&t.push(`the unsent draft is sent or cleared`),e.pendingAttachments&&t.push(`pending attachments are sent or cleared`),e.locallyQueuedPrompts&&t.push(`locally queued prompts reach the Machine`),e.queuedFollowups&&t.push(`queued follow-ups are delivered`),t}function Xc(e=Q){return e.updateAvailable&&Yc(e).length===0}var Zc="On that machine, run `bivy status` (or `bivy restart`).";function Qc(e,t,n=Q,r){let i=r?`Machine ${r}`:`The Machine`;return n.locallyQueuedPrompts>0?{kind:`local-queue`,label:n.locallyQueuedPrompts===1?`Prompt queued on this device`:`${n.locallyQueuedPrompts} prompts queued on this device`,detail:`Not yet delivered to ${r?`Machine ${r}`:`the Machine`}. Keep Bivy open — it sends as soon as the connection is back.`}:e===`reconnecting`||e===`connecting`||e===`linking`||e===`pairing`?{kind:`reconnecting`,label:r?`Reconnecting to ${r}`:`Reconnecting Machine`,detail:t?`Showing the cached transcript. Keep drafting — sending resumes once the connection is back.`:`Waiting for ${r?`Machine ${r}`:`the Machine`} to answer. If this sticks, run \`bivy status\` on that machine.`}:e===`offline`&&t?{kind:`cached-transcript`,label:`Cached transcript`,detail:`${i} is offline — this copy may be behind, and prompts can't send until it reconnects. ${Zc}`}: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. ${Zc}`}:e===`offline`?{kind:`offline-page`,label:`Offline`,detail:`${i} is unreachable. Your draft is kept on this device. ${Zc}`}:{kind:`live-control`,label:`Live control`,detail:`${i} is connected. Prompts send now and transcript changes sync live.`}}var $c=66e4,el=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}:{}},$c),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}:{}},$c)}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})})}},tl=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}},nl=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)}},rl=class{deps;finishingMachines=new Set;constructor(e){this.deps=e}listConfigs(){return this.deps.listConfigs()}createConfig(e){return this.deps.createConfig(e)}updateConfig(e,t){return this.deps.updateConfig(e,t)}removeConfig(e){return this.deps.removeConfig(e)}listSizes(e,t){return this.deps.listSizes(e,t)}async setProviderToken(e,t){await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}async connectProvider(e,t){return await this.deps.validateProviderToken(e,t),await this.deps.setProviderToken(e,t),this.ensureDefaultRunner(e)}getProviderToken(e){return this.deps.getProviderToken(e)}removeProviderToken(e){return this.deps.removeProviderToken(e)}async runWorkItem(e,t){let n=await this.launch({...t,setupId:t.configId,hostedTasks:!0,workItemId:e,purpose:`queue-item`,name:`Ephemeral queue runner`});try{await this.deps.assignWorkItem(e,{node:this.deps.nodeLabel(n.nodeId??``),runtimeId:t.runtimeId,model:t.model,ephemeral:!0})}catch(e){throw this.deps.refreshNodes(),e}return this.deps.refreshNodes(),n}launchQueueWorker(e){return this.launch({...e,setupId:e.configId,hostedTasks:!0,purpose:`queue-default`,name:`Ephemeral queue worker`})}async ensureDefaultRunner(e){try{let t=(await this.listConfigs()).find(t=>t.provider===e);if(t)return t;let n=this.deps.defaultConfig(e);return await this.createConfig({provider:e,name:`${n.name} runner`,region:n.region,size:n.size,ttlMinutes:60,teardownOnAgentFinish:!0})}catch{return null}}async launch(e){if(!this.deps.signedIn())throw Error(`Sign in to launch an ephemeral machine.`);let t=e.githubToken??await this.deps.githubToken(),n=await this.deps.launchMachine({...e,repo:e.repo??this.deps.draftRepo(),githubToken:t||void 0});return this.deps.refreshNodes(),n}async destroy(e){await this.deps.destroyMachine(e),this.deps.refreshNodes()}async teardownFinishedSession(e){if(this.deps.direct()||this.deps.followupCount(e)>0)return;let t=this.deps.currentNodeId();if(!t)return;let n=(await this.deps.machines().catch(()=>[])).find(e=>e.nodeId===t&&e.teardownOnAgentFinish);n&&!this.finishingMachines.has(n.id)&&(this.deps.recordSessionCorrelation(e,n),this.finishingMachines.add(n.id),this.deps.schedule(()=>{if(this.deps.followupCount(e)>0||this.deps.currentNodeId()!==t){this.finishingMachines.delete(n.id);return}this.destroy(n).catch(e=>{this.finishingMachines.delete(n.id),this.deps.reportError(e instanceof Error?e:Error(String(e)))})},3e3))}async resumeAndConnect(e,t=9e4){try{await this.deps.connectToNode(e,t)}catch(e){this.deps.reportError(this.error(e))}}async reprovision(e,t){try{let n=this.deps.correlations().find(n=>n.nodeId===e||n.sessionId===t);if(n?.computeSource===`managed`){if(!n.setupId)throw Error(`This managed session no longer has a Machine profile to rebuild from.`);await this.deps.restoreManagedMachine({configId:n.setupId,nodeId:n.nodeId,sessionId:t,requestId:`restore:${t}:${n.nodeId}:${n.machineId||`legacy`}`}),await this.deps.connectToNode(n.nodeId,12e4);return}let r=this.deps.roomKey(e);if(!r)throw Error(`This device no longer holds this session's key, so it can't rebuild it.`);let i=this.deps.nodes().find(t=>t.id===e),a=(await this.deps.machines()).find(t=>t.nodeId===e)??(i?this.deps.machineFromNode(i):null)??(n?this.deps.machineFromCorrelation(n):null);if(!a)throw Error(`No record of the machine to rebuild — re-launch it from Ephemeral settings.`);await this.launch({provider:a.provider,region:a.region||void 0,ttlMinutes:a.ttlMinutes,repo:a.repo,setupId:a.setupId,teardownOnAgentFinish:a.teardownOnAgentFinish,reuseNodeId:e,reuseRoomKeyB64:r,restoreSessionId:t}),await this.deps.connectToNode(e,12e4)}catch(e){this.deps.reportError(this.error(e))}}isCurrentNodeResumable(){if(this.deps.direct())return!1;let e=this.deps.currentNodeId();if(!e)return!1;let t=this.deps.correlations().find(t=>t.nodeId===e),n=this.deps.nodes().find(t=>t.id===e);return t?.computeSource===`managed`?!n:this.deps.roomKey(e)?n?!n.online&&!!this.deps.machineFromNode(n):!!t:!1}error(e){return e instanceof Error?e:Error(String(e))}},il=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)}},al=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 As(t,this.store.getState().activeSession.working)}supportsSteering(){let e=this.store.getState(),t=e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId;return js(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=Ms(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}:{}})}},ol=`bivy.device.id`,sl=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android.*Mobile/,`Android phone`],[/Android/,`Android tablet`],[/CrOS/,`Chromebook`],[/Macintosh|Mac OS X/,`Mac`],[/Windows/,`Windows PC`],[/Linux/,`Linux`]];function cl(e,t=0){let n=sl.find(([t])=>t.test(e))?.[1]??`Browser`;return n===`Mac`&&t>1?`iPad`:n}var ll;function ul(){if(ll)return ll;let e=``;try{e=localStorage.getItem(ol)??``}catch{}if(!e){e=`web:${crypto.randomUUID()}`;try{localStorage.setItem(ol,e)}catch{}}return ll={id:e,label:cl(navigator.userAgent,navigator.maxTouchPoints)},ll}var dl=class extends Error{disclosure;constructor(e){super(e),this.disclosure=e,this.name=`NeedsDisclosureError`}};function fl(){return`r-${crypto.randomUUID()}`}function pl(){return crypto.randomUUID()}var ml=/^(localhost|127\.0\.0\.1|\[?::1\]?)$/,hl=`bivy-room-v1`,gl=8e3,_l=24e4;function vl(e=_t(r())){return n?!1:dc(`directNode`,!1)||new URLSearchParams(location.search).has(`local`)?!0:ml.test(location.hostname)&&!e.s&&!location.hash.includes(`payload=`)}var yl=new class e{store=new ks;local=_t(r());direct;solo;directPairCode=``;transport;transportGeneration=0;syncingActivationCredentials=!1;pendingLaunchRestoration=Promise.resolve();pendingPrompt=null;pendingLaunches=new Map;bootProgressTimers=new Map;bootstrapPhaseByNode=new Map;pendingAgentPick=null;pendingFollowups=[];pendingResume=[];resumingNode=new Set;ephemeralCorrelations=[];correlatedSessions=new Set;terminalListeners=new Set;pendingTranscriptions=new Map;pendingSpeech=new Map;pendingAcks=new Map;transcriptCache=Ps({maxSessions:50});attachmentLoader=new zs;attachmentDiskCache=new Rs;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 al(this.store,{send:e=>this.send(e),createClientMessageId:pl,now:Date.now,persistBackstop:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},cancelBackstop:e=>this.cancelScheduledFollowup(e)}),this.nodeCoordinator=new tl({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 el({reportForkProgress:e=>this.store.setForkProgress({status:`working`,message:e}),send:e=>{this.sendToCurrentNode(e)},sendRequest:e=>{this.sendToCurrentNode(e)},createRequestId:fl,createClientMessageId:pl,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()}${lc({kind:`session`,id:e})}`,refreshAccountSessions:()=>{this.refreshAccountSessions()},launchManagedDestination:async(e,t)=>{let n=await Ft(this.local,e,{runtimeId:t});if(!n.nodeId)throw Error(`Managed fork destination launched without a node id`);return n.nodeId},reportCrossNodeFork:(e,t)=>{e===`error`?this.store.setError(t):e===`success`&&this.store.setNotice(t)}},{navigateNew:()=>Z({kind:`new`}),focusComposer:()=>this.focusComposer(),clearPendingPromptAndFollowups:()=>{this.pendingPrompt=null,this.pendingFollowups=[]},resetActiveSession:()=>{this.promptTargetSessionId=null,this.store.resetActiveSession()},seedDraftDefaults:()=>this.seedDraftDefaults(),listRuntimes:()=>this.listRuntimes(),listModels:()=>this.listModels(),hasNodeSettings:()=>!!this.store.getState().settings.nodeSettings,getNodeSettings:()=>this.getNodeSettings(),listRepos:()=>this.listRepos(),draftRepo:()=>this.store.getState().draft.repo,listBranches:e=>this.listBranches(e),activeSessionId:()=>{if(this.promptTargetSessionId)return this.promptTargetSessionId;let e=this.store.getState(),t=cc();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:()=>pc&&yc()?this.store.getState().draft.ephemeralConfig:null,startEphemeralLaunch:(e,t,n)=>{let r=new Date().toISOString(),i={id:e,prompt:t,config:n,logs:[],followups:[],phase:`provisioning`,createdAt:r,updatedAt:r};this.pendingLaunches.set(e,i),this.pendingLaunchStore.put(i),this.store.persistPendingSession(e,t.text,!0,n.name),this.launchDraftRunnerAndBind(e)},send:e=>this.send(e),resetDeletedActiveSession:()=>{this.store.resetActiveSession(),Z({kind:`new`})},removeSessionLocal:e=>this.store.removeSessionLocal(e),persistDeletedSessionTombstones:()=>this.persistDeletedSessionTombstones(),deleteTranscriptCache:e=>{this.transcriptCache.delete(e)},refreshSessions:()=>this.refreshSessions(),resolveSessionId:e=>e||this.store.getState().activeSession.activeSessionId}),this.credentialsModelsCoordinator=new nl({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 rl({listConfigs:()=>$t(this.local),createConfig:e=>en(this.local,e),updateConfig:(e,t)=>tn(this.local,e,t),removeConfig:e=>nn(this.local,e),listSizes:(e,t)=>ji(e,{exec:ki(this.local),keys:this.ephemeralKeys},t),signedIn:()=>this.signedIn,direct:()=>this.direct,currentNodeId:()=>this.local.cur,roomKey:e=>this.local.keys()[e],draftRepo:()=>this.store.getState().draft.repo||void 0,githubToken:()=>this.githubTaskToken.get(),machines:()=>this.ephemeralMachines.list(),nodes:()=>this.store.getState().connection.nodes,correlations:()=>this.ephemeralCorrelations,launchMachine:e=>Mi({...e,debugKeepMachine:mc},{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),restoreManagedMachine:e=>It(this.local,e),destroyMachine:e=>Ni(e,{store:this.local,exec:ki(this.local),keys:this.ephemeralKeys,machines:this.ephemeralMachines}),machineFromNode:e=>di(e),machineFromCorrelation:ui,connectToNode:(e,t)=>this.connectToNode(e,t),refreshNodes:()=>{this.refreshNodes()},reportError:e=>this.store.setError(e.message),defaultConfig:e=>{let t=ni(e);return{name:G(e)?.name??e,region:t?.defaultRegion??null,size:t?.defaultSize??null}},validateProviderToken:(e,t)=>ri(e,t,ki(this.local)),setProviderToken:(e,t)=>this.ephemeralKeys.setToken(e,t),removeProviderToken:e=>this.ephemeralKeys.remove(e),getProviderToken:e=>this.ephemeralKeys.getToken(e),assignWorkItem:(e,t)=>Pn(this.local,e,t),nodeLabel:e=>ai(e),followupCount:e=>this.store.getFollowups(e).length,recordSessionCorrelation:(e,t)=>{this.recordSessionCorrelation(e,t)},schedule:(e,t)=>{setTimeout(e,t)}}),this.accountCoordinator=new il({local:this.local,sendGithubDisconnect:({appId:e,hookId:t})=>this.send({kind:`github.app.disconnect`,requestId:fl(),appId:e||void 0,hookId:t||void 0}),refreshNodes:()=>this.refreshNodes(),api:{fetchMe:Vt,fetchGithubApp:Kt,fetchGithubQueue:Nn,fetchAutomationRuns:Dn,cancelAutomationRun:jn,disconnectGithubApp:qt,removeNode:Wt,enablePush:qn,disablePush:Jn,pushStatus:Yn,getNotificationPreferences:Xn,setNotificationPreferences:Zn,createOneOffRun:En,setGithubAppDefaultNode:Jt,setGithubAppTriggerAccess:Yt,assignWorkItem:Pn,deleteWorkItem:Fn,clearWorkQueue:In},runContext:()=>{let e=this.store.getState(),t=e.activeSession.activeSessionId??void 0,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t):void 0,r=t?this.resolveSessionNodeId(t):e.connection.currentNodeId??void 0,i=r?e.connection.nodes.find(e=>e.id===r):void 0;return{accountMode:this.accountMode(),sessionId:t,nodeId:r,roomKey:r?this.local.keys()[r]:void 0,nodeLabel:i?.name?`bivy/${i.name}`:void 0,repo:e.draft.repo??void 0,runtimeId:e.catalogs.selectedAgentId??void 0,model:e.catalogs.currentModel?.id,sandbox:n?.sandbox??(t?void 0:e.draft.sandbox??e.settings.nodeSettings?.defaultSandbox)}},encrypt:async(e,t)=>D(await E(C(e)),t),recordRunAccepted:()=>this.recordProductMilestone(`run_accepted`)}),this.store.onHistoryPersist=(e,t,n,r)=>{let i=this.store.attachmentsForHistory(t);this.transcriptCache.put(e,t,n,r,i)},this.store.requestFreshHistory=()=>{let e=this.store.getState().activeSession.activeSessionId;e&&this.requestHistory(e)},this.store.requestReplay=(e,t)=>{this.send({kind:`session.replay`,sessionId:e,afterSeq:t})},this.store.onSessionSettled=()=>{this.refreshSessions();let e=this.store.getState().activeSession.activeSessionId;e&&(this.store.settleSendingFollowups(e),this.followupCoordinator.drain(e),this.maybeTeardownFinishedEphemeral(e))},this.store.onSessionCreatedElsewhere=()=>this.refreshSessions();let e=/^#pair=([A-Za-z0-9_-]+)$/.exec(location.hash);e&&(this.directPairCode=e[1]??``,history.replaceState(null,``,location.pathname+location.search));try{!n&&xt(this.local,location.hash)&&history.replaceState(null,``,location.pathname+location.search)}catch{}this.seedDraftDefaults(),this.detectGithubAppReturn(),this.direct=vl(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=cc(),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=dc(`directNode`,!1);return this.direct?new sa({bootstrap:new URLSearchParams(location.search).get(`bootstrap`)||``,...t?{tokenStore:r(),pairCode:this.directPairCode,deviceName:ul().label,requireToken:!0}:{},handlers:e}):new ga({store:this.local,handlers:e})}productMetricClient(){return matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`}recordProductMilestone(e,t=!1){if(this.direct||this.solo||!this.local.s)return;let n=`bivy.product-metric.${e}`;if(t){try{if(localStorage.getItem(n)===`1`)return}catch{}if(this.productMetricsInFlight.has(e))return;this.productMetricsInFlight.add(e)}An(this.local,e,this.productMetricClient()).then(()=>{if(t)try{localStorage.setItem(n,`1`)}catch{}}).catch(()=>{}).finally(()=>this.productMetricsInFlight.delete(e))}static FIRST_RUN_STEP_EVENTS={machine_online:{ok:`first_run_machine_ready`,failed:`first_run_machine_failed`},agent_installed:{ok:`first_run_agent_verified`,failed:`first_run_agent_failed`},credential_valid:{ok:`first_run_provider_connected`,failed:`first_run_provider_failed`}};observeActivationMilestones(t,n){let r=this.store.getState(),i=e=>({direct:this.direct,signedIn:e.connection.signedIn,status:e.connection.status,runtimes:e.catalogs.runtimes,readiness:e.catalogs.activationReadiness}),a=rt(i(t)),o=rt(i(r));!a.activated&&o.activated&&this.recordProductMilestone(`activation_ready`,!0);for(let[t,n]of Object.entries(e.FIRST_RUN_STEP_EVENTS)){let e=a.checks.find(e=>e.id===t)?.state,r=o.checks.find(e=>e.id===t)?.state;e!==`passed`&&r===`passed`&&this.recordProductMilestone(n.ok,!0),e!==`failed`&&r===`failed`&&this.recordProductMilestone(n.failed,!0)}if(n.type===`session.history`)return;let s=e=>e.activeSession.transcript.filter(e=>e.role===`assistant`&&!!e.text&&!e.tool).length;s(t)===0&&s(r)>0&&(Kc(),this.recordProductMilestone(`first_useful_response`,!0))}needsAuth(){return this.connectionRequirement().type===`authentication-required`}needsNode(){return this.connectionRequirement().type===`node-required`}needsSetup(){return this.connectionRequirement().type!==`ready`}connectionRequirement(){return this.nodeCoordinator.requirement({direct:this.direct,solo:this.solo,signedIn:!!this.local.s,currentNodeId:this.local.cur||null})}listNodes(){return Et(this.local)}centralGithubApp(){return Dt(this.local)}createCentralGithubInstall(e=`/`){return Ot(this.local,e)}managedAutomationTarget(){return kt(this.local)}async managedCredentialReady(){return(await At(this.local)).ready}async waitForManagedCredential(e=2e4,t=-1){let n=Date.now()+e;for(;Date.now()<n;){let e=await At(this.local);if(e.ready&&e.generation>t)return;await new Promise(e=>setTimeout(e,750))}throw Error(`The encrypted Bivy Cloud credential was not published. Try provider setup again.`)}async setupManagedCredentials(){let e=this.store.getState().activeSession.activeSessionId;if(!e||!this.pendingLaunches.has(e))throw Error(`The original Cloud session is no longer available.`);await this.retryPendingLaunch(e)}ensureManagedSessionDefaults(){return Pt(this.local)}createNodeClaim(){return Lt(this.local)}listNodeClaims(){return Rt(this.local)}revokeNodeClaim(e){return zt(this.local,e)}selectNode(e){this.switchNode(e)}get signedIn(){return!!this.local.s}async completeSignIn(e,t=()=>!0){if(e&&t()){this.local.s=e,this.local.cp||(this.local.cp=d());try{await m()}catch(t){throw this.local.s===e&&(this.local.s=``,await m().catch(()=>{})),t}if(!t()){this.local.s===e&&(this.local.s=``,await m());return}if(this.solo){location.reload();return}this.nativeSubscriptionsStopped=!1,this.store.setSignedIn(!0),this.syncDeviceVault().catch(()=>{}),this.connect()}}nativeSubscriptionSyncAt=0;nativeSubscriptionSyncToken=``;nativeSubscriptionSyncing=!1;nativeSubscriptionsStopped=!1;syncNativeSubscriptions(){let e=this.local.s;!this.nativeSubscriptionsStopped&&e&&o()?.synchronize({token:e,controlPlane:d()}).catch(()=>{this.store.setError(`Notification registration could not be refreshed. Open Notifications to retry.`)}),!this.nativeSubscriptionsStopped&&e&&l()&&!this.nativeSubscriptionSyncing&&(e===this.nativeSubscriptionSyncToken&&Date.now()-this.nativeSubscriptionSyncAt<3e5||(this.nativeSubscriptionSyncing=!0,this.nativeSubscriptionSyncToken=e,this.nativeSubscriptionSyncAt=Date.now(),s(e).catch(()=>{!this.nativeSubscriptionsStopped&&this.local.s===e&&this.store.setError(`Subscription status could not be refreshed. Open Subscriptions to retry.`)}).finally(()=>{this.nativeSubscriptionSyncing=!1})))}connect(){this.nodeCoordinator.connect(),this.syncNativeSubscriptions()}foregroundTimer=null;backgroundDisconnectTimer=null;livenessTimer=null;pendingLivenessPings=new Set;installLifecycleHandlers(){if(typeof document>`u`)return;let n=()=>{this.backgroundDisconnectTimer&&=(clearTimeout(this.backgroundDisconnectTimer),null),this.refreshAfterForeground(),this.syncNativeSubscriptions()};document.addEventListener(`visibilitychange`,()=>{if(document.visibilityState===`visible`){n();return}this.direct||this.backgroundDisconnectTimer||(this.backgroundDisconnectTimer=setTimeout(()=>{this.backgroundDisconnectTimer=null,document.visibilityState===`hidden`&&this.transport.close()},e.BACKGROUND_DISCONNECT_DELAY_MS))}),f(n),window.addEventListener(`pageshow`,n),window.addEventListener(`focus`,n),window.addEventListener(`popstate`,e=>{e.state?.bivyNativeLink||this.applyRoute(cc(),{navigate:!1})}),t(e=>{let t=uc(e,d());t&&(history.replaceState(null,``,t.path),this.pendingRoute=cc(),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:ul(),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=fl();this.pendingLivenessPings.add(t),this.send({kind:`ping`,requestId:t}),this.livenessTimer=setTimeout(()=>{this.livenessTimer=null,this.store.getState().connection.status===`online`&&this.pendingLivenessPings.delete(t)&&this.transport.reconnect()},e.LIVENESS_TIMEOUT_MS)}async refreshNodes(){if(!this.direct&&this.signedIn){this.lastNodeRefreshAt=Date.now();try{let e=await this.listNodes();this.store.setNodes(e),this.local.cur&&!e.some(e=>e.id===this.local.cur)&&(this.currentNodeIsRebuildable()?this.markCurrentNodeAwaitingRebuild():this.clearCurrentNode()),this.refreshAccountSessions()}catch{}}}clearCurrentNode(){try{this.transport.close()}catch{}this.local.cur=``,this.store.setCurrentNode(null),this.store.resetSession(),this.store.setStatus(`offline`)}currentNodeIsRebuildable(){let e=this.local.cur;if(!e)return!1;try{if(!this.local.keys()[e])return!1}catch{return!1}return this.ephemeralCorrelations.some(t=>t.nodeId===e)}markCurrentNodeAwaitingRebuild(){if(this.store.getState().connection.status!==`offline`){try{this.transport.close()}catch{}this.store.setStatus(`offline`)}}lastNodeRefreshAt=0;refreshNodesThrottled(){!this.direct&&this.signedIn&&(Date.now()-this.lastNodeRefreshAt<1e4||this.refreshNodes())}pickDraftEphemeralRunner(e){this.store.setDraftEphemeralConfig(e),this.listModels()}switchNode(e){this.store.setDraftEphemeralConfig(null),this.nodeCoordinator.switchNode(e)}connectToNode(e,t){return this.nodeCoordinator.connectToNode(e,t)}async signOut(){this.nativeSubscriptionsStopped=!0,await Promise.allSettled([h(),c()]),this.nativeSubscriptionSyncToken=``,this.nativeSubscriptionSyncAt=0,this.sessionTitleKeys?.close(),this.machineRequests?.close();try{this.transport.close()}catch{}let e=this.local.device()?.pub;try{e=(await Ui(this.local)).pub}catch{}try{await Gn(this.local,e)}catch{}try{await Bi()}catch{}await this.attachmentDiskCache.clear(),this.local.clear(),await m(),this.store.setSignedIn(!1),location.assign(`/`)}listDevices(){return Un(this.local)}isCurrentDevice(e){return!!e&&this.local.device()?.pub===e}removeDevice(e){return Wn(this.local,e)}isProvisionalSessionId(e){return e.startsWith(`starting-`)||this.pendingLaunches.has(e)||this.store.getState().sessionIndex.sessions.some(t=>t.sessionId===e&&t.pendingLaunch)}sendToCurrentNode(e){typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId)||this.transport.send(e)}async appendLaunchFollowup(e,t){this.pendingLaunches.has(e)||await this.pendingLaunchRestoration;let n=this.pendingLaunches.get(e);if(!n){this.store.setError(`Couldn't find the saved Cloud startup. Your message has not been sent.`);return}n.followups.push(t);try{await this.pendingLaunchStore.put(n)}catch{this.store.setError(`Couldn't save the queued message. Keep this page open until startup finishes.`)}}send(e){this.sessionCoordinator.send(e.kind===`prompt`?{...e,device:ul()}:e)}updateNode(){Fs(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=fl();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 Us(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:t})),this.machineRequests.request(e,t,n)):this.store.getState().connection.status===`online`?this.awaitAck(t,n):Promise.reject(Error(`Connect to the machine first.`))}async acrossMachines(e,t){let{nodes:n,status:r}=this.store.getState().connection,i=r===`online`?[this.direct?null:this.local.cur||null]:[],a=this.direct?i:[...i,...n.filter(e=>e.online&&e.id!==this.local.cur).map(e=>e.id)],o=await Promise.allSettled(a.map(async n=>t(await this.machineRequest(n,{kind:e})).map(e=>({...e,nodeId:n}))));return{items:o.flatMap(e=>e.status===`fulfilled`?e.value:[]),unreachable:a.filter((e,t)=>o[t].status===`rejected`).map(e=>n.find(t=>t.id===e)?.name||`A machine`)}}resolveAck(e){let t=String(e.requestId||``),n=t?this.pendingAcks.get(t):void 0;if(n){if(clearTimeout(n.timer),this.pendingAcks.delete(t),String(e.type||``).endsWith(`.error`)){let t=Error(String(e.error||`Save failed`));Object.assign(t,e),n.reject(t)}else n.resolve(e)}}async discoverNativeSessions(){let e=(await this.awaitAck({kind:`session.discover`},2e4)).sessions;return Array.isArray(e)?e:[]}async importNativeSession(e,t,n={}){let r;try{r=await this.awaitAck({kind:`session.import`,runtimeId:e,ref:t,acceptDisclosure:n.acceptDisclosure??!1},6e4)}catch(e){let t=e;throw t?.needsDisclosure?new dl(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=pl();this.store.addUserMessage(a,e),this.send({kind:`prompt`,sessionId:i,text:a,clientMessageId:e})}else this.openSession(i,t);return i}waitForOnline(e=2e4){return this.store.getState().connection.status===`online`?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{i(),n(Error(`Destination machine did not come online`))},e),i=this.store.subscribe(()=>{this.store.getState().connection.status===`online`&&(clearTimeout(r),i(),t())})})}promoteSession(e,t){return this.sessionCoordinator.promote(e,t)}forkInFlight=!1;startSessionLike(e,t,n){return this.sessionCoordinator.startLike(e,t,n)}async forkSession(e,t={},n){if(this.forkInFlight)throw Error(`A session fork is already in progress`);this.forkInFlight=!0,this.store.setForkProgress({status:`working`,message:`Preparing to fork the session…`});let r=this.store.getState(),i=r.sessionIndex.sessions.find(t=>t.sessionId===e),a=t.sourceAgentId||i?.runtimeId,o=t.agentId||a,s=(e,t)=>{let n=r.catalogs.runtimes.find(t=>t.id===e);return String(n?.displayName||n?.name||t||e||`agent`)},c=i?.name||`session ${e.slice(0,8)}`,l=s(a,i?.agentName),u=s(o,o===a?i?.agentName:void 0);try{await n?.();let r=await this.sessionCoordinator.fork(e,t);return this.store.getState().activeSession.activeSessionId!==r.sessionId&&this.openSession(r.sessionId,void 0,{navigate:!1}),await this.waitForForkReady(r.sessionId),Z({kind:`session`,id:r.sessionId}),this.store.setNotice(`This session was forked from “${c}” with ${l} to ${u}.`),this.store.setForkProgress(null),r}catch(e){throw this.store.setForkProgress({status:`error`,message:e instanceof Error?e.message:String(e)}),e}finally{this.forkInFlight=!1}}waitForForkReady(e){let t=()=>{let t=this.store.getState().activeSession;return t.activeSessionId===e&&!t.opening};return t()?Promise.resolve():(this.store.setForkProgress({status:`working`,message:`Loading the forked session…`}),new Promise((e,n)=>{let r=setTimeout(()=>{i(),n(Error(`The fork was created, but its conversation could not be loaded. Reopen it from the session list.`))},3e4),i=this.store.subscribe(()=>{t()&&(clearTimeout(r),i(),e())})}))}refreshSessions(){if(this.send({kind:`terminal.list`}),!this.direct&&this.signedIn){this.refreshAccountSessions(),this.local.cur&&this.send({kind:`sessions.list`});return}this.send({kind:`sessions.list`})}async decryptSessionTitle(e){if(!e.titleEnc)return`Untitled session`;let t=this.local.keys()[e.nodeId];if(!t)return`Untitled session`;try{return(await O(await E(C(t)),e.titleEnc)).trim()||`Untitled session`}catch{return`Untitled session`}}sessionTitleKeys;async refreshAccountSessions(){if(!this.direct&&this.signedIn)try{let e=await Bt(this.local);this.sessionTitleKeys??=new Bs(this.local,(e,t)=>new ga({store:e,pairingOnly:!0,handlers:{onStatus:e=>{e===`online`&&t()},onEvent:()=>{}}}),()=>{this.refreshAccountSessions()}),this.sessionTitleKeys.ensure(e.filter(e=>e.titleEnc).map(e=>e.nodeId));let t=this.store.getState().sessionIndex.sessions,n=(await Promise.all(e.map(async e=>{let n=String(e.sessionId||e.id||``),r=String(e.nodeId||``),i=t.find(e=>e.sessionId===n&&(!e.nodeId||e.nodeId===r)),a=await this.decryptSessionTitle(e);return{...i,sessionId:n,nodeId:r,name:a===`Untitled session`&&i?.name||a,source:e.source||i?.source,branch:e.branch||i?.branch,status:e.status,attention:Array.isArray(e.attention)?e.attention:i?.attention,updatedAt:e.updatedAt||i?.updatedAt}}))).filter(e=>e.sessionId&&e.nodeId),r=new Set(n.map(e=>e.sessionId)),i=this.store.getState().sessionIndex.sessions,a=this.ephemeralCorrelations.filter(e=>!r.has(e.sessionId)&&!!this.local.keys()[e.nodeId]).map(e=>{let t=i.find(t=>t.sessionId===e.sessionId);return{...t,sessionId:e.sessionId,nodeId:e.nodeId,name:t?.name||(e.repo?`${e.repo}`:`Rebuildable session`),source:t?.source,status:`saved`,rebuildable:!0,updatedAt:t?.updatedAt}}),o=new Set([...this.pendingLaunches.values()].map(e=>e.sessionId));this.store.setSessions([...n,...a].filter(e=>!o.has(e.sessionId)))}catch{}}eventWithNodeScope(e){if(this.direct||!this.local.cur)return e;let t=this.local.cur;if(e.type===`sessions.list`){let n=e,r=Array.isArray(n.sessions)?n.sessions:[],i=new Set(r.map(e=>String(e?.sessionId||e?.id||``)).filter(Boolean)),a=this.store.getState().sessionIndex.sessions.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.sessionId));return{...e,sessions:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`session.created`)return{...e,nodeId:t};if(e.type===`terminal.list`){let n=e,r=Array.isArray(n.terminals)?n.terminals:[],i=new Set(r.map(e=>String(e?.termId||``)).filter(Boolean)),a=this.store.getState().sessionIndex.runTerminals.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.termId));return{...e,terminals:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`terminal.created`){let n=e;return n.terminal?{...e,terminal:{...n.terminal,nodeId:n.terminal.nodeId||t}}:e}return e}static DELETED_SESSIONS_KEY=`bivy.deleted-sessions`;restoreDeletedSessionTombstones(){try{let t=localStorage.getItem(e.DELETED_SESSIONS_KEY);t&&this.store.seedDeletedSessionTombstones(JSON.parse(t)),this.persistDeletedSessionTombstones()}catch{}}persistDeletedSessionTombstones(){try{let t=this.store.deletedSessionTombstones();Object.keys(t).length?localStorage.setItem(e.DELETED_SESSIONS_KEY,JSON.stringify(t)):localStorage.removeItem(e.DELETED_SESSIONS_KEY)}catch{}}sessionCacheKey(){return`bivy.sessions.${this.direct?`direct`:this.local.cur||``}`}seedSessionsFromCache(){if(this.direct||this.local.cur)try{let e=localStorage.getItem(this.sessionCacheKey());e&&this.store.seedSessions(JSON.parse(e))}catch{}}installSessionCachePersist(){if(typeof localStorage>`u`)return;let e=this.store.getState().sessionIndex.sessions;this.store.subscribe(()=>{let t=this.store.getState().sessionIndex.sessions;if(t!==e){e=t;try{localStorage.setItem(this.sessionCacheKey(),JSON.stringify(t.slice(0,100)))}catch{}}})}installFollowupAutoDrain(){let e=this.store.getState().activeSession.working,t=this.store.getState().activeSession.activeSessionId;this.store.subscribe(()=>{let n=this.store.getState().activeSession.activeSessionId,r=this.store.getState().activeSession.working,i=n!=null&&n===t&&e&&!r;e=r,t=n,i&&this.followupCoordinator.drain(n)})}async findLiveRunTerminal(e,t,n=4e3){let r=()=>this.store.getState().sessionIndex.runTerminals.find(n=>n.sessionId===e&&(!t||!n.nodeId||n.nodeId===t))??null;return r()||(this.direct||!t||t===this.local.cur&&this.store.getState().connection.status===`online`?null:(await this.connectToNode(t),this.send({kind:`terminal.list`}),new Promise(e=>{let t=setTimeout(()=>{i(),e(r())},n),i=this.store.subscribe(()=>{let n=r();n&&(clearTimeout(t),i(),e(n))})})))}selectSessionTarget(e){return this.promptTargetSessionId=e,this.sessionSelectionEpoch+=1,Z({kind:`session`,id:e}),this.sessionSelectionEpoch}isCurrentSessionTarget(e,t){return this.promptTargetSessionId===e&&(t===void 0||t===this.sessionSelectionEpoch)}openSessionOnNode(e,t,n){if(this.selectSessionTarget(e),this.pendingLaunches.has(e)){this.openPendingLaunch(e);return}if(!this.direct&&n&&n!==this.local.cur){this.pendingCrossNodeOpen={sessionId:e,path:t},Z({kind:`session`,id:e}),this.switchNode(n),this.store.beginOpen(e);return}this.openSession(e,t)}openSession(e,t,n={}){if(this.promptTargetSessionId=e,this.pendingLaunches.has(e)){this.openPendingLaunch(e,n);return}n.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.send({kind:`session.open`,sessionId:e,path:t}),this.listModels(),this.seedAndRequestHistory(e)}async seedAndRequestHistory(e){try{let t=await this.transcriptCache.get(e);t&&this.store.getState().activeSession.activeSessionId===e&&(this.store.restoreAttachments(t.attachments),this.store.seedHistory(e,t.messages,t.count,t.historyHash))}catch{}this.requestHistory(e)}onReconnected(){let e=!1;if(this.pendingCrossNodeOpen){let t=this.pendingCrossNodeOpen;this.pendingCrossNodeOpen=null,this.openSession(t.sessionId,t.path),e=!0}this.refreshAccountSessions(),this.store.clearActivationReadiness(),this.syncingActivationCredentials=!0;let t=this.transportGeneration;this.syncAccountCredentialsWithNode().finally(()=>{t===this.transportGeneration&&(this.syncingActivationCredentials=!1,this.send({kind:`activation.readiness`}))}),this.resyncScheduledFollowups(),this.seedEphemeralNodeIfNeeded(),this.maybePromptFirstRunModelAuth(),this.refreshEphemeralCorrelations(),e||this.applyInitialRoute();let n=this.store.getState().activeSession.activeSessionId;if(n&&!e?(this.requestHistory(n),this.listModels(),this.followupCoordinator.retrySending(n),this.drainPendingResume(n)):n||this.retryPendingSessionNew(),this.pendingGithubAppCode){let{code:e,state:t}=this.pendingGithubAppCode;this.pendingGithubAppCode=null,this.githubAppManifestCode(e,t)}}detectGithubAppReturn(){try{let e=new URLSearchParams(location.search),t=!1;try{t=sessionStorage.getItem(`bivy.githubAppPending`)===`1`,t&&sessionStorage.removeItem(`bivy.githubAppPending`)}catch{}if(!e.has(`bivy_github_app`)&&!t)return;let n=(e.get(`code`)||``).trim(),r=(e.get(`state`)||``).trim();e.delete(`bivy_github_app`),e.delete(`code`),e.delete(`state`);let i=e.toString();history.replaceState(null,``,location.pathname+(i?`?${i}`:``)+location.hash),n&&r?(this.pendingGithubAppCode={code:n,state:r},this.store.setGithubAppPhase(`completing`,{returning:!0,state:r})):this.store.setGithubAppPhase(`error`,{returning:!0,error:`GitHub did not return a code.`})}catch{}}requestHistory(e){let t=this.store.getHistoryCursor(e);this.send({kind:`history`,sessionId:e,...t})}draftSessionFields(){let e=this.store.getState(),t=e.catalogs.currentModel?{provider:e.catalogs.currentModel.provider,id:e.catalogs.currentModel.id}:void 0;return{repo:e.draft.repo||void 0,branch:e.draft.repo&&e.draft.branch||void 0,agent:e.catalogs.selectedAgentId||void 0,sandbox:e.draft.sandbox||void 0,acknowledgeReducedProtections:e.draft.acknowledgeReducedProtections||void 0,model:t}}getNodeSettings(){this.send({kind:`node.settings.get`})}setNodeSettings(e){return this.awaitAck({kind:`node.settings.set`,settings:e}).then(()=>void 0)}setSessionSandbox(e){this.store.setDraftSandbox(e)}acknowledgeSessionAgentReducedProtections(e){this.store.setDraftAcknowledgeReducedProtections(e)}newSession(e={}){let t=this.store.getState(),n=t.activeSession.activeSessionId?t.sessionIndex.sessions.find(e=>e.sessionId===t.activeSession.activeSessionId)?.nodeId??this.local.cur:this.local.cur,r=t.connection.nodes.find(e=>e.id===n)?.name??``,i=this.ephemeralCorrelations.find(e=>e.nodeId===n)?.setupId;this.sessionCoordinator.newSession(e),n?.startsWith(`eph-`)&&this.listEphemeralConfigs().then(e=>{let t=this.store.getState();if(t.activeSession.activeSessionId||t.draft.ephemeralConfig||this.local.cur!==n)return;let a=(i?e.find(e=>e.id===i):void 0)??(/^Hosted\s+/i.test(r)?e.find(e=>e.computeSource===`managed`):void 0);a&&this.pickDraftEphemeralRunner(a)}).catch(()=>{})}seedDraftDefaults(){let e=this.local.lastChoice();e.repo&&this.store.setDraftRepo(e.repo);let t=e.modelId?{provider:e.modelProvider,id:e.modelId}:null;this.store.setDraftModel(t),this.store.seedDraftAgentModel(e.agentId,t)}maybeRestoreDraftAgent(e){if(e.type!==`runtimes.list`)return;let t=this.store.getState();if(t.activeSession.activeSessionId)return;let n=this.local.lastChoice().agentId,r=n?t.catalogs.runtimes.find(e=>e.id===n):void 0;if(r&&n!==t.catalogs.selectedAgentId&&String(r.status||`available`)===`available`){this.chooseAgent(r);return}t.catalogs.selectedAgentId&&t.catalogs.modelsRuntimeId!==t.catalogs.selectedAgentId&&this.listModels()}sendPrompt(e,t,n){this.sessionCoordinator.sendPrompt(e,t,n),this.commitStagedPin(e)}stagedPin=null;stagePin(e){this.stagedPin={...e,at:Date.now()}}async commitStagedPin(e){let t=this.stagedPin;if(this.stagedPin=null,!(!t||Date.now()-t.at>6e5||!t.context||!e.includes(t.context)))try{await this.appCommand(`apps.pin`,t.sessionId,{appId:t.appId,viewId:t.viewId,words:e})}catch{}}async launchDraftRunnerAndBind(e){let t=this.pendingLaunches.get(e);if(!t)return;let{config:n}=t,r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};try{let i=t.prompt.frame&&`agent`in t.prompt.frame?String(t.prompt.frame.agent||``):``,a=n.computeSource===`managed`?this.prepareManagedCredential(i,t.prompt.frame.model?.provider):Promise.resolve(!0);this.store.updateLaunchCheckpoint(e,`capacity`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(e,`repository`,`skipped`),n.computeSource===`managed`&&r(`Reserving secure managed compute…`);let o=n.computeSource===`managed`?Ft(this.local,n.id,{runtimeId:i,requestId:e}):this.launchEphemeral({provider:n.provider,region:n.region??void 0,size:n.size??void 0,image:n.image??void 0,ttlMinutes:n.ttlMinutes??void 0,teardownOnAgentFinish:n.teardownOnAgentFinish===!0,name:n.name,setupId:n.id,onProgress:r}),[s,c]=await Promise.all([o,a]);if(this.store.updateLaunchCheckpoint(e,`account`,`done`),!s.nodeId)throw Error(`machine launched without a node id`);this.store.updateLaunchCheckpoint(e,`capacity`,`done`),this.store.updateLaunchCheckpoint(e,`machine`,`done`),this.store.updateLaunchCheckpoint(e,`service`,`active`),t.machine=s,t.phase=`booting`,t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.bindPendingSessionNode(e,s.nodeId),n.computeSource===`managed`&&!c?await this.beginManagedCredentialSetup(e,s.nodeId):this.startPendingRunner(e)}catch(r){let i=`Launch failed: ${r?.message||r}`;t.logs.push(i),t.phase=`failed`,t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),r instanceof jt&&r.code===`managed_credentials_required`?(this.store.updateLaunchCheckpoint(e,`capacity`,`waiting`),this.store.updateLaunchCheckpoint(e,`account`,`failed`,r.message,r.code)):r instanceof jt&&r.code===`managed_image_unavailable`?this.store.updateLaunchCheckpoint(e,`machine`,`failed`,i,r.code):this.failLaunchCheckpoint(e,i),this.store.failPendingSession(e);let a=r instanceof jt?r.actions:[];this.store.setError(`Couldn't start ${n.name}: ${r?.message||r}`,a)}}managedLaunchProvider(e,t){return e.startsWith(`codex`)?`openai-codex`:e.startsWith(`claude`)?`anthropic`:t??null}async prepareManagedCredential(e,t){let n=await this.managedCredentialReady().catch(()=>!1),r=await this.tryPublishManagedCredential(e,n,t);return this.managedLaunchProvider(e,t)?r:r||n}async tryPublishManagedCredential(e,t,n){if(this.store.getState().connection.status!==`online`)return!1;let r=this.managedLaunchProvider(e,n),i=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&(!r||e.provider===r));if(!i)return!1;if(i.unattended&&t)return!0;try{i.unattended&&await this.setCredentialUnattended(i.provider,i.label,!1);let e=(await At(this.local)).generation;return await this.setCredentialUnattended(i.provider,i.label,!0),await this.waitForManagedCredential(2e4,e),!0}catch{return!1}}async beginManagedCredentialSetup(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.phase=`credential-setup`,n.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(n),this.managedCredentialSetupNodes.add(t),this.managedCredentialReturnSessionId=e,this.store.updateLaunchCheckpoint(e,`credentials`,`active`),this.switchNode(t),await this.waitForOnline(12e4),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.listProviders(),this.listCredentialRecords();let r=n.prompt.frame,i=this.managedLaunchProvider(String(r?.agent||``),r?.model?.provider)??this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`)?.provider??`anthropic`;this.store.setNeedsModelAuth({nodeId:t,provider:i})}failLaunchCheckpoint(e,t){let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.launchProgress,r=[`account`,`capacity`,`machine`,`service`,`credentials`,`repository`,`agent`,`message`],i=[...r].reverse().find(e=>n?.checkpoints[e]?.state===`active`)??r.find(e=>!n?.checkpoints[e]||n.checkpoints[e]?.state===`waiting`)??`message`;this.store.updateLaunchCheckpoint(e,i,`failed`,t)}openPendingLaunch(e,t={}){let n=this.pendingLaunches.get(e);n&&(t.navigate!==!1&&Z({kind:`session`,id:e}),this.store.beginOpen(e),this.store.addUserMessage(n.prompt.text,n.prompt.clientMessageId,n.prompt.attachments))}startPendingRunner(e){let t=this.pendingLaunches.get(e),n=t?.machine?.nodeId;if(!t||!n||t.transport)return;let r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};r(`Machine accepted. Waiting for its secure Bivy service to come online…`),this.startBootProgress(n,e,r);let i=new Proxy(this.local,{get:(e,t,r)=>t===`cur`?n:Reflect.get(e,t,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),a,o,s=()=>this.pendingLaunches.get(e)===t&&t.transport===a,c=!1,l=!1,u=()=>{if(c&&(l||t.config.computeSource!==`managed`)&&this.pendingLaunches.has(e)){let{model:e,...n}=t.prompt.frame;a.send(n)}};a=new ga({store:i,handlers:{onStatus:i=>{if(o){o.onStatus(i);return}s()&&(c=i===`online`,c&&(t.modelApproved=!1,t.modelSelecting=void 0,t.modelQuery=void 0,t.models=void 0,r(`${t.config.name} is online. Preparing credentials, repository, and agent…`),this.store.updateLaunchCheckpoint(e,`service`,`done`),this.store.updateLaunchCheckpoint(e,`credentials`,l?`done`:`active`),this.clearBootProgress(n),u()))},onEvent:n=>{if(o){o.onEvent(n);return}if(!s())return;(n.type===`credentials.records`||n.type===`providers.list`)&&t.sessionId&&!t.modelQuery&&this.refreshLaunchModels(e);let r=n.type===`models.list`?n.current:n.model;if(n.type===`session.error`&&t.sessionId&&!t.modelApproved&&n.sessionId===t.sessionId){t.modelSelecting=void 0,t.modelQuery=void 0,t.prompt.frame={...t.prompt.frame,model:void 0},this.pendingLaunchStore.put(t).catch(()=>{}),this.store.setLaunchModelChoice(e,{models:t.models??[],error:typeof n.error==`string`?n.error:`Couldn't select this model. Choose another model or refresh.`});return}if(n.type===`models.list`&&n.sessionId===t.sessionId&&!t.modelApproved){if(t.modelQuery=void 0,n.modelSelection===!1){t.modelApproved=!0,this.sendPendingLaunchPrompt(e,t.sessionId,a);return}t.models=(Array.isArray(n.models)?n.models:[]).filter(e=>e&&e.configured!==!1&&typeof e.id==`string`&&e.id!==`unknown`&&typeof e.provider==`string`&&e.provider!==`unknown`&&e.id&&e.provider);let i=t.models?.find(e=>e.id===r?.id&&e.provider===r?.provider),o=t.prompt.frame.model;if(!t.modelSelecting&&i&&(!o||o.id===i.id&&o.provider===i.provider))t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);else{let n=t.models?.find(e=>e.id===o?.id&&e.provider===o?.provider);n&&!t.modelSelecting?this.chooseLaunchModel(e,n):(this.store.updateLaunchCheckpoint(e,`message`,`waiting`),this.store.setLaunchModelChoice(e,{models:t.models??[],current:i,selecting:!!t.modelSelecting,error:o&&!n?lt(o,t.models??[],t.config.computeSource===`managed`):void 0}))}return}if(n.type===`model.updated`&&n.sessionId===t.sessionId&&t.modelSelecting&&r?.id===t.modelSelecting.id&&r?.provider===t.modelSelecting.provider){t.modelSelecting=void 0,t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);return}if(n.type===`session.error`){this.failPendingLaunch(e,String(n.error||`Session creation failed.`));return}if(n.type===`session.history`&&n.requestId===t.prompt.requestId&&n.sessionId){t.prompt.frame&&`repo`in t.prompt.frame&&t.prompt.frame.repo&&this.store.updateLaunchCheckpoint(e,`repository`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`done`),t.sessionId=String(n.sessionId),t.modelApproved?this.sendPendingLaunchPrompt(e,t.sessionId,a):this.refreshLaunchModels(e);return}n.type===`session.user_message`&&(t.promptSent||t.promptSending)&&n.sessionId===t.sessionId&&n.clientMessageId===t.prompt.clientMessageId&&this.finishPendingLaunch(e,String(t.sessionId),a,()=>(o=this.buildTransportHandlers(),o),n)},onError:e=>{if(o){o.onError?.(e);return}s()&&(/^node offline$/i.test(e.trim())||r(`Connection retry: ${e}`))}}}),t.transport=a,this.pollBootstrapStatus(n,e,r,()=>{l=!0,u()}),a.connect()}refreshLaunchModels(e){let t=this.pendingLaunches.get(e);if(!t?.sessionId||!t.transport||t.modelApproved||t.modelSelecting)return;let n={};t.modelQuery=n,this.store.setLaunchModelChoice(e,{models:t.models??[],loading:!0});let r=()=>{this.pendingLaunches.get(e)===t&&t.modelQuery===n&&(t.modelQuery=void 0,this.store.setLaunchModelChoice(e,{models:t.models??[],error:`Couldn't load models from this machine. Refresh to try again; your prompt is still saved.`}))};setTimeout(r,15e3),Promise.resolve().then(()=>t.transport?.send({kind:`models.list`,sessionId:t.sessionId})).catch(r)}async chooseLaunchModel(e,t){let n=this.pendingLaunches.get(e);if(!n?.sessionId||!n.transport||n.modelSelecting||n.modelApproved||n.modelQuery)return;let r=n.models?.find(e=>e.id===t.id&&e.provider===t.provider);if(!r)return;let i={...r};n.modelSelecting=i,this.store.setLaunchModelChoice(e,{models:n.models??[],current:i,selecting:!0}),setTimeout(()=>{this.pendingLaunches.get(e)===n&&n.modelSelecting===i&&(n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Model selection wasn't confirmed. Refresh or choose again; your prompt is still saved.`}))},15e3);try{if(n.prompt.frame={...n.prompt.frame,model:{id:i.id,provider:String(i.provider)}},await this.pendingLaunchStore.put(n),this.pendingLaunches.get(e)!==n||n.modelSelecting!==i)return;await n.transport.send({kind:`model.select`,sessionId:n.sessionId,id:i.id,provider:i.provider})}catch{n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Couldn't select this model. Refresh and try again.`})}}async sendPendingLaunchPrompt(e,t,n){let r=this.pendingLaunches.get(e);if(r&&!r.promptSending&&r.modelApproved){this.store.updateLaunchCheckpoint(e,`message`,`active`),r.sessionId=t,r.promptSending=!0,this.store.getState().activeSession.activeSessionId===e&&this.store.pushSystemMessage(`Setup · Repository and agent are ready. Sending your prompt…`);try{if(await n.send({kind:`prompt`,sessionId:t,text:r.prompt.text,clientMessageId:r.prompt.clientMessageId,attachments:r.prompt.attachments}),!this.pendingLaunches.has(e))return;r.promptSent=!0,r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}catch(t){if(!this.pendingLaunches.has(e))return;r.logs.push(`First-message delivery retry: ${t?.message||t}`),r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}finally{r.promptSending=!1,setTimeout(()=>{let r=this.pendingLaunches.get(e);r&&r.phase!==`failed`&&r.sessionId===t&&this.sendPendingLaunchPrompt(e,t,n)},3e3)}}}async finishPendingLaunch(e,t,n,r,i){let a=this.pendingLaunches.get(e),o=a?.machine?.nodeId;if(!a||!o)return;this.store.updateLaunchCheckpoint(e,`message`,`done`),this.clearBootProgress(o),this.pendingLaunches.delete(e),this.pendingLaunchStore.remove(e).catch(()=>{}),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),this.store.completePendingSession(e,t,o);let s=this.store.getState().activeSession.activeSessionId===t;if(s){let e=r();this.transport.close(),this.local.cur=o,this.store.setCurrentNode(o),this.transport=n,this.pendingCrossNodeOpen={sessionId:t},Z({kind:`session`,id:t}),this.store.setStatus(`connecting`),e.onStatus(`online`),e.onEvent(i),this.listRuntimes(),this.listProviders(),this.getNodeSettings()}for(let e of a.followups)await n.send({kind:`prompt`,sessionId:t,...e});s||setTimeout(()=>n.close(),1e3),setTimeout(()=>this.refreshSessions(),1500)}failPendingLaunch(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.machine?.nodeId&&this.clearBootProgress(n.machine.nodeId);let r=n.transport;n.transport=void 0,r?.close(),n.logs.push(`Startup failed: ${t}`),this.store.setLaunchModelChoice(e,void 0),n.modelQuery=void 0,n.modelSelecting=void 0,n.modelApproved=!1,n.phase=`failed`,n.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(n),/not available on this node|command not found|agent is not installed/i.test(t)?(this.store.updateLaunchCheckpoint(e,`credentials`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`failed`,t)):this.failLaunchCheckpoint(e,t),this.store.failPendingSession(e),this.store.setError(`Couldn't start ${n.config.name}: ${t}`)}startBootProgress(e,t,n){this.clearBootProgress(e);let r=[[15e3,`Booting the machine and installing Bivy…`],[45e3,`Still installing Bivy (45s elapsed). A first boot can take a few minutes…`],[9e4,`Still waiting for Bivy to join the secure relay (90s elapsed)…`],[18e4,`Boot is taking longer than usual (3 min elapsed). Still retrying…`],[_l,`Still offline after ${Math.round(_l/6e4)} min. Check the provider's machine logs for a failed install.`]].map(([e,r])=>setTimeout(()=>{this.pendingLaunches.has(t)&&n(r)},e));this.bootProgressTimers.set(e,r)}clearBootProgress(e){for(let t of this.bootProgressTimers.get(e)??[])clearTimeout(t);this.bootProgressTimers.delete(e),this.bootstrapPhaseByNode.delete(e)}pollBootstrapStatus(e,t,n,r){let i={booting:`The machine booted and cloud-init started.`,installing:`Cloud-init is installing Bivy…`,starting:`Bivy is installed. Starting its secure service…`,ready:`The secure Bivy service is ready.`,failed:`Cloud-init reported that the Bivy install failed.`},a=!1,o=async()=>{let s=this.pendingLaunches.get(t);if(s&&s.machine?.nodeId===e){try{let o=await Et(this.local);this.store.setNodes(o);let c=o.find(t=>t.id===e)?.bootstrapStatus?.phase;c&&c!==this.bootstrapPhaseByNode.get(e)&&(this.bootstrapPhaseByNode.set(e,c),n(i[c]||`Bootstrap: ${c}`),c===`ready`&&this.store.updateLaunchCheckpoint(t,`service`,`done`),c===`failed`&&this.failPendingLaunch(t,i.failed)),(s.config.computeSource===`managed`?(await gn(this.local)).find(t=>t.nodeId===e)?.milestones?.credentialsReadyAt:c===`ready`)&&!a&&this.pendingLaunches.has(t)&&s.phase!==`failed`&&(a=!0,this.store.updateLaunchCheckpoint(t,`credentials`,`done`),r())}catch{}this.pendingLaunches.has(t)&&setTimeout(o,3e3)}};o()}async restorePendingLaunches(){let e=await this.pendingLaunchStore.list();for(let t of e){if(this.store.isSessionDeleted(t.id)){await this.pendingLaunchStore.remove(t.id);continue}this.pendingLaunches.set(t.id,t),this.store.persistPendingSession(t.id,t.prompt.text,!1,t.config.name,Date.parse(t.createdAt)||Date.now()),t.machine?.nodeId&&t.phase!==`failed`?(this.store.retryPendingSession(t.id),this.store.setLaunchModelChoice(t.id,void 0),this.store.updateLaunchCheckpoint(t.id,`account`,`done`),this.store.updateLaunchCheckpoint(t.id,`capacity`,`done`),this.store.updateLaunchCheckpoint(t.id,`machine`,`done`),this.store.updateLaunchCheckpoint(t.id,`service`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(t.id,`repository`,`skipped`),this.store.bindPendingSessionNode(t.id,t.machine.nodeId),t.phase===`credential-setup`?this.beginManagedCredentialSetup(t.id,t.machine.nodeId):this.startPendingRunner(t.id)):t.phase===`provisioning`?(t.phase=`failed`,t.logs.push(`Startup was interrupted before the cloud provider confirmed the machine.`),t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.failPendingSession(t.id)):t.phase===`failed`&&this.store.failPendingSession(t.id)}}async retryPendingLaunch(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close(),t.logs.push(`Retrying startup…`),t.phase=t.machine?.nodeId?`booting`:`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),t.machine?.nodeId?this.startPendingRunner(e):await this.launchDraftRunnerAndBind(e)}async retryPendingLaunchOnFreshMachine(e){let t=this.pendingLaunches.get(e);if(!t)return;let n=t.transport;t.transport=void 0,n?.close();let r=t.machine?.nodeId;r&&await this.destroyHostedMachine(r).catch(()=>{}),t.machine=void 0,t.sessionId=void 0,t.promptSent=!1,t.logs.push(`Replacing the Cloud Machine and retrying the preserved first message…`),t.phase=`provisioning`,t.updatedAt=new Date().toISOString(),this.store.retryPendingSession(e),await this.pendingLaunchStore.put(t),await this.launchDraftRunnerAndBind(e)}async dismissPendingLaunch(e){let t=this.pendingLaunches.get(e);this.pendingLaunches.delete(e),t?.transport?.close(),t?.machine?.nodeId&&this.clearBootProgress(t.machine.nodeId),this.store.dismissPendingSession(e),this.persistDeletedSessionTombstones(),await this.pendingLaunchStore.remove(e),this.store.getState().activeSession.activeSessionId??this.newSession()}invokeAgentCommand(e,t){let n=this.store.getState().activeSession.activeSessionId;n&&this.send({kind:`session.command.invoke`,sessionId:n,name:e,args:t})}listRepos(){this.store.getState().catalogs.repos.length===0&&this.store.setReposLoading(!0);let e=this.store.getState().draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||e)){cn(this.local).then(e=>this.store.apply({type:`repos.list`,repos:e,authed:!0})).catch(e=>this.store.apply({type:`repos.list`,repos:[],authed:!1,error:String(e?.message||e)}));return}this.send({kind:`repos.list`})}githubConnectStart(){this.store.setGithubConnect({status:`starting`}),this.send({kind:`github.connect.start`})}githubConnectPoll(){this.send({kind:`github.connect.poll`})}githubConnectReset(){this.store.setGithubConnect({status:`idle`})}chooseRepo(e){let t=e!==this.store.getState().draft.repo;this.store.setDraftRepo(e),t&&this.store.clearBranches(),this.local.setLastChoice({repo:e})}chooseRepoBranch(e,t){this.store.setDraftRepo(e),this.store.setDraftBranch(t),this.local.setLastChoice({repo:e})}listBranches(e){let t=this.store.getState();t.catalogs.branchesRepo===e&&t.catalogs.branches.length>0||this.store.setBranchesLoading(!0);let n=t.draft.ephemeralConfig?.computeSource===`managed`;if(!this.direct&&this.signedIn&&(!this.local.cur||n)){ln(this.local,e).then(t=>this.store.apply({type:`branches.list`,repo:e,branches:t})).catch(t=>this.store.apply({type:`branches.list`,repo:e,branches:[],error:String(t?.message||t)}));return}this.send({kind:`branches.list`,repo:e})}listRuntimes(){this.send({kind:`runtimes.list`})}requestCapabilities(){this.send({kind:`capabilities.get`})}cloudModelQuery=0;isCloudModelDraft(){let e=this.store.getState();return!e.activeSession.activeSessionId&&!this.direct&&!(!e.draft.ephemeralConfig&&this.local.cur)}async listCloudModels(){let e=++this.cloudModelQuery,t=this.store.getState(),n=t.draft.ephemeralConfig,r=t.catalogs.selectedAgentId,i=this.local.cur,a=t.catalogs.models,o=t.settings.credentialRecords;try{let[t,s]=await Promise.all([this.ephemeralKeys.modelKeyEntries(),this.ephemeralKeys.oauthCredentialEntries()]),c=this.store.getState();if(e!==this.cloudModelQuery||!this.isCloudModelDraft()||c.draft.ephemeralConfig!==n||c.catalogs.selectedAgentId!==r||this.local.cur!==i)return;let l=[...o.filter(e=>e.sync===`account`&&e.kind!==`reference`),...t.filter(e=>e.scope===`account`||n?.computeSource!==`managed`),...s].map(e=>e.provider);this.store.apply({type:`models.list`,runtimeId:r,models:ct(l,a)})}catch{e===this.cloudModelQuery&&this.isCloudModelDraft()&&this.store.setError(`Couldn't load account models. Open the model picker to try again.`)}}listModels(){if(this.isCloudModelDraft()){this.listCloudModels();return}let e=this.store.getState(),t=e.activeSession.activeSessionId,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.pendingLaunch===!0:!1,r=t&&!n?t:void 0,i=r?void 0:e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId??void 0;this.send({kind:`models.list`,sessionId:r,runtimeId:i})}runtimeModelWaiters=new Map;modelsForRuntime(e,t=2e4){return new Promise(n=>{let r=e=>{clearTimeout(i),n(e)},i=setTimeout(()=>{let t=this.runtimeModelWaiters.get(e);t?.splice(t.indexOf(r)>>>0,1),n(this.store.cachedModelsFor(e)??[])},t);this.runtimeModelWaiters.set(e,[...this.runtimeModelWaiters.get(e)??[],r]),this.send({kind:`models.list`,runtimeId:e})})}settleRuntimeModels(e){let t=this.runtimeModelWaiters.get(e);if(!t?.length)return;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(),Z({kind:`new`})),this.store.setSelectedAgentLocal(e.id),this.local.setLastChoice({agentId:e.id}),this.isCloudModelDraft()){this.listModels();return}this.send({kind:`runtime.select`,id:e.id})}installAgent(e){this.pendingAgentPick=e,this.store.setInstalling(e),this.send({kind:`runtime.install`,id:e})}maybeSelectInstalledAgent(e){if(e.type===`runtime.install.error`&&e.id===this.pendingAgentPick){this.pendingAgentPick=null;return}if(e.type!==`runtime.install.done`||!this.pendingAgentPick||e.id!==this.pendingAgentPick)return;this.pendingAgentPick=null;let t=this.store.getState();if(t.activeSession.transcript.some(e=>e.role===`user`))return;let n=t.catalogs.runtimes.find(t=>t.id===e.id);n&&String(n.status||`available`)===`available`&&this.chooseAgent(n)}listProviders(){this.credentialsModelsCoordinator.listProviders()}getProviderAuth(e){this.credentialsModelsCoordinator.getProviderAuth(e)}saveApiKey(e,t){return this.credentialsModelsCoordinator.saveApiKey(e,t)}removeProvider(e){this.credentialsModelsCoordinator.removeProvider(e)}resetOauth(e){this.credentialsModelsCoordinator.resetOauth(e)}startOauth(e,t){this.credentialsModelsCoordinator.startOauth(e,t)}openOauthOnNode(e){return this.credentialsModelsCoordinator.openOauthOnNode(e)}submitOauthCode(e,t){this.credentialsModelsCoordinator.submitOauthCode(e,t)}listCredentialRecords(){this.credentialsModelsCoordinator.listCredentials()}async previewNativeCredentials(e,t){return await this.nativeCredentialCommand(e,{kind:`credentials.native.preview`,label:t})}async importNativeCredentials(e,t,n,r){return await this.nativeCredentialCommand(e,{kind:`credentials.native.import`,previewId:t,agents:n,sync:r})}async nativeCredentialCommand(e,t){let n=this.store.getState().connection;if(n.status!==`online`||n.currentNodeId!==e)throw Error(`Connect to the selected machine before scanning or importing.`);let r=await this.awaitAck(t,2e4);if(this.store.getState().connection.currentNodeId!==e)throw Error(`Machine changed. Scan again on the selected machine.`);return r}syncAccountCredentialsWithNode(){return this.credentialsModelsCoordinator.syncAccountCredentials()}setCredential(e,t,n){return this.credentialsModelsCoordinator.setCredential(e,t,n)}removeCredential(e,t){return this.credentialsModelsCoordinator.removeCredential(e,t)}setCredentialSync(e,t,n){return this.credentialsModelsCoordinator.setCredentialSync(e,t,n)}setCredentialUnattended(e,t,n){return this.credentialsModelsCoordinator.setCredentialUnattended(e,t,n)}testCredential(e,t){return this.credentialsModelsCoordinator.testCredential(e,t)}getCredentialPresets(){this.credentialsModelsCoordinator.getPresets()}setActivePreset(e){this.credentialsModelsCoordinator.setActivePreset(e)}setPresetMapping(e,t,n){return this.credentialsModelsCoordinator.setPresetMapping(e,t,n)}listLocalModels(){this.credentialsModelsCoordinator.listLocalModels()}listLocalModelPresets(){this.credentialsModelsCoordinator.listLocalModelPresets()}discoverLocalModels(){return this.credentialsModelsCoordinator.discoverLocalModels()}verifyLocalModel(e,t){return this.credentialsModelsCoordinator.verifyLocalModel(e,t)}saveLocalModel(e){return this.credentialsModelsCoordinator.saveLocalModel(e)}removeLocalModel(e){this.credentialsModelsCoordinator.removeLocalModel(e)}listRulesets(){this.send({kind:`rulesets.list`})}saveRuleset(e,t){return this.awaitAck({kind:`rulesets.save`,ruleset:e,active:t}).then(()=>void 0)}removeRuleset(e){this.send({kind:`rulesets.remove`,name:e})}getSttConfig(){this.send({kind:`stt.config.get`})}setSttProvider(e){this.send({kind:`stt.config.set`,provider:e})}saveSttKey(e,t){return this.awaitAck({kind:`stt.config.set`,setKey:{provider:e,value:t}}).then(()=>void 0)}removeSttKey(e){this.send({kind:`stt.config.set`,removeKey:e})}transcribe(e,t){let n=fl();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=fl();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:fl(),origin:d(),org:e||void 0})}githubAppManifestCode(e,t){this.store.setGithubAppPhase(`completing`),this.send({kind:`github.app.manifest.code`,requestId:fl(),code:e,state:t})}async githubAppConnectExisting(e){this.store.setGithubAppPhase(`completing`);try{await this.awaitAck({kind:`github.app.connect-existing`,appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel||void 0},6e4)}catch(e){throw this.store.setGithubAppPhase(`error`,{error:e instanceof Error?e.message:String(e),returning:!1}),e}}connectHostedGithubApp(e){return sn(this.local,e)}fetchMe(){return this.accountCoordinator.fetchMe()}deleteAccount(){return Ht(this.local)}invokeAccountExtensionAction(e){return u()?Ut(this.local,e):Promise.reject(Error(`Account service actions are unavailable in this app.`))}fetchGithubApp(){return this.accountCoordinator.fetchGithubApp()}fetchGithubQueue(e=30){return this.accountCoordinator.fetchGithubQueue(e)}fetchAutomationRuns(e=50,t={}){return this.accountCoordinator.fetchAutomationRuns(e,t)}cancelAutomationRun(e){return this.accountCoordinator.cancelAutomationRun(e)}setGithubAppDefaultNode(e,t){return this.accountCoordinator.setGithubAppDefaultNode(e,t)}setGithubAppTriggerAccess(e,t){return this.accountCoordinator.setGithubAppTriggerAccess(e,t)}assignWorkItem(e,t){return this.accountCoordinator.assignWorkItem(e,t)}deleteWorkItem(e){return this.accountCoordinator.deleteWorkItem(e)}clearWorkQueue(){return this.accountCoordinator.clearWorkQueue()}githubAppDisconnect(e,t){return this.accountCoordinator.disconnectGithubApp(e,t)}removeNode(e){return this.accountCoordinator.removeNode(e)}enablePush(){return i?o()?.enable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.enablePush()}disablePush(){return i?o()?.disable({token:this.local.s,controlPlane:d()})??Promise.reject(Error(`Native notifications are unavailable.`)):this.accountCoordinator.disablePush()}async listTailnetMachines(){let e=await this.awaitAck({kind:`tailnet.machines`},15e3);return Array.isArray(e.machines)?e.machines:[]}async getAccess(){return await this.awaitAck({kind:`access.get`},15e3)}pushStatus(){return i?o()?.status({token:this.local.s,controlPlane:d()})??Promise.resolve({supported:!1,subscribed:!1,permission:`default`}):this.accountCoordinator.pushStatus()}getNotificationPreferences(){return this.accountCoordinator.getNotificationPreferences()}setNotificationPreferences(e){return this.accountCoordinator.setNotificationPreferences(e)}ephemeralModelKeys=vi();deviceOAuthCredentials=_i();ephemeralKeys=ra({local:gi(),modelKeys:this.ephemeralModelKeys,oauthCredentials:this.deviceOAuthCredentials,oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled(),remote:this.deviceVaultRemote(),device:()=>Ui(this.local),enabled:()=>!this.direct&&!!this.local.s,providerTokenSyncEnabled:()=>!this.direct&&!!this.local.s,state:{load:async()=>{try{return JSON.parse(localStorage.getItem(`bivy_device_vault_state`)||`null`)??void 0}catch{return}},save:async e=>{try{localStorage.setItem(`bivy_device_vault_state`,JSON.stringify(e))}catch{}}}});ephemeralPrefs=Si();ephemeralSetups=wi();ephemeralMachines=Ei();pendingLaunchStore=Ti();seededEphemeralNodes=new Set;firstRunAuthNodes=new Set;managedCredentialSetupNodes=new Set;managedCredentialGrantInFlight=!1;managedCredentialReturnSessionId=null;listEphemeralKeys(){return this.ephemeralKeys.list()}listEphemeralModelKeys(){return this.ephemeralKeys.listModelKeys()}setEphemeralModelKey(e,t,n=`account`,r=`default`){return this.ephemeralKeys.setModelKey(e,t,n,r)}removeEphemeralModelKey(e,t=`default`){return this.ephemeralKeys.removeModelKey(e,t)}getEphemeralToken(e){return this.ephemeralCoordinator.getProviderToken(e)}setEphemeralToken(e,t){return this.ephemeralCoordinator.setProviderToken(e,t)}connectEphemeralProvider(e,t){return this.ephemeralCoordinator.connectProvider(e,t)}defaultEphemeralRunner(e){return this.ensureDefaultRunner(e)}ensureDefaultRunner(e){return this.ephemeralCoordinator.ensureDefaultRunner(e)}removeEphemeralToken(e){return this.ephemeralCoordinator.removeProviderToken(e)}oauthRecoveryEnabled(){try{return!this.direct&&!!this.local.s&&localStorage.getItem(`bivy_oauth_browser_recovery`)===`1`}catch{return!1}}getOAuthBrowserRecovery(){return this.oauthRecoveryEnabled()}async setOAuthBrowserRecovery(e){if(this.direct)throw Error(`OAuth browser recovery requires a signed-in account`);if(!e)for(let e of await this.ephemeralKeys.oauthCredentialEntries())await this.ephemeralKeys.removeOAuthCredential(e.provider,e.label);try{localStorage.setItem(`bivy_oauth_browser_recovery`,e?`1`:`0`)}catch{}e&&await this.syncAccountCredentialsWithNode()}syncDeviceVault(){return this.ephemeralKeys.sync()}getDeviceVaultSyncState(){return this.ephemeralKeys.getSyncState()}deviceVaultRemote(){let e=()=>(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),t=()=>({authorization:`Bearer ${this.local.s}`,"content-type":`application/json`});return{get:async()=>{let t=await Ui(this.local),n=await fetch(`${e()}/device-vault?device=${encodeURIComponent(t.pub)}`,{headers:{authorization:`Bearer ${this.local.s}`}});if(!n.ok)throw Error(`device-vault get failed (${n.status})`);let r=await n.json();return{vault:r.vault??null,wrappedKey:r.wrappedKey??null,requests:Array.isArray(r.requests)?r.requests:[],generation:r.generation??0,keyGeneration:r.keyGeneration??0,recipients:Array.isArray(r.recipients)?r.recipients:[]}},putVault:async(n,r,i)=>{let a=await Ui(this.local),o=await fetch(`${e()}/device-vault`,{method:`PUT`,headers:t(),body:JSON.stringify({devicePublicKeyB64:a.pub,ciphertext:n,expectedGeneration:r,keyGeneration:i})});if(o.status===409)throw new Ji;if(!o.ok)throw Error(`device-vault put failed (${o.status})`);return{generation:(await o.json()).generation??(r??0)+1}},requestKey:async()=>{let n=await Ui(this.local);await fetch(`${e()}/device-vault/key/request`,{method:`POST`,headers:t(),body:JSON.stringify({devicePublicKeyB64:n.pub})})},putWrapped:async(n,r,i,a)=>{let o=await fetch(`${e()}/device-vault/key/wrapped`,{method:`PUT`,headers:t(),body:JSON.stringify({targetDevicePublicKeyB64:n,wrappedKey:r,wrappedByPublicKeyB64:i,generation:a})});if(o.status!==403&&!o.ok)throw Error(`device-vault wrapped-key put failed (${o.status})`)}}}getEphemeralPrefs(e){return this.ephemeralPrefs.get(e)}setEphemeralPrefs(e,t){return this.ephemeralPrefs.set(e,t)}listEphemeralSetups(e){return this.ephemeralSetups.list(e)}createEphemeralSetup(e,t){return this.ephemeralSetups.create(e,t)}updateEphemeralSetup(e,t){return this.ephemeralSetups.update(e,t)}removeEphemeralSetup(e){return this.ephemeralSetups.remove(e)}listEphemeralMachines(){return this.ephemeralMachines.list()}async seedEphemeralNodeIfNeeded(){if(!pc||this.direct)return;let e=this.local.cur;if(!e||this.seededEphemeralNodes.has(e))return;let t;try{t=await this.ephemeralMachines.list()}catch{return}if(!t.some(t=>t.nodeId===e))return;let n;try{n=await this.ephemeralKeys.modelKeyEntries()}catch{return}if(this.seededEphemeralNodes.add(e),n.length){if(this.store.getState().connection.status!==`online`||this.local.cur!==e){this.seededEphemeralNodes.delete(e);return}for(let{provider:e,key:t}of n)this.send({kind:`provider.apiKey`,provider:e,key:t})}}async maybeGrantManagedCredential(){let e=this.local.cur;if(!e||!this.managedCredentialSetupNodes.has(e)||this.managedCredentialGrantInFlight)return;let t=this.store.getState().settings.credentialRecords.find(e=>e.sync===`account`&&e.kind!==`reference`&&!e.unattended);if(t){this.managedCredentialGrantInFlight=!0;try{await this.setCredentialUnattended(t.provider,t.label,!0),await this.waitForManagedCredential();let e=this.managedCredentialReturnSessionId;this.managedCredentialReturnSessionId=null,e&&this.pendingLaunches.has(e)&&(this.openPendingLaunch(e),await this.retryPendingLaunch(e))}catch(e){this.store.setError(e instanceof Error?e.message:String(e))}finally{this.managedCredentialGrantInFlight=!1}}}async maybePromptFirstRunModelAuth(){if(!pc||this.direct)return;let e=this.local.cur;e&&!this.firstRunAuthNodes.has(e)&&(await this.ephemeralMachines.list().catch(()=>[])).some(t=>t.nodeId===e)&&(this.firstRunAuthNodes.add(e),this.listProviders(),setTimeout(()=>{let t=this.store.getState();if(t.connection.status!==`online`||this.local.cur!==e||t.presentation.needsModelAuth||t.presentation.oauth||t.catalogs.providers.some(e=>e.configured))return;let n=t.catalogs.providers.find(e=>e.oauth&&e.id===`anthropic`)?.id??t.catalogs.providers.find(e=>e.oauth)?.id??`anthropic`;this.store.setNeedsModelAuth({nodeId:e,provider:n})},gl))}dismissModelAuthPrompt(){this.store.setNeedsModelAuth(null)}maybeTeardownFinishedEphemeral(e){return this.isProvisionalSessionId(e)||[...this.pendingLaunches.values()].some(t=>t.sessionId===e)?Promise.resolve():this.ephemeralCoordinator.teardownFinishedSession(e)}listEphemeralSizes(e,t){return this.ephemeralCoordinator.listSizes(e,t)}launchEphemeral(e){return this.ephemeralCoordinator.launch(e)}destroyEphemeral(e){return this.ephemeralCoordinator.destroy(e)}resumeAndConnectNode(e,t=9e4){return this.ephemeralCoordinator.resumeAndConnect(e,t)}correlationApi(){return{base:(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),auth:{authorization:`Bearer ${this.local.s}`,"content-type":`application/json`}}}async refreshEphemeralCorrelations(){if(!this.direct&&this.local.s)try{let{base:e,auth:t}=this.correlationApi(),n=await fetch(`${e}/session-correlation`,{headers:{authorization:t.authorization}});if(!n.ok)return;let r=await n.json();Array.isArray(r.correlations)&&(this.ephemeralCorrelations=r.correlations)}catch{}}async recordSessionCorrelation(e,t){if(this.isProvisionalSessionId(e)||this.direct||!this.local.s||!t.nodeId||!e)return;let n=`${t.nodeId}:${e}`;if(this.correlatedSessions.has(n))return;this.correlatedSessions.add(n);let r={sessionId:e,nodeId:t.nodeId,provider:t.provider,region:t.region||void 0,ttlMinutes:t.ttlMinutes,repo:t.repo,setupId:t.setupId,machineId:t.id,app:t.app,computeSource:t.computeSource};try{let{base:t,auth:n}=this.correlationApi(),i=await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`PUT`,headers:n,body:JSON.stringify(r)});if(i.status===410){this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e);return}if(!i.ok)throw Error(`Couldn't save session routing metadata.`);this.ephemeralCorrelations=[r,...this.ephemeralCorrelations.filter(t=>t.sessionId!==e)]}catch{this.correlatedSessions.delete(n)}}reprovisionEphemeral(e,t){return this.ephemeralCoordinator.reprovision(e,t)}isCurrentNodeResumable(){return this.ephemeralCoordinator.isCurrentNodeResumable()}shouldAutoResume(){return this.store.getState().connection.status!==`online`&&this.isCurrentNodeResumable()&&!this.resumingNode.has(this.local.cur)}async resumeNodeForSession(e){let t=this.local.cur;if(t&&!this.resumingNode.has(t)){this.resumingNode.add(t);try{await this.reprovisionEphemeral(t,e)}finally{this.resumingNode.delete(t)}}}drainPendingResume(e){let t=this.pendingResume.filter(t=>t.sessionId===e);if(t.length){this.pendingResume=this.pendingResume.filter(t=>t.sessionId!==e);for(let n of t)this.send({kind:`prompt`,sessionId:e,text:n.text,clientMessageId:n.clientMessageId,attachments:n.attachments})}}githubTaskToken=bi();getGithubTaskToken(){return this.githubTaskToken.get()}setGithubTaskToken(e){return this.githubTaskToken.set(e)}removeGithubTaskToken(){return this.githubTaskToken.remove()}runWorkItemOnEphemeral(e,t){return this.ephemeralCoordinator.runWorkItem(e,t)}launchEphemeralQueueWorker(e){return this.ephemeralCoordinator.launchQueueWorker(e)}getEphemeralQueueDefault(){return Xt(this.local)}setEphemeralQueueDefault(e){return Zt(this.local,e)}listEphemeralConfigs(){return this.ephemeralCoordinator.listConfigs()}createEphemeralConfig(e){return this.ephemeralCoordinator.createConfig(e)}updateEphemeralConfig(e,t){return this.ephemeralCoordinator.updateConfig(e,t)}removeEphemeralConfig(e){return this.ephemeralCoordinator.removeConfig(e)}getQueueRouting(){return an(this.local)}setQueueRouting(e){return on(this.local,e)}getHostedProvisioning(){return fn(this.local)}setHostedProvisioning(e){return pn(this.local,e)}listHostedAudit(){return hn(this.local)}listHostedMachines(){return gn(this.local)}destroyHostedMachine(e){return _n(this.local,e)}validateHostedProviderCredential(e,t,n){return un(this.local,e,t,n)}rotateHostedProvisioning(){return mn(this.local)}triggerHostedProvision(e=!1){return vn(this.local,e)}onTerminal(e){return this.terminalListeners.add(e),()=>this.terminalListeners.delete(e)}sendTerminal(e){this.send(e)}closeSessionTui(e){this.send({kind:`terminal.close.tui`,sessionId:e})}applyLinkPayload(e){return n||!xt(this.local,e)?!1:(this.store.setSignedIn(this.signedIn),this.switchNode(this.local.cur),this.refreshNodes(),!0)}reconcileSessionList(e){switch(String(e.type||``)){case`session.renamed`:case`session.branch_renamed`:case`session.closed`:this.refreshSessions();return;case`session.deleted`:e.sessionId&&this.transcriptCache.delete(e.sessionId),this.refreshSessions();return;default:return}}maybeRefreshModelsForRuntime(e){let t=this.store.getState(),n=e.type===`session.history`&&!!e.sessionId&&e.sessionId===t.activeSession.activeSessionId&&!t.catalogs.currentModel;(e.type===`runtime.updated`||n)&&this.listModels()}retryPendingSessionNew(){!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||this.store.getState().activeSession.activeSessionId||this.send(this.pendingPrompt.frame)}maybeFlushPendingPrompt(e){if(!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||e.type!==`session.history`||e.requestId!==this.pendingPrompt.requestId)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId;if(!t)return;Z({kind:`session`,id:t},{replace:!0});let{text:n,clientMessageId:r,attachments:i}=this.pendingPrompt;this.pendingPrompt=null,this.send({kind:`prompt`,sessionId:t,text:n,clientMessageId:r,attachments:i});let a=this.pendingFollowups;this.pendingFollowups=[];for(let e of a)this.send({kind:`prompt`,sessionId:t,text:e.text,clientMessageId:e.clientMessageId,attachments:e.attachments});this.refreshSessions()}abort(){let e=this.store.getState().activeSession.activeSessionId;e&&this.send({kind:`abort`,sessionId:e})}resolveTurnAttention(e,t){this.send({kind:`session.turn_attention.resolve`,sessionId:e,action:t})}setLimitRetry(e){let t=this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.limit_retry`,sessionId:t,enabled:e})}accountMode(){return!!(this.local.s&&this.local.cp)}resolveSessionNodeId(e){return this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.nodeId}resolveNodeLabel(e){let t=this.store.getState().connection.nodes.find(t=>t.id===e);return t?.name?`bivy/${t.name}`:void 0}async persistScheduledFollowup(e,t,n){if(!this.accountMode()||!n)return;let r=this.resolveSessionNodeId(e);if(!r)return;let i=this.local.keys()[r];if(i)try{let a=await D(await E(C(i)),n),o=new Date(Date.now()+6e4).toISOString(),s=await bn(this.local,{name:`Follow-up`,templateCiphertext:`${hl}:${r}:${a}`,trigger:`schedule`,schedule:{kind:`once`,at:o},nodeLabel:this.resolveNodeLabel(r),targetKind:`existing_session`,targetSessionId:e,message:!0,enabled:!0});this.store.attachFollowupAutomation(e,t,s.id)||this.cancelScheduledFollowup(s.id)}catch{}}startRun(e,t){return this.accountCoordinator.startRun(e,t)}cancelScheduledFollowup(e){e&&wn(this.local,e).catch(()=>{})}async editScheduledFollowup(e,t,n){let r=this.store.getFollowups(e).find(e=>e.id===t);if(!r||r.status!==`scheduled`)return`This message is no longer pending.`;if(!r.scheduledAutomationId)return`This message has no automation to update.`;if(!Number.isFinite(n.getTime())||n.getTime()<=Date.now())return`Pick a time in the future.`;try{await Sn(this.local,r.scheduledAutomationId,{schedule:{kind:`once`,at:n.toISOString()}})}catch(e){return e instanceof Error?e.message:`Could not reschedule the message.`}return this.store.rescheduleFollowup(e,t,n.getTime(),Date.now()),null}async resyncScheduledFollowups(){if(!this.accountMode())return;let e;try{e=await yn(this.local)}catch{return}let t=new Set(e.filter(e=>e.enabled&&e.nextRunAt!=null).map(e=>e.id));for(let e of Object.keys(this.store.getState().sessionIndex.followupsBySession))this.store.pruneScheduledFollowups(e,t)}supportsSteering(){return this.followupCoordinator.supportsSteering()}getFollowups(e){return this.followupCoordinator.list(e)}editFollowup(e,t,n,r){return this.followupCoordinator.edit(e,t,n,r)}removeFollowup(e,t){return this.followupCoordinator.remove(e,t)}reorderFollowup(e,t,n){return this.followupCoordinator.reorder(e,t,n)}sendFollowupNow(e,t){this.followupCoordinator.sendNow(e,t)}steerNow(e,t){return this.followupCoordinator.steer(e,t)}renameSession(e,t){let n=t.trim();n&&(e===this.store.getState().activeSession.activeSessionId&&this.store.setActiveTitle(n),this.store.renameSessionLocal(e,n),this.send({kind:`session.rename`,sessionId:e,name:n}),this.refreshSessions())}async deleteSession(e,t){if(this.isProvisionalSessionId(e)&&(await this.pendingLaunchRestoration,this.pendingLaunches.has(e))){await this.dismissPendingLaunch(e);return}let n=this.ephemeralCorrelations.find(t=>t.sessionId===e),r=n&&this.store.getState().connection.nodes.some(e=>e.id===n.nodeId&&e.online);if(!this.direct&&n&&!r){await this.deleteRetiredSession(e);return}this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.sessionCoordinator.deleteSession(e,t)}async deleteRetiredSession(e){try{let{base:t,auth:n}=this.correlationApi();if(!(await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`DELETE`,headers:n,signal:AbortSignal.timeout(15e3)})).ok)throw Error(`Couldn't delete the retired session. Refresh and try again.`);this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e),this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.store.getState().activeSession.activeSessionId===e&&(this.store.resetActiveSession(),Z({kind:`new`})),this.store.removeSessionLocal(e),this.persistDeletedSessionTombstones(),await this.transcriptCache.delete(e),this.refreshSessions()}catch(e){this.store.setError(e instanceof Error?e.message:`Couldn't delete the retired session.`)}}pauseSession(e){this.sessionCoordinator.pauseSession(e)}resumeSession(e){this.sessionCoordinator.resumeSession(e)}refreshPrStatus(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.pr.refresh`,sessionId:t})}refreshAllPrStatus(){this.send({kind:`sessions.pr.refresh_all`})}rewind(e,t){let n=t||this.store.getState().activeSession.activeSessionId;n&&e&&this.send({kind:`session.rewind`,sessionId:n,checkpointId:e})}revertFile(e,t,n){let r=n||this.store.getState().activeSession.activeSessionId;r&&e&&this.send({kind:`session.revert_file`,sessionId:r,path:e,content:t})}listCheckpoints(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.checkpoints`,sessionId:t})}resolveApproval(e,t,n=!1){this.send({kind:`approval`,id:e,approved:t,...t&&n?{remember:!0}:{}}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}answerQuestion(e,t,n){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,answers:n}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}cancelQuestion(e,t){this.send({kind:`session.question.answer`,requestId:e,sessionId:t,cancelled:!0}),this.direct||An(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}},bl=g();function xl({tone:e,variant:t=`outline`,upper:n=!1,className:r=``,children:i,...a}){return(0,bl.jsx)(`span`,{className:`badge${n?` upper`:``}${r?` ${r}`:``}`,"data-tone":e,"data-variant":t,...a,children:i})}function Sl(){return(0,y.useSyncExternalStore)(yl.store.subscribe,yl.store.getState)}export{wn as $,Ho as A,O as At,li as B,dc as C,rt as Ct,Zs as D,Ae as Dt,lc as E,Ne as Et,Wa as F,$n as G,ii as H,Oa as I,On as J,tr as K,Ma as L,Ka as M,C as Mt,Ga as N,v as Nt,$s as O,ye as Ot,Ia as P,bn as Q,Aa as R,pc as S,at as St,cc as T,Fe as Tt,ni as U,G as V,nr as W,Vn as X,jn as Y,Rn as Z,Bc as _,Cn as _t,ul as a,yn as at,bc as b,Sn as bt,Qc as c,Bn as ct,Lc as d,bt as dt,Hn as et,Uc as f,Tt as ft,Hc as g,Tn as gt,Gc as h,xn as ht,yl as i,Dn as it,bo as j,D as jt,hs as k,E as kt,qc as l,Ln as lt,Vc as m,Mn as mt,xl as n,Et as nt,Xc as o,Kt as ot,Jc as p,An as pt,yt as q,dl as r,kn as rt,Wc as s,fn as st,Sl as t,zn as tt,zc as u,St as ut,Rc as v,wt as vt,Z as w,Qe as wt,xc as x,pt as xt,Yc as y,Ct as yt,ja as z};
|