@bivy/bivy 0.21.0 → 0.21.1-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/apps/styles.css +16 -0
  2. package/dist/credentials/store.js +5 -2
  3. package/dist/runtime/oauth/model-oauth.js +4 -3
  4. package/dist/server.js +5 -3
  5. package/package.json +1 -1
  6. package/web/assets/{AutomationsView-HnUfeti_.js → AutomationsView-tGFmNyI7.js} +1 -1
  7. package/web/assets/{ChangesCard-Dnkguen5.js → ChangesCard-x8Ci1OJd.js} +1 -1
  8. package/web/assets/{LibraryView-CSKKV8TI.js → LibraryView-D4o-Q00g.js} +1 -1
  9. package/web/assets/ProviderConnect-8mZJqRVo.js +1 -0
  10. package/web/assets/{SessionList-CYU9IGnd.js → SessionList-CP2yG8sC.js} +1 -1
  11. package/web/assets/{Settings-HQZtxiMV.js → Settings-B_0J-UTo.js} +5 -5
  12. package/web/assets/{Sheet-DoPtOHBC.js → Sheet-R7TmTqRs.js} +1 -1
  13. package/web/assets/{Terminal-DY6UB5U-.js → Terminal-CNTaC3Bo.js} +1 -1
  14. package/web/assets/{VoiceSettings-BoQ_Mhpm.js → VoiceSettings-BXzO0bps.js} +1 -1
  15. package/web/assets/{abnfDiagram-VCTEODGH-n-P11_L4.js → abnfDiagram-VCTEODGH-Cq-C3Lr0.js} +1 -1
  16. package/web/assets/architecture-7GRP2DOG-Cno3tf-L.js +1 -0
  17. package/web/assets/{architectureDiagram-5GKGNRK7-C0b9IP5U.js → architectureDiagram-5GKGNRK7-wZNIEiGX.js} +1 -1
  18. package/web/assets/{blockDiagram-I7D4REHJ-iVx1FQBD.js → blockDiagram-I7D4REHJ-Chp4nb_t.js} +1 -1
  19. package/web/assets/{c4Diagram-7LVT6UL2-DIwEaAvJ.js → c4Diagram-7LVT6UL2-BBZgTvoW.js} +1 -1
  20. package/web/assets/channel-GDYVufe9.js +1 -0
  21. package/web/assets/{chunk-4HAMMTFA-DSsyukSz.js → chunk-4HAMMTFA-BpLEAQIx.js} +1 -1
  22. package/web/assets/{chunk-75Z2AOVW-zwLYo-XL.js → chunk-75Z2AOVW-F40u6_2Y.js} +1 -1
  23. package/web/assets/{chunk-DU6HZSFF-PGuLkqeP.js → chunk-DU6HZSFF-C88MDoWn.js} +1 -1
  24. package/web/assets/{chunk-F27PBJKO-CpkyeGC9.js → chunk-F27PBJKO-Bp19aIde.js} +1 -1
  25. package/web/assets/{chunk-GMAD6QVW-CZSmK3Ms.js → chunk-GMAD6QVW-Cw1YRFlT.js} +1 -1
  26. package/web/assets/{chunk-GVQU2GXP-C2XMkY6v.js → chunk-GVQU2GXP-qzDxZ9bJ.js} +1 -1
  27. package/web/assets/{chunk-IMKFNOWR-DAIVz3j5.js → chunk-IMKFNOWR-C4YxuO1E.js} +1 -1
  28. package/web/assets/{chunk-L3NEJ4N5-C0geNTDK.js → chunk-L3NEJ4N5-CnsRJGpX.js} +1 -1
  29. package/web/assets/{chunk-OSK3NFVY-D-WN2fBr.js → chunk-OSK3NFVY-XFuK4lk5.js} +1 -1
  30. package/web/assets/{chunk-P2QGCYS3-DYGhprKz.js → chunk-P2QGCYS3-Car8pEAm.js} +1 -1
  31. package/web/assets/{chunk-POPQ4Y6H-Dlsu2a2Q.js → chunk-POPQ4Y6H-C1EKvqZ4.js} +1 -1
  32. package/web/assets/{chunk-PWAF6VOD-DK0QWYdc.js → chunk-PWAF6VOD-BUoMTcIG.js} +1 -1
  33. package/web/assets/{chunk-SHT3W25Y-BpQHIdUi.js → chunk-SHT3W25Y-ykYte0jd.js} +1 -1
  34. package/web/assets/{chunk-SVP7TREG-Cs5YWxpG.js → chunk-SVP7TREG-3Xq4d9je.js} +1 -1
  35. package/web/assets/{chunk-TICWLB2K-BRsWLPXA.js → chunk-TICWLB2K-BMl68KBL.js} +1 -1
  36. package/web/assets/classDiagram-ZZMXUADV-DN8Jvz7c.js +1 -0
  37. package/web/assets/classDiagram-v2-VYDZK3BY-DN8Jvz7c.js +1 -0
  38. package/web/assets/{cynefin-OW5HDTMX-DoHWnu_-.js → cynefin-OW5HDTMX-IlsT6Bvi.js} +1 -1
  39. package/web/assets/{cynefinDiagram-5FMLGOSQ-CgPeHmV5.js → cynefinDiagram-5FMLGOSQ-DsFXDffD.js} +1 -1
  40. package/web/assets/{dagre-GXQ25YYZ-CrIlgwM7.js → dagre-GXQ25YYZ-BT9x18HY.js} +1 -1
  41. package/web/assets/{diagram-S7CK7UJ4-BM_l51zV.js → diagram-S7CK7UJ4-h7v7VpuX.js} +1 -1
  42. package/web/assets/{diagram-UQ7AKVKN-CfkxqgPI.js → diagram-UQ7AKVKN-DiuWIKwN.js} +1 -1
  43. package/web/assets/{diagram-VSXAHHWV-0y5vCI9g.js → diagram-VSXAHHWV-BKjRfJo2.js} +1 -1
  44. package/web/assets/{diagram-VX7I27RA-BMkMy7jn.js → diagram-VX7I27RA-DnVCmPjE.js} +1 -1
  45. package/web/assets/{diagram-Z3DM3KII--0fxfDqG.js → diagram-Z3DM3KII-CxC5BEc6.js} +1 -1
  46. package/web/assets/{ebnfDiagram-PWID7BFC-6tPNzbJl.js → ebnfDiagram-PWID7BFC-D-1Zewzr.js} +1 -1
  47. package/web/assets/{erDiagram-RLTQ6QDP-Bjqm_o3R.js → erDiagram-RLTQ6QDP-ghS1KvWh.js} +1 -1
  48. package/web/assets/eventmodeling-NTZA5JFV-kHQaM7OX.js +1 -0
  49. package/web/assets/flowDiagram-HODETNUW-YHAGAr8z.js +1 -0
  50. package/web/assets/{ganttDiagram-EL5Y4UJY-92X7KOOI.js → ganttDiagram-EL5Y4UJY-CKmSuwpO.js} +1 -1
  51. package/web/assets/{gitGraph-4MIJSDKK-B5F-u7Vq.js → gitGraph-4MIJSDKK-CJ8uJDAa.js} +1 -1
  52. package/web/assets/{gitGraphDiagram-WWUBYQGX-Ct2hVG0b.js → gitGraphDiagram-WWUBYQGX-B3SYH-DA.js} +1 -1
  53. package/web/assets/{index-BKSbod42.css → index-CtJDDeFG.css} +1 -1
  54. package/web/assets/{index-CnjJQpgZ.js → index-dgtJdWG6.js} +2 -2
  55. package/web/assets/{info-A6RAGUB7-D3xmYWyC.js → info-A6RAGUB7-CHMpm9Sw.js} +1 -1
  56. package/web/assets/{infoDiagram-27XIBGKW-lzqZ7xaA.js → infoDiagram-27XIBGKW-BHmi8_bS.js} +1 -1
  57. package/web/assets/{ishikawaDiagram-5VMMS53U-CsVZHXR0.js → ishikawaDiagram-5VMMS53U-DuEd11bq.js} +1 -1
  58. package/web/assets/{journeyDiagram-3NMN7TZE-DN9AdyVy.js → journeyDiagram-3NMN7TZE-C1KezsV9.js} +1 -1
  59. package/web/assets/{kanban-definition-UXKFOSKX-gvkBaOFe.js → kanban-definition-UXKFOSKX-tOVvDQBr.js} +1 -1
  60. package/web/assets/{mermaid-parser.core-CPwOm7-a.js → mermaid-parser.core-Dq1OiZoj.js} +3 -3
  61. package/web/assets/{mermaid.core-F09Wr40d.js → mermaid.core-CYjB0fst.js} +4 -4
  62. package/web/assets/{mindmap-definition-YA3MSWOX-Qzc2J9Pm.js → mindmap-definition-YA3MSWOX-BY2WZE3p.js} +1 -1
  63. package/web/assets/mount-BGs1QFmE.js +36 -0
  64. package/web/assets/{packet-AYTQ26CC-Unxh5mP2.js → packet-AYTQ26CC-tsR35EiE.js} +1 -1
  65. package/web/assets/{pegDiagram-XKGWAZYB-BIqcRp3m.js → pegDiagram-XKGWAZYB-Coaafenl.js} +1 -1
  66. package/web/assets/{pie-WAS4IAKB-BipHZKbc.js → pie-WAS4IAKB-CIlN9kjj.js} +1 -1
  67. package/web/assets/{pieDiagram-E7YTZNPT-gaTNuzPD.js → pieDiagram-E7YTZNPT-CUVdLLU5.js} +1 -1
  68. package/web/assets/{quadrantDiagram-AXDQQJYC-3BEmlbuE.js → quadrantDiagram-AXDQQJYC-COv79LP4.js} +1 -1
  69. package/web/assets/{radar-RG4KPBEZ-Cm1_Q0XJ.js → radar-RG4KPBEZ-DCZMZllq.js} +1 -1
  70. package/web/assets/{railroad-74A4TZTK-CJ4K8tjT.js → railroad-74A4TZTK-Cuf665ol.js} +1 -1
  71. package/web/assets/railroad-abnf-HS5TGJTU-DrGYU-jG.js +1 -0
  72. package/web/assets/railroad-ebnf-LZEXJU2U-BFBhzvHT.js +1 -0
  73. package/web/assets/railroad-peg-WCYAUIDC-CSIEQtd_.js +1 -0
  74. package/web/assets/{railroadDiagram-O6MQD6OU-Nzyn7Xx6.js → railroadDiagram-O6MQD6OU-r3TxV9m7.js} +1 -1
  75. package/web/assets/{requirementDiagram-BXWQKSXE-9zXuiai_.js → requirementDiagram-BXWQKSXE-D65szw1G.js} +1 -1
  76. package/web/assets/{sankeyDiagram-P5KCCOFB-Cnw1rQun.js → sankeyDiagram-P5KCCOFB-DGJIDPIs.js} +1 -1
  77. package/web/assets/{sequenceDiagram-WJ2MYXX4-BSLLRV-U.js → sequenceDiagram-WJ2MYXX4-yC5Yj8N1.js} +1 -1
  78. package/web/assets/{settingsRoute-C2Up46o6.js → settingsRoute-CsB3Exnz.js} +1 -1
  79. package/web/assets/{stateDiagram-D77RDMKH-D07b4cJB.js → stateDiagram-D77RDMKH-_AbIjSyZ.js} +1 -1
  80. package/web/assets/stateDiagram-v2-MP3YSRHH-yrf2Tsly.js +1 -0
  81. package/web/assets/{swimlanes-42K2YHIH-RpDl0CG9.js → swimlanes-42K2YHIH-VRYlQaT0.js} +1 -1
  82. package/web/assets/swimlanesDiagram-VR7AAH4N-BswVzQRA.js +8 -0
  83. package/web/assets/{timeline-definition-24CTP7MA-BgQOP12r.js → timeline-definition-24CTP7MA-D4xtmeYc.js} +1 -1
  84. package/web/assets/{treeView-Q6P3EWNA-BiSBsrlo.js → treeView-Q6P3EWNA-CD3aFEk1.js} +1 -1
  85. package/web/assets/{treemap-WGGIJYW6-CNdjKqUG.js → treemap-WGGIJYW6-DviYL4fV.js} +1 -1
  86. package/web/assets/useStore-CzjbLTh5.js +16 -0
  87. package/web/assets/{vennDiagram-4TSXK5OY-DLzOr3Yv.js → vennDiagram-4TSXK5OY-B0DtUoPv.js} +1 -1
  88. package/web/assets/{wardley-WFR3VGLG-LCC8FWVb.js → wardley-WFR3VGLG-TVLfF7ZC.js} +1 -1
  89. package/web/assets/{wardleyDiagram-VM6X3IG4-WrwzM3YW.js → wardleyDiagram-VM6X3IG4-Wv5CnXD3.js} +1 -1
  90. package/web/assets/{xychartDiagram-S5SC5T6Z-B_HuoAnl.js → xychartDiagram-S5SC5T6Z-b9CK2fje.js} +1 -1
  91. package/web/index.html +2 -2
  92. package/web/sw.js +1 -1
  93. package/web/assets/ProviderConnect-DNgxGmP9.js +0 -1
  94. package/web/assets/architecture-7GRP2DOG-DyG-wgaH.js +0 -1
  95. package/web/assets/channel-HmCJmS4T.js +0 -1
  96. package/web/assets/classDiagram-ZZMXUADV-BmdAoNdO.js +0 -1
  97. package/web/assets/classDiagram-v2-VYDZK3BY-BmdAoNdO.js +0 -1
  98. package/web/assets/eventmodeling-NTZA5JFV-CoCZxN1n.js +0 -1
  99. package/web/assets/flowDiagram-HODETNUW-CznfWzEq.js +0 -1
  100. package/web/assets/mount-Bvl-yslT.js +0 -36
  101. package/web/assets/railroad-abnf-HS5TGJTU-BVKI4cmM.js +0 -1
  102. package/web/assets/railroad-ebnf-LZEXJU2U-UMcDSelb.js +0 -1
  103. package/web/assets/railroad-peg-WCYAUIDC-C00zpjQU.js +0 -1
  104. package/web/assets/stateDiagram-v2-MP3YSRHH-DaG9Yzhk.js +0 -1
  105. package/web/assets/swimlanesDiagram-VR7AAH4N-7003ldWX.js +0 -8
  106. package/web/assets/useStore-CxjHbFPA.js +0 -16
@@ -1,16 +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-CnjJQpgZ.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()}})}var re=2048,A=500;function ie(){return RegExp(`!\\[([^\\]]{0,${A}})\\]\\(([^)\\s]{1,${re}})\\)`,`g`)}function ae(e){return String(e||``).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}function oe(e){let t=String(e||``).trim();return!t||t.length>re?null:t.startsWith(`https://`)?`remote`:/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith(`//`)||t.startsWith(`/`)||t.startsWith(`~`)||t.startsWith(`#`)||t.includes(`\\`)||t.split(`/`).some(e=>e===`..`)||/[\x00-\x1f\x7f]/.test(t)?null:`workspace`}function se(e,t=6){if(!e)return[];let n=[],r=new Set;for(let i of String(e).matchAll(ie())){let e=ae(i[2]??``),a=oe(e);if(a&&!r.has(e)&&(r.add(e),n.push({ref:e,origin:a}),n.length>=t))break}return n}function ce(e,t){return String(e||``).replace(ie(),(e,n,r)=>{let i=ae(r),a=oe(i);return a?t({alt:n??``,ref:i,origin:a}):e})}var le=`bivy`,ue=512,de=/^[\w-]{1,64}$/,fe=new Set([`view`]);function pe(e){let t={},n=String(e||``).trim().replace(/^\{|\}$/g,``);if(!n||n.length>ue)return t;for(let e of n.matchAll(/([#.]?[\w-]{1,64})(?:\s*=\s*(?:"([^"\n]{0,512})"|'([^'\n]{0,512})'|([^\s"'}]{1,512})))?/g)){let n=e[1]??``,r=e[2]??e[3]??e[4];n.startsWith(`#`)?t.id=n.slice(1):n.startsWith(`.`)?t.class=t.class?`${String(t.class)} ${n.slice(1)}`:n.slice(1):n&&(t[n]=r===void 0||r)}return t}function me(e){let t=/^::([a-z][\w-]{0,31})[ \t]{0,32}(\{[^}\n]{0,512}\})?$/i.exec(String(e||``).trim());if(!t||!fe.has((t[1]??``).toLowerCase()))return null;let{src:n,app:r,...i}=pe(t[2]??``);if(typeof r==`string`&&de.test(r))return{ref:null,spec:{type:`app`,appId:r},attrs:i};let a=typeof n==`string`?ae(n):``;return!a||oe(a)!==`workspace`?null:{ref:a,spec:null,attrs:i}}function he(e){return String(e||``).trim().toLowerCase()===le}function ge(e){let t=String(e||``).trim();if(!t||t.length>16384)return null;let n;try{n=JSON.parse(t)}catch{return null}return!n||typeof n!=`object`||Array.isArray(n)?null:n}function _e(e){return typeof e.$schema==`string`&&/vega-lite/i.test(e.$schema)?!0:[`mark`,`layer`,`hconcat`,`vconcat`,`concat`,`facet`,`repeat`].some(t=>t in e)}function ve(e){let t=e.spec?.type;if(typeof t==`string`&&t.trim())return t.trim().toLowerCase();if(e.spec)return _e(e.spec)?`chart`:`unknown`;if(String(e.mimeType||``).toLowerCase().startsWith(`image/`))return`image`;let n=String(e.path||``).toLowerCase().split(`.`).pop()??``;return n===`csv`||n===`tsv`?`table`:`file`}var ye=8;function be(e,t=6){let n=[],r=new Set,i=(e,a)=>{if(!(n.length>=t||a>ye||!e||typeof e!=`object`)){if(Array.isArray(e)){for(let t of e)i(t,a+1);return}for(let[o,s]of Object.entries(e)){if(o===`url`&&typeof s==`string`){let e=ae(s);if(oe(e)===`workspace`&&!r.has(e)&&(r.add(e),n.push(e),n.length>=t))return;continue}i(s,a+1)}}};return i(e,0),n}function xe(e){return String(e||``).replace(/[&<>]/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`})[e])}function j(e){return xe(e).replace(/"/g,`&quot;`)}function Se(e,t){return`<a href="${j(t)}" target="_blank" rel="noopener">${e}</a>`}function Ce(e,t){return`<img class="md-image" data-md-ref="${j(t)}" alt="${j(e)}" loading="lazy">`}function we(e){return`<div class="md-component"${[e.ref?` data-md-ref="${j(e.ref)}"`:``,e.spec?` data-md-spec="${j(JSON.stringify(e.spec))}"`:``,Object.keys(e.attrs).length?` data-md-attrs="${j(JSON.stringify(e.attrs))}"`:``].join(``)}></div>`}function Te(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 Ee(e){let t=[],n=[];return ce(xe(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}),({alt:e,ref:t})=>{let r=`LINK${n.length}`;return n.push(Ce(e,t)),r}).replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g,(e,t,r)=>{let i=`LINK${n.length}`;return n.push(Se(t,r)),i}).replace(/https?:\/\/[^\s<>"]+/g,e=>{let{href:t,suffix:r}=Te(e);if(!t)return e;let i=`LINK${n.length}`;return n.push(Se(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 De(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 Oe(e){let t=De(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 ke(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)}>${Ee(e)}</th>`).join(``)}</tr></thead><tbody>${n.map(e=>`<tr>${e.map((e,t)=>`<td${r(t)}>${Ee(e)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div>`}function Ae(e){let t=String(e||``).match(/^[ \t]*/);return(t?t[0]:``).replace(/\t/g,` `).length}function je(e){let t=String(e||``).match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(!t)return null;let n=/\d/.test(t[2][0]);return{indent:Ae(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 Ne(e,t,n){let r=je(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=je(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=je(n);if(r&&r.indent===a||n.trim()&&Ae(n)<=a&&!r)break;l.push(n),t++}let u=Pe(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 Pe(e,t=0,n=0){let r=[],i=t;for(;i<e.length;){let t=e[i];if(!t.trim()){i++;continue}if(Ae(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++;let o=he(n)?ge(a.join(`
2
- `)):null;if(o){r.push(we({ref:null,spec:o,attrs:{}}));continue}r.push(`<pre><code${n?` class="language-${j(n)}"`:``}>${xe(a.join(`
3
- `))}</code></pre>`);continue}let a=me(t);if(a){r.push(we(a)),i++;continue}if(/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(t)){r.push(`<hr>`),i++;continue}let o=De(t),s=Oe(e[i+1]||``);if(Ae(t)<=3&&o.length>=2&&s&&s.length===o.length){let t=[],n=i+2;for(;n<e.length;){let r=De(e[n]);if(r.length!==o.length)break;t.push(r),n++}r.push(ke(o,s,t)),i=n;continue}let c=t.match(/^\s{0,3}(#{1,6})\s+(.+)$/);if(c){let e=c[1].length;r.push(`<h${e}>${Ee(c[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>${Ie(t.join(`
4
- `))}</blockquote>`);continue}let l=Ne(e,i,n);if(l){r.push(l.html),i=l.next;continue}let u=[];for(;i<e.length;){let t=e[i];if(!t.trim()||Ae(t)<n)break;if(u.length){let n=De(t),r=Oe(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)||je(t)||me(t)||Ae(t)<=3&&n.length>=2&&r&&r.length===n.length)break}u.push(t.trim()),i++}r.push(`<p>${Ee(u.join(` `))}</p>`)}return{html:r.join(``),next:i,blocks:r}}var M=new Map,Fe=400;function Ie(e){let t=String(e),n=M.get(t);if(n!==void 0)return M.delete(t),M.set(t,n),n;let r=Pe(t.replace(/\r\n/g,`
5
- `).split(`
6
- `)).html;if(M.set(t,r),M.size>Fe){let e=M.keys().next().value;e!==void 0&&M.delete(e)}return r}function Le(e){return String(e||``).trim().toLowerCase().replace(/[.\-\s]+/g,`_`)}function Re(e){let t=Le(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 ze(e){return Le(e?.type||e?.kind||e?.name)}function Be(e){let t=ze(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 Ve(e){let t=ze(e);return t?t===`tool_result`||t===`toolresult`||t===`function_result`||t.endsWith(`_tool_result`)||t.endsWith(`_function_result`):!1}function N(e){return String(e?.toolName||e?.name||e?.tool?.name||e?.tool||e?.function?.name||e?.toolCall?.name||e?.call?.name||`tool`).toLowerCase()}function He(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 Ue=new Set([`shell`,`read`,`write`,`edit`,`search`,`fetch`,`plan`,`delegation`]);function P(e){let t=e?.detail;if(t&&typeof t==`object`&&typeof t.kind==`string`&&Ue.has(t.kind))return t}function We(e){return e?.toolCallId||e?.toolUseId||e?.tool_use_id||e?.callId||e?.id||e?.toolCall?.id||e?.call?.id||e?.function?.id||``}function F(e){return String(e?.parentToolUseId||e?.parent_tool_use_id||e?.parentToolCallId||e?.parentCallId||``)}var I={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 Ge(e){if(e.status===`cancelled`)return I.cancelled;if(e.checks?.some(e=>e.status===`failed`))return I.checks_failed;let t=e.output?.failure?.toLowerCase()??``;if(e.status===`failed`)return/timed?\s*out/.test(t)?I.timed_out:I.agent_failed;if(e.status===`needs_attention`)return I.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`?I.waiting:n?I.running:e.output?.prUrl?I.pr_open:e.output?.branch||e.output?.commit||e.output?.checkpoint||e.output?.artifactUrl?I.changes_ready:(e.events??[]).map(e=>e.summary.toLowerCase()).some(e=>e.includes(`no file changes`)||e.includes(`no changes`))?I.no_changes:I.needs_review}function Ke(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 qe(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 Je(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 Ye=[[`codex`,`openai-codex`],[`claude`,`anthropic`],[`grok`,`xai`],[`gemini`,`google`]];function Xe(e,t){let n=String(e??``).trim().toLowerCase(),r=Ye.find(([e])=>n.startsWith(e));return r?r[1]:String(t??``).trim().toLowerCase()||void 0}var Ze=240,Qe=50,$e=new Set([`pending`,`claimed`,`running`]),et=new Set([`succeeded`,`failed`,`cancelled`,`done`]),tt=new Set([`pending`,`claimed`,`running`,`waiting`,`needs_attention`]),nt=new Set([`checks_failed`,`needs_review`,`agent_failed`,`timed_out`]);function rt(e){return e===`waiting`?`waiting`:e===`needs_attention`?`needs_attention`:$e.has(e)?e===`running`?`running`:`queued`:et.has(e)?`finished`:`queued`}function it(e){return e.repo?`${e.repo}${Number.isInteger(e.issueNumber)?`#${e.issueNumber}`:``}`:e.externalId||e.url||void 0}function at(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 ot(e,t){if(t&&Je(t))return Xe(e)}var st=new Set([`trigger_received`,`trigger_matched`,`queued`,`routed`,`provisioning`,`claimed`,`agent_started`,`checks_started`,`checks_completed`,`result_delivery`,`notification`,`retry`,`cancel_requested`,`terminal`]),ct={triggered:`trigger_received`,attempt_started:`agent_started`,completed:`terminal`,cancelled:`terminal`};function lt(e){let t=(e.events??[]).flatMap(e=>{let t=st.has(e.kind)?e.kind:ct[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 ut(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 dt(e,t,n){let r=[],i=Math.max(1,Math.trunc(e.attempt??1)),a=t.kind===`agent_failed`?ot(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`}),tt.has(e.status)&&r.push({kind:`cancel`,label:`Cancel Run`});let o=e.events?.some(e=>e.kind===`policy_denial`);return(et.has(e.status)&&nt.has(t.kind)||e.status===`needs_attention`&&o)&&(!e.maxAttempts||i<e.maxAttempts)&&r.push({kind:`retry`,label:`Retry Run`}),r}function ft(e,t,n){let r=Ge(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=dt(e,r,a),u=lt(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:rt(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`,...it(e)?{reference:it(e)}:{},...e.definitionId?{automationId:e.definitionId}:{}},...a?{sessionId:a}:{},...o?{machine:{id:o,...n?.resolveMachineName?.(o)?{name:n.resolveMachineName(o)}:{}}}:{},timestamps:i,...at(i)===void 0?{}:{durationMs:at(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,Qe),events:(e.events??[]).slice(-200),...e.receiptEvidence?{receiptEvidence:e.receiptEvidence}:{},references:c,...s?{failureSummary:s.slice(0,Ze)}:{},timeline:u,operationalState:ut(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 pt(e,t){return ft(e,`automation_run`,t)}function mt(e){return`/runs/${encodeURIComponent(e)}`}function ht(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 gt=[{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 _t(e){let t=[],n,r=!1;for(let i of gt){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?gt.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 vt(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 _t({accountSignedIn:t,machineOnline:n,agentInstalled:r,credentialValid:i,repositoryReady:a})}var L=(e,t)=>({kind:`api_key`,label:e,...t?{helpUrl:t}:{}}),yt=(e,t)=>({kind:`oauth`,label:e,...t?{oauthProviderId:t}:{}}),R={kind:`reference`,label:`Password manager or environment`},bt=[{id:`anthropic`,name:`Anthropic`,authMethods:[yt(`Claude Pro / Max`,`anthropic`),L(`Anthropic API key`,`https://console.anthropic.com/settings/keys`),R],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:[L(`OpenAI API key`,`https://platform.openai.com/api-keys`),R],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:[yt(`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:[L(`Gemini API key`,`https://aistudio.google.com/app/apikey`),R],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:[yt(`Grok / X subscription`,`xai`),L(`xAI API key`,`https://console.x.ai`),R],env:[`XAI_API_KEY`,`GROK_API_KEY`],compatibility:`openai`,models:[]},{id:`openrouter`,name:`OpenRouter`,authMethods:[L(`OpenRouter API key`,`https://openrouter.ai/keys`),R],env:[`OPENROUTER_API_KEY`],compatibility:`openai`,models:[]},{id:`groq`,name:`Groq`,authMethods:[L(`Groq API key`,`https://console.groq.com/keys`),R],env:[`GROQ_API_KEY`],compatibility:`openai`,models:[]},{id:`mistral`,name:`Mistral`,authMethods:[L(`Mistral API key`,`https://console.mistral.ai/api-keys`),R],env:[`MISTRAL_API_KEY`],compatibility:`openai`,models:[]},{id:`deepseek`,name:`DeepSeek`,authMethods:[L(`DeepSeek API key`,`https://platform.deepseek.com/api_keys`),R],env:[`DEEPSEEK_API_KEY`],compatibility:`openai`,models:[]},{id:`together`,name:`Together AI`,authMethods:[L(`Together API key`,`https://api.together.ai/settings/api-keys`),R],env:[`TOGETHER_API_KEY`],compatibility:`openai`,models:[]},{id:`fireworks`,name:`Fireworks AI`,authMethods:[L(`Fireworks API key`,`https://fireworks.ai/account/api-keys`),R],env:[`FIREWORKS_API_KEY`],compatibility:`openai`,models:[]},{id:`cohere`,name:`Cohere`,authMethods:[L(`Cohere API key`,`https://dashboard.cohere.com/api-keys`),R],env:[`COHERE_API_KEY`],models:[]},{id:`perplexity`,name:`Perplexity`,authMethods:[L(`Perplexity API key`,`https://www.perplexity.ai/settings/api`),R],env:[`PERPLEXITY_API_KEY`],compatibility:`openai`,models:[]}];bt.filter(e=>e.authMethods.some(e=>e.kind===`api_key`)).map(e=>e.id);var xt=new Map;for(let e of bt){xt.set(e.id,e);for(let t of e.aliases??[])xt.set(t,e)}function St(e){return xt.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 bt)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 wt(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. Keep one of your machines with that credential online so Bivy Cloud can sync it, or sign in to ${e.provider} on Bivy Cloud, 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 Tt=`session-contract.v1`,Et={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 z(e,t){return{area:e,code:t,message:Et[t]??t}}var Dt=new Set([`auth`,`resume`,`toolInterception`,`sandbox`]);function Ot(e){let t=[],n=e.detectedVersion?e.versionSource??`reported`:`unknown`;n===`unknown`&&t.push(z(`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(z(`executionMode`,`execution_mode_unstructured`)),o===`unavailable`&&t.push(z(`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(z(`auth`,`auth_unknown`)),l===`none`&&t.push(z(`auth`,`auth_unconfigured`));let d={kind:l,origin:e.authOrigin??`unknown`,state:u},f=e.resumeAdvertised??!1,p=f?`guaranteed`:`unavailable`;f||t.push(z(`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(z(`toolInterception`,`tool_interception_mcp_only`)),_===`unavailable`&&t.push(z(`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(z(`sandbox`,`sandbox_observed_only`)),x===`unavailable`&&t.push(z(`sandbox`,`sandbox_unavailable`));let S={...e.sandboxTier?{tier:e.sandboxTier}:{},runtimeEnforcement:y,evidenceClass:b,state:x},C=e.supportTier??`experimental`,w=t.some(e=>Dt.has(e.area)),T=e.certification===`release-tested`&&w&&!e.acknowledgedAt;return{schemaVersion:Tt,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 kt(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 At(e){let t=String(e||``).trim();if(!t)return null;try{t=new URL(t).hash.replace(/^#/,``)||t}catch{}return kt(t)}function B(e,t,n){try{return JSON.parse(e.getItem(t)||JSON.stringify(n))}catch{return n}}function jt(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 B(e,`bivy_keys`,{})},addKey(t,n){let r=this.keys();r[t]=n,e.setItem(`bivy_keys`,JSON.stringify(r))},nodePubs(){return B(e,`bivy_nodepubs`,{})},addNodePub(t,n){let r=this.nodePubs();r[t]=n,e.setItem(`bivy_nodepubs`,JSON.stringify(r))},pairSecrets(){return B(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 B(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 B(e,`bivy_device`,null)},setDevice(t){e.setItem(`bivy_device`,JSON.stringify(t))},clearDevice(){try{e.removeItem(`bivy_device`)}catch{}},sessions(){return B(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 B(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 Mt=[`question_asked`,`agent_notice`,`approval_requested`,`agent_waiting`,`session_done`,`session_error`,`terminal_bell`,`automation_blocked`,`app_notes`],Nt=[{id:`question_asked`,label:`Agent asked a question`,description:`An agent is waiting on an answer from you.`},{id:`agent_notice`,label:`Agent messages`,description:"An agent asked you to take a look with `bivy notify` while you were away."},{id:`approval_requested`,label:`Approval needed`,description:`A tool wants to run and needs you to approve or deny it.`},{id:`agent_waiting`,label:`Agent waiting`,description:"A `bivy run` agent went quiet and may need input."},{id:`session_done`,label:`Session finished`,description:`A session completed its turn — ready to review.`},{id:`session_error`,label:`Session error`,description:`The last turn failed and needs attention.`},{id:`terminal_bell`,label:`Terminal bell`,description:`A terminal rang the bell while you were away.`},{id:`automation_blocked`,label:`Automation blocked`,description:`An automation run could not start because of plan limits or policy.`},{id:`app_notes`,label:`Reviewer notes`,description:`Someone with a shared preview link left notes on your app.`}];function Pt(e){let t={};for(let n of Mt){let r=e&&typeof e==`object`?e[n]:void 0;t[n]=typeof r!=`boolean`||r}return t}function Ft(e,t){let n;try{n=At(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 It(){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 Lt(e,t=fetch){let n=await t(`${V(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 Rt(e,t,n=fetch){let r=await n(`${V(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 zt(e,t,n,r=fetch){let i=await r(`${V(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 V(e){return(e.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``)}async function Bt(e,t=fetch){let n=await t(`${V(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 Vt(e,t=fetch){let n=await t(`${V(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 Ht(e,t=`/`,n=fetch){let r=await n(`${V(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 Ut(e,t=fetch){let n=await t(`${V(e)}/account/managed-automation-target`,{method:`POST`,headers:H(e)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.nodeId||!r.config)throw Error(r.error||`managed automation setup failed: ${n.status}`);return{nodeId:r.nodeId,config:r.config}}var Wt=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 Gt(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 Wt(e.reason||e.error||n,t,e.code,r)}async function Kt(e,t=fetch){let n=await t(`${V(e)}/account/onboarding/managed-defaults`,{method:`POST`,headers:H(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.reason||r.error||`managed session setup failed: ${n.status}`);return ln(r.config)}async function qt(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(`${V(e)}/account/managed-machines`,{method:`POST`,headers:H(e),body:JSON.stringify({configId:t,...i?{runtimeId:i}:{},...a?{requestId:a}:{}})}),s=await o.json().catch(()=>({}));if(!o.ok||!s.machine)throw Gt(s,o.status,`managed Machine launch failed: ${o.status}`);return s.machine}async function Jt(e,t,n=fetch){let r=await n(`${V(e)}/account/managed-machines/restore`,{method:`POST`,headers:H(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok||!i.machine)throw Gt(i,r.status,`managed Machine restore failed: ${r.status}`);return i.machine}async function Yt(e,t=fetch){let n=await t(`${V(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 Xt(e,t=fetch){let n=await t(`${V(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(`${V(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 Qt(e,t=fetch){let n=await t(`${V(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 H(e){return{authorization:`Bearer ${e.s}`,"content-type":`application/json`}}async function $t(e,t=fetch){let n=await t(`${V(e)}/me`,{headers:H(e)});if(!n.ok)throw Error(`account request failed: ${n.status}`);return await n.json()}async function en(e,t=fetch){let n=await t(`${V(e)}/account`,{method:`DELETE`,headers:H(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`account deletion failed: ${n.status}`)}async function tn(e,t,n=fetch){let r=await n(`${V(e)}/account/extension/actions/${encodeURIComponent(t)}`,{method:`POST`,headers:H(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 nn(e,t,n=fetch){let r=await n(`${V(e)}/nodes/${encodeURIComponent(t)}`,{method:`DELETE`,headers:H(e)});if(!r.ok)throw Error(`remove node failed: ${r.status}`)}function rn(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 an(e,t=fetch){let n=await t(`${V(e)}/account/github-app`,{headers:H(e)});if(!n.ok)throw Error(`github-app request failed: ${n.status}`);return rn(await n.json())}async function on(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(`${V(e)}/account/github-app${a}`,{method:`DELETE`,headers:H(e)});if(!o.ok)throw Error(`disconnect failed: ${o.status}`)}async function sn(e,t,n,r=fetch){let i=await r(`${V(e)}/account/github-app/default-node`,{method:`POST`,headers:H(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 cn(e,t,n,r=fetch){let i=await r(`${V(e)}/account/github-app/trigger-access`,{method:`POST`,headers:H(e),body:JSON.stringify(n?{triggerAccess:t,appId:n}:{triggerAccess:t})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`set trigger access failed: ${i.status}`);return a.triggerAccess??`everyone`}function ln(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 un(e,t=fetch){let n=await t(`${V(e)}/account/ephemeral-configs`,{headers:H(e)});if(!n.ok)throw Error(`ephemeral-configs request failed: ${n.status}`);let r=await n.json().catch(()=>[]);return Array.isArray(r)?r.map(ln).filter(e=>e.id):[]}function dn(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 fn(e,t=fetch){let n=await t(`${V(e)}/account/queue-routing`,{headers:H(e)});if(!n.ok)throw Error(`queue-routing request failed: ${n.status}`);return dn(await n.json().catch(()=>({})))}async function pn(e,t,n=fetch){let r=await n(`${V(e)}/account/queue-routing`,{method:`PUT`,headers:H(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set queue routing failed: ${r.status}`);return dn(i)}async function mn(e,t,n=fetch){let r=await n(`${V(e)}/account/hosted-github-app/connect`,{method:`POST`,headers:H(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 hn(e,t=fetch){let n=await t(`${V(e)}/account/hosted-github-repositories`,{headers:H(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 gn(e,t,n=fetch){let[r,i]=t.split(`/`);if(!r||!i)throw Error(`Repository must be owner/name`);let a=await n(`${V(e)}/account/hosted-github-repositories/${encodeURIComponent(r)}/${encodeURIComponent(i)}/branches`,{headers:H(e)}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o?.error||`hosted branch request failed: ${a.status}`);return Array.isArray(o?.branches)?o.branches:[]}function _n(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 vn(e,t=fetch){let n=await t(`${V(e)}/account/hosted-provisioning`,{headers:H(e)});if(!n.ok)throw Error(`hosted-provisioning request failed: ${n.status}`);return _n(await n.json().catch(()=>({})))}async function yn(e,t,n=fetch){let r=await n(`${V(e)}/account/hosted-provisioning`,{method:`PUT`,headers:H(e),body:JSON.stringify(t)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i?.error||`set hosted provisioning failed: ${r.status}`);return _n(i)}async function bn(e,t=fetch){let n=await t(`${V(e)}/account/hosted-machines`,{headers:H(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 xn(e,t,n=fetch){let r=await n(`${V(e)}/account/hosted-machines/${encodeURIComponent(t)}`,{method:`DELETE`,headers:H(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`hosted machine teardown failed: ${r.status}`)}}async function U(e,t,n={},r=fetch){let i=await r(`${V(e)}${t}`,{...n,headers:H(e)}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a?.error||`automation request failed: ${i.status}`);return a}function Sn(e,t=fetch){return U(e,`/account/automations`,{},t)}function Cn(e,t,n=fetch){return U(e,`/account/automations`,{method:`POST`,body:JSON.stringify(t)},n)}function wn(e,t,n=fetch){return U(e,`/account/automations/${encodeURIComponent(t)}/webhook/rotate`,{method:`POST`},n)}function Tn(e,t,n,r=fetch){return U(e,`/account/automations/${encodeURIComponent(t)}`,{method:`PUT`,body:JSON.stringify(n)},r)}function En(e,t,n=fetch){return U(e,`/account/automations/simulate`,{method:`POST`,body:JSON.stringify(t)},n)}async function Dn(e,t,n=fetch){let r=await n(`${V(e)}/account/automations/${encodeURIComponent(t)}`,{method:`DELETE`,headers:H(e)});if(!r.ok)throw Error(`delete automation failed: ${r.status}`)}function On(e,t,n=fetch,r=crypto.randomUUID()){return U(e,`/account/automations/${encodeURIComponent(t)}/run`,{method:`POST`,body:JSON.stringify({sourceKey:r})},n)}function kn(e,t,n=fetch){return U(e,`/account/automation-runs`,{method:`POST`,body:JSON.stringify(t)},n)}function An(e,t=50,n={},r=fetch){let i=new URLSearchParams({limit:String(t)});return n.summary&&i.set(`summary`,`1`),U(e,`/account/automation-runs?${i}`,{},r)}var jn=class extends Error{reason;status;constructor(e,t,n){super(e),this.reason=t,this.status=n,this.name=`RunFetchError`}};async function Mn(e,t,n=fetch){let r;try{r=await n(`${V(e)}/account/automation-runs/${encodeURIComponent(t)}`,{headers:H(e)})}catch{throw new jn(`Could not reach the control plane`,`error`)}if(r.status===404)return null;if(r.status===401)throw new jn(`Unauthorized`,`unauthorized`,401);if(!r.ok)throw new jn(`automation run request failed: ${r.status}`,`error`,r.status);return await r.json()}async function Nn(e,t,n,r=fetch){let i=await r(`${V(e)}/account/product-events`,{method:`POST`,headers:H(e),body:JSON.stringify({event:t,client:n})});if(!i.ok)throw Error(`product event request failed: ${i.status}`)}function Pn(e,t,n=fetch){return U(e,`/account/automation-runs/${encodeURIComponent(t)}/cancel`,{method:`POST`},n).then(e=>e.run)}function Fn(e,t,n=fetch){return U(e,`/account/automation-runs/${encodeURIComponent(t)}/retry`,{method:`POST`},n).then(e=>e.run)}async function In(e,t=30,n=fetch){let r=await n(`${V(e)}/account/work-items?limit=${encodeURIComponent(String(t))}`,{headers:H(e)});if(!r.ok)throw Error(`work-items request failed: ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}async function Ln(e,t,n,r=fetch){let i=await r(`${V(e)}/account/work-items/${encodeURIComponent(t)}/assign`,{method:`POST`,headers:H(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 Rn(e,t,n=fetch){let r=await n(`${V(e)}/account/work-items/${encodeURIComponent(t)}`,{method:`DELETE`,headers:H(e)});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`delete work item failed: ${r.status}`)}}async function zn(e,t=fetch){let n=await t(`${V(e)}/account/work-items`,{method:`DELETE`,headers:H(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 Bn(e,t=fetch){let n=await t(`${V(e)}/account/slack-hook`,{headers:H(e)});if(!n.ok)throw Error(`Slack integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function Vn(e,t,n=fetch){let r=await n(`${V(e)}/account/slack-hook`,{method:`POST`,headers:H(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 Hn(e,t=fetch){let n=await t(`${V(e)}/account/slack-hook`,{method:`DELETE`,headers:H(e)});if(!n.ok)throw Error(`Disconnect Slack failed: ${n.status}`)}async function Un(e,t=fetch){let n=await t(`${V(e)}/account/linear-hook`,{headers:H(e)});if(!n.ok)throw Error(`Linear integration request failed: ${n.status}`);return(await n.json().catch(()=>({})))?.hook??null}async function Wn(e,t={},n=fetch){let r=await n(`${V(e)}/account/linear-hook`,{method:`POST`,headers:H(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 Gn(e,t=fetch){let n=await t(`${V(e)}/account/linear-hook`,{method:`DELETE`,headers:H(e)});if(!n.ok)throw Error(`Disconnect Linear failed: ${n.status}`)}async function Kn(e,t=fetch){let n=await t(`${V(e)}/devices`,{headers:H(e)});if(!n.ok)throw Error(`devices request failed: ${n.status}`);let r=await n.json();return Array.isArray(r)?r:[]}async function qn(e,t,n=fetch){let r=await n(`${V(e)}/devices/${encodeURIComponent(t)}`,{method:`DELETE`,headers:H(e)});if(!r.ok)throw Error(`remove device failed: ${r.status}`)}async function Jn(e,t,n=fetch){await n(`${V(e)}/auth/logout`,{method:`POST`,headers:H(e),body:JSON.stringify(t?{devicePublicKeyB64:t}:{})})}function Yn(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 Xn(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(`${V(e)}/api/push/vapid-public-key`,{headers:H(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:Yn(String(i.publicKey))});if(!(await t(`${V(e)}/api/push/subscribe`,{method:`POST`,headers:H(e),body:JSON.stringify({subscription:a})})).ok)throw Error(`Could not register for push notifications.`);return`Push notifications enabled.`}async function Zn(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(`${V(e)}/api/push/subscribe`,{method:`DELETE`,headers:H(e),body:JSON.stringify({endpoint:i})}).catch(()=>{}),`Push notifications disabled on this device.`}async function Qn(){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 $n(e,t=fetch){let n=await t(`${V(e)}/api/push/preferences`,{headers:H(e)});if(!n.ok)throw Error(`notification preferences request failed: ${n.status}`);return Pt((await n.json().catch(()=>({})))?.preferences)}async function er(e,t,n=fetch){let r=await n(`${V(e)}/api/push/preferences`,{method:`PUT`,headers:H(e),body:JSON.stringify(t)});if(!r.ok)throw Error(`could not save notification preferences: ${r.status}`);return Pt((await r.json().catch(()=>({})))?.preferences)}var tr=[{id:`fly`,name:`Fly.io`,computeClass:`byo-cloud`,tokenLabel:`Fly.io access token`,blurb:`Bivy creates a temporary Fly Machine, runs the session, then destroys it.`,steps:[`Open your Fly.io access tokens and sign in.`,`Click Create token — use a short-lived/deploy token if your account offers one.`,`Copy the token and paste it below. Revoke it after the session if you like.`],links:[{label:`Create a Fly.io token`,url:`https://fly.io/user/personal_access_tokens`},{label:`Fly Machines docs`,url:`https://fly.io/docs/machines/`}]}];function nr(e){let t=String(e||``).trim().toLowerCase();return tr.find(e=>e.id===t)||null}function rr(){try{return new Date().toISOString()}catch{return``}}function ir(){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 ar(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 or(e,t){try{let n=globalThis.indexedDB;if(n)return ar(n,e===`provider-keys`?`bivy-ephemeral`:`bivy-ephemeral-${e}`,e,t)}catch{}return ir()}function sr(e=or(`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 tr.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=nr(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=nr(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:rr()})},async remove(t){let n=nr(t);n&&await e.delete(n.id)}}}function cr(e=or(`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 lr(e=or(`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:rr()})},async remove(i,a=`default`){let o=t(i);o&&await e.delete(r(o,n(a)))}}}function ur(e=or(`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)}}}new TextEncoder;var dr=`bivy`,W=`device-key`,fr=`x25519`;function pr(){try{return typeof globalThis<`u`&&!!globalThis.indexedDB}catch{return!1}}var mr=4e3;function hr(){return new Promise((e,t)=>{let n=!1,r=e=>{n||(n=!0,e())},i=setTimeout(()=>r(()=>t(Error(`indexedDB.open timed out`))),mr),a=indexedDB.open(dr,1);a.onupgradeneeded=()=>{a.result.objectStoreNames.contains(W)||a.result.createObjectStore(W)},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 gr(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 _r(){if(!pr())return;let e=await hr();try{await gr(e.transaction(W,`readwrite`).objectStore(W),e=>e.delete(fr))}finally{e.close()}}function vr(){return pr()?{async load(){let e=await hr();try{let t=await gr(e.transaction(W,`readonly`).objectStore(W),e=>e.get(fr));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 hr();try{let r=n.transaction(W,`readwrite`);r.onerror=e=>e.preventDefault(),await gr(r.objectStore(W),n=>n.put({priv:e,pub:t},fr)),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)});let i=await gr(n.transaction(W,`readonly`).objectStore(W),e=>e.get(fr));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 yr=new WeakMap;function br(e,t){if(t)return xr(e,t);let n=yr.get(e);if(n)return n;let r=xr(e,vr()??void 0);return yr.set(e,r),r.catch(()=>{yr.get(e)===r&&yr.delete(e)}),r}async function xr(e,t){let n=t??vr();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 Sr(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 Cr(e,t,n){let r=await Sr(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 wr(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 Tr=class extends Error{constructor(){super(`Device vault changed concurrently`),this.name=`DeviceVaultConflictError`}},Er=()=>({v:3,providerTokens:{},modelKeys:{},oauthCredentials:{}}),Dr=()=>({phase:`idle`,attemptedAt:null,succeededAt:null,pending:!1,failure:null}),Or=e=>{let t=e?Date.parse(e):NaN;return Number.isFinite(t)?t:0};function kr(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=Er(),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:Or(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 Ar(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 jr(e,t){let n=Er();for(let r of new Set([...Object.keys(e.providerTokens),...Object.keys(t.providerTokens)]))n.providerTokens[r]=Ar(e.providerTokens[r],t.providerTokens[r]);for(let r of new Set([...Object.keys(e.modelKeys),...Object.keys(t.modelKeys)]))n.modelKeys[r]=Ar(e.modelKeys[r],t.modelKeys[r]);for(let r of new Set([...Object.keys(e.oauthCredentials),...Object.keys(t.oauthCredentials)]))n.oauthCredentials[r]=Ar(e.oauthCredentials[r],t.oauthCredentials[r]);return n}function G(e,t=`default`){let n=String(e||``).trim().toLowerCase(),r=String(t||`default`).trim().toLowerCase()||`default`;return r==="default"?n:`${n}:${r}`}function Mr(e){let t=e.indexOf(`:`);return t<0?{provider:e,label:`default`}:{provider:e.slice(0,t),label:e.slice(t+1)||`default`}}function Nr(){return crypto.getRandomValues(new Uint8Array(32))}function Pr(e){let t=e.randomKey??Nr,n=e.now??Date.now,r=null,i=0,a=0,o=Er(),s=null,c=0,l={},u={},d={},f={},p={},m={},h=Dr(),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??Dr()})(),y=()=>c=Math.max(c+1,n()),S=async(e,t)=>D(await E(t),JSON.stringify(e)),C=async(e,t)=>kr(JSON.parse(await O(await E(t),e))),w=async(e,t,n)=>D(await Cr(e.priv,t,`device-vault`),b(n)),T=async(e,t,n)=>x(await O(await Cr(e.priv,t,`device-vault`),n));async function ee(){let t=Er();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(Or(n.updatedAt),l[n.id]??1)})}for(let[e,n]of Object.entries(f))t.providerTokens[e]=Ar(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=G(n.provider,n.label);t.modelKeys[e]={value:{provider:n.provider,label:n.label,key:n.key},updatedAt:Math.max(Or(n.updatedAt),u[e]??1)}}}for(let[e,n]of Object.entries(p))t.modelKeys[e]=Ar(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=G(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]=Ar(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=Or(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=Or(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=>G(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??Mr(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=jr(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 Tr)||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=>G(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=>[G(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=G(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=G(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=G(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=G(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=>[G(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=G(r.provider,r.label),i=Math.max(Number(r.refreshedAt)||0,Number(r.updatedAt)||0),a=n.find(e=>G(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=G(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 Fr=`bivy_local_token`,Ir=15e3,Lr=`This device isn't paired with this machine. Run 'bivy tailscale pair' there and open the link on this device.`,Rr=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(Fr)||``}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(Lr);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(Fr,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(Fr,e.token)}catch(e){console.warn(`local bootstrap failed`,e)}}notPaired(){this.unpaired=!0,this.connected=!1,this.setStatus(`offline`),this.handlers.onError?.(Lr)}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(Fr,``),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,Ir)}},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.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))}}},zr=8388608,Br=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>zr||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++}},Vr=15e3,Hr=15e3,Ur=4,Wr=3;function Gr(){return b(crypto.getRandomValues(new Uint8Array(12)))}function Kr(e){return/device limit|another account|isn't authorized|not authorized|forbidden/i.test(e)}var qr=class{store;handlers;fetchImpl;WS;pairingOnly;ws=null;connected=!1;initialBackoff;backoff;closedByUs=!1;reconnectTimer=null;decodedOnLink=!1;staleKeyStrikes=0;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 Br({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||=br(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.decodedOnLink=!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>=Ur&&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));this.decodedOnLink=!0,this.staleKeyStrikes=0,s()&&o.readyState===1&&this.acceptFrame(t)&&this.transfers.accept(t.data)}).catch(()=>{s()&&o.readyState===1&&(this.handlers.onError?.(this.forgetStaleKey()?`This machine's key changed. Pairing this device with it again.`:`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,Vr)}shouldResync(){let e=this.ws;if(!e)return!1;let t=Date.now();return e._resyncAt!==void 0&&t-e._resyncAt<Hr?!1:(e._resyncAt=t,!0)}forgetStaleKey(){return this.decodedOnLink||!this.store.s||++this.staleKeyStrikes<2?!1:(this.staleKeyStrikes=0,this.store.addKey(this.store.cur,``),this.curKey=null,!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 wr(n,r.pub);this.pairSent=!0,this.rawSend(JSON.stringify({t:`pair`,p:JSON.stringify({k:`pair.hello`,devicePublicKeyB64:r.pub,proofB64:i,label:Jr()})}))}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:Jr()})}))}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 Cr(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 Cr(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(Kr(e)){this.handlers.onError?.(e),this.close();return}if(this.pairAttempts+=1,this.pairAttempts>=Wr){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:Gr(),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,Gr))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 Jr(){return globalThis.navigator?.platform||`Device`}var Yr=Object.freeze({repo:null,branch:null,sandbox:null,acknowledgeReducedProtections:!1,ephemeralConfig:null});function Xr(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{...Yr}}}var Zr=512,Qr=class{nextSeq=0;held=new Map;maxHeld;constructor(e={}){this.maxHeld=Math.max(1,e.maxHeld??Zr)}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 $r(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 ei(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 ti(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.termId==`string`?t:void 0}function ni(e,t,n){if(t.type===`terminal.list`){let n=Array.isArray(t.terminals)?t.terminals.map(ti).filter(e=>!!e):[];return{handled:!0,value:{...e,runTerminals:n}}}if(t.type===`terminal.created`){let n=ti(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 ri(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 ii(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 ai(e){return/^\/[a-zA-Z]/.test(e.trimStart())}function oi(e){return!!(e&&typeof e==`object`&&typeof e.name==`string`&&e.name.startsWith(`/`)&&e.name.length>=2)}function si(e){let t=e.trim();if(!ai(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 ci(e,t=[]){let n=t.filter(oi),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 li(e,t=[]){let n=e.trimStart().toLowerCase();if(!n.startsWith(`/`)||/\s/.test(n))return[];let r=t.filter(oi);return n===`/`?r:r.filter(e=>e.name.toLowerCase().startsWith(n)||e.aliases?.some(e=>e.toLowerCase().startsWith(n)))}function ui(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!oi(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 di(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 fi(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 pi(e){if(e&&e.length!==0)return e.find(e=>e.state===`open`)??e[0]}var mi=[`read-only`,`workspace-write`,`danger-full-access`];function hi(e){let t=String(e??``).trim().toLowerCase().replace(/_/g,`-`);return mi.includes(t)?t:void 0}function gi(e){let t=String(e??``).trim().toLowerCase();return[`never`,`risky`,`always`,`autonomous`].includes(t)?t:void 0}function _i(e){let t=String(e??``).trim().toLowerCase();return[`trusted_workstation`,`isolated_customer_cloud`,`restricted`].includes(t)?t:void 0}var vi=[`guaranteed`,`degraded`,`unavailable`];function yi(e){return!!e&&typeof e==`object`&&vi.includes(e.state)}function bi(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`&&yi(t.executionMode)&&yi(t.auth)&&yi(t.resume)&&yi(t.toolInterception)&&yi(t.sandbox)&&Array.isArray(t.degradedReasons)&&typeof t.requiresAcknowledgement==`boolean`)return t}function xi(e){return typeof e==`string`&&e.startsWith(`repo:`)?e.slice(5):null}function Si(e){return typeof e==`string`&&(e.startsWith(`issue:`)||e.startsWith(`queue:`))}function Ci(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 wi(e){let t=e?.source,n=xi(t),r=e?.githubIssueUrl||null;!r&&typeof t==`string`&&t.startsWith(`github:issue`)&&(r=t.split(`:`).slice(1).join(`:`)||null);let i=fi(e?.prs,e?.prUrl);return{issueUrl:r,prUrl:(pi(i)?.state===`open`?pi(i)?.url:null)??e?.prUrl??null,branch:e?.branch||null,repo:n,prs:i}}function Ti(e){return wi({source:e.source,branch:e.branch,prUrl:e.prUrl,prs:e.prs})}function Ei(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 Di(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 Oi(e){return!e||typeof e!=`object`||!e.os||typeof e.os.platform!=`string`||typeof e.generatedAt!=`string`?null:e}function ki(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 Ai(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=ji(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:Ni(t?.status,!!t?.needsAction,!!t?.isStreaming,a),sessionState:a,branch:t?.branch||void 0,rebuildable:t?.rebuildable?!0:void 0,sandbox:hi(t?.sandbox??t?.bivySession?.sandbox),approvalMode:gi(t?.approvalMode??t?.bivySession?.approvalMode),ephemeral:(t?.ephemeral??t?.bivySession?.ephemeral)===!0||void 0,executionProfile:_i(t?.executionProfile??t?.bivySession?.executionProfile),contract:bi(t?.contract??t?.bivySession?.contract),auditHealth:t?.auditHealth??t?.bivySession?.auditHealth,eventLogHealth:t?.eventLogHealth??t?.bivySession?.eventLogHealth,prUrl:t?.prUrl||void 0,prs:fi(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 ji(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 Mi(e){return e?.displayStatus===`needs_attention`?`needs_action`:e?.displayStatus}function Ni(e,t,n,r){return e===`saved`?`saved`:Mi(r)||(t||e===`needs_action`?`needs_action`:e===`working`||n?`working`:e===`failed`?`failed`:`idle`)}function Pi(e){return Array.isArray(e)?e.map(e=>({id:String(e?.id||e?.model||``),label:e?.label||e?.name,...e})):[]}function Fi(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 Ii(e,t){return!e||!t?!1:e.id===t.id&&e.provider===t.provider}function Li(e){return e?String(e.displayName||e.name||e.id||``):``}function Ri(e){return ki(e)??void 0}function zi(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 Bi(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&&!zi(i,a)?{row:{sessionId:a,status:`idle`,needsAction:!1}}:{}}}case`session.question`:{let t=String(r.requestId||``),i=Ri(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&&!zi(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,...zi(n,t)?{}:{row:{sessionId:t,status:`working`,needsAction:!1}}}}default:return{handled:!1,value:e}}}function K(e,t){return!!t&&t!==e}function Vi(e){return(Array.isArray(e.actions)?e.actions:[e.action]).filter(e=>typeof e==`string`&&e.length>0)}function Hi(e,t,n){let r=t,i=String(r.sessionId||``);switch(t.type){case`session.state`:{let t=ji(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:Mi(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(K(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}`:Ke(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=Vi(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:!K(e.activeSessionId,r.sessionId)&&r.provider?[{kind:`model-auth`,provider:String(r.provider),reason:String(r.reason||``)}]:[]};case`session.usage`:return{handled:!0,patch:K(e.activeSessionId,r.sessionId)?void 0:{usage:Ei(r.usage)},commands:[]};case`session.warning`:return{handled:!0,commands:!K(e.activeSessionId,r.sessionId)&&r.warning?[{kind:`entry`,role:`system`,text:String(r.warning)}]:[]};case`session.changes`:{if(K(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 K(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 K(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 Ui=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`)},Wi=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 Gi(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||Wi(t.shot))&&(t.before===void 0||Wi(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(Ui))&&(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 Ki=[`open`,`changed`,`gone`,`done`];function qi(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`])&&Ki.includes(t.state)&&(t.shot===void 0||Wi(t.shot))}function Ji(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 Yi=[{id:`1h`,label:`1 hour`,ms:36e5},{id:`1d`,label:`1 day`,ms:864e5},{id:`7d`,label:`7 days`,ms:6048e5}];function Xi(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 Zi(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 Qi(e){return!!e&&e.type===`bivy_attachment`&&!!e.ref&&typeof e.ref.hash==`string`&&(e.ref.kind===`image`||e.ref.kind===`file`)}function $i(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 ea=0,q=()=>`e${Date.now().toString(36)}-${(ea++).toString(36)}`;function ta(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`text`||t===`output_text`||!t&&typeof e?.text==`string`}function na(e){let t=String(e?.type||e?.kind||``).toLowerCase();return t===`thinking`||t===`reasoning`}var ra=/^\s*(?:\[Request interrupted by user|<(?:task-notification|system-reminder)[\s>/])/;function ia(e){return ra.test(e)}function aa(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.filter(ta).map(e=>String(e?.text??e?.content??``)).join(`
7
- `);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 aa(t);try{return JSON.stringify(e)}catch{return String(e)}}return e==null?``:String(e)}function oa(e){return Array.isArray(e)?e.filter(na).map(e=>String(e?.text??e?.thinking??e?.reasoning??``)).join(`
8
- `):``}function sa(e){if(Array.isArray(e)){let t=e.filter(ta).map(e=>String(e?.text??e?.content??``)).join(`
9
- `);if(t)return la(t);try{return JSON.stringify(e)}catch{return String(e)}}return la(aa(e))}var ca=[{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 la(e){for(let t of ca){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(`
10
- `).map(e=>e.startsWith(t.indent)?e.slice(t.indent.length):e).join(`
11
- `):i}return e}function ua(e,t,n=q){if(!Array.isArray(e))return[];let r=[];for(let i of e)if(Be(i)){let e=F(i)||t||``;r.push({callId:We(i)||n(),name:N(i),input:He(i),status:`running`,detail:P(i),...e?{parentToolUseId:e}:{}})}else if(Ve(i)){let e=We(i),t=sa(i?.content),n=P(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:N(i),input:{},status:`done`,result:t,...a?{detail:a}:{}})}return r}function da(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:sa(e?.content),detail:e?.isError||e?.is_error?P(e)??{kind:`unknown`,result:{isError:!0}}:P(e)}}function fa(e){let t=new Map;function n(e){if(!e||typeof e!=`object`)return;if(Qi(e)){t.set(e.ref.hash,$i(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 pa(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=aa(s);if(e===`user`){if(Array.isArray(s)){for(let e of s)if(Ve(e))for(let n of ua([e],void 0,a))ga(t,n,a)}let e=fa(s);(c&&!ia(c)||e.length)&&t.push({id:a(),role:`user`,text:c,...e.length?{attachments:e}:{}})}else if(e===`system`)c&&!ia(c)&&t.push({id:a(),role:`system`,text:c});else if(e===`toolresult`||e===`tool_result`){let e=da(o);e&&ga(t,e,a)}else{let e=F(o),n=e=>{let n=e.trim();n&&t.push(qe(n)?{id:a(),role:`error`,text:Ke(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(`
12
- `)),i=[]},u=()=>{r(c.join(`
13
- `)),c=[]},d=()=>{l(),u()};for(let n of s)if(Be(n)||Ve(n)){d();for(let r of ua([n],e,a))ga(t,r,a)}else if(n?.type===`bivy_app`&&Ji(n.app))d(),t.push({id:`app-${n.app.appId}`,role:`assistant`,text:``,app:n.app});else if(n?.type===`bivy_notice`&&Xi(n.notice))d(),t.push({id:n.notice.id,role:`assistant`,text:``,notice:n.notice});else if(n?.type===`bivy_delegation`&&Zi(n.delegation))d(),t.push({id:`delegation-${n.delegation.id}`,role:`assistant`,text:``,delegation:n.delegation});else if(n?.type===`bivy_app_review`&&Gi(n.review))d(),t.push({id:n.review.id,role:`assistant`,text:``,review:n.review});else if(n?.type===`bivy_app_pin`&&qi(n.pin))d(),t.push({id:n.pin.id,role:`assistant`,text:``,pin:n.pin});else if(Qi(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:[{...$i(n.ref,{createdAt:e,artifact:n.artifact}),description:typeof n.caption==`string`?n.caption:void 0}]})}else ta(n)?(u(),i.push(String(n?.text??n?.content??``))):na(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:Ke(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(Ve).map(e=>({id:We(e),content:e.content})):[];for(let e of r){let r=fa(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,toolOutput:!0})}}}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 ma(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,`
14
- `).replace(/\n{3,}/g,`
15
-
16
- `).trim()}function ha(e,t){return e&&typeof e==`object`&&!Array.isArray(e)&&t&&typeof t==`object`&&!Array.isArray(t)?{...e,...t}:t??e}function ga(e,t,n=q){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`?ha(r.tool.input,t.input):r.tool.input}:e.push({id:n(),role:`assistant`,text:``,tool:t})}function _a(e=!0){return{assistantId:null,thinkingId:null,finalized:e,thinkingText:``,sawThinking:!1,pendingText:``,committedText:``,committedThinking:``}}function va(e){return{...e,transcript:[...e.transcript],draft:{...e.draft}}}function ya(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 ba(e,t){let n={id:ya(e.transcript),...t};return e.transcript.push(n),n}function xa(e,t,n){e.transcript=e.transcript.map(e=>e.id===t?{...e,...n}:e)}function Sa(e,t){e.transcript=e.transcript.filter(e=>e.id!==t)}function Ca(e,t){e.working=!0,e.workingLabel=t}function wa(e,t,n,r){let i=t===`assistant`?`assistant`:`thinking`,a=t===`assistant`?`assistantId`:`thinkingId`,o=i===`assistant`&&r?Ie(n):void 0,s=e.draft[a];s?xa(e,s,{text:n,html:o,streaming:!r}):(s=ba(e,{role:i,text:n,html:o,streaming:!r}).id,e.draft[a]=s),r&&(e.draft[a]=null)}function Ta(e){e.draft.assistantId&&xa(e,e.draft.assistantId,{streaming:!1}),e.draft.thinkingId&&xa(e,e.draft.thinkingId,{streaming:!1}),e.draft.assistantId=null,e.draft.thinkingId=null}function Ea(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,wa(e,`thinking`,n,!0))}function Da(e){return(e.pendingText.startsWith(e.committedText)?e.pendingText.slice(e.committedText.length):e.pendingText).trim()}function Oa(e){let t=Da(e.draft);t&&(e.draft.committedText=e.draft.pendingText,qe(t)?(e.draft.assistantId&&(Sa(e,e.draft.assistantId),e.draft.assistantId=null),ba(e,{role:`error`,text:Ke(t)})):wa(e,`assistant`,t,!0))}function ka(e){let t=Da(e.draft);t&&wa(e,`assistant`,t,!1)}function Aa(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 ja(e,t,n){if(t)n.thinkingText=t;else{let t=Aa(e);t.kind===`delta`?n.thinkingText+=t.text:t.kind===`full`&&(n.thinkingText=t.text)}return n.thinkingText.trim()}function Ma(e,t){return e&&t&&typeof e==`object`&&typeof t==`object`&&!Array.isArray(e)&&!Array.isArray(t)?{...e,...t}:t??e}function Na(e,t){let n=t.callId?e.transcript.findIndex(e=>e.tool?.callId===t.callId):-1;if(n<0){ba(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`?Ma(i.input,t.input):i.input}}}function Pa(e){e.transcript=e.transcript.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function Fa(e,t){let n=We(e);if(n)return n;let r=N(e),i=He(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}`:ya(t)}function Ia(e,t){let n=N(e);if(n===`agent_output`||n===`stderr`||n===`stdout`)return`Reading agent output…`;let r=We(e),i=P(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 La(e,t){return e.some(e=>e.attachments?.some(e=>e.hash===t))}function Ra(e,t,n){let r=Re(t);if(!r)return{handled:!1,value:e,commands:[]};let i=va(e),a=[];switch(r){case`agent_start`:case`turn_start`:i.draft.finalized=!1,Ca(i,r===`agent_start`?`Planning…`:`Thinking…`);break;case`message_start`:t.message?.role===`assistant`&&(i.draft.finalized&&(i.draft=_a(!1)),Ca(i,`Drafting response…`));break;case`app_published`:{let e=t.app;if(!Ji(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(!Zi(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:(Ea(i),Oa(i),i.transcript.push(n));break}case`notice`:{let e=t.notice;if(!Xi(e)||i.transcript.some(t=>t.notice?.id===e.id))break;Ea(i),Oa(i),i.transcript.push({id:e.id,role:`assistant`,text:``,notice:e});break}case`app_review`:{let e=t.review;if(!Gi(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(!qi(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(La(i.transcript,r.hash))break;let o=typeof t.caption==`string`?t.caption:``;ba(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=aa(n.content).trim();if(a&&(i.draft.pendingText=a),ja(t,oa(n.content).trim(),i.draft)&&!a&&(i.draft.sawThinking=!0),r===`message_end`||r===`message_boundary`)Ea(i),Oa(i),i.draft.finalized=!0;else{let e=a?`Drafting response…`:`Thinking…`;(!i.working||i.workingLabel!==e)&&Ca(i,e),ka(i)}for(let e of ua(n.content))Na(i,e);break}case`start`:Ea(i),Oa(i),Ta(i),Na(i,{callId:Fa(t,i.transcript),name:N(t),input:He(t),status:`running`,detail:P(t),...F(t)?{parentToolUseId:F(t)}:{}}),Ca(i,Ia(t,i.transcript));break;case`update`:Na(i,{callId:Fa(t,i.transcript),name:N(t),input:He(t),status:`running`,detail:P(t),...F(t)?{parentToolUseId:F(t)}:{}}),Ca(i,Ia(t,i.transcript));break;case`result`:Na(i,{callId:Fa(t,i.transcript),name:N(t),input:{},status:`done`,result:sa(t.result),detail:P(t)});break;case`turn_end`:Ca(i,`Planning next step…`);break;case`agent_end`:Ta(i),Pa(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=fa(t.result??t.message??t.output).filter(e=>!La(i.transcript,e.hash));e.length&&(ba(i,{role:`assistant`,text:``,attachments:e,toolOutput:!0}),a.push({kind:`remember-agent-attachments`}))}return{handled:!0,value:i,commands:a}}function J(e,t=!1){return{queue:e,changed:!1,accepted:t}}function za(e,t){switch(t.type){case`enqueue`:{let n=e.find(e=>e.id===t.item.id);if(n)return{...J(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{...J(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 J(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{...J(e),edit:{ok:!1,reason:`not_found`}};let r=e[n];if(r.status!==`queued`)return{...J(e),edit:{ok:!1,reason:`not_queued`}};if(r.version!==t.expectedVersion)return{...J(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`?J(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?J(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 J(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 J(e);let r=Math.max(0,Math.min(t.toIndex,e.length-1));if(r===n)return J(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 J(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}:J(e);case`revert-to-queued`:{let n=e.findIndex(e=>e.id===t.id);if(n<0||e[n].status!==`sending`)return J(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}:J(e);case`clear`:return e.length?{queue:[],changed:!0,accepted:!0}:J(e,!0)}}function Ba(e){return e.map(e=>e.tool?.status===`running`?{...e,tool:{...e.tool,status:`done`}}:e)}function Va(e){return e===`openai-codex`?`openai`:e}var Ha=[`status`,`signedIn`,`nodes`,`currentNodeId`,`nodeUpdate`,`nodeUpdating`,`nodeUpdateAcknowledged`],Ua=[`sessions`,`runTerminals`,`tuiSessions`,`pausedSessionIds`,`commandsBySession`,`followupsBySession`],Wa=[`activeSessionId`,`activeRuntimeId`,`activeTitle`,`github`,`transcript`,`working`,`workingLabel`,`opening`,`approvals`,`questions`,`turnAttentions`,`usage`,`changes`,`changesHistory`,`checkpoints`],Ga=[`models`,`modelsRuntimeId`,`currentModelId`,`currentModel`,`thinking`,`runtimes`,`currentAgentName`,`selectedAgentId`,`installingRuntimeId`,`repos`,`reposAuthed`,`reposError`,`reposLoading`,`reposReason`,`githubConnect`,`branches`,`branchesRepo`,`branchesDefault`,`branchesError`,`branchesLoading`,`providers`,`activationReadiness`],Ka=[`nodeSettings`,`providerAuth`,`credentialRecords`,`credentialPresets`,`localModels`,`localModelPresets`,`rulesets`,`sttConfig`,`nodeStats`,`capabilities`],qa=[`forkProgress`,`oauth`,`needsModelAuth`,`githubApp`,`prResult`,`prRefreshAllResult`,`error`,`notice`];function Ja(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 Ya(){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:{...Yr}}}function Xa(e=!0){return _a(e)}function Za(e){return e.role===`assistant`&&!e.tool&&!e.toolOutput&&!!e.attachments?.length}function Qa(e){return e.tool?`tool:${e.tool.callId}`:`${e.role}:${e.text}`}function $a(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?eo(e,0,r):e.length;if(!t.after)return eo(e,n,r);for(let i=r-1;i>=n;i--){let n=e[i];if(!Za(n)&&Qa(n)===t.after)return eo(e,i+1,r)}return r}function eo(e,t,n){for(;t<n&&Za(e[t]);)t++;return t}var to=class e{state=Ya();listeners=new Set;notifyPending=!1;notifyHandle=null;draft=Xa();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;inlineImagesByRef=new Map;transcriptCache=new Map;static CACHE_MAX=30;recentlyDeleted=new Map;historyRaw=new Map;deferredHistory=null;awaitingOpenHistory=!1;onHistoryPersist;requestReplay;seqReassembler=new Qr;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(pa(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 pa(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.inlineImagesByRef.set(t,n)}withInlineImageRefs(e){if(this.inlineImagesByRef.size===0)return e;let t=!1,n=e.map(e=>{if(e.role!==`assistant`||!e.text)return e;let n=se(e.text);if(!n.length)return e;let r;for(let{ref:t}of n){let n=this.inlineImagesByRef.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=Xa(),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||Li(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?Ti(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=Ja(this.state.connection,e,Ha),n=Ja(this.state.sessionIndex,e,Ua),r=Ja(this.state.activeSession,e,Wa),i=Ja(this.state.catalogs,e,Ga),a=Ja(this.state.settings,e,Ka),o=Ja(this.state.presentation,e,qa);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=ui((t&&typeof t==`object`?t:void 0)?.commands);if(di(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=za(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(Ai(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(Ai(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=Xa(),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:Xr(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:q(),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=Xr(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:Xr(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=Li(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=>Ii(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:Ii(t,e)}))})}setSelectedAgentLocal(e){let t={selectedAgentId:e,currentAgentName:Li(this.state.catalogs.runtimes.find(t=>t.id===e))||this.state.catalogs.currentAgentName,draft:Xr(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=Xa(),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:Xr(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:q(),role:`user`,text:e,html:Ie(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=$r(this.state.connection,e);if(n.handled){this.setValues({connection:n.value,...n.error?{presentation:{...this.state.presentation,error:n.error}}:{}});return}let r=ei(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=ni({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=ri(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=ii(this.state.presentation,e);if(o.handled){this.setValues({presentation:o.value});return}let s=Bi({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=Hi({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:q()}:{}},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:q(),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=ji(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:Mi(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:q(),role:`user`,text:i,html:Ie(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=Pi(t.models),i=t.current?Pi([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=>Ii(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=>Ii(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:Fi(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?Pi([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:Ii(e,n)}))});return}case`thinking.updated`:{let t=e;t.thinking&&this.set({thinking:Fi(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:Li(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=Va(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=Le(r?.type);if(n&&i!==`user_question`&&i!==`user_question_resolved`&&i!==`app_published`&&i!==`app_review`&&i!==`app_pin`&&i!==`notice`){let e=i===`agent_end`,r=ji(t.state??t.sessionState);this.updateSessionRow(n,{status:Mi(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=Di(e.stats);t&&this.set({nodeStats:t});return}case`capabilities`:{let t=Oi(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=Ra({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.inlineImagesByRef.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=ji(e.sessionState??e.bivySession?.state),l=!(c?c.agent===`working`:e.isStreaming),u=this.withCachedAttachments(l?Ba(pa(a)):pa(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=Xa(),this.deferredHistory=null;let f=ji(e.sessionState??e.bivySession?.state);t&&f&&this.updateSessionRow(t,{sessionState:f,status:Mi(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:wi(e),transcript:this.withPendingUserEntries(d),working:f?f.agent===`working`:!!e.isStreaming,opening:!1,usage:Ei(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(!Za(a)){i=Qa(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=$a(i,e);i=[...i.slice(0,t),{id:q(),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=fi(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 no(e,t){return e>0||t}function ro(e){let t=e?.streamingBehaviors;return Array.isArray(t)&&t.includes(`steer`)}function io(e){return e.find(e=>e.status===`queued`)}var ao=`t`;function oo(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(ao,{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(ao,e)}catch{return r(null)}let o=t(a.objectStore(ao));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 so(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 co=`bivy-attachments-v1`,lo=67108864,uo=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(co)).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>lo)return;let a=await caches.open(co),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<=lo)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(co)}catch{}}},fo=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<=lo){for(;this.bytes+n>lo&&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()}},po=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()}},mo=15e3,ho=()=>Error(`The machine is not reachable.`),go=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,ho())},mo),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,ho())}),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 _o(e,t,n,r=18e4){if(e.keys()[t])return Promise.resolve();let i=new Proxy(e,{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)});return new Promise((a,o)=>{let s=!1,c=``,l=e=>{s||(s=!0,clearTimeout(u),d.close(),e?o(e):a())},u=setTimeout(()=>l(Error(c||`The machine didn't come online in time.`)),r),d=n(i,{onStatus:n=>{n===`online`&&e.keys()[t]?l():n===`offline`&&l(Error(c||`The machine refused to pair with this device.`))},onEvent:()=>{},onError:e=>{c=e}});d.connect().catch(e=>l(e instanceof Error?e:Error(String(e))))})}function vo(){return window.navigation}var yo=0,Y=[],bo=[],xo,So=[];function Co(){if(!(xo||Y.some(e=>e.closing)))for(let e of So.splice(0))e()}function wo(e){So.push(e),setTimeout(Co,0)}function To(){if(xo)return;let e=Y.at(-1);if(e?.closing){xo=e;let t=vo();e.returnKey&&t?t.traverseTo(e.returnKey):history.back();return}for(let e of bo.splice(0))e.disposed||(e.returnKey=vo()?.currentEntry?.key,history.pushState({...history.state,__bivyModal:e.id},``,location.href),Y.push(e));Y.at(-1)?.closing?To():Co()}typeof window<`u`&&window.addEventListener(`popstate`,e=>{let t=Y.at(-1);if(t&&e.state?.__bivyModal===t.id){e.stopImmediatePropagation(),xo=void 0,queueMicrotask(To);return}let n=Y.pop();xo=void 0,n&&(e.stopImmediatePropagation(),n.disposed||n.onBack(),queueMicrotask(To))});function Eo(e){let t={id:++yo,onBack:e,closing:!1,disposed:!1};return queueMicrotask(()=>{t.disposed||(bo.push(t),To())}),{close(){t.closing||(t.closing=!0,To())},dispose(){t.disposed=!0,t.closing=!0,To()}}}var Do=[`appearance`,`notifications`,`import`,`providers`,`models`,`instructions`,`voice`,`share`,`github`,`linear`,`slack`,`queue`,`webhooks`,`rulesets`,`nodes`,`account`,`link`];function Oo(e){return Do.includes(e)}var ko=[`runs`,`rulesets`];function Ao(e){return e===`queue`?`runs`:ko.includes(e)?e:null}var jo=/^\/(artifacts|apps)\/?$/,Mo=/^\/sessions\/([^/]+)\/?$/,No=/^\/settings(?:\/([^/]+))?\/?$/,Po=/^\/automations(?:\/([^/]+))?\/?$/;function Fo(e=location.pathname){let t=Mo.exec(e);if(t&&t[1]){let e=decodeURIComponent(t[1]);return e===`new`?{kind:`new`}:{kind:`session`,id:e}}let n=ht(e);if(n)return{kind:`run`,id:n};let r=No.exec(e);if(r){let e=r[1]?decodeURIComponent(r[1]):``;return{kind:`settings`,view:Oo(e)?e:null}}let i=Po.exec(e);if(i)return{kind:`automations`,section:Ao(i[1]?decodeURIComponent(i[1]):``)};let a=jo.exec(e);return a?{kind:`library`,view:a[1]}:{kind:`root`}}function Io(e){return(e.kind===`session`?`/sessions/${encodeURIComponent(e.id)}`:e.kind===`run`?mt(e.id):e.kind===`new`?`/sessions/new`:e.kind===`settings`?e.view?`/settings/${e.view}`:`/settings`:e.kind===`automations`?e.section?`/automations/${e.section}`:`/automations`:e.kind===`library`?`/${e.view}`:`/`)+location.search+location.hash}function X(e,t={}){let n=Io(e);n!==location.pathname+location.search+location.hash&&(t.replace?history.replaceState(null,``,n):history.pushState(null,``,n))}function Lo(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 Ro(e,t,n=globalThis.__BIVY_RUNTIME_CONFIG__){return!n||typeof n!=`object`||!(e in n)?t:n[e]===!0}var zo=Ro(`ephemeralMachinesEnabled`,{BASE_URL:`/`,DEV:!1,EPHEMERAL_MACHINES_ENABLED:``,MODE:`production`,PROD:!0,SSR:!1}.EPHEMERAL_MACHINES_ENABLED===`1`),Bo=`bivy.pwa.first-success`,Vo=`bivy.product-metric.first_useful_response`,Ho=`bivy.pwa.install-dismissed`,Uo=new Set,Wo=null,Go=!1,Ko=!1,qo=0;function Jo(){try{return localStorage.getItem(Bo)===`1`||localStorage.getItem(Vo)===`1`}catch{return!1}}function Yo(){return typeof window>`u`?!1:window.matchMedia?.(`(display-mode: standalone)`).matches===!0||navigator.standalone===!0}function Xo(){try{return localStorage.getItem(Ho)===`1`}catch{return!1}}Ko=typeof window<`u`&&Xo();function Zo(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 Qo(){return typeof navigator>`u`?null:Zo(navigator.userAgent,navigator.platform,navigator.maxTouchPoints,Yo())}var Z={updateAvailable:!1,installChoice:null,standalone:Yo(),shellCached:!1,firstSuccess:typeof window<`u`&&Jo(),hasDraft:!1,pendingAttachments:0,readingAttachments:!1,turnActive:!1,locallyQueuedPrompts:0,queuedFollowups:0};function Q(e){let t={...Z,...e};Object.keys(t).every(e=>t[e]===Z[e])||(Z=t,Uo.forEach(e=>e()))}function $o(){let e=Yo();Q({standalone:e,installChoice:e||Go||Ko||!Z.firstSuccess?null:Wo?`native`:Qo()})}async function es(){try{Q({shellCached:!!(await navigator.serviceWorker?.getRegistration())?.active})}catch{Q({shellCached:!1})}}function ts(){let e=e=>{e.preventDefault(),Wo=e,$o()},t=()=>{Wo=null,Go=!0,$o()},n=()=>{es()},r=window.matchMedia?.(`(display-mode: standalone)`);return window.addEventListener(`beforeinstallprompt`,e),window.addEventListener(`appinstalled`,t),navigator.serviceWorker?.addEventListener(`controllerchange`,n),r?.addEventListener?.(`change`,$o),$o(),es(),()=>{window.removeEventListener(`beforeinstallprompt`,e),window.removeEventListener(`appinstalled`,t),navigator.serviceWorker?.removeEventListener(`controllerchange`,n),r?.removeEventListener?.(`change`,$o)}}function ns(e){return Uo.add(e),()=>Uo.delete(e)}function rs(){return Z}function is(e){Q({updateAvailable:e})}function as(e){Q(e)}function os(e){Q({turnActive:e})}function ss(){qo+=1,Q({locallyQueuedPrompts:qo})}function cs(){qo=0,Q({locallyQueuedPrompts:0})}function ls(e){Q({queuedFollowups:Math.max(0,Math.floor(e))})}function us(){try{localStorage.setItem(Bo,`1`)}catch{}Q({firstSuccess:!0}),$o()}function ds(){Ko=!0,Wo=null;try{localStorage.setItem(Ho,`1`)}catch{}Q({installChoice:null})}async function fs(){let e=Wo;if(!e||Z.standalone||!Z.firstSuccess)return`unavailable`;Wo=null,Q({installChoice:null});try{return await e.prompt(),(await e.userChoice).outcome}catch{return`unavailable`}}function ps(e=Z){let t=[];return e.turnActive&&t.push(`the active turn finishes`),e.readingAttachments&&t.push(`file reading finishes`),e.hasDraft&&t.push(`the unsent draft is sent or cleared`),e.pendingAttachments&&t.push(`pending attachments are sent or cleared`),e.locallyQueuedPrompts&&t.push(`locally queued prompts reach the Machine`),e.queuedFollowups&&t.push(`queued follow-ups are delivered`),t}function ms(e=Z){return e.updateAvailable&&ps(e).length===0}var hs="On that machine, run `bivy status` (or `bivy restart`).";function gs(e,t,n=Z,r){let i=r?`Machine ${r}`:`The Machine`;return n.locallyQueuedPrompts>0?{kind:`local-queue`,label:n.locallyQueuedPrompts===1?`Prompt queued on this device`:`${n.locallyQueuedPrompts} prompts queued on this device`,detail:`Not yet delivered to ${r?`Machine ${r}`:`the Machine`}. Keep Bivy open — it sends as soon as the connection is back.`}:e===`reconnecting`||e===`connecting`||e===`linking`||e===`pairing`?{kind:`reconnecting`,label:r?`Reconnecting to ${r}`:`Reconnecting Machine`,detail:t?`Showing the cached transcript. Keep drafting — sending resumes once the connection is back.`:`Waiting for ${r?`Machine ${r}`:`the Machine`} to answer. If this sticks, run \`bivy status\` on that machine.`}:e===`offline`&&t?{kind:`cached-transcript`,label:`Cached transcript`,detail:`${i} is offline — this copy may be behind, and prompts can't send until it reconnects. ${hs}`}: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. ${hs}`}:e===`offline`?{kind:`offline-page`,label:`Offline`,detail:`${i} is unreachable. Your draft is kept on this device. ${hs}`}:{kind:`live-control`,label:`Live control`,detail:`${i} is connected. Prompts send now and transcript changes sync live.`}}var _s=66e4,vs=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}:{}},_s),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}:{}},_s)}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})})}},ys=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}},bs=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})}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)}};function xs(e){return!!e?.startsWith(`eph-managed-auto-`)}var Ss={online:{label:`Online`},asleep:{label:`Asleep`,hint:`wakes when you send`},offline:{label:`Offline`}};function Cs(e){return e?.online?`online`:xs(e?.id)?`asleep`:`offline`}function ws(e,t,n){let r=e=>!!n.find(t=>t.id===e)?.online,i=t.filter(e=>xs(e.nodeId)&&r(e.nodeId)).sort((e,t)=>Date.parse(t.createdAt)-Date.parse(e.createdAt));return e.filter(e=>e.computeSource===`managed`).map(e=>{let t=i[0],r=!t&&n.some(e=>xs(e.id)&&!e.online);return{key:e.id,label:(e.name||`Bivy Cloud`).replace(/^Hosted\s+/i,``),online:!!t,asleep:r,nodeId:t?.nodeId,config:e}})}var Ts=class{deps;constructor(e){this.deps=e}listConfigs(){return this.deps.listConfigs()}async reprovision(e,t){try{if(!xs(e))throw Error(`This session's machine can't be rebuilt.`);await this.deps.restoreManagedMachine({configId:`managed-default`,nodeId:e,sessionId:t,requestId:`wake:${t}:${Date.now()}`}),await this.deps.connectToNode(e,12e4)}catch(e){this.deps.reportError(e instanceof Error?e:Error(String(e)))}}isCurrentNodeResumable(){if(this.deps.direct())return!1;let e=this.deps.currentNodeId();return xs(e)?!this.deps.nodes().find(t=>t.id===e)?.online:!1}},Es=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)}},Ds=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 no(t,this.store.getState().activeSession.working)}supportsSteering(){let e=this.store.getState(),t=e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId;return ro(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=io(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}:{}})}},Os=`bivy.device.id`,ks=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android.*Mobile/,`Android phone`],[/Android/,`Android tablet`],[/CrOS/,`Chromebook`],[/Macintosh|Mac OS X/,`Mac`],[/Windows/,`Windows PC`],[/Linux/,`Linux`]];function As(e,t=0){let n=ks.find(([t])=>t.test(e))?.[1]??`Browser`;return n===`Mac`&&t>1?`iPad`:n}var js;function Ms(){if(js)return js;let e=``;try{e=localStorage.getItem(Os)??``}catch{}if(!e){e=`web:${crypto.randomUUID()}`;try{localStorage.setItem(Os,e)}catch{}}return js={id:e,label:As(navigator.userAgent,navigator.maxTouchPoints)},js}var Ns=class extends Error{disclosure;constructor(e){super(e),this.disclosure=e,this.name=`NeedsDisclosureError`}};function $(){return`r-${crypto.randomUUID()}`}function Ps(){return crypto.randomUUID()}var Fs=/^(localhost|127\.0\.0\.1|\[?::1\]?)$/,Is=`bivy-room-v1`,Ls=24e4;function Rs(e=jt(r())){return n?!1:Ro(`directNode`,!1)||new URLSearchParams(location.search).has(`local`)?!0:Fs.test(location.hostname)&&!e.s&&!location.hash.includes(`payload=`)}var zs=new class e{store=new to;local=jt(r());direct;solo;directPairCode=``;transport;transportGeneration=0;syncingActivationCredentials=!1;pendingLaunchRestoration=Promise.resolve();pendingPrompt=null;pendingLaunches=new Map;bootProgressTimers=new Map;bootstrapPhaseByNode=new Map;pendingAgentPick=null;pendingFollowups=[];pendingResume=[];resumingNode=new Set;ephemeralCorrelations=[];terminalListeners=new Set;pendingTranscriptions=new Map;pendingSpeech=new Map;pendingAcks=new Map;transcriptCache=oo({maxSessions:50});attachmentLoader=new fo;attachmentDiskCache=new uo;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 Ds(this.store,{send:e=>this.send(e),createClientMessageId:Ps,now:Date.now,persistBackstop:(e,t,n)=>{this.persistScheduledFollowup(e,t,n)},cancelBackstop:e=>this.cancelScheduledFollowup(e)}),this.nodeCoordinator=new ys({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 vs({reportForkProgress:e=>this.store.setForkProgress({status:`working`,message:e}),send:e=>{this.sendToCurrentNode(e)},sendRequest:e=>{this.sendToCurrentNode(e)},createRequestId:$,createClientMessageId:Ps,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()}${Io({kind:`session`,id:e})}`,refreshAccountSessions:()=>{this.refreshAccountSessions()},launchManagedDestination:async(e,t)=>{let n=await qt(this.local,e,{runtimeId:t});if(!n.nodeId)throw Error(`Managed fork destination launched without a node id`);return n.nodeId},reportCrossNodeFork:(e,t)=>{e===`error`?this.store.setError(t):e===`success`&&this.store.setNotice(t)}},{navigateNew:()=>X({kind:`new`}),focusComposer:()=>this.focusComposer(),clearPendingPromptAndFollowups:()=>{this.pendingPrompt=null,this.pendingFollowups=[]},resetActiveSession:()=>{this.promptTargetSessionId=null,this.store.resetActiveSession()},seedDraftDefaults:()=>this.seedDraftDefaults(),listRuntimes:()=>this.listRuntimes(),listModels:()=>this.listModels(),hasNodeSettings:()=>!!this.store.getState().settings.nodeSettings,getNodeSettings:()=>this.getNodeSettings(),listRepos:()=>this.listRepos(),draftRepo:()=>this.store.getState().draft.repo,listBranches:e=>this.listBranches(e),activeSessionId:()=>{if(this.promptTargetSessionId)return this.promptTargetSessionId;let e=this.store.getState(),t=Fo();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:()=>zo?this.store.getState().draft.ephemeralConfig:null,startEphemeralLaunch:(e,t,n)=>{let r=new Date().toISOString(),i={id:e,prompt:t,config:n,logs:[],followups:[],phase:`provisioning`,createdAt:r,updatedAt:r};this.pendingLaunches.set(e,i),this.pendingLaunchStore.put(i),this.store.persistPendingSession(e,t.text,!0,n.name),this.launchDraftRunnerAndBind(e)},send:e=>this.send(e),resetDeletedActiveSession:()=>{this.store.resetActiveSession(),X({kind:`new`})},removeSessionLocal:e=>this.store.removeSessionLocal(e),persistDeletedSessionTombstones:()=>this.persistDeletedSessionTombstones(),deleteTranscriptCache:e=>{this.transcriptCache.delete(e)},refreshSessions:()=>this.refreshSessions(),resolveSessionId:e=>e||this.store.getState().activeSession.activeSessionId}),this.credentialsModelsCoordinator=new bs({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 Ts({listConfigs:()=>un(this.local),direct:()=>this.direct,currentNodeId:()=>this.local.cur,nodes:()=>this.store.getState().connection.nodes,restoreManagedMachine:e=>Jt(this.local,e),connectToNode:(e,t)=>this.connectToNode(e,t),reportError:e=>this.store.setError(e.message)}),this.accountCoordinator=new Es({local:this.local,sendGithubDisconnect:({appId:e,hookId:t})=>this.send({kind:`github.app.disconnect`,requestId:$(),appId:e||void 0,hookId:t||void 0}),refreshNodes:()=>this.refreshNodes(),api:{fetchMe:$t,fetchGithubApp:an,fetchGithubQueue:In,fetchAutomationRuns:An,cancelAutomationRun:Pn,disconnectGithubApp:on,removeNode:nn,enablePush:Xn,disablePush:Zn,pushStatus:Qn,getNotificationPreferences:$n,setNotificationPreferences:er,createOneOffRun:kn,setGithubAppDefaultNode:sn,setGithubAppTriggerAccess:cn,assignWorkItem:Ln,deleteWorkItem:Rn,clearWorkQueue:zn},runContext:()=>{let e=this.store.getState(),t=e.activeSession.activeSessionId??void 0,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t):void 0,r=t?this.resolveSessionNodeId(t):e.connection.currentNodeId??void 0,i=r?e.connection.nodes.find(e=>e.id===r):void 0;return{accountMode:this.accountMode(),sessionId:t,nodeId:r,roomKey:r?this.local.keys()[r]:void 0,nodeLabel:i?.name?`bivy/${i.name}`:void 0,repo:e.draft.repo??void 0,runtimeId:e.catalogs.selectedAgentId??void 0,model:e.catalogs.currentModel?.id,sandbox:n?.sandbox??(t?void 0:e.draft.sandbox??e.settings.nodeSettings?.defaultSandbox)}},encrypt:async(e,t)=>D(await E(C(e)),t),recordRunAccepted:()=>this.recordProductMilestone(`run_accepted`)}),this.store.onHistoryPersist=(e,t,n,r)=>{let i=this.store.attachmentsForHistory(t);this.transcriptCache.put(e,t,n,r,i)},this.store.requestFreshHistory=()=>{let e=this.store.getState().activeSession.activeSessionId;e&&this.requestHistory(e)},this.store.requestReplay=(e,t)=>{this.send({kind:`session.replay`,sessionId:e,afterSeq:t})},this.store.onSessionSettled=()=>{this.refreshSessions();let e=this.store.getState().activeSession.activeSessionId;e&&(this.store.settleSendingFollowups(e),this.followupCoordinator.drain(e))},this.store.onSessionCreatedElsewhere=()=>this.refreshSessions();let e=/^#pair=([A-Za-z0-9_-]+)$/.exec(location.hash);e&&(this.directPairCode=e[1]??``,history.replaceState(null,``,location.pathname+location.search));try{!n&&Ft(this.local,location.hash)&&history.replaceState(null,``,location.pathname+location.search)}catch{}this.seedDraftDefaults(),this.detectGithubAppReturn(),this.direct=Rs(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=Fo(),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.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=Ro(`directNode`,!1);return this.direct?new Rr({bootstrap:new URLSearchParams(location.search).get(`bootstrap`)||``,...t?{tokenStore:r(),pairCode:this.directPairCode,deviceName:Ms().label,requireToken:!0}:{},handlers:e}):new qr({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)}Nn(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=vt(i(t)),o=vt(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&&(us(),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 Bt(this.local)}centralGithubApp(){return Vt(this.local)}createCentralGithubInstall(e=`/`){return Ht(this.local,e)}managedAutomationTarget(){return Ut(this.local)}async connectCloudComputer(e){let t=await qt(this.local,e,{requestId:`pair:${Date.now()}`});if(!t.nodeId)throw Error(`Bivy Cloud started without a node id.`);return await _o(this.local,t.nodeId,(e,t)=>new qr({store:e,pairingOnly:!0,handlers:t})),t.nodeId}async setupManagedCredentials(){let e=this.store.getState().activeSession.activeSessionId,t=e?this.pendingLaunches.get(e):void 0;if(!e||!t)throw Error(`The original Cloud session is no longer available.`);let n=t.machine?.nodeId;if(!n)return this.retryPendingLaunch(e);this.switchNode(n),await this.waitForOnline(12e4),this.listProviders(),this.listCredentialRecords();let r=t.prompt.frame,i=this.managedLaunchProvider(String(r?.agent||``),r?.model?.provider)??`anthropic`;this.store.setNeedsModelAuth({nodeId:n,provider:i})}ensureManagedSessionDefaults(){return Kt(this.local)}createNodeClaim(){return Yt(this.local)}listNodeClaims(){return Xt(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(Fo(),{navigate:!1})}),t(e=>{let t=Lo(e,d());t&&(history.replaceState(null,``,t.path),this.pendingRoute=Fo(),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:Ms(),text:t}).catch(()=>{})}onAppsChanged(e){return this.appsChangedListeners.add(e),()=>this.appsChangedListeners.delete(e)}onComposerFocus(e){return this.composerFocusListeners.add(e),()=>this.composerFocusListeners.delete(e)}focusComposer(){for(let e of this.composerFocusListeners)e()}onComposerPrefill(e){return this.composerPrefillListeners.add(e),()=>this.composerPrefillListeners.delete(e)}prefillComposer(e,t=[]){for(let n of this.composerPrefillListeners)n(e,t);return this.focusComposer(),this.composerPrefillListeners.size>0}onOpenSlash(e){return this.slashOpenListeners.add(e),()=>this.slashOpenListeners.delete(e)}openSlashCommands(){let e=this.store.getState(),t=e.activeSession.activeSessionId;t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.status===`saved`&&this.openSession(t):this.listModels();for(let e of this.slashOpenListeners)e()}applyRoute(e,t={}){e.kind===`session`?this.openSession(e.id,void 0,t):e.kind!==`settings`&&e.kind!==`automations`&&e.kind!==`library`&&e.kind!==`run`&&this.newSession(t)}applyInitialRoute(){let e=this.pendingRoute;if(!e)return;this.pendingRoute=null;let t=this.pendingRouteNode;this.pendingRouteNode=null,e.kind===`session`&&(t?this.openSessionOnNode(e.id,void 0,t):this.applyRoute(e,{navigate:!1}))}refreshAfterForeground(){this.foregroundTimer&&clearTimeout(this.foregroundTimer),this.foregroundTimer=setTimeout(()=>{if(this.foregroundTimer=null,this.needsSetup())return;let e=this.store.getState().connection.status;if(e===`offline`){this.connect();return}if(e!==`online`)return;this.refreshSessions();let t=this.store.getState().activeSession.activeSessionId;t?this.requestHistory(t):this.retryPendingSessionNew(),this.listModels(),this.verifyLiveness()},150)}static BACKGROUND_DISCONNECT_DELAY_MS=15e3;static LIVENESS_TIMEOUT_MS=2e3;verifyLiveness(){this.livenessTimer&&clearTimeout(this.livenessTimer),this.pendingLivenessPings.clear();let t=$();this.pendingLivenessPings.add(t),this.send({kind:`ping`,requestId:t}),this.livenessTimer=setTimeout(()=>{this.livenessTimer=null,this.store.getState().connection.status===`online`&&this.pendingLivenessPings.delete(t)&&this.transport.reconnect()},e.LIVENESS_TIMEOUT_MS)}async refreshNodes(){if(!this.direct&&this.signedIn){this.lastNodeRefreshAt=Date.now();try{let e=await this.listNodes();this.store.setNodes(e),this.local.cur&&!e.some(e=>e.id===this.local.cur)&&(this.currentNodeIsRebuildable()?this.markCurrentNodeAwaitingRebuild():this.clearCurrentNode()),this.refreshAccountSessions()}catch{}}}clearCurrentNode(){try{this.transport.close()}catch{}this.local.cur=``,this.store.setCurrentNode(null),this.store.resetSession(),this.store.setStatus(`offline`)}currentNodeIsRebuildable(){let e=this.local.cur;if(!e)return!1;try{if(!this.local.keys()[e])return!1}catch{return!1}return this.ephemeralCorrelations.some(t=>t.nodeId===e)}markCurrentNodeAwaitingRebuild(){if(this.store.getState().connection.status!==`offline`){try{this.transport.close()}catch{}this.store.setStatus(`offline`)}}lastNodeRefreshAt=0;refreshNodesThrottled(){!this.direct&&this.signedIn&&(Date.now()-this.lastNodeRefreshAt<1e4||this.refreshNodes())}pickDraftEphemeralRunner(e){this.store.setDraftEphemeralConfig(e),this.listModels()}switchNode(e){this.store.setDraftEphemeralConfig(null),this.nodeCoordinator.switchNode(e)}connectToNode(e,t){return this.nodeCoordinator.connectToNode(e,t)}async signOut(){this.nativeSubscriptionsStopped=!0,await Promise.allSettled([h(),c()]),this.nativeSubscriptionSyncToken=``,this.nativeSubscriptionSyncAt=0,this.sessionTitleKeys?.close(),this.machineRequests?.close();try{this.transport.close()}catch{}let e=this.local.device()?.pub;try{e=(await br(this.local)).pub}catch{}try{await Jn(this.local,e)}catch{}try{await _r()}catch{}await this.attachmentDiskCache.clear(),this.local.clear(),await m(),this.store.setSignedIn(!1),location.assign(`/`)}listDevices(){return Kn(this.local)}isCurrentDevice(e){return!!e&&this.local.device()?.pub===e}removeDevice(e){return qn(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:Ms()}:e)}updateNode(){so(this.store,()=>this.transport.send({kind:`node.update`}))}awaitAck(e,t=1e4){if(typeof e.sessionId==`string`&&this.isProvisionalSessionId(e.sessionId))return Promise.reject(Error(`Cloud startup hasn't created a conversation yet.`));let n=$();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingAcks.delete(n),i(Error(`Timed out waiting for the machine to respond.`))},t);this.pendingAcks.set(n,{resolve:r,reject:i,timer:a}),this.sendToCurrentNode({...e,requestId:n})})}fetchAttachment(e,t=0){if(!e)return Promise.resolve(null);let n=this.attachmentHomes.get(e),r=n&&n!==this.local.cur?n:null,i=r?`bivy.sessions.${r}`:this.sessionCacheKey();return this.attachmentLoader.fetch(JSON.stringify([i,e]),t,async()=>{let t=await this.attachmentDiskCache.get(i,e);if(t)return t;if(!r&&i!==this.sessionCacheKey())return null;let n={kind:`attachment.fetch`,hash:e},a=await(r?this.machineRequest(r,n,6e5):this.awaitAck(n,6e5));if(!a||typeof a.data!=`string`)return null;let o={mimeType:String(a.mimeType||`application/octet-stream`),data:a.data};return this.attachmentDiskCache.put(i,e,o),o})}async appCommand(e,t,n={},r){let{connection:i}=this.store.getState();e===`apps.open`&&Object.assign(n,{scale:typeof devicePixelRatio==`number`&&devicePixelRatio>=1.5?2:1});let a=this.isOtherMachine(r);if(!a&&i.status!==`online`)throw Error(`Connect to the machine to open its apps.`);let o=a?await this.machineRequest(r,{kind:e,sessionId:t,...n}):await this.awaitAck({kind:e,sessionId:t,...n},3e4);if(!a&&this.store.getState().connection.currentNodeId!==i.currentNodeId)throw Error(`Machine changed. Reopen Apps on the selected machine.`);let s=a?r:i.currentNodeId;if(e===`apps.list`&&s){for(let e of o.apps??[])for(let t of e.views)if(t.kind===`web`)for(let e of t.notes??[])e.shot&&this.attachmentHomes.set(e.shot.hash,s)}return o}async fileCommand(e,t,n){if(this.store.getState().connection.status!==`online`)throw Error(`Connect to the machine to browse its files.`);return this.awaitAck({kind:e,sessionId:t,path:n},3e4)}async listMachineArtifacts(){let e=await this.acrossMachines(`artifacts.list`,e=>e.artifacts??[]);for(let t of e.items)t.nodeId&&this.attachmentHomes.set(t.hash,t.nodeId);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}async listMachineApps(){let e=await this.acrossMachines(`apps.list`,e=>e.apps??[]);return e.items.sort((e,t)=>t.createdAt-e.createdAt),e}attachmentHomes=new Map;machineRequests;isOtherMachine(e){return!this.direct&&!!e&&e!==this.local.cur}machineRequest(e,t,n=3e4){return this.isOtherMachine(e)?(this.machineRequests??=new go(this.local,(e,t)=>new qr({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 Ns(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=Ps();this.store.addUserMessage(a,e),this.send({kind:`prompt`,sessionId:i,text:a,clientMessageId:e})}else this.openSession(i,t);return i}waitForOnline(e=2e4){return this.store.getState().connection.status===`online`?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{i(),n(Error(`Destination machine did not come online`))},e),i=this.store.subscribe(()=>{this.store.getState().connection.status===`online`&&(clearTimeout(r),i(),t())})})}promoteSession(e,t){return this.sessionCoordinator.promote(e,t)}forkInFlight=!1;startSessionLike(e,t,n){return this.sessionCoordinator.startLike(e,t,n)}async forkSession(e,t={},n){if(this.forkInFlight)throw Error(`A session fork is already in progress`);this.forkInFlight=!0,this.store.setForkProgress({status:`working`,message:`Preparing to fork the session…`});let r=this.store.getState(),i=r.sessionIndex.sessions.find(t=>t.sessionId===e),a=t.sourceAgentId||i?.runtimeId,o=t.agentId||a,s=(e,t)=>{let n=r.catalogs.runtimes.find(t=>t.id===e);return String(n?.displayName||n?.name||t||e||`agent`)},c=i?.name||`session ${e.slice(0,8)}`,l=s(a,i?.agentName),u=s(o,o===a?i?.agentName:void 0);try{await n?.();let r=await this.sessionCoordinator.fork(e,t);return this.store.getState().activeSession.activeSessionId!==r.sessionId&&this.openSession(r.sessionId,void 0,{navigate:!1}),await this.waitForForkReady(r.sessionId),X({kind:`session`,id:r.sessionId}),this.store.setNotice(`This session was forked from “${c}” with ${l} to ${u}.`),this.store.setForkProgress(null),r}catch(e){throw this.store.setForkProgress({status:`error`,message:e instanceof Error?e.message:String(e)}),e}finally{this.forkInFlight=!1}}waitForForkReady(e){let t=()=>{let t=this.store.getState().activeSession;return t.activeSessionId===e&&!t.opening};return t()?Promise.resolve():(this.store.setForkProgress({status:`working`,message:`Loading the forked session…`}),new Promise((e,n)=>{let r=setTimeout(()=>{i(),n(Error(`The fork was created, but its conversation could not be loaded. Reopen it from the session list.`))},3e4),i=this.store.subscribe(()=>{t()&&(clearTimeout(r),i(),e())})}))}refreshSessions(){if(this.send({kind:`terminal.list`}),!this.direct&&this.signedIn){this.refreshAccountSessions(),this.local.cur&&this.send({kind:`sessions.list`});return}this.send({kind:`sessions.list`})}async decryptSessionTitle(e){if(!e.titleEnc)return`Untitled session`;let t=this.local.keys()[e.nodeId];if(!t)return`Untitled session`;try{return(await O(await E(C(t)),e.titleEnc)).trim()||`Untitled session`}catch{return`Untitled session`}}sessionTitleKeys;async refreshAccountSessions(){if(!this.direct&&this.signedIn)try{let e=await Qt(this.local);this.sessionTitleKeys??=new po(this.local,(e,t)=>new qr({store:e,pairingOnly:!0,handlers:{onStatus:e=>{e===`online`&&t()},onEvent:()=>{}}}),()=>{this.refreshAccountSessions()}),this.sessionTitleKeys.ensure(e.filter(e=>e.titleEnc).map(e=>e.nodeId));let t=this.store.getState().sessionIndex.sessions,n=(await Promise.all(e.map(async e=>{let n=String(e.sessionId||e.id||``),r=String(e.nodeId||``),i=t.find(e=>e.sessionId===n&&(!e.nodeId||e.nodeId===r)),a=await this.decryptSessionTitle(e);return{...i,sessionId:n,nodeId:r,name:a===`Untitled session`&&i?.name||a,source:e.source||i?.source,branch:e.branch||i?.branch,status:e.status,attention:Array.isArray(e.attention)?e.attention:i?.attention,updatedAt:e.updatedAt||i?.updatedAt}}))).filter(e=>e.sessionId&&e.nodeId),r=new Set(n.map(e=>e.sessionId)),i=this.store.getState().sessionIndex.sessions,a=this.ephemeralCorrelations.filter(e=>!r.has(e.sessionId)&&!!this.local.keys()[e.nodeId]).map(e=>{let t=i.find(t=>t.sessionId===e.sessionId);return{...t,sessionId:e.sessionId,nodeId:e.nodeId,name:t?.name||(e.repo?`${e.repo}`:`Rebuildable session`),source:t?.source,status:`saved`,rebuildable:!0,updatedAt:t?.updatedAt}}),o=new Set([...this.pendingLaunches.values()].map(e=>e.sessionId));this.store.setSessions([...n,...a].filter(e=>!o.has(e.sessionId)))}catch{}}eventWithNodeScope(e){if(this.direct||!this.local.cur)return e;let t=this.local.cur;if(e.type===`sessions.list`){let n=e,r=Array.isArray(n.sessions)?n.sessions:[],i=new Set(r.map(e=>String(e?.sessionId||e?.id||``)).filter(Boolean)),a=this.store.getState().sessionIndex.sessions.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.sessionId));return{...e,sessions:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`session.created`)return{...e,nodeId:t};if(e.type===`terminal.list`){let n=e,r=Array.isArray(n.terminals)?n.terminals:[],i=new Set(r.map(e=>String(e?.termId||``)).filter(Boolean)),a=this.store.getState().sessionIndex.runTerminals.filter(e=>e.nodeId&&e.nodeId!==t&&!i.has(e.termId));return{...e,terminals:[...r.map(e=>({...e,nodeId:e.nodeId||t})),...a]}}if(e.type===`terminal.created`){let n=e;return n.terminal?{...e,terminal:{...n.terminal,nodeId:n.terminal.nodeId||t}}:e}return e}static DELETED_SESSIONS_KEY=`bivy.deleted-sessions`;restoreDeletedSessionTombstones(){try{let t=localStorage.getItem(e.DELETED_SESSIONS_KEY);t&&this.store.seedDeletedSessionTombstones(JSON.parse(t)),this.persistDeletedSessionTombstones()}catch{}}persistDeletedSessionTombstones(){try{let t=this.store.deletedSessionTombstones();Object.keys(t).length?localStorage.setItem(e.DELETED_SESSIONS_KEY,JSON.stringify(t)):localStorage.removeItem(e.DELETED_SESSIONS_KEY)}catch{}}sessionCacheKey(){return`bivy.sessions.${this.direct?`direct`:this.local.cur||``}`}seedSessionsFromCache(){if(this.direct||this.local.cur)try{let e=localStorage.getItem(this.sessionCacheKey());e&&this.store.seedSessions(JSON.parse(e))}catch{}}installSessionCachePersist(){if(typeof localStorage>`u`)return;let e=this.store.getState().sessionIndex.sessions;this.store.subscribe(()=>{let t=this.store.getState().sessionIndex.sessions;if(t!==e){e=t;try{localStorage.setItem(this.sessionCacheKey(),JSON.stringify(t.slice(0,100)))}catch{}}})}installFollowupAutoDrain(){let e=this.store.getState().activeSession.working,t=this.store.getState().activeSession.activeSessionId;this.store.subscribe(()=>{let n=this.store.getState().activeSession.activeSessionId,r=this.store.getState().activeSession.working,i=n!=null&&n===t&&e&&!r;e=r,t=n,i&&this.followupCoordinator.drain(n)})}async findLiveRunTerminal(e,t,n=4e3){let r=()=>this.store.getState().sessionIndex.runTerminals.find(n=>n.sessionId===e&&(!t||!n.nodeId||n.nodeId===t))??null;return r()||(this.direct||!t||t===this.local.cur&&this.store.getState().connection.status===`online`?null:(await this.connectToNode(t),this.send({kind:`terminal.list`}),new Promise(e=>{let t=setTimeout(()=>{i(),e(r())},n),i=this.store.subscribe(()=>{let n=r();n&&(clearTimeout(t),i(),e(n))})})))}selectSessionTarget(e){return this.promptTargetSessionId=e,this.sessionSelectionEpoch+=1,X({kind:`session`,id:e}),this.sessionSelectionEpoch}isCurrentSessionTarget(e,t){return this.promptTargetSessionId===e&&(t===void 0||t===this.sessionSelectionEpoch)}openSessionOnNode(e,t,n){if(this.selectSessionTarget(e),this.pendingLaunches.has(e)){this.openPendingLaunch(e);return}if(!this.direct&&n&&n!==this.local.cur){this.pendingCrossNodeOpen={sessionId:e,path:t},X({kind:`session`,id:e}),this.switchNode(n),this.store.beginOpen(e);return}this.openSession(e,t)}openSession(e,t,n={}){if(this.promptTargetSessionId=e,this.pendingLaunches.has(e)){this.openPendingLaunch(e,n);return}n.navigate!==!1&&X({kind:`session`,id:e}),this.store.beginOpen(e),this.send({kind:`session.open`,sessionId:e,path:t}),this.listModels(),this.seedAndRequestHistory(e)}async seedAndRequestHistory(e){try{let t=await this.transcriptCache.get(e);t&&this.store.getState().activeSession.activeSessionId===e&&(this.store.restoreAttachments(t.attachments),this.store.seedHistory(e,t.messages,t.count,t.historyHash))}catch{}this.requestHistory(e)}onReconnected(){let e=!1;if(this.pendingCrossNodeOpen){let t=this.pendingCrossNodeOpen;this.pendingCrossNodeOpen=null,this.openSession(t.sessionId,t.path),e=!0}this.refreshAccountSessions(),this.store.clearActivationReadiness(),this.syncingActivationCredentials=!0;let t=this.transportGeneration;this.syncAccountCredentialsWithNode().finally(()=>{t===this.transportGeneration&&(this.syncingActivationCredentials=!1,this.send({kind:`activation.readiness`}))}),this.resyncScheduledFollowups(),this.refreshEphemeralCorrelations(),e||this.applyInitialRoute();let n=this.store.getState().activeSession.activeSessionId;if(n&&!e?(this.requestHistory(n),this.listModels(),this.followupCoordinator.retrySending(n),this.drainPendingResume(n)):n||this.retryPendingSessionNew(),this.pendingGithubAppCode){let{code:e,state:t}=this.pendingGithubAppCode;this.pendingGithubAppCode=null,this.githubAppManifestCode(e,t)}}detectGithubAppReturn(){try{let e=new URLSearchParams(location.search),t=!1;try{t=sessionStorage.getItem(`bivy.githubAppPending`)===`1`,t&&sessionStorage.removeItem(`bivy.githubAppPending`)}catch{}if(!e.has(`bivy_github_app`)&&!t)return;let n=(e.get(`code`)||``).trim(),r=(e.get(`state`)||``).trim();e.delete(`bivy_github_app`),e.delete(`code`),e.delete(`state`);let i=e.toString();history.replaceState(null,``,location.pathname+(i?`?${i}`:``)+location.hash),n&&r?(this.pendingGithubAppCode={code:n,state:r},this.store.setGithubAppPhase(`completing`,{returning:!0,state:r})):this.store.setGithubAppPhase(`error`,{returning:!0,error:`GitHub did not return a code.`})}catch{}}requestHistory(e){let t=this.store.getHistoryCursor(e);this.send({kind:`history`,sessionId:e,...t})}draftSessionFields(){let e=this.store.getState(),t=e.catalogs.currentModel?{provider:e.catalogs.currentModel.provider,id:e.catalogs.currentModel.id}:void 0;return{repo:e.draft.repo||void 0,branch:e.draft.repo&&e.draft.branch||void 0,agent:e.catalogs.selectedAgentId||void 0,sandbox:e.draft.sandbox||void 0,acknowledgeReducedProtections:e.draft.acknowledgeReducedProtections||void 0,model:t}}getNodeSettings(){this.send({kind:`node.settings.get`})}setNodeSettings(e){return this.awaitAck({kind:`node.settings.set`,settings:e}).then(()=>void 0)}setSessionSandbox(e){this.store.setDraftSandbox(e)}acknowledgeSessionAgentReducedProtections(e){this.store.setDraftAcknowledgeReducedProtections(e)}newSession(e={}){let t=this.store.getState(),n=t.activeSession.activeSessionId?t.sessionIndex.sessions.find(e=>e.sessionId===t.activeSession.activeSessionId)?.nodeId??this.local.cur:this.local.cur,r=t.connection.nodes.find(e=>e.id===n)?.name??``,i=this.ephemeralCorrelations.find(e=>e.nodeId===n)?.setupId;this.sessionCoordinator.newSession(e),n?.startsWith(`eph-`)&&this.listEphemeralConfigs().then(e=>{let t=this.store.getState();if(t.activeSession.activeSessionId||t.draft.ephemeralConfig||this.local.cur!==n)return;let a=(i?e.find(e=>e.id===i):void 0)??(/^Hosted\s+/i.test(r)?e.find(e=>e.computeSource===`managed`):void 0);a&&this.pickDraftEphemeralRunner(a)}).catch(()=>{})}seedDraftDefaults(){let e=this.local.lastChoice();e.repo&&this.store.setDraftRepo(e.repo);let t=e.modelId?{provider:e.modelProvider,id:e.modelId}:null;this.store.setDraftModel(t),this.store.seedDraftAgentModel(e.agentId,t)}maybeRestoreDraftAgent(e){if(e.type!==`runtimes.list`)return;let t=this.store.getState();if(t.activeSession.activeSessionId)return;let n=this.local.lastChoice().agentId,r=n?t.catalogs.runtimes.find(e=>e.id===n):void 0;if(r&&n!==t.catalogs.selectedAgentId&&String(r.status||`available`)===`available`){this.chooseAgent(r);return}t.catalogs.selectedAgentId&&t.catalogs.modelsRuntimeId!==t.catalogs.selectedAgentId&&this.listModels()}sendPrompt(e,t,n){this.sessionCoordinator.sendPrompt(e,t,n),this.commitStagedPin(e)}stagedPin=null;stagePin(e){this.stagedPin={...e,at:Date.now()}}async commitStagedPin(e){let t=this.stagedPin;if(this.stagedPin=null,!(!t||Date.now()-t.at>6e5||!t.context||!e.includes(t.context)))try{await this.appCommand(`apps.pin`,t.sessionId,{appId:t.appId,viewId:t.viewId,words:e})}catch{}}async launchDraftRunnerAndBind(e){let t=this.pendingLaunches.get(e);if(!t)return;let{config:n}=t,r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};try{let i=t.prompt.frame&&`agent`in t.prompt.frame?String(t.prompt.frame.agent||``):``;if(this.store.updateLaunchCheckpoint(e,`capacity`,`active`),(!t.prompt.frame||!(`repo`in t.prompt.frame)||!t.prompt.frame.repo)&&this.store.updateLaunchCheckpoint(e,`repository`,`skipped`),n.computeSource===`managed`&&r(`Reserving secure managed compute…`),n.computeSource!==`managed`)throw Error(`This machine profile is no longer supported.`);let a=await qt(this.local,n.id,{runtimeId:i,requestId:e});if(this.store.updateLaunchCheckpoint(e,`account`,`done`),!a.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=a,t.phase=`booting`,t.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(t),this.store.bindPendingSessionNode(e,a.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 Wt&&r.code===`managed_credentials_required`?(this.store.updateLaunchCheckpoint(e,`capacity`,`waiting`),this.store.updateLaunchCheckpoint(e,`account`,`failed`,r.message,r.code)):r instanceof Wt&&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 Wt?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}failLaunchCheckpoint(e,t){let n=this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.launchProgress,r=[`account`,`capacity`,`machine`,`service`,`credentials`,`repository`,`agent`,`message`],i=[...r].reverse().find(e=>n?.checkpoints[e]?.state===`active`)??r.find(e=>!n?.checkpoints[e]||n.checkpoints[e]?.state===`waiting`)??`message`;this.store.updateLaunchCheckpoint(e,i,`failed`,t)}openPendingLaunch(e,t={}){let n=this.pendingLaunches.get(e);n&&(t.navigate!==!1&&X({kind:`session`,id:e}),this.store.beginOpen(e),this.store.addUserMessage(n.prompt.text,n.prompt.clientMessageId,n.prompt.attachments))}startPendingRunner(e){let t=this.pendingLaunches.get(e),n=t?.machine?.nodeId;if(!t||!n||t.transport)return;let r=e=>{t.logs.push(e),t.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(t)};r(`Machine accepted. Waiting for its secure Bivy service to come online…`),this.startBootProgress(n,e,r);let i=new Proxy(this.local,{get:(e,t,r)=>t===`cur`?n:Reflect.get(e,t,r),set:(e,t,n,r)=>t===`cur`||Reflect.set(e,t,n,r)}),a,o,s=()=>this.pendingLaunches.get(e)===t&&t.transport===a,c=!1,l=!1,u=()=>{if(c&&(l||t.config.computeSource!==`managed`)&&this.pendingLaunches.has(e)){let{model:e,...n}=t.prompt.frame;a.send(n)}};a=new qr({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?wt(o,t.models??[],t.config.computeSource===`managed`):void 0}))}return}if(n.type===`model.updated`&&n.sessionId===t.sessionId&&t.modelSelecting&&r?.id===t.modelSelecting.id&&r?.provider===t.modelSelecting.provider){t.modelSelecting=void 0,t.modelApproved=!0,this.store.setLaunchModelChoice(e,void 0),this.sendPendingLaunchPrompt(e,t.sessionId,a);return}if(n.type===`session.error`){this.failPendingLaunch(e,String(n.error||`Session creation failed.`));return}if(n.type===`session.history`&&n.requestId===t.prompt.requestId&&n.sessionId){t.prompt.frame&&`repo`in t.prompt.frame&&t.prompt.frame.repo&&this.store.updateLaunchCheckpoint(e,`repository`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`done`),t.sessionId=String(n.sessionId),t.modelApproved?this.sendPendingLaunchPrompt(e,t.sessionId,a):this.refreshLaunchModels(e);return}n.type===`session.user_message`&&(t.promptSent||t.promptSending)&&n.sessionId===t.sessionId&&n.clientMessageId===t.prompt.clientMessageId&&this.finishPendingLaunch(e,String(t.sessionId),a,()=>(o=this.buildTransportHandlers(),o),n)},onError:e=>{if(o){o.onError?.(e);return}s()&&(/^node offline$/i.test(e.trim())||r(`Connection retry: ${e}`))}}}),t.transport=a,this.pollBootstrapStatus(n,e,r,()=>{l=!0,u()}),a.connect()}refreshLaunchModels(e){let t=this.pendingLaunches.get(e);if(!t?.sessionId||!t.transport||t.modelApproved||t.modelSelecting)return;let n={};t.modelQuery=n,this.store.setLaunchModelChoice(e,{models:t.models??[],loading:!0});let r=()=>{this.pendingLaunches.get(e)===t&&t.modelQuery===n&&(t.modelQuery=void 0,this.store.setLaunchModelChoice(e,{models:t.models??[],error:`Couldn't load models from this machine. Refresh to try again; your prompt is still saved.`}))};setTimeout(r,15e3),Promise.resolve().then(()=>t.transport?.send({kind:`models.list`,sessionId:t.sessionId})).catch(r)}async chooseLaunchModel(e,t){let n=this.pendingLaunches.get(e);if(!n?.sessionId||!n.transport||n.modelSelecting||n.modelApproved||n.modelQuery)return;let r=n.models?.find(e=>e.id===t.id&&e.provider===t.provider);if(!r)return;let i={...r};n.modelSelecting=i,this.store.setLaunchModelChoice(e,{models:n.models??[],current:i,selecting:!0}),setTimeout(()=>{this.pendingLaunches.get(e)===n&&n.modelSelecting===i&&(n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Model selection wasn't confirmed. Refresh or choose again; your prompt is still saved.`}))},15e3);try{if(n.prompt.frame={...n.prompt.frame,model:{id:i.id,provider:String(i.provider)}},await this.pendingLaunchStore.put(n),this.pendingLaunches.get(e)!==n||n.modelSelecting!==i)return;await n.transport.send({kind:`model.select`,sessionId:n.sessionId,id:i.id,provider:i.provider})}catch{n.modelSelecting=void 0,this.store.setLaunchModelChoice(e,{models:n.models??[],error:`Couldn't select this model. Refresh and try again.`})}}async sendPendingLaunchPrompt(e,t,n){let r=this.pendingLaunches.get(e);if(r&&!r.promptSending&&r.modelApproved){this.store.updateLaunchCheckpoint(e,`message`,`active`),r.sessionId=t,r.promptSending=!0,this.store.getState().activeSession.activeSessionId===e&&this.store.pushSystemMessage(`Setup · Repository and agent are ready. Sending your prompt…`);try{if(await n.send({kind:`prompt`,sessionId:t,text:r.prompt.text,clientMessageId:r.prompt.clientMessageId,attachments:r.prompt.attachments}),!this.pendingLaunches.has(e))return;r.promptSent=!0,r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}catch(t){if(!this.pendingLaunches.has(e))return;r.logs.push(`First-message delivery retry: ${t?.message||t}`),r.updatedAt=new Date().toISOString(),await this.pendingLaunchStore.put(r)}finally{r.promptSending=!1,setTimeout(()=>{let r=this.pendingLaunches.get(e);r&&r.phase!==`failed`&&r.sessionId===t&&this.sendPendingLaunchPrompt(e,t,n)},3e3)}}}async finishPendingLaunch(e,t,n,r,i){let a=this.pendingLaunches.get(e),o=a?.machine?.nodeId;if(!a||!o)return;this.store.updateLaunchCheckpoint(e,`message`,`done`),this.clearBootProgress(o),this.pendingLaunches.delete(e),this.pendingLaunchStore.remove(e).catch(()=>{}),this.pendingPrompt?.provisionalId===e&&(this.pendingPrompt=null),this.store.completePendingSession(e,t,o);let s=this.store.getState().activeSession.activeSessionId===t;if(s){let e=r();this.transport.close(),this.local.cur=o,this.store.setCurrentNode(o),this.transport=n,this.pendingCrossNodeOpen={sessionId:t},X({kind:`session`,id:t}),this.store.setStatus(`connecting`),e.onStatus(`online`),e.onEvent(i),this.listRuntimes(),this.listProviders(),this.getNodeSettings()}for(let e of a.followups)await n.send({kind:`prompt`,sessionId:t,...e});s||setTimeout(()=>n.close(),1e3),setTimeout(()=>this.refreshSessions(),1500)}failPendingLaunch(e,t){let n=this.pendingLaunches.get(e);if(!n)return;n.machine?.nodeId&&this.clearBootProgress(n.machine.nodeId);let r=n.transport;n.transport=void 0,r?.close(),n.logs.push(`Startup failed: ${t}`),this.store.setLaunchModelChoice(e,void 0),n.modelQuery=void 0,n.modelSelecting=void 0,n.modelApproved=!1,n.phase=`failed`,n.updatedAt=new Date().toISOString(),this.pendingLaunchStore.put(n),/not available on this node|command not found|agent is not installed/i.test(t)?(this.store.updateLaunchCheckpoint(e,`credentials`,`done`),this.store.updateLaunchCheckpoint(e,`agent`,`failed`,t)):this.failLaunchCheckpoint(e,t),this.store.failPendingSession(e),this.store.setError(`Couldn't start ${n.config.name}: ${t}`)}startBootProgress(e,t,n){this.clearBootProgress(e);let r=[[15e3,`Booting the machine and installing Bivy…`],[45e3,`Still installing Bivy (45s elapsed). A first boot can take a few minutes…`],[9e4,`Still waiting for Bivy to join the secure relay (90s elapsed)…`],[18e4,`Boot is taking longer than usual (3 min elapsed). Still retrying…`],[Ls,`Still offline after ${Math.round(Ls/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 Bt(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 bn(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),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 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)){hn(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)){gn(this.local,e).then(t=>this.store.apply({type:`branches.list`,repo:e,branches:t})).catch(t=>this.store.apply({type:`branches.list`,repo:e,branches:[],error:String(t?.message||t)}));return}this.send({kind:`branches.list`,repo:e})}listRuntimes(){this.send({kind:`runtimes.list`})}requestCapabilities(){this.send({kind:`capabilities.get`})}cloudModelQuery=0;isCloudModelDraft(){let e=this.store.getState();return!e.activeSession.activeSessionId&&!this.direct&&!(!e.draft.ephemeralConfig&&this.local.cur)}async listCloudModels(){let e=++this.cloudModelQuery,t=this.store.getState(),n=t.draft.ephemeralConfig,r=t.catalogs.selectedAgentId,i=this.local.cur,a=t.catalogs.models,o=t.settings.credentialRecords;try{let[t,s]=await Promise.all([this.ephemeralKeys.modelKeyEntries(),this.ephemeralKeys.oauthCredentialEntries()]),c=this.store.getState();if(e!==this.cloudModelQuery||!this.isCloudModelDraft()||c.draft.ephemeralConfig!==n||c.catalogs.selectedAgentId!==r||this.local.cur!==i)return;let l=[...o.filter(e=>e.sync===`account`&&e.kind!==`reference`),...t.filter(e=>e.scope===`account`||n?.computeSource!==`managed`),...s].map(e=>e.provider);this.store.apply({type:`models.list`,runtimeId:r,models:Ct(l,a)})}catch{e===this.cloudModelQuery&&this.isCloudModelDraft()&&this.store.setError(`Couldn't load account models. Open the model picker to try again.`)}}listModels(){if(this.isCloudModelDraft()){this.listCloudModels();return}let e=this.store.getState(),t=e.activeSession.activeSessionId,n=t?e.sessionIndex.sessions.find(e=>e.sessionId===t)?.pendingLaunch===!0:!1,r=t&&!n?t:void 0,i=r?void 0:e.activeSession.activeRuntimeId??e.catalogs.selectedAgentId??void 0;this.send({kind:`models.list`,sessionId:r,runtimeId:i})}runtimeModelWaiters=new Map;modelsForRuntime(e,t=2e4){return new Promise(n=>{let r=e=>{clearTimeout(i),n(e)},i=setTimeout(()=>{let t=this.runtimeModelWaiters.get(e);t?.splice(t.indexOf(r)>>>0,1),n(this.store.cachedModelsFor(e)??[])},t);this.runtimeModelWaiters.set(e,[...this.runtimeModelWaiters.get(e)??[],r]),this.send({kind:`models.list`,runtimeId:e})})}settleRuntimeModels(e){let t=this.runtimeModelWaiters.get(e);if(!t?.length)return;let n=this.store.cachedModelsFor(e)??[];if(n.length){this.runtimeModelWaiters.delete(e);for(let e of t)e(n)}}prefetchModels(){if(this.store.getState().activeSession.activeSessionId)return;let e=this.store.getState().catalogs.runtimes.filter(e=>String(e.status||`available`)===`available`).map(e=>e.id);e.length&&this.send({kind:`models.prefetch`,runtimeIds:e})}chooseModel(e){let t=this.store.getState().activeSession.activeSessionId;if(t&&this.isProvisionalSessionId(t)){this.chooseLaunchModel(t,e);return}this.credentialsModelsCoordinator.selectModel(e,t)}setThinkingLevel(e){let t=this.store.getState().activeSession.activeSessionId??void 0;t&&this.isProvisionalSessionId(t)||(this.store.setThinkingLevel(e),this.send({kind:`thinking.set_level`,level:e,sessionId:t}))}chooseAgent(e,t){if(String(e.status||`available`)!==`available`&&e.install){this.installAgent(e.id);return}let n=this.store.getState(),r=n.activeSession.activeSessionId,i=n.activeSession.transcript.some(e=>e.role===`user`);if(r&&i){let i=n.activeSession.activeRuntimeId??n.sessionIndex.sessions.find(e=>e.sessionId===r)?.runtimeId;this.pendingPrompt=null,this.pendingFollowups=[],this.forkSession(r,{agentId:e.id,sourceAgentId:i,retireSource:!1},t).catch(e=>this.store.setError(e instanceof Error?e.message:String(e)));return}if(r&&(this.pendingPrompt=null,this.pendingFollowups=[],this.promptTargetSessionId=null,this.store.resetActiveSession(),X({kind:`new`})),this.store.setSelectedAgentLocal(e.id),this.local.setLastChoice({agentId:e.id}),this.isCloudModelDraft()){this.listModels();return}this.send({kind:`runtime.select`,id:e.id})}installAgent(e){this.pendingAgentPick=e,this.store.setInstalling(e),this.send({kind:`runtime.install`,id:e})}maybeSelectInstalledAgent(e){if(e.type===`runtime.install.error`&&e.id===this.pendingAgentPick){this.pendingAgentPick=null;return}if(e.type!==`runtime.install.done`||!this.pendingAgentPick||e.id!==this.pendingAgentPick)return;this.pendingAgentPick=null;let t=this.store.getState();if(t.activeSession.transcript.some(e=>e.role===`user`))return;let n=t.catalogs.runtimes.find(t=>t.id===e.id);n&&String(n.status||`available`)===`available`&&this.chooseAgent(n)}listProviders(){this.credentialsModelsCoordinator.listProviders()}getProviderAuth(e){this.credentialsModelsCoordinator.getProviderAuth(e)}saveApiKey(e,t){return this.credentialsModelsCoordinator.saveApiKey(e,t)}removeProvider(e){this.credentialsModelsCoordinator.removeProvider(e)}resetOauth(e){this.credentialsModelsCoordinator.resetOauth(e)}startOauth(e,t){this.credentialsModelsCoordinator.startOauth(e,t)}openOauthOnNode(e){return this.credentialsModelsCoordinator.openOauthOnNode(e)}submitOauthCode(e,t){this.credentialsModelsCoordinator.submitOauthCode(e,t)}listCredentialRecords(){this.credentialsModelsCoordinator.listCredentials()}async previewNativeCredentials(e,t){return await this.nativeCredentialCommand(e,{kind:`credentials.native.preview`,label:t})}async importNativeCredentials(e,t,n,r){return await this.nativeCredentialCommand(e,{kind:`credentials.native.import`,previewId:t,agents:n,sync:r})}async nativeCredentialCommand(e,t){let n=this.store.getState().connection;if(n.status!==`online`||n.currentNodeId!==e)throw Error(`Connect to the selected machine before scanning or importing.`);let r=await this.awaitAck(t,2e4);if(this.store.getState().connection.currentNodeId!==e)throw Error(`Machine changed. Scan again on the selected machine.`);return r}syncAccountCredentialsWithNode(){return this.credentialsModelsCoordinator.syncAccountCredentials()}setCredential(e,t,n){return this.credentialsModelsCoordinator.setCredential(e,t,n)}removeCredential(e,t){return this.credentialsModelsCoordinator.removeCredential(e,t)}setCredentialSync(e,t,n){return this.credentialsModelsCoordinator.setCredentialSync(e,t,n)}testCredential(e,t){return this.credentialsModelsCoordinator.testCredential(e,t)}getCredentialPresets(){this.credentialsModelsCoordinator.getPresets()}setActivePreset(e){this.credentialsModelsCoordinator.setActivePreset(e)}setPresetMapping(e,t,n){return this.credentialsModelsCoordinator.setPresetMapping(e,t,n)}listLocalModels(){this.credentialsModelsCoordinator.listLocalModels()}listLocalModelPresets(){this.credentialsModelsCoordinator.listLocalModelPresets()}discoverLocalModels(){return this.credentialsModelsCoordinator.discoverLocalModels()}verifyLocalModel(e,t){return this.credentialsModelsCoordinator.verifyLocalModel(e,t)}saveLocalModel(e){return this.credentialsModelsCoordinator.saveLocalModel(e)}removeLocalModel(e){this.credentialsModelsCoordinator.removeLocalModel(e)}listRulesets(){this.send({kind:`rulesets.list`})}saveRuleset(e,t){return this.awaitAck({kind:`rulesets.save`,ruleset:e,active:t}).then(()=>void 0)}removeRuleset(e){this.send({kind:`rulesets.remove`,name:e})}getSttConfig(){this.send({kind:`stt.config.get`})}setSttProvider(e){this.send({kind:`stt.config.set`,provider:e})}saveSttKey(e,t){return this.awaitAck({kind:`stt.config.set`,setKey:{provider:e,value:t}}).then(()=>void 0)}removeSttKey(e){this.send({kind:`stt.config.set`,removeKey:e})}transcribe(e,t){let n=$();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingTranscriptions.delete(n),i(Error(`Transcription timed out. Check your connection and try again.`))},6e4);this.pendingTranscriptions.set(n,{resolve:r,reject:i,timer:a}),this.transport.send({kind:`transcribe`,requestId:n,audio:e,mimeType:t})})}resolveTranscription(e){let t=String(e.requestId||``),n=t?this.pendingTranscriptions.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingTranscriptions.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve(String(e.text??``).trim())}synthesize(e,t,n){let r=$();return new Promise((i,a)=>{let o=setTimeout(()=>{this.pendingSpeech.delete(r),a(Error(`Speech generation timed out. Check your connection and try again.`))},6e4);this.pendingSpeech.set(r,{resolve:i,reject:a,timer:o}),this.transport.send({kind:`synthesize`,requestId:r,text:e,voice:t,instructions:n})})}resolveSpeech(e){let t=String(e.requestId||``),n=t?this.pendingSpeech.get(t):void 0;if(!n)return;clearTimeout(n.timer),this.pendingSpeech.delete(t);let r=e.error;r?n.reject(Error(String(r))):n.resolve({audio:String(e.audio??``),mimeType:String(e.mimeType??`audio/mpeg`)})}githubAppManifestStart(e){this.store.setGithubAppPhase(`starting`),this.send({kind:`github.app.manifest.start`,requestId:$(),origin:d(),org:e||void 0})}githubAppManifestCode(e,t){this.store.setGithubAppPhase(`completing`),this.send({kind:`github.app.manifest.code`,requestId:$(),code:e,state:t})}async githubAppConnectExisting(e){this.store.setGithubAppPhase(`completing`);try{await this.awaitAck({kind:`github.app.connect-existing`,appId:e.appId,privateKeyPem:e.privateKeyPem,nodeLabel:e.nodeLabel||void 0},6e4)}catch(e){throw this.store.setGithubAppPhase(`error`,{error:e instanceof Error?e.message:String(e),returning:!1}),e}}connectHostedGithubApp(e){return mn(this.local,e)}fetchMe(){return this.accountCoordinator.fetchMe()}deleteAccount(){return en(this.local)}invokeAccountExtensionAction(e){return u()?tn(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=lr();deviceOAuthCredentials=cr();ephemeralKeys=Pr({local:sr(),modelKeys:this.ephemeralModelKeys,oauthCredentials:this.deviceOAuthCredentials,oauthRecoveryEnabled:()=>this.oauthRecoveryEnabled(),remote:this.deviceVaultRemote(),device:()=>br(this.local),enabled:()=>!this.direct&&!!this.local.s,providerTokenSyncEnabled:()=>!this.direct&&!!this.local.s,state:{load:async()=>{try{return JSON.parse(localStorage.getItem(`bivy_device_vault_state`)||`null`)??void 0}catch{return}},save:async e=>{try{localStorage.setItem(`bivy_device_vault_state`,JSON.stringify(e))}catch{}}}});pendingLaunchStore=ur();listEphemeralModelKeys(){return this.ephemeralKeys.listModelKeys()}setEphemeralModelKey(e,t,n=`account`,r=`default`){return this.ephemeralKeys.setModelKey(e,t,n,r)}removeEphemeralModelKey(e,t=`default`){return this.ephemeralKeys.removeModelKey(e,t)}oauthRecoveryEnabled(){try{return!this.direct&&!!this.local.s&&localStorage.getItem(`bivy_oauth_browser_recovery`)===`1`}catch{return!1}}getOAuthBrowserRecovery(){return this.oauthRecoveryEnabled()}async setOAuthBrowserRecovery(e){if(this.direct)throw Error(`OAuth browser recovery requires a signed-in account`);if(!e)for(let e of await this.ephemeralKeys.oauthCredentialEntries())await this.ephemeralKeys.removeOAuthCredential(e.provider,e.label);try{localStorage.setItem(`bivy_oauth_browser_recovery`,e?`1`:`0`)}catch{}e&&await this.syncAccountCredentialsWithNode()}syncDeviceVault(){return this.ephemeralKeys.sync()}getDeviceVaultSyncState(){return this.ephemeralKeys.getSyncState()}deviceVaultRemote(){let e=()=>(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),t=()=>({authorization:`Bearer ${this.local.s}`,"content-type":`application/json`});return{get:async()=>{let t=await br(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 br(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 Tr;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 br(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})`)}}}dismissModelAuthPrompt(){this.store.setNeedsModelAuth(null)}correlationApi(){return{base:(this.local.cp||(typeof location<`u`?location.origin:``)).replace(/\/$/,``),auth:{authorization:`Bearer ${this.local.s}`,"content-type":`application/json`}}}async refreshEphemeralCorrelations(){if(!this.direct&&this.local.s)try{let{base:e,auth:t}=this.correlationApi(),n=await fetch(`${e}/session-correlation`,{headers:{authorization:t.authorization}});if(!n.ok)return;let r=await n.json();Array.isArray(r.correlations)&&(this.ephemeralCorrelations=r.correlations)}catch{}}reprovisionEphemeral(e,t){return this.ephemeralCoordinator.reprovision(e,t)}isCurrentNodeResumable(){return this.ephemeralCoordinator.isCurrentNodeResumable()}shouldAutoResume(){return this.store.getState().connection.status!==`online`&&this.isCurrentNodeResumable()&&!this.resumingNode.has(this.local.cur)}async resumeNodeForSession(e){let t=this.local.cur;if(t&&!this.resumingNode.has(t)){this.resumingNode.add(t);try{await this.reprovisionEphemeral(t,e)}finally{this.resumingNode.delete(t)}}}drainPendingResume(e){let t=this.pendingResume.filter(t=>t.sessionId===e);if(t.length){this.pendingResume=this.pendingResume.filter(t=>t.sessionId!==e);for(let n of t)this.send({kind:`prompt`,sessionId:e,text:n.text,clientMessageId:n.clientMessageId,attachments:n.attachments})}}listEphemeralConfigs(){return this.ephemeralCoordinator.listConfigs()}getQueueRouting(){return fn(this.local)}setQueueRouting(e){return pn(this.local,e)}setHostedProvisioning(e){return yn(this.local,e)}listHostedMachines(){return bn(this.local)}destroyHostedMachine(e){return xn(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||!Ft(this.local,e)?!1:(this.store.setSignedIn(this.signedIn),this.switchNode(this.local.cur),this.refreshNodes(),!0)}reconcileSessionList(e){switch(String(e.type||``)){case`session.renamed`:case`session.branch_renamed`:case`session.closed`:this.refreshSessions();return;case`session.deleted`:e.sessionId&&this.transcriptCache.delete(e.sessionId),this.refreshSessions();return;default:return}}maybeRefreshModelsForRuntime(e){let t=this.store.getState(),n=e.type===`session.history`&&!!e.sessionId&&e.sessionId===t.activeSession.activeSessionId&&!t.catalogs.currentModel;(e.type===`runtime.updated`||n)&&this.listModels()}retryPendingSessionNew(){!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||this.store.getState().activeSession.activeSessionId||this.send(this.pendingPrompt.frame)}maybeFlushPendingPrompt(e){if(!this.pendingPrompt||this.pendingPrompt.provisionalId||[...this.pendingLaunches.values()].some(e=>e.prompt.requestId===this.pendingPrompt?.requestId)||e.type!==`session.history`||e.requestId!==this.pendingPrompt.requestId)return;let t=e.sessionId||this.store.getState().activeSession.activeSessionId;if(!t)return;X({kind:`session`,id:t},{replace:!0});let{text:n,clientMessageId:r,attachments:i}=this.pendingPrompt;this.pendingPrompt=null,this.send({kind:`prompt`,sessionId:t,text:n,clientMessageId:r,attachments:i});let a=this.pendingFollowups;this.pendingFollowups=[];for(let e of a)this.send({kind:`prompt`,sessionId:t,text:e.text,clientMessageId:e.clientMessageId,attachments:e.attachments});this.refreshSessions()}abort(){let e=this.store.getState().activeSession.activeSessionId;e&&this.send({kind:`abort`,sessionId:e})}resolveTurnAttention(e,t){this.send({kind:`session.turn_attention.resolve`,sessionId:e,action:t})}setLimitRetry(e){let t=this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.limit_retry`,sessionId:t,enabled:e})}accountMode(){return!!(this.local.s&&this.local.cp)}resolveSessionNodeId(e){return this.store.getState().sessionIndex.sessions.find(t=>t.sessionId===e)?.nodeId}resolveNodeLabel(e){let t=this.store.getState().connection.nodes.find(t=>t.id===e);return t?.name?`bivy/${t.name}`:void 0}async persistScheduledFollowup(e,t,n){if(!this.accountMode()||!n)return;let r=this.resolveSessionNodeId(e);if(!r)return;let i=this.local.keys()[r];if(i)try{let a=await D(await E(C(i)),n),o=new Date(Date.now()+6e4).toISOString(),s=await Cn(this.local,{name:`Follow-up`,templateCiphertext:`${Is}:${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&&Dn(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 Tn(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 Sn(this.local)}catch{return}let t=new Set(e.filter(e=>e.enabled&&e.nextRunAt!=null).map(e=>e.id));for(let e of Object.keys(this.store.getState().sessionIndex.followupsBySession))this.store.pruneScheduledFollowups(e,t)}supportsSteering(){return this.followupCoordinator.supportsSteering()}getFollowups(e){return this.followupCoordinator.list(e)}editFollowup(e,t,n,r){return this.followupCoordinator.edit(e,t,n,r)}removeFollowup(e,t){return this.followupCoordinator.remove(e,t)}reorderFollowup(e,t,n){return this.followupCoordinator.reorder(e,t,n)}sendFollowupNow(e,t){this.followupCoordinator.sendNow(e,t)}steerNow(e,t){return this.followupCoordinator.steer(e,t)}renameSession(e,t){let n=t.trim();n&&(e===this.store.getState().activeSession.activeSessionId&&this.store.setActiveTitle(n),this.store.renameSessionLocal(e,n),this.send({kind:`session.rename`,sessionId:e,name:n}),this.refreshSessions())}async deleteSession(e,t){if(this.isProvisionalSessionId(e)&&(await this.pendingLaunchRestoration,this.pendingLaunches.has(e))){await this.dismissPendingLaunch(e);return}let n=this.ephemeralCorrelations.find(t=>t.sessionId===e),r=n&&this.store.getState().connection.nodes.some(e=>e.id===n.nodeId&&e.online);if(!this.direct&&n&&!r){await this.deleteRetiredSession(e);return}this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.sessionCoordinator.deleteSession(e,t)}async deleteRetiredSession(e){try{let{base:t,auth:n}=this.correlationApi();if(!(await fetch(`${t}/session-correlation/${encodeURIComponent(e)}`,{method:`DELETE`,headers:n,signal:AbortSignal.timeout(15e3)})).ok)throw Error(`Couldn't delete the retired session. Refresh and try again.`);this.ephemeralCorrelations=this.ephemeralCorrelations.filter(t=>t.sessionId!==e),this.promptTargetSessionId===e&&(this.promptTargetSessionId=null),this.store.getState().activeSession.activeSessionId===e&&(this.store.resetActiveSession(),X({kind:`new`})),this.store.removeSessionLocal(e),this.persistDeletedSessionTombstones(),await this.transcriptCache.delete(e),this.refreshSessions()}catch(e){this.store.setError(e instanceof Error?e.message:`Couldn't delete the retired session.`)}}pauseSession(e){this.sessionCoordinator.pauseSession(e)}resumeSession(e){this.sessionCoordinator.resumeSession(e)}refreshPrStatus(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.pr.refresh`,sessionId:t})}refreshAllPrStatus(){this.send({kind:`sessions.pr.refresh_all`})}rewind(e,t){let n=t||this.store.getState().activeSession.activeSessionId;n&&e&&this.send({kind:`session.rewind`,sessionId:n,checkpointId:e})}revertFile(e,t,n){let r=n||this.store.getState().activeSession.activeSessionId;r&&e&&this.send({kind:`session.revert_file`,sessionId:r,path:e,content:t})}listCheckpoints(e){let t=e||this.store.getState().activeSession.activeSessionId;t&&this.send({kind:`session.checkpoints`,sessionId:t})}resolveApproval(e,t,n=!1){this.send({kind:`approval`,id:e,approved:t,...t&&n?{remember:!0}:{}}),this.direct||Nn(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||Nn(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||Nn(this.local,`remote_intervention`,matchMedia(`(max-width: 700px)`).matches?`mobile`:`desktop`).catch(()=>{})}},Bs=g();function Vs({tone:e,variant:t=`outline`,upper:n=!1,className:r=``,children:i,...a}){return(0,Bs.jsx)(`span`,{className:`badge${n?` upper`:``}${r?` ${r}`:``}`,"data-tone":e,"data-variant":t,...a,children:i})}function Hs(){return(0,y.useSyncExternalStore)(zs.store.subscribe,zs.store.getState)}export{Sn as $,Va as A,v as At,ci as B,zo as C,ve as Ct,Io as D,O as Dt,Fo as E,E as Et,pi as F,Vn as G,jn as H,xi as I,Gn as J,Cn as K,ai as L,Yi as M,Ci as N,wo as O,D as Ot,Si as P,An as Q,li as R,ps as S,Ie as St,X as T,be as Tt,Pn as U,Nt as V,Wn as W,Bt as X,Hn as Y,Mn as Z,as as _,vt as _t,Ms as a,Pt as at,is as b,Je as bt,Cs as c,Fn as ct,gs as d,En as dt,an as et,ds as f,Rt as ft,fs as g,bt as gt,ss as h,Ot as ht,zs as i,It as it,ma as j,Eo as k,C as kt,ms as l,wn as lt,ts as m,Tn as mt,Vs as n,Un as nt,Ss as o,zt as ot,rs as p,Lt as pt,Dn as q,Ns as r,Bn as rt,ws as s,Nn as st,Hs as t,vn as tt,cs as u,On as ut,ls as v,pt as vt,Ro as w,me as wt,ns as x,Ge as xt,os as y,Xe as yt,si as z};