pi-outpost 0.43.0 → 0.44.0

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 (99) hide show
  1. package/dist/contract/validate-structured-exchange.mjs +1 -1
  2. package/dist/pi-outpost.mjs +670 -557
  3. package/dist/pi-outpost.sea.mjs +2 -2
  4. package/dist/sea-prep.blob +2 -2
  5. package/dist/web/assets/{CodeEditor-B123NBEk.js → CodeEditor-DrXTrob5.js} +2 -2
  6. package/dist/web/assets/{PdfViewer-CvlaA88J.js → PdfViewer-CKkstSlI.js} +2 -2
  7. package/dist/web/assets/{abnfDiagram-WEYOIA3C-DJT_Ic7m.js → abnfDiagram-WEYOIA3C-BMPw9qSy.js} +1 -1
  8. package/dist/web/assets/{architecture-WOLXFQ4H-1X6UB03L.js → architecture-WOLXFQ4H-C9efllvE.js} +1 -1
  9. package/dist/web/assets/{architectureDiagram-ZHVYKT53-DtAcdgDf.js → architectureDiagram-ZHVYKT53-tyrWhugO.js} +1 -1
  10. package/dist/web/assets/{blockDiagram-RJAE7QA3-LwDn-ru7.js → blockDiagram-RJAE7QA3-BvhwNFuo.js} +1 -1
  11. package/dist/web/assets/{c4Diagram-XDPPPE54-HoGbXw41.js → c4Diagram-XDPPPE54-CYTCmqwG.js} +1 -1
  12. package/dist/web/assets/channel-lJvkhanb.js +1 -0
  13. package/dist/web/assets/{chunk-2E7WHVMD-CgiRHuHp.js → chunk-2E7WHVMD-DfvNQ7zk.js} +1 -1
  14. package/dist/web/assets/{chunk-4EMNKR2T-DMtN1wk6.js → chunk-4EMNKR2T-B77UmEya.js} +1 -1
  15. package/dist/web/assets/{chunk-55XCU76K-Cs2Iijw1.js → chunk-55XCU76K-SXrPsvEy.js} +1 -1
  16. package/dist/web/assets/{chunk-7S6XSTFO-Je4Wj9Rr.js → chunk-7S6XSTFO-DyqsoUUs.js} +1 -1
  17. package/dist/web/assets/{chunk-AQDTSKZB-C8GB_Ui_.js → chunk-AQDTSKZB-DSe0lG0z.js} +1 -1
  18. package/dist/web/assets/{chunk-DSNLSHJZ-DaRLU1qt.js → chunk-DSNLSHJZ-6b70YpkQ.js} +3 -3
  19. package/dist/web/assets/{chunk-HAGFOTED-D-D65AyF.js → chunk-HAGFOTED-YGDsk_ng.js} +1 -1
  20. package/dist/web/assets/{chunk-HNE4Q36P-BwNe1j6O.js → chunk-HNE4Q36P-CYfBi-8I.js} +1 -1
  21. package/dist/web/assets/{chunk-NQOKRVIF-L8-NQaTk.js → chunk-NQOKRVIF-ezhi5MLZ.js} +1 -1
  22. package/dist/web/assets/{chunk-UHW7PFBP-HDXbOEZI.js → chunk-UHW7PFBP-BiEM0DeV.js} +1 -1
  23. package/dist/web/assets/{chunk-VQ5W62QI-ekymdHY7.js → chunk-VQ5W62QI-Byhs-p2L.js} +1 -1
  24. package/dist/web/assets/{chunk-WQQL4CDK-CvUSO1KH.js → chunk-WQQL4CDK-BhjGwd43.js} +1 -1
  25. package/dist/web/assets/{chunk-YZO67HFG-CjeirPb6.js → chunk-YZO67HFG-DM-i_t3H.js} +1 -1
  26. package/dist/web/assets/{chunk-ZAUX2LTX-cTNIHs1b.js → chunk-ZAUX2LTX-Bm3Uc7GI.js} +1 -1
  27. package/dist/web/assets/{chunk-ZCHMQSOR-CDrGWvIC.js → chunk-ZCHMQSOR-D0CF4Y5q.js} +1 -1
  28. package/dist/web/assets/{classDiagram-v2-4MYWR3UA-C1S0UW8z.js → classDiagram-v2-4MYWR3UA-DIp-A-bH.js} +1 -1
  29. package/dist/web/assets/{conversationExport-jN-MYzY9.js → conversationExport-ew4uMgY-.js} +1 -1
  30. package/dist/web/assets/{cynefin-EF2NZ3EQ-BsGJ6FOt.js → cynefin-EF2NZ3EQ-DEqwJh-m.js} +1 -1
  31. package/dist/web/assets/{cynefinDiagram-WF24UDRP-qfjwnjVR.js → cynefinDiagram-WF24UDRP-B2_YsgbY.js} +1 -1
  32. package/dist/web/assets/{dagre-NK4GIZVX-3mDxlBxx.js → dagre-NK4GIZVX-CP5T5-OL.js} +1 -1
  33. package/dist/web/assets/{diagram-CBK3MWTC-CFOomBRX.js → diagram-CBK3MWTC-25gQp8xi.js} +1 -1
  34. package/dist/web/assets/{diagram-I5XIIV2D-B42chBq4.js → diagram-I5XIIV2D-DDeiTymO.js} +1 -1
  35. package/dist/web/assets/{diagram-ODIL2UCW-DPHTNf2y.js → diagram-ODIL2UCW-C9x9px0W.js} +1 -1
  36. package/dist/web/assets/{diagram-PFBEJUXE-BWAna7eo.js → diagram-PFBEJUXE-Bj8QzC75.js} +1 -1
  37. package/dist/web/assets/{diagram-RJA3I4VV-C9scCIzU.js → diagram-RJA3I4VV-CHCttOa6.js} +1 -1
  38. package/dist/web/assets/{diagram-TYUNFSNR-C7NO-Ebj.js → diagram-TYUNFSNR-BJIxOIM0.js} +1 -1
  39. package/dist/web/assets/{dist-DhU_QeGu.js → dist-BIDv_v9w.js} +1 -1
  40. package/dist/web/assets/{dist-B5P2_Wxl.js → dist-CSfql6lx.js} +1 -1
  41. package/dist/web/assets/{dist-BN_neRHz.js → dist-CVM3cF88.js} +1 -1
  42. package/dist/web/assets/{dist-CPiugJt4.js → dist-Depi-PS1.js} +1 -1
  43. package/dist/web/assets/{dist-CeyFaRuq.js → dist-DmTkB365.js} +1 -1
  44. package/dist/web/assets/{dist-nSu4Hl9U.js → dist-Dmki7L_A.js} +1 -1
  45. package/dist/web/assets/{dist-CpBfDDqU.js → dist-OdCumL08.js} +1 -1
  46. package/dist/web/assets/{docxExport-DTdmyOrq.js → docxExport-ButYIRWK.js} +1 -1
  47. package/dist/web/assets/{ebnfDiagram-V4P3TTPT-CKVJPcOo.js → ebnfDiagram-V4P3TTPT-DzpZ_Qfa.js} +1 -1
  48. package/dist/web/assets/{elk-QONTBCTQ-Bjpp_hUm.js → elk-QONTBCTQ-DpIODhoo.js} +1 -1
  49. package/dist/web/assets/{erDiagram-KYQIGQAA-ahXNOH2j.js → erDiagram-KYQIGQAA-CRuO12zS.js} +1 -1
  50. package/dist/web/assets/{eventmodeling-K75KTNOO-DFuS5JWb.js → eventmodeling-K75KTNOO-CtYiNkCf.js} +1 -1
  51. package/dist/web/assets/flowDiagram-IUGLLWBU-DxsAdbMQ.js +1 -0
  52. package/dist/web/assets/{ganttDiagram-R7GPNTJY-CUF0vHKX.js → ganttDiagram-R7GPNTJY-D-gj2q4G.js} +1 -1
  53. package/dist/web/assets/{gitGraph-VSP46ZUC-BuhP1sw9.js → gitGraph-VSP46ZUC-Bb7DEUb5.js} +1 -1
  54. package/dist/web/assets/{gitGraphDiagram-PDYL7XHY-mwsEay51.js → gitGraphDiagram-PDYL7XHY-CZjEb9YQ.js} +1 -1
  55. package/dist/web/assets/{index-B56c-g9j.js → index-C19jc-P5.js} +24 -24
  56. package/dist/web/assets/index-Ch818Mrd.css +2 -0
  57. package/dist/web/assets/{info-OHQRW6UA-DPDtdGUp.js → info-OHQRW6UA-BiuRqWZW.js} +1 -1
  58. package/dist/web/assets/{infoDiagram-MVDRKAX5-DX6YZ_rL.js → infoDiagram-MVDRKAX5-C8rRY53v.js} +1 -1
  59. package/dist/web/assets/{ishikawaDiagram-HPEHV2GE-atu1SIZJ.js → ishikawaDiagram-HPEHV2GE-CNccUc-H.js} +1 -1
  60. package/dist/web/assets/{journeyDiagram-BOSHW7O7-cgcHl15d.js → journeyDiagram-BOSHW7O7-DZ_zqfcG.js} +1 -1
  61. package/dist/web/assets/{kanban-definition-FNSA4HC5-wHlf1Ksj.js → kanban-definition-FNSA4HC5-CRrdKQZ4.js} +1 -1
  62. package/dist/web/assets/{line-DbL7nSAS.js → line-SDUIsevL.js} +1 -1
  63. package/dist/web/assets/{loadReferencedImage-CzNYo1b1.js → loadReferencedImage-DgPSViBj.js} +1 -1
  64. package/dist/web/assets/{mermaid-parser.core-D-w11H_2.js → mermaid-parser.core-B9OsUm1E.js} +3 -3
  65. package/dist/web/assets/{mermaid.core-CzmHcBmx.js → mermaid.core-oMdyM7QA.js} +4 -4
  66. package/dist/web/assets/{mermaidToImage-Hjyav5KM.js → mermaidToImage-CMYk5EZ9.js} +3 -3
  67. package/dist/web/assets/{mindmap-definition-6OY57UG3-CENIwM-L.js → mindmap-definition-6OY57UG3-VpKar2xk.js} +1 -1
  68. package/dist/web/assets/{packet-JDAUHWVQ-jKce2Koi.js → packet-JDAUHWVQ-CnEeuOFS.js} +1 -1
  69. package/dist/web/assets/{pdf-DqL0VQOW.js → pdf-D7HW9_AD.js} +1 -1
  70. package/dist/web/assets/{pegDiagram-ECIUJNBX-CGOM8vu4.js → pegDiagram-ECIUJNBX-DSVspgUz.js} +1 -1
  71. package/dist/web/assets/{pie-XZMESJXO-B5yMqhIx.js → pie-XZMESJXO-DhlX_fEq.js} +1 -1
  72. package/dist/web/assets/{pieDiagram-GNMPY74T-VIPVJFkC.js → pieDiagram-GNMPY74T-DcCCg1jH.js} +1 -1
  73. package/dist/web/assets/{quadrantDiagram-D57K4MC3-Bhcw441k.js → quadrantDiagram-D57K4MC3-BYmwUhXj.js} +1 -1
  74. package/dist/web/assets/{radar-ABXABTNO-GySynPpW.js → radar-ABXABTNO-KBbrGw9T.js} +1 -1
  75. package/dist/web/assets/{railroad-I3PHUGI6-Er78o-E7.js → railroad-I3PHUGI6-C2nOdCHp.js} +1 -1
  76. package/dist/web/assets/{railroad-abnf-LNEFI6M7-CmRixQEB.js → railroad-abnf-LNEFI6M7-_DZ2CaHL.js} +1 -1
  77. package/dist/web/assets/{railroad-ebnf-DWYD2UWJ-TpIgAYZi.js → railroad-ebnf-DWYD2UWJ-Djkrn3gF.js} +1 -1
  78. package/dist/web/assets/{railroad-peg-JR7BVNR7-BYBFcRhP.js → railroad-peg-JR7BVNR7-LPbLPuo-.js} +1 -1
  79. package/dist/web/assets/{railroadDiagram-Y72NRBL7-C49UsCkt.js → railroadDiagram-Y72NRBL7-DUl--5rO.js} +1 -1
  80. package/dist/web/assets/{requirementDiagram-EQYSW5RA-C-Ot8mK5.js → requirementDiagram-EQYSW5RA-DDoDZc1t.js} +1 -1
  81. package/dist/web/assets/{sankeyDiagram-SY24JHO5-BbgF5ilv.js → sankeyDiagram-SY24JHO5-Ch2rGHOZ.js} +1 -1
  82. package/dist/web/assets/{sequenceDiagram-BLEHNHQU-BeKw8Gmx.js → sequenceDiagram-BLEHNHQU-BKY6MDSt.js} +1 -1
  83. package/dist/web/assets/{stateDiagram-v2-A6IESKWZ-dOQPr6MB.js → stateDiagram-v2-A6IESKWZ-D2Hm09Pz.js} +1 -1
  84. package/dist/web/assets/{swimlanes-B3ENRKFQ-CE-O5FAt.js → swimlanes-B3ENRKFQ-BORgWBjS.js} +1 -1
  85. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-DQBo8bWi.js +8 -0
  86. package/dist/web/assets/{timeline-definition-JXYKGLGB-BRmnUVft.js → timeline-definition-JXYKGLGB-BdWT8knP.js} +1 -1
  87. package/dist/web/assets/{treeView-D4JQ5SDB-qrcJIxSz.js → treeView-D4JQ5SDB-BCvhCO9W.js} +1 -1
  88. package/dist/web/assets/{treemap-SAJKECNS-wbrhe8YH.js → treemap-SAJKECNS-rHZw2tP_.js} +1 -1
  89. package/dist/web/assets/{usecaseDiagram-WPOLBNNX-DnxJ8olM.js → usecaseDiagram-WPOLBNNX-D46t8FL9.js} +1 -1
  90. package/dist/web/assets/{vennDiagram-Q3Y3IDCW-hBXedDkZ.js → vennDiagram-Q3Y3IDCW-BfisX7BG.js} +1 -1
  91. package/dist/web/assets/{wardley-7MLQ67FV-wA7AmV0Q.js → wardley-7MLQ67FV-BFQApzxh.js} +1 -1
  92. package/dist/web/assets/{wardleyDiagram-IVAIDKWA-B-bb5lDE.js → wardleyDiagram-IVAIDKWA-C-6UVM4l.js} +1 -1
  93. package/dist/web/assets/{xychartDiagram-4URNHDU4-DhCniusd.js → xychartDiagram-4URNHDU4-KM-JLRya.js} +1 -1
  94. package/dist/web/index.html +2 -2
  95. package/package.json +1 -1
  96. package/dist/web/assets/channel-BS1PdTTb.js +0 -1
  97. package/dist/web/assets/flowDiagram-IUGLLWBU-B2S9crxg.js +0 -1
  98. package/dist/web/assets/index-uwznXVRc.css +0 -2
  99. package/dist/web/assets/swimlanesDiagram-AYQRV4AK-Bx2hw5cd.js +0 -8
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-ttIAb4XJ.js","assets/rolldown-runtime-COiEfhsA.js","assets/mermaid.core-CzmHcBmx.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-BWF7jMDv.js","assets/chunk-DSNLSHJZ-DaRLU1qt.js","assets/chunk-7S6XSTFO-Je4Wj9Rr.js","assets/dist-CumnGVmJ.js","assets/chunk-YZO67HFG-CjeirPb6.js","assets/chunk-AQDTSKZB-C8GB_Ui_.js","assets/chunk-DUW6YSOI-Dgx8z5s3.js","assets/chunk-UHW7PFBP-HDXbOEZI.js","assets/chunk-HAGFOTED-D-D65AyF.js","assets/chunk-J5ZVWO5B-oDCd-gWO.js","assets/rough.esm-Dy-Kn_BL.js","assets/chunk-ZAUX2LTX-cTNIHs1b.js","assets/chunk-WQQL4CDK-CvUSO1KH.js","assets/line-DbL7nSAS.js","assets/path-fybaL0A-.js","assets/array-BifhSqXX.js","assets/chunk-HNE4Q36P-BwNe1j6O.js","assets/mermaidToImage-Hjyav5KM.js","assets/CodeEditor-B123NBEk.js","assets/dist-7keixpik.js","assets/docxExport-DTdmyOrq.js","assets/loadReferencedImage-CzNYo1b1.js","assets/conversationExport-jN-MYzY9.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-ttIAb4XJ.js","assets/rolldown-runtime-COiEfhsA.js","assets/mermaid.core-oMdyM7QA.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-BWF7jMDv.js","assets/chunk-DSNLSHJZ-6b70YpkQ.js","assets/chunk-7S6XSTFO-DyqsoUUs.js","assets/dist-CumnGVmJ.js","assets/chunk-YZO67HFG-DM-i_t3H.js","assets/chunk-AQDTSKZB-DSe0lG0z.js","assets/chunk-DUW6YSOI-Dgx8z5s3.js","assets/chunk-UHW7PFBP-BiEM0DeV.js","assets/chunk-HAGFOTED-YGDsk_ng.js","assets/chunk-J5ZVWO5B-oDCd-gWO.js","assets/rough.esm-Dy-Kn_BL.js","assets/chunk-ZAUX2LTX-Bm3Uc7GI.js","assets/chunk-WQQL4CDK-BhjGwd43.js","assets/line-SDUIsevL.js","assets/path-fybaL0A-.js","assets/array-BifhSqXX.js","assets/chunk-HNE4Q36P-CYfBi-8I.js","assets/mermaidToImage-CMYk5EZ9.js","assets/CodeEditor-DrXTrob5.js","assets/dist-7keixpik.js","assets/docxExport-ButYIRWK.js","assets/loadReferencedImage-DgPSViBj.js","assets/conversationExport-ew4uMgY-.js"])))=>i.map(i=>d[i]);
2
2
  import{i as e,n as t,t as n}from"./rolldown-runtime-COiEfhsA.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var r=n((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},ee=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function te(e,t){return E(e.type,t,e.props)}function D(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ne(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var re=/\/+/g;function ie(e,t){return typeof e==`object`&&e&&e.key!=null?ne(``+e.key):t.toString(36)}function O(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 k(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,k(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ie(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(re,`$&/`)+`/`),k(o,r,i,``,function(e){return e})):o!=null&&(D(o)&&(o=te(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(re,`$&/`)+`/`)+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+ie(a,u),c+=k(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+ie(a,u++),c+=k(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return k(O(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 ae(e,t,n){if(e==null)return e;var r=[],i=0;return k(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function oe(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 se=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 ce(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,se)}catch(e){se(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function A(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 ce(A.bind(null,e))}var le={map:ae,forEach:function(e,t,n){ae(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return ae(e,function(){t++}),t},toArray:function(e){return ae(e,function(e){return e})||[]},only:function(e){if(!D(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=A,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)!ee.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 E(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)ee.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 E(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=D,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:oe}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=ce,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.1`})),i=n(((e,t)=>{t.exports=r()})),a=n((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,te());else{var t=n(l);t!==null&&re(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function ee(){return g?!0:!(e.unstable_now()-T<w)}function E(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&ee());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&re(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?te():S=!1}}}var te;if(typeof y==`function`)te=function(){y(E)};else if(typeof MessageChannel<`u`){var D=new MessageChannel,ne=D.port2;D.port1.onmessage=E,te=function(){ne.postMessage(null)}}else te=function(){_(E,0)};function re(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,re(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,te()))),r},e.unstable_shouldYield=ee,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),o=n(((e,t)=>{t.exports=a()})),s=n((e=>{var t=i();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var a={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},o=Symbol.for(`react.portal`),s=Symbol.for(`react.recoverable`),c=Symbol.for(`react.optimistic_key`);function l(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:r==null?null:r===c?c:``+r,children:e,containerInfo:t,implementation:n}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function d(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,e.browser=function(e){return{$$typeof:s,_reason:e}},e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return l(e,t,null,r)},e.flushSync=function(e){var t=u.T,n=a.p;try{if(u.T=null,a.p=2,e)return e()}finally{u.T=t,a.p=n,a.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,a.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&a.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin),i=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?a.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:i,fetchPriority:o}):n===`script`&&a.d.X(e,{crossOrigin:r,integrity:i,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`){if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=d(t.as,t.crossOrigin);a.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}}else t??a.d.M(e)}},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin);a.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`){if(t){var n=d(t.as,t.crossOrigin);a.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}else a.d.m(e)}},e.requestFormReset=function(e){a.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return u.H.useFormState(e,t,n)},e.useFormStatus=function(){return u.H.useHostTransitionStatus()},e.version=`19.3.1`})),c=n(((e,t)=>{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=s()})),l=n((e=>{var t=o(),n=i(),r=c();function a(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function s(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function l(e){for(var t=e,n=t;n&&!n.alternate;)t=n,t.flags&4098&&(e=t.return),n=t.return;for(;t.return;)t=t.return;return t.tag===3?e:null}function u(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function d(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function f(e){if(l(e)!==e)throw Error(a(188))}function p(e){var t=e.alternate;if(!t){if(t=l(e),t===null)throw Error(a(188));return t===e?e:null}for(var n=e,r=t;;){var i=n.return;if(i===null)break;var o=i.alternate;if(o===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===n)return f(i),e;if(o===r)return f(i),t;o=o.sibling}throw Error(a(188))}if(n.return!==r.return)n=i,r=o;else{for(var s=!1,c=i.child;c;){if(c===n){s=!0,n=i,r=o;break}if(c===r){s=!0,r=i,n=o;break}c=c.sibling}if(!s){for(c=o.child;c;){if(c===n){s=!0,n=o,r=i;break}if(c===r){s=!0,r=o,n=i;break}c=c.sibling}if(!s)throw Error(a(189))}}if(n.alternate!==r)throw Error(a(190))}if(n.tag!==3)throw Error(a(188));return n.stateNode.current===n?e:t}function m(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=m(e),t!==null)return t;e=e.sibling}return null}function h(e,t,n,r,i,a){for(;e!==null;){if((e.tag===5||e.tag===27||e.tag===6)&&n(e,r,i,a)||(e.tag!==22||e.memoizedState===null)&&(t||e.tag!==5&&e.tag!==27)&&h(e.child,t,n,r,i,a))return!0;e=e.sibling}return!1}function g(e){for(e=e.return;e!==null;){if(e.tag===3||e.tag===5||e.tag===27)return e;e=e.return}return null}function _(e){var t=!1;for(e=e.return;e!==null&&(e.tag===4&&(t=!0),e.tag!==3&&e.tag!==5&&e.tag!==27);)e=e.return;return t}function v(e){var t=[null,null],n=g(e);return n===null||y(t,e,n.child,{foundSelf:!1}),t}function y(e,t,n,r){for(;n!==null;){if(n===t)r.foundSelf=!0;else if(n.tag===5||n.tag===27||n.tag===6){if(r.foundSelf)return e[1]=n,!0;e[0]=n}else if((n.tag!==22||n.memoizedState===null)&&y(e,t,n.child,r))return!0;n=n.sibling}return!1}function b(e){switch(e.tag){case 5:case 27:case 6:return e.stateNode;case 3:return e.stateNode.containerInfo;default:throw Error(a(559))}}var x=null,S=null;function C(e,t,n){return e===n||e===t&&(x=e,!0)}function w(e,t,n){return e===n?(S=e,!1):e===t&&(S!==null&&(x=e),!0)}function T(e){if(e===null)return null;do e=e===null?null:e.return;while(e&&e.tag!==5&&e.tag!==27&&e.tag!==3);return e||null}function ee(e,t,n){for(var r=0,i=e;i;i=n(i))r++;i=0;for(var a=t;a;a=n(a))i++;for(;0<r-i;)e=n(e),r--;for(;0<i-r;)t=n(t),i--;for(;r--;){if(e===t||t!==null&&e===t.alternate)return e;e=n(e),t=n(t)}return null}var E=Object.assign,te=Symbol.for(`react.element`),D=Symbol.for(`react.transitional.element`),ne=Symbol.for(`react.portal`),re=Symbol.for(`react.fragment`),ie=Symbol.for(`react.strict_mode`),O=Symbol.for(`react.profiler`),k=Symbol.for(`react.consumer`),ae=Symbol.for(`react.context`),oe=Symbol.for(`react.forward_ref`),se=Symbol.for(`react.suspense`),ce=Symbol.for(`react.suspense_list`),A=Symbol.for(`react.memo`),le=Symbol.for(`react.lazy`),ue=Symbol.for(`react.activity`),de=Symbol.for(`react.legacy_hidden`),j=Symbol.for(`react.memo_cache_sentinel`),fe=Symbol.for(`react.view_transition`),pe=Symbol.for(`react.recoverable`),me=Symbol.iterator;function he(e){return typeof e!=`object`||!e?null:(e=me&&e[me]||e[`@@iterator`],typeof e==`function`?e:null)}var ge=Symbol.for(`react.client.reference`);function _e(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===ge?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case re:return`Fragment`;case O:return`Profiler`;case ie:return`StrictMode`;case se:return`Suspense`;case ce:return`SuspenseList`;case ue:return`Activity`;case fe:return`ViewTransition`}if(typeof e==`object`)switch(e.$$typeof){case ne:return`Portal`;case ae:return e.displayName||`Context`;case k:return(e._context.displayName||`Context`)+`.Consumer`;case oe:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case A:return t=e.displayName||null,t===null?_e(e.type)||`Memo`:t;case le:t=e._payload,e=e._init;try{return _e(e(t))}catch{}}return null}var ve=Array.isArray,ye=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,be=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,xe={pending:!1,data:null,method:null,action:null},Se=[],Ce=-1;function we(e){return{current:e}}function Te(e){0>Ce||(e.current=Se[Ce],Se[Ce]=null,Ce--)}function Ee(e,t){Ce++,Se[Ce]=e.current,e.current=t}var De=we(null),Oe=we(null),ke=we(null),Ae=we(null);function je(e,t){switch(Ee(ke,t),Ee(Oe,e),Ee(De,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?jp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=jp(t),e=Mp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Te(De),Ee(De,e)}function Me(){Te(De),Te(Oe),Te(ke)}function Ne(e){var t=e.memoizedState;t!==null&&(Oh._currentValue=t.memoizedState,Ee(Ae,e)),t=De.current;var n=Mp(t,e.type);t!==n&&(Ee(Oe,e),Ee(De,n))}function Pe(e){Oe.current===e&&(Te(De),Te(Oe)),Ae.current===e&&(Te(Ae),Oh._currentValue=xe)}var Fe,Ie;function Le(e){if(Fe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Fe=t&&t[1]||``,Ie=-1<e.stack.indexOf(`
3
3
  at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
4
4
  `+Fe+e+Ie}var Re=!1;function ze(e,t){if(!e||Re)return``;Re=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
@@ -17,7 +17,7 @@ Error generating stack: `+e.message+`
17
17
  `),n=je(t);if(n===-1)return;let r=t[n],i=/^(\s*)(flowchart|graph)([ \t]+(TD|TB|BT|LR|RL)\b)?(.*)$/i.exec(r);if(i!==null){let[,e,r,,a,o]=i,s=a===void 0?`TB`:Ae(a),c=ke(s),l=[...t];return l[n]=`${e}${r} ${c}${o}`,{direction:s,turned:l.join(`
18
18
  `)}}let a=/^(\s*)stateDiagram(-v2)?\s*$/i.exec(r);if(a!==null)return Ne(t,n,a[1])}function Ne(e,t,n){let r=0;for(let n=t+1;n<e.length;n+=1){let t=e[n],i=r===0?/^\s*direction\s+(TD|TB|BT|LR|RL)\s*$/i.exec(t):null;if(i!==null){let r=Ae(i[1]),a=[...e];return a[n]=t.replace(/(direction\s+)(TD|TB|BT|LR|RL)/i,`$1${ke(r)}`),{direction:r,turned:a.join(`
19
19
  `)}}r+=(t.match(/\{/g)?.length??0)-(t.match(/\}/g)?.length??0),r<0&&(r=0)}let i=[...e];return i.splice(t+1,0,`${n} direction LR`),{direction:`TB`,turned:i.join(`
20
- `)}}var Pe=Promise.resolve();function Fe(e){let t=Pe.then(e,e);return Pe=t.then(()=>void 0,()=>void 0),t}var Ie=`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,Le=`flex flex-wrap items-center gap-3 text-xs`,Re=null;async function ze(e){let t=await(Re??=me(()=>import(`./mermaid.core-CzmHcBmx.js`).then(e=>e.t),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])));return t.default.initialize({startOnLoad:!1,theme:e,look:`classic`,securityLevel:`strict`,suppressErrorRendering:!0}),t}function Be(e){let t=/viewBox="\s*[\d.-]+[\s,]+[\d.-]+[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(e),n=t?Number(t[1]):NaN;return Number.isFinite(n)&&n>0?n:void 0}function Ve(e,t){if(typeof e!=`object`||!e||!(`props`in e))return null;let n=e.props;if(t!==void 0&&!RegExp(`\\blanguage-${t}\\b`).test(n.className??``))return null;let r=n.children;return typeof r==`string`?r:Array.isArray(r)&&r.every(e=>typeof e==`string`)?r.join(``):null}function He(e){let t=Ve(e,`mermaid`);return t===null?null:t.trim()}function Ue(e){let{children:t,...n}=e,r=He(t);if(r!==null)return(0,A.jsx)(We,{code:r});let i=Ve(t);return i===null?(0,A.jsx)(`pre`,{...n,children:t}):(0,A.jsxs)(`div`,{className:`code-block relative`,"data-testid":`code-block`,children:[(0,A.jsx)(`pre`,{...n,children:t}),(0,A.jsx)(le,{iconOnly:!0,text:i.replace(/\n$/,``),className:`absolute right-1.5 top-1.5 rounded border border-zinc-300 bg-white/80 px-1.5 py-0.5 text-xs text-zinc-500 hover:text-zinc-800 dark:border-zinc-700 dark:bg-zinc-900/80 dark:text-zinc-400 dark:hover:text-zinc-100`})]})}function We({code:e}){let t=(0,d.useId)().replace(/[^a-zA-Z0-9]/g,``),n=m()===`light`?`default`:`dark`,[r,i]=(0,d.useState)(null),[a,o]=(0,d.useState)(null),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(!1),[f,p]=(0,d.useState)(!1),[h,g]=(0,d.useState)(null),_=(0,d.useRef)(!1),v=(0,d.useRef)(0),y=(0,d.useMemo)(()=>Me(e),[e]),b=y===void 0?`landscape`:Oe(y.direction),[x,S]=(0,d.useState)(void 0),C=r?.svg??null,w=r!==null&&r.orientation!==b,T=(0,d.useRef)(null),ee=(0,d.useRef)(e);ee.current=e,(0,d.useEffect)(()=>(v.current+=1,i(null),S(void 0),u(!1),o(null),g(null),()=>{v.current+=1}),[e]);async function E(){if(!r||_.current)return;_.current=!0,p(!0),g(null);let e=v.current;try{let{renderDiagram:n}=await me(async()=>{let{renderDiagram:e}=await import(`./mermaidToImage-Hjyav5KM.js`).then(e=>e.r);return{renderDiagram:e}},__vite__mapDeps([21,1])),i=await n(r.source,`mermaid-download-${t}`);if(e!==v.current)return;let a=URL.createObjectURL(new Blob([i.svg],{type:`image/svg+xml;charset=utf-8`}));try{let e=document.createElement(`a`);e.href=a,e.download=`diagram.svg`,e.click()}finally{URL.revokeObjectURL(a)}}catch(t){e===v.current&&g(t instanceof Error?t.message:String(t))}finally{_.current=!1,p(!1)}}return(0,d.useEffect)(()=>{let e=!1,r=setTimeout(()=>void Fe(async()=>{try{let r=(await ze(n)).default,a=ee.current,s=Me(a),c=s===void 0?`landscape`:Oe(s.direction);if(x!==void 0&&s!==void 0){let n=x===c?a:s.turned,{svg:l}=await r.render(`mermaid-${t}`,n);e||(i({svg:l,orientation:x,source:n}),o(null));return}let l=await r.render(`mermaid-${t}`,a),u={svg:l.svg,orientation:c,source:a},d=Be(l.svg);if(s!==void 0&&d!==void 0&&d>710){let e=await r.render(`mermaid-${t}-turned`,s.turned),n=Be(e.svg);if(n!==void 0){let t=c===`landscape`?Ee(d,n):Ee(n,d);t!==c&&(u={svg:e.svg,orientation:t,source:s.turned})}}e||(i(u),o(null))}catch(t){e||(i(null),o(t instanceof Error?t.message:String(t)))}}),300);return()=>{e=!0,clearTimeout(r)}},[e,t,n,x]),C?(0,A.jsxs)(`div`,{ref:T,className:`my-2 flex flex-col gap-2 rounded-lg border border-zinc-200 bg-zinc-50 p-3 dark:border-zinc-800 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`${Le} order-3`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>c(!s),title:s?`Show diagram`:`Show code`,className:Ie,children:s?`⚏ diagram`:`⌗ code`}),!s&&y!==void 0&&r!==null&&(0,A.jsx)(`button`,{type:`button`,"data-testid":`mermaid-orientation`,onClick:()=>S(e=>Te(e??r.orientation)),title:r.orientation===`portrait`?`Turn it across the page — it is drawn down`:`Turn it down the page — it is drawn across`,"aria-label":`Turn the diagram ${Te(r.orientation)}`,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,children:r.orientation===`portrait`?`↔ landscape`:`↕ portrait`}),!s&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>u(!0),"aria-label":`Show diagram at full size`,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,children:`⤢ enlarge`}),(0,A.jsx)(`button`,{type:`button`,className:Ie,disabled:f,onClick:()=>void E(),title:`Save as .svg — insert it as a picture in a document`,children:f?`preparing SVG…`:`⤓ download SVG`}),(0,A.jsx)(le,{text:e,className:Ie}),h&&(0,A.jsxs)(`span`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:[`Could not download SVG: `,h]})]}),s?(0,A.jsx)(`pre`,{className:`overflow-x-auto font-mono text-xs text-zinc-500 dark:text-zinc-400`,children:e}):(0,A.jsx)(`div`,{className:`flex justify-center overflow-x-auto [&_svg]:max-w-full`,dangerouslySetInnerHTML:{__html:C}}),w&&!s&&(0,A.jsxs)(`div`,{className:`mt-1 text-center text-xs text-zinc-400 dark:text-zinc-600`,"data-testid":`mermaid-turned`,children:[`drawn `,r?.orientation,` to fit — the source asks for `,b]}),(0,A.jsx)(Ce,{label:`diagram`,testId:`mermaid-enlarged`,open:l,onClose:()=>u(!1),anchorRef:T,actions:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,className:Ie,disabled:f,onClick:()=>void E(),children:f?`preparing SVG…`:`⤓ download SVG`}),h&&(0,A.jsxs)(`span`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:[`Could not download SVG: `,h]})]}),children:(0,A.jsx)(`div`,{style:{width:Be(C)},className:`[&_svg]:!h-auto [&_svg]:!max-w-none [&_svg]:!w-full`,dangerouslySetInnerHTML:{__html:C}})})]}):(0,A.jsxs)(`pre`,{className:`my-2 overflow-x-auto rounded-lg border border-zinc-200 bg-zinc-50 p-3 font-mono text-xs text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400`,children:[e,a&&(0,A.jsx)(`div`,{className:`mt-2 text-red-600 dark:text-red-400`,children:a})]})}function Ge({html:e,className:t=``,as:n=`div`}){return(0,A.jsx)(n,{className:`rendered-ansi overflow-x-auto font-mono text-xs leading-relaxed [&_span]:whitespace-pre-wrap ${t}`,dangerouslySetInnerHTML:{__html:e}})}function Ke({lines:e,fill:t=!1}){return(0,A.jsx)(`div`,{className:`overflow-auto rounded border border-zinc-200 font-mono text-xs leading-relaxed dark:border-zinc-800 ${t?`max-h-full`:`max-h-72`}`,children:w(C(e)).map((e,t)=>e===null?(0,A.jsx)(`div`,{className:`bg-zinc-100 px-2 text-center text-zinc-400 dark:bg-zinc-800/60 dark:text-zinc-600`,children:`⋯`},t):(0,A.jsxs)(`div`,{className:`grid grid-cols-2`,children:[(0,A.jsx)(`div`,{className:`whitespace-pre-wrap break-words border-r border-zinc-200 px-2 dark:border-zinc-800 ${e.changed?e.left===null?`bg-zinc-50 dark:bg-zinc-900/40`:`bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`text-zinc-500 dark:text-zinc-500`}`,children:e.left??` `}),(0,A.jsx)(`div`,{className:`whitespace-pre-wrap break-words px-2 ${e.changed?e.right===null?`bg-zinc-50 dark:bg-zinc-900/40`:`bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:`text-zinc-500 dark:text-zinc-500`}`,children:e.right??` `})]},t))})}function qe({lines:e}){return(0,A.jsx)(`pre`,{className:`max-h-72 overflow-auto rounded border border-zinc-200 font-mono text-xs leading-relaxed dark:border-zinc-800`,children:T(e).map((e,t)=>e===null?(0,A.jsx)(`div`,{className:`bg-zinc-100 px-2 text-center text-zinc-400 dark:bg-zinc-800/60 dark:text-zinc-600`,children:`⋯`},t):(0,A.jsxs)(`div`,{className:e.type===`add`?`bg-emerald-50 px-2 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:e.type===`del`?`bg-red-50 px-2 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`px-2 text-zinc-500 dark:text-zinc-500`,children:[e.type===`add`?`+ `:e.type===`del`?`− `:` `,e.text]},t))})}function Je({item:e,canEdit:t,onEdit:n}){let[r,i]=(0,d.useState)(null),a=(0,d.useRef)(null),o=t&&e.entryId!==void 0,s=r!==null;(0,d.useEffect)(()=>{s&&a.current?.focus()},[s]),(0,d.useEffect)(()=>{i(null)},[e.entryId,e.text]);function c(){let a=r?.trim();t&&e.entryId&&a&&(a===e.text||n(e.entryId,a,e.images),i(null))}return(0,A.jsxs)(`div`,{className:`group ml-auto flex max-w-[85%] items-start gap-1.5`,children:[o&&!s&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>i(e.text),title:`edit this prompt and ask again (branches the conversation)`,"aria-label":`Edit this prompt`,className:`mt-1.5 shrink-0 rounded px-1 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✎`}),(0,A.jsxs)(`div`,{className:`min-w-0 flex-1 rounded-xl bg-blue-100 px-4 py-2 text-[15px] text-blue-950 dark:bg-blue-950/60 dark:text-zinc-100`,children:[e.images&&e.images.length>0&&(0,A.jsx)(`div`,{className:`mb-1.5 flex flex-wrap gap-1.5`,children:e.images.map((e,t)=>(0,A.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:``,className:`max-h-48 max-w-full rounded-lg object-contain`},t))}),s?(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`textarea`,{ref:a,value:r,"aria-label":`Edit prompt`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),c()),e.key===`Escape`&&i(null)},rows:Math.min(10,Math.max(2,r.split(`
20
+ `)}}var Pe=Promise.resolve();function Fe(e){let t=Pe.then(e,e);return Pe=t.then(()=>void 0,()=>void 0),t}var Ie=`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,Le=`flex flex-wrap items-center gap-3 text-xs`,Re=null;async function ze(e){let t=await(Re??=me(()=>import(`./mermaid.core-oMdyM7QA.js`).then(e=>e.t),__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])));return t.default.initialize({startOnLoad:!1,theme:e,look:`classic`,securityLevel:`strict`,suppressErrorRendering:!0}),t}function Be(e){let t=/viewBox="\s*[\d.-]+[\s,]+[\d.-]+[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(e),n=t?Number(t[1]):NaN;return Number.isFinite(n)&&n>0?n:void 0}function Ve(e,t){if(typeof e!=`object`||!e||!(`props`in e))return null;let n=e.props;if(t!==void 0&&!RegExp(`\\blanguage-${t}\\b`).test(n.className??``))return null;let r=n.children;return typeof r==`string`?r:Array.isArray(r)&&r.every(e=>typeof e==`string`)?r.join(``):null}function He(e){let t=Ve(e,`mermaid`);return t===null?null:t.trim()}function Ue(e){let{children:t,...n}=e,r=He(t);if(r!==null)return(0,A.jsx)(We,{code:r});let i=Ve(t);return i===null?(0,A.jsx)(`pre`,{...n,children:t}):(0,A.jsxs)(`div`,{className:`code-block relative`,"data-testid":`code-block`,children:[(0,A.jsx)(`pre`,{...n,children:t}),(0,A.jsx)(le,{iconOnly:!0,text:i.replace(/\n$/,``),className:`absolute right-1.5 top-1.5 rounded border border-zinc-300 bg-white/80 px-1.5 py-0.5 text-xs text-zinc-500 hover:text-zinc-800 dark:border-zinc-700 dark:bg-zinc-900/80 dark:text-zinc-400 dark:hover:text-zinc-100`})]})}function We({code:e}){let t=(0,d.useId)().replace(/[^a-zA-Z0-9]/g,``),n=m()===`light`?`default`:`dark`,[r,i]=(0,d.useState)(null),[a,o]=(0,d.useState)(null),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(!1),[f,p]=(0,d.useState)(!1),[h,g]=(0,d.useState)(null),_=(0,d.useRef)(!1),v=(0,d.useRef)(0),y=(0,d.useMemo)(()=>Me(e),[e]),b=y===void 0?`landscape`:Oe(y.direction),[x,S]=(0,d.useState)(void 0),C=r?.svg??null,w=r!==null&&r.orientation!==b,T=(0,d.useRef)(null),ee=(0,d.useRef)(e);ee.current=e,(0,d.useEffect)(()=>(v.current+=1,i(null),S(void 0),u(!1),o(null),g(null),()=>{v.current+=1}),[e]);async function E(){if(!r||_.current)return;_.current=!0,p(!0),g(null);let e=v.current;try{let{renderDiagram:n}=await me(async()=>{let{renderDiagram:e}=await import(`./mermaidToImage-CMYk5EZ9.js`).then(e=>e.r);return{renderDiagram:e}},__vite__mapDeps([21,1])),i=await n(r.source,`mermaid-download-${t}`);if(e!==v.current)return;let a=URL.createObjectURL(new Blob([i.svg],{type:`image/svg+xml;charset=utf-8`}));try{let e=document.createElement(`a`);e.href=a,e.download=`diagram.svg`,e.click()}finally{URL.revokeObjectURL(a)}}catch(t){e===v.current&&g(t instanceof Error?t.message:String(t))}finally{_.current=!1,p(!1)}}return(0,d.useEffect)(()=>{let e=!1,r=setTimeout(()=>void Fe(async()=>{try{let r=(await ze(n)).default,a=ee.current,s=Me(a),c=s===void 0?`landscape`:Oe(s.direction);if(x!==void 0&&s!==void 0){let n=x===c?a:s.turned,{svg:l}=await r.render(`mermaid-${t}`,n);e||(i({svg:l,orientation:x,source:n}),o(null));return}let l=await r.render(`mermaid-${t}`,a),u={svg:l.svg,orientation:c,source:a},d=Be(l.svg);if(s!==void 0&&d!==void 0&&d>710){let e=await r.render(`mermaid-${t}-turned`,s.turned),n=Be(e.svg);if(n!==void 0){let t=c===`landscape`?Ee(d,n):Ee(n,d);t!==c&&(u={svg:e.svg,orientation:t,source:s.turned})}}e||(i(u),o(null))}catch(t){e||(i(null),o(t instanceof Error?t.message:String(t)))}}),300);return()=>{e=!0,clearTimeout(r)}},[e,t,n,x]),C?(0,A.jsxs)(`div`,{ref:T,className:`my-2 flex flex-col gap-2 rounded-lg border border-zinc-200 bg-zinc-50 p-3 dark:border-zinc-800 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`${Le} order-3`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>c(!s),title:s?`Show diagram`:`Show code`,className:Ie,children:s?`⚏ diagram`:`⌗ code`}),!s&&y!==void 0&&r!==null&&(0,A.jsx)(`button`,{type:`button`,"data-testid":`mermaid-orientation`,onClick:()=>S(e=>Te(e??r.orientation)),title:r.orientation===`portrait`?`Turn it across the page — it is drawn down`:`Turn it down the page — it is drawn across`,"aria-label":`Turn the diagram ${Te(r.orientation)}`,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,children:r.orientation===`portrait`?`↔ landscape`:`↕ portrait`}),!s&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>u(!0),"aria-label":`Show diagram at full size`,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200 disabled:opacity-50`,children:`⤢ enlarge`}),(0,A.jsx)(`button`,{type:`button`,className:Ie,disabled:f,onClick:()=>void E(),title:`Save as .svg — insert it as a picture in a document`,children:f?`preparing SVG…`:`⤓ download SVG`}),(0,A.jsx)(le,{text:e,className:Ie}),h&&(0,A.jsxs)(`span`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:[`Could not download SVG: `,h]})]}),s?(0,A.jsx)(`pre`,{className:`overflow-x-auto font-mono text-xs text-zinc-500 dark:text-zinc-400`,children:e}):(0,A.jsx)(`div`,{className:`flex justify-center overflow-x-auto [&_svg]:max-w-full`,dangerouslySetInnerHTML:{__html:C}}),w&&!s&&(0,A.jsxs)(`div`,{className:`mt-1 text-center text-xs text-zinc-400 dark:text-zinc-600`,"data-testid":`mermaid-turned`,children:[`drawn `,r?.orientation,` to fit — the source asks for `,b]}),(0,A.jsx)(Ce,{label:`diagram`,testId:`mermaid-enlarged`,open:l,onClose:()=>u(!1),anchorRef:T,actions:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,className:Ie,disabled:f,onClick:()=>void E(),children:f?`preparing SVG…`:`⤓ download SVG`}),h&&(0,A.jsxs)(`span`,{role:`alert`,className:`text-red-600 dark:text-red-400`,children:[`Could not download SVG: `,h]})]}),children:(0,A.jsx)(`div`,{style:{width:Be(C)},className:`[&_svg]:!h-auto [&_svg]:!max-w-none [&_svg]:!w-full`,dangerouslySetInnerHTML:{__html:C}})})]}):(0,A.jsxs)(`pre`,{className:`my-2 overflow-x-auto rounded-lg border border-zinc-200 bg-zinc-50 p-3 font-mono text-xs text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400`,children:[e,a&&(0,A.jsx)(`div`,{className:`mt-2 text-red-600 dark:text-red-400`,children:a})]})}function Ge({html:e,className:t=``,as:n=`div`}){return(0,A.jsx)(n,{className:`rendered-ansi overflow-x-auto font-mono text-xs leading-relaxed [&_span]:whitespace-pre-wrap ${t}`,dangerouslySetInnerHTML:{__html:e}})}function Ke({lines:e,fill:t=!1}){return(0,A.jsx)(`div`,{className:`overflow-auto rounded border border-zinc-200 font-mono text-xs leading-relaxed dark:border-zinc-800 ${t?`max-h-full`:`max-h-72`}`,children:w(C(e)).map((e,t)=>e===null?(0,A.jsx)(`div`,{className:`bg-zinc-100 px-2 text-center text-zinc-400 dark:bg-zinc-800/60 dark:text-zinc-600`,children:`⋯`},t):(0,A.jsxs)(`div`,{className:`grid grid-cols-2`,children:[(0,A.jsx)(`div`,{className:`whitespace-pre-wrap break-words border-r border-zinc-200 px-2 dark:border-zinc-800 ${e.changed?e.left===null?`bg-zinc-50 dark:bg-zinc-900/40`:`bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`text-zinc-500 dark:text-zinc-500`}`,children:e.left??` `}),(0,A.jsx)(`div`,{className:`whitespace-pre-wrap break-words px-2 ${e.changed?e.right===null?`bg-zinc-50 dark:bg-zinc-900/40`:`bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:`text-zinc-500 dark:text-zinc-500`}`,children:e.right??` `})]},t))})}function qe({lines:e}){return(0,A.jsx)(`pre`,{className:`max-h-72 overflow-auto rounded border border-zinc-200 font-mono text-xs leading-relaxed dark:border-zinc-800`,children:T(e).map((e,t)=>e===null?(0,A.jsx)(`div`,{className:`bg-zinc-100 px-2 text-center text-zinc-400 dark:bg-zinc-800/60 dark:text-zinc-600`,children:`⋯`},t):(0,A.jsxs)(`div`,{className:e.type===`add`?`bg-emerald-50 px-2 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:e.type===`del`?`bg-red-50 px-2 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`px-2 text-zinc-500 dark:text-zinc-500`,children:[e.type===`add`?`+ `:e.type===`del`?`− `:` `,e.text]},t))})}function Je({item:e,canEdit:t,onEdit:n}){let[r,i]=(0,d.useState)(null),a=(0,d.useRef)(null),o=t&&e.entryId!==void 0,s=r!==null;(0,d.useEffect)(()=>{s&&a.current?.focus()},[s]),(0,d.useEffect)(()=>{i(null)},[e.entryId,e.text]);function c(){let a=r?.trim();t&&e.entryId&&a&&(a===e.text||n(e.entryId,a,e.images),i(null))}return(0,A.jsxs)(`div`,{className:`group ml-auto flex max-w-[85%] items-start gap-1.5`,children:[o&&!s&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>i(e.text),title:`edit this prompt and ask again (branches the conversation)`,"aria-label":`Edit this prompt`,className:`mt-1.5 shrink-0 rounded px-1 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✎`}),(0,A.jsxs)(`div`,{className:`min-w-0 flex-1 rounded-xl bg-blue-100 px-4 py-2 text-[15px] text-blue-950 dark:bg-blue-950/60 dark:text-zinc-100`,children:[e.images&&e.images.length>0&&(0,A.jsx)(`div`,{className:`mb-1.5 flex flex-wrap gap-1.5`,children:e.images.map((e,t)=>(0,A.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:``,className:`max-h-48 max-w-full rounded-lg object-contain`},t))}),s?(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`textarea`,{ref:a,value:r,"aria-label":`Edit prompt`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),c()),e.key===`Escape`&&i(null)},rows:Math.min(10,Math.max(2,r.split(`
21
21
  `).length)),className:`w-full resize-none rounded-md bg-white/70 px-2 py-1 text-[15px] outline-none ring-1 ring-blue-300 dark:bg-zinc-900/60 dark:ring-blue-900`}),(0,A.jsxs)(`div`,{className:`mt-1.5 flex items-center justify-end gap-2 text-xs`,children:[(0,A.jsx)(`span`,{className:`mr-auto text-blue-900/70 dark:text-zinc-400`,children:t?`asks again from here — the current answer moves to its own branch`:`waiting: the agent is running (or the connection dropped)`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>i(null),className:`rounded border border-blue-300 px-2 py-0.5 hover:bg-white/60 dark:border-zinc-700 dark:hover:bg-zinc-800`,children:`cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:c,disabled:!t||!r.trim()||r.trim()===e.text,className:`rounded border border-blue-400 bg-white/70 px-2 py-0.5 font-medium disabled:opacity-50 dark:border-blue-800 dark:bg-zinc-900/60`,children:`send`})]})]}):(0,A.jsx)(`div`,{className:`whitespace-pre-wrap`,children:e.text})]})]})}var Ye=`urn:structured-exchange:1`,Xe=[`graph`,`sequence`];function Ze(e){return Qe(e)?[`graph`,`sequence`,`table`]:Xe}function Qe(e){return e===`urn:structured-exchange:2`||e===`urn:structured-exchange:3`}function $e(e){if(Array.isArray(e))return{cells:e};let t=e.heading;return typeof t==`string`?{cells:[],role:e.role,heading:t}:{cells:e.cells,role:e.role}}var et={nodes:500,edges:2e3,participants:100,messages:1e3,columns:50,rows:5e3,removals:500,ref:200,localId:200,label:500,kind:100,kindsPerVocabulary:64,columnName:200,cell:1e3},tt=`urn:structured-exchange:2`,nt={profile:200,attributesPerItem:50,removeAttributesPerItem:50,attributeName:200,attributeString:1e3,attributeListItems:50,revision:200,locationsPerItem:10,uri:2e3,position:1e6,artifactsPerItem:20,artifactsPerDocument:50,artifactRel:100,artifactMediaType:100,artifactLabel:500,artifactDigest:71,relations:2e3,heading:500,headingDepth:6,viewpoints:20,viewpointConcern:500},rt=8e6,it=`urn:structured-exchange:3`,at=[Ye,tt,it];function ot(e){return at.find(t=>t===e)}var st=4e6,ct=Math.max(st,rt);function lt(e){return Qe(e)?rt:st}var ut=e=>new TextEncoder().encode(e).length;function dt(e){return e===`bytes`?ct:e===`relations`?nt.relations:et[e]}function ft(e,t){let n=dt(e),r=t?.[e];return r===void 0||r>=n?{limit:n,level:`ceiling`}:{limit:r,level:`deployment`}}function pt(e,t,n){let r=ut(e),i=ft(`bytes`,t),a=n===void 0?1/0:lt(n),o=Math.min(i.limit,a),s=o===a&&a<i.limit?`ceiling`:i.level;if(!(r<=o))return{rule:`document-too-large`,path:``,message:`document is ${r} bytes, past the ${o}-byte ${s===`ceiling`?`contract ceiling`:`limit this deployment applies`}`,limit:o,observed:r,level:s}}var mt={graph:[`nodes`,`edges`],sequence:[`participants`,`messages`],table:[`columns`,`rows`,`relations`]};function ht(e,t){if(t===void 0)return[];let n=[];for(let r of mt[e.kind]??[]){let i=e.data[r];if(!Array.isArray(i))continue;let{limit:a,level:o}=ft(r,t);o===`deployment`&&i.length>a&&n.push({rule:`collection-past-deployment-limit`,path:`/data/${r}`,message:`${r} has ${i.length} entries, past the ${a} this deployment allows`,limit:a,observed:i.length,level:o})}return n}function gt(e,t){let n={};for(let t of mt[e.kind]??[]){let r=e.data[t];Array.isArray(r)&&(n[t]=r.length)}return{kind:e.kind,bytes:ut(t),counts:n}}var _t=6.6,vt=5.4;function yt(e,t,n){let r=e.flatMap(e=>e.split(/\r?\n/)).reduce((e,t)=>Math.max(e,t.length),0);return Math.min(Math.max(r*_t+22,t),n)}function bt(e,t,n,r){let i=t.map(e=>wt(e).length).reduce((e,t)=>Math.max(e,t),0);return Math.max(yt(e,n,r),Math.min(i*vt+22,r))}function xt(e,t,n=_t){let r=Math.max(Math.floor((t-22)/n+1e-6),4),i=[],a=e.split(/\r?\n/);if(a.length>1)return a.flatMap(e=>xt(e,t,n)).slice(0,3);let o=``;for(let t of e.split(/\s+/)){let e=o===``?t:`${o} ${t}`;if(e.length<=r)o=e;else for(o!==``&&i.push(o),o=t;o.length>r&&i.length<3;)i.push(o.slice(0,r)),o=o.slice(r)}if(o!==``&&i.push(o),i.length===0)return[``];if(i.length<=3)return i;let s=i.slice(0,3);return s[2]=`${s[2].slice(0,Math.max(r-1,1))}…`,s}function St(e,t){return e*15+t*15+14}function Ct(e,t){return e.flatMap(e=>xt(wt(e),t,vt))}function wt(e){return`${e.field}: ${e.from===void 0?``:`${e.from} → `}${e.to}`}function Tt(e,t){return`${e}: ${Et(t)}`}function Et(e){return Array.isArray(e)?e.map(e=>Et(e)).join(`, `):e===null?`null`:typeof e==`object`&&e&&typeof e.ref==`string`?`<${e.ref}>`:String(e)}function Dt(e){let t=e.range===void 0?``:` lines ${e.range.startLine}–${e.range.endLine}`,n=e.revision===void 0?``:` at ${e.revision}`;return`${e.uri}${t}${n}`}function Ot(e){let t=e.label===void 0?e.uri:`${e.label} (${e.uri})`,n=e.mediaType===void 0?``:`, ${e.mediaType}`;return`${e.rel}: ${t}${n} — ${e.sha256.slice(0,14)}…`}var kt=864e5,At=/^(\d{4})-(\d{2})-(\d{2})$/;function jt(e){let t=At.exec(e);if(t===null)return;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(n,r-1,i));if(a.setUTCFullYear(n,r-1,i),a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===i)return Math.round(a.getTime()/kt)}function Mt(e){let t=new Date(e*kt);return`${String(t.getUTCFullYear()).padStart(4,`0`)}-${String(t.getUTCMonth()+1).padStart(2,`0`)}-${String(t.getUTCDate()).padStart(2,`0`)}`}function Nt(e=new Date){return Math.round(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())/kt)}function Pt(e){let t=jt(e.type===`activity`?e.start:e.date),n=jt(e.type===`activity`?e.end:e.date);return t===void 0||n===void 0?void 0:{start:t,end:n}}function Ft(e){let t=new Map;return e.rows.forEach((e,n)=>{e.type===`task`&&(t.has(e.id)||t.set(e.id,{id:e.id,type:`task`,row:n,days:It(e)}),e.items.forEach((e,r)=>{e.id===void 0||t.has(e.id)||t.set(e.id,{id:e.id,type:e.type,row:n,item:r,days:Pt(e)})}))}),t}function It(e){let t;for(let n of e.items){let e=Pt(n);e!==void 0&&(t=t===void 0?{...e}:{start:Math.min(t.start,e.start),end:Math.max(t.end,e.end)})}return t}function Lt(e){return e.type??`finish-to-start`}function Rt(e){return{from:e.startsWith(`finish`)?`end`:`start`,to:e.endsWith(`finish`)?`end`:`start`}}function zt(e,t){let n=t.get(e.from)?.days,r=t.get(e.to)?.days;if(n===void 0||r===void 0)return;let i=Rt(Lt(e));return r[i.to]>=n[i.from]}function Bt(e){if(`date`in e){let t=jt(e.date)??0;return{start:t,end:t}}return{start:jt(e.start)??0,end:jt(e.end)??0}}function Vt(e){if(e.previous===void 0)return;let t=Bt(e.type===`activity`?{start:e.start,end:e.end}:{date:e.date}),n=Bt(e.previous);return{start:t.start-n.start,end:t.end-n.end}}function Ht(e){if(e===0)return``;let t=e>0?`+`:`−`,n=Math.abs(e);return n<14?`${t}${n}d`:n<70?`${t}${Math.round(n/7)}w`:`${t}${Math.round(n/30.44)}mo`}function Ut(e){let t=Vt(e);return t===void 0?``:t.start===t.end?Ht(t.start):t.start===0?`end${Ht(t.end)}`:t.end===0?`start${Ht(t.start)}`:`${Ht(t.start)}, end${Ht(t.end)}`}function Wt(e,t){if(e.role!==void 0||t?.role!==void 0)return!0;let n=Vt(e);return n!==void 0&&(n.start!==0||n.end!==0)}function Gt(e){return e.role!==void 0||e.items.some(t=>Wt(t,e))}var Kt={week:12,month:4,quarter:.75};function qt(e,t){let n=e>=8?`week`:e>=1?`month`:`quarter`;if(t===void 0)return n;let r=[`week`,`month`,`quarter`];return r[Math.max(r.indexOf(n),r.indexOf(t))]}var Jt=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Yt(e){return e.width>=24?e.label:e.width>=9?e.label.charAt(0):``}function Xt(e,t){return t===`month`?Yt(e):e.width>=e.label.length*6+4?e.label:``}function Zt(e){return((e+3)%7+7)%7}function Qt(e){let t=e-Zt(e)+3,n=new Date(t*kt).getUTCFullYear();return Math.floor((t-nn(n,0))/7)+1}function $t(e){if(e.label!==void 0&&e.label!==``)return e.label;if(e.type===`milestone`&&e.kind!==void 0&&e.kind!==``)return e.kind}function en(e){return e.length*_t}function tn(e,t){let n=new Date(e*kt),r=n.getUTCFullYear(),i=n.getUTCMonth(),a=[];for(;;){i+=1,i===12&&(i=0,r+=1);let e=nn(r,i);if(e>t)return a;a.push({day:e,year:r,month:i})}}function nn(e,t){let n=new Date(0);return n.setUTCFullYear(e,t,1),Math.round(n.getTime()/kt)}function rn(e,t){let n=e=>e===`bar`||e===`ghost`;return n(e)&&t===`star`||e===`star`&&n(t)}function an(e,t){return e.x0<t.x1&&t.x0<e.x1}function on(e,t){if(t<=0||e.width<=t)return;let n=e.items.filter(e=>e.change!==void 0);if(n.length>0){let e=Math.min(...n.flatMap(e=>e.ghost===void 0?[e.glyph.x]:[e.glyph.x,e.ghost.x]));return e<t*.9?void 0:Math.max(0,e-t/6)}if(`x`in e.today&&e.today.x>t*.8)return Math.max(0,e.today.x-t/3)}function sn(e,t,n={}){let r=jt(e.time.start)??0,i=jt(e.time.end)??r,a=n.pxPerDay??Kt[e.time.scale]??4,o=(i-r+1)*a,s=e=>(e-r)*a,c=tn(r,i),l=new Date(r*kt),u=[{day:r,year:l.getUTCFullYear(),month:l.getUTCMonth()},...c],d=u.map((e,t)=>{let n=t+1<u.length?u[t+1].day:i+1;return{label:Jt[e.month],x:s(e.day),width:(n-e.day)*a,year:e.year,month:e.month}}),f=[];u.forEach((e,t)=>{let n=d[t],r=f[f.length-1];r!==void 0&&r.label===String(e.year)?r.width+=n.width:f.push({label:String(e.year),x:n.x,width:n.width})});let p=qt(a,n.unit),m=(e,t)=>e.map((n,r)=>{let o=r+1<e.length?e[r+1]:i+1;return{label:t(n),x:s(n),width:(o-n)*a}}),h=f,g;if(p===`week`){let e=[];for(let t=r-Zt(r)+7;t<=i;t+=7)e.push(t);g=m([r,...e],e=>`W${Qt(e)}`),h=d.map(e=>({label:`${e.label} ${e.year}`,x:e.x,width:e.width}))}else if(p===`quarter`){let e=u.filter((e,t)=>t===0||e.month%3==0);g=e.map((t,n)=>{let r=n+1<e.length?e[n+1].day:i+1;return{label:`Q${Math.floor(t.month/3)+1}`,x:s(t.day),width:(r-t.day)*a}})}else g=d;let _=g.slice(1).map(e=>e.x),v=[],y=[],b=0,x=e.comparedTo!==void 0,S=(e,t)=>{if(!x)return;if(e.role===`added`||t.role===`added`)return`(new)`;let n=Ut(e);return n===``?void 0:`(${n})`},C=(e,t,n)=>{let r=S(e,t);return r===void 0?n:n===void 0?r:`${n} ${r}`},w=(e,t)=>{if(x)return e.role===`removed`||t.role===`removed`?`removed`:e.role===`added`||t.role===`added`?`added`:Ut(e)===``?void 0:`moved`},T=(e,t)=>{let n=[],r=[],i=[],c=e.map(e=>({...e,days:Pt(e.item)})).filter(e=>e.days!==void 0).sort((e,t)=>Number(e.item.type===`milestone`)-Number(t.item.type===`milestone`)||e.days.start-t.days.start||e.row-t.row||e.index-t.index);for(let{item:e,index:t,row:l,days:u,text:d,note:f,change:p}of c){let c=[],m;if(p===`moved`&&e.previous!==void 0){let t=Bt(e.previous);if(e.type===`activity`)m={x0:s(t.start),x1:s(t.end+1)};else{let e=s(t.start)+a/2;m={x0:e-7,x1:e+7,cx:e}}c.push({kind:`ghost`,x0:m.x0,x1:m.x1})}let h,g,_,v;if(e.type===`activity`){if(g=s(u.start),_=s(u.end+1),c.push({kind:`bar`,x0:g,x1:_}),d!==void 0){let e=en(d);h=e+12<=_-g?{text:d,inside:!0,x:g+6,width:e}:cn(d,g,_,o),f!==void 0&&(h.note=f),c.push({kind:`label`,x0:h.x,x1:h.x+h.width})}}else v=s(u.start)+a/2,g=v-7,_=v+7,c.push({kind:`star`,x0:g,x1:_}),d!==void 0&&(h=cn(d,g,_,o),f!==void 0&&(h.note=f),c.push({kind:`label`,x0:h.x,x1:h.x+h.width}));let y=n.findIndex(e=>c.every(t=>e.every(e=>rn(t.kind,e.kind)||!an(t,e))));y===-1&&(y=n.length,n.push([])),n[y].push(...c),r.push({row:l,item:t,type:e.type,lane:y,days:u,...e.kind?{kind:e.kind}:{},...p===void 0?{}:{change:p}}),i.push({label:h===void 0?void 0:{...h,...p===`removed`?{struck:!0}:{}},x0:g,x1:_,cx:v,ghost:m})}return r.forEach((e,n)=>{let r=i[n],a=t+4+e.lane*24+12,o=e.type===`activity`?{x:r.x0,y:a-6,width:r.x1-r.x0,height:12}:{x:r.x0,y:a-7,width:14,height:14},s=r.ghost;y.push({...e,glyph:o,...r.cx===void 0?{}:{center:{x:r.cx,y:a}},...r.label===void 0?{}:{label:{...r.label,y:a-8,height:16}},...s===void 0?{}:e.type===`activity`?{ghost:{x:s.x0,y:a-6,width:s.x1-s.x0,height:12}}:{ghost:{x:s.x0,y:a-7,width:14,height:14},ghostCenter:{x:s.cx,y:a}}})}),Math.max(1,n.length)},ee=e=>e*24+8,E=(e,t)=>{let n=T(e.items.map((n,r)=>({row:t,index:r,item:n,text:C(n,e,$t(n)),note:S(n,e),change:w(n,e)})),b),r=ee(n);v.push({type:`task`,row:t,y:b,height:r,lanes:n,label:e.label,id:e.id}),b+=r},te,D=()=>{if(te!==void 0){if(te.tasks.length===0){let e=te.label?26:10;v.push({type:`separator`,row:te.row,y:b,height:e,...te.label?{label:te.label}:{}}),b+=e}else{let e=T(te.tasks.flatMap(({task:e,row:t})=>e.items.map((n,r)=>({row:t,index:r,item:n,text:C(n,e,$t(n)??(n.type===`activity`?e.label:void 0)),note:S(n,e),change:w(n,e)}))),b),t=ee(e);v.push({type:`section`,row:te.row,y:b,height:t,lanes:e,...te.label?{label:te.label}:{},tasks:te.tasks.map(({task:e})=>e.id)}),b+=t}te=void 0}},ne=(()=>{let t=new Set;if(!(n.onlyChanged&&x))return;let r;return e.rows.forEach((e,n)=>{e.type===`separator`?r=n:Gt(e)&&(t.add(n),r!==void 0&&t.add(r))}),t})(),re=ne===void 0?0:e.rows.filter((e,t)=>e.type===`task`&&!ne.has(t)).length;e.rows.forEach((e,t)=>{if(ne===void 0||ne.has(t)){if(e.type===`separator`){if(n.compact){D(),te={row:t,...e.label?{label:e.label}:{},tasks:[]};return}let r=e.label?26:10;v.push({type:`separator`,row:t,y:b,height:r,...e.label?{label:e.label}:{}}),b+=r}else te===void 0?E(e,t):te.tasks.push({task:e,row:t})}}),D();let ie=[];for(let t of e.rows)if(t.type===`task`)for(let e of t.items)e.kind&&!ie.includes(e.kind)&&ie.push(e.kind);for(let t of[...e.periods??[],...e.references??[]])t.kind&&!ie.includes(t.kind)&&ie.push(t.kind);let O=[];(e.periods??[]).forEach((e,t)=>{let n=Math.max(jt(e.start)??r,r),o=Math.min(jt(e.end)??i,i);n>o||O.push({index:t,x:s(n),width:(o-n+1)*a,start:e.start,end:e.end,...e.label?{label:e.label}:{},...e.kind?{kind:e.kind}:{}})});let k=(e.references??[]).flatMap((e,t)=>{let n=jt(e.date);return n===void 0||n<r||n>i?[]:[{index:t,x:s(n)+a/2,label:e.label,date:e.date,...e.kind?{kind:e.kind}:{}}]}),ae=[];if(t>=r&&t<=i){let e=s(t)+a/2;ae.push({x0:e-26,x1:e+26})}let oe=[],se=[...O.filter(e=>e.label).map(e=>({of:`period`,index:e.index,text:e.label,x:e.x+3,room:e.width-6})),...k.map(e=>{let t=en(e.label)*(10/11);return{of:`reference`,index:e.index,text:e.label,x:Math.min(Math.max(2,e.x-t/2),o-t-2),room:o-4}})].sort((e,t)=>e.x-t.x);for(let e of se){let t=en(e.text)*(10/11);if(t>e.room)continue;let n={x0:e.x-2,x1:e.x+t+2};ae.some(e=>n.x0<e.x1&&e.x0<n.x1)||(ae.push(n),oe.push({of:e.of,index:e.index,text:e.text,x:e.x,width:t}))}return{width:o,height:b,start:r,end:i,years:f,months:d,monthLines:c.map(e=>s(e.day)),unit:p,upper:h,lower:g,unitLines:_,rows:v,items:y,dependencies:ln(e,v,y,s),today:t<r?{outside:`before`,day:t}:t>i?{outside:`after`,day:t}:{x:s(t)+a/2,day:t},kinds:ie,hiddenTasks:re,periods:O,references:k,headerLabels:oe}}function cn(e,t,n,r){let i=en(e),a=n+4;if(a+i<=r)return{text:e,inside:!1,x:a,width:i};let o=t-4-i;return o>=0?{text:e,inside:!1,x:o,width:i}:{text:e,inside:!1,x:Math.max(0,r-i),width:i}}function ln(e,t,n,r){let i=Ft(e),a=new Map(n.map(e=>[`${e.row}:${e.item}`,e])),o=new Map(t.map(e=>[e.row,e])),s=(e,t)=>{let s=i.get(e);if(s?.days===void 0)return;if(s.item!==void 0){let e=a.get(`${s.row}:${s.item}`);if(e===void 0)return;let n=e.glyph.y+e.glyph.height/2;return e.center===void 0?{x:t===`start`?e.glyph.x:e.glyph.x+e.glyph.width,y:n}:{x:e.center.x+(t===`start`?-7:7),y:n}}let c=r(t===`start`?s.days.start:s.days.end+1),l=o.get(s.row);if(l!==void 0&&l.type===`task`)return{x:c,y:l.y+4+12};let u=n.filter(e=>e.row===s.row).sort((e,n)=>t===`start`?e.glyph.x-n.glyph.x:n.glyph.x+n.glyph.width-(e.glyph.x+e.glyph.width));if(u.length!==0)return{x:c,y:u[0].glyph.y+u[0].glyph.height/2}},c=[];return(e.dependencies??[]).forEach((e,t)=>{let n=Lt(e),r=Rt(n),a=s(e.from,r.from),o=s(e.to,r.to),l=zt(e,i);if(a===void 0||o===void 0||l===void 0)return;let u={x:a.x+(r.from===`end`?8:-8),y:a.y},d={x:o.x+(r.to===`start`?-8:8),y:o.y};if(a.y===o.y&&r.from===`end`&&r.to===`start`&&o.x>=a.x-14){c.push({index:t,from:e.from,to:e.to,type:n,satisfied:l,points:[a,o]});return}let f=o.y>a.y?o.y-12:(o.y,a.y,o.y+12);c.push({index:t,from:e.from,to:e.to,type:n,satisfied:l,points:[a,u,{x:u.x,y:f},{x:d.x,y:f},d,o]})}),c}function un(e){let t=e.rows.reduce((e,t)=>Math.max(e,(t.label??``).length),0);return Math.min(Math.max(t*_t+24,120),280)}function dn(e,t){for(let n of e.rows){if(n.type!==`task`)continue;if(n.id===t)return`"${n.label}" (${t})`;let e=n.items.find(e=>e.id===t);if(e!==void 0){let n=$t(e);return n===void 0?t:`"${n}" (${t})`}}return t}function fn(e,t,n){let r=n===!1?` — not satisfied by the dates`:``;return`${dn(e,t.to)} waits on ${dn(e,t.from)} (${Lt(t)})${r}`}function pn(e){let t=[];e.title!==void 0&&e.title!==``&&t.push(e.title),e.comparedTo!==void 0&&t.push(`Compared with ${e.comparedTo.label}${e.comparedTo.date===void 0?``:` (${e.comparedTo.date})`}`),t.push(`From ${e.time.start} to ${e.time.end}, by ${e.time.scale}`);for(let n of e.rows){if(t.push(``),n.type===`separator`){t.push(n.label?`— ${n.label} —`:`———`);continue}let e=n.role===void 0?``:n.role===`added`?` — new`:` — removed`;t.push(`${n.label} [${n.id}]${n.items.length===0?` — no items`:``}${e}`);for(let e of n.items){let n=e.type===`activity`?`${e.start} to ${e.end}`:e.date,r=e.label===void 0?``:`: ${e.label}`,i=e.kind===void 0?``:` [${e.kind}]`,a=e.id===void 0?``:` (${e.id})`,o=(()=>{if(e.role===`added`)return` — new`;if(e.role===`removed`)return` — removed`;let t=Ut(e);return t===``||e.previous===void 0?``:` — moved ${t}, was ${`date`in e.previous?e.previous.date:`${e.previous.start} to ${e.previous.end}`}`})();t.push(` ${e.type} ${n}${r}${i}${a}${o}`)}}let n=[...(e.periods??[]).map(e=>` period ${e.start} to ${e.end}${e.label?`: ${e.label}`:``}${e.kind?` [${e.kind}]`:``}`),...(e.references??[]).map(e=>` reference ${e.date}: ${e.label}${e.kind?` [${e.kind}]`:``}`)];n.length>0&&t.push(``,`Calendar`,...n);let r=e.dependencies??[];if(r.length>0){let n=Ft(e);t.push(``,`Dependencies`);for(let i of r)t.push(` ${fn(e,i,zt(i,n))}`)}return t}function mn(e){let t=[],n=(e,n)=>{let r=jt(e);return r===void 0&&t.push({rule:`invalid-date`,path:n,message:`"${e}" is not a day of the calendar`}),r},r=n(e.time.start,`/data/time/start`),i=n(e.time.end,`/data/time/end`),a=r!==void 0&&i!==void 0&&r<=i?{start:r,end:i}:void 0;r!==void 0&&i!==void 0&&r>i&&t.push({rule:`inverted-range`,path:`/data/time`,message:`the timeline starts on ${e.time.start}, after it ends on ${e.time.end}`});let o=`${e.time.start} to ${e.time.end}`,s=new Map,c=(e,n)=>{if(e===void 0)return;let r=s.get(e);r===void 0?s.set(e,n):t.push({rule:`duplicate-identifier`,path:`${n}/id`,message:`identifier "${e}" is already declared at ${r}`})},l=e.comparedTo!==void 0;e.comparedTo?.date!==void 0&&n(e.comparedTo.date,`/data/comparedTo/date`);let u=e=>t.push({rule:`comparison-without-reference`,path:e,message:"previous dates and change roles describe a comparison; declare `comparedTo` naming the plan they compare with"}),d=new Set;return e.rows.forEach((e,r)=>{if(e.type!==`task`)return;let i=`/data/rows/${r}`;c(e.id,i),e.role!==void 0&&!l&&u(`${i}/role`),e.items.forEach((r,s)=>{let f=`${i}/items/${s}`;if(c(r.id,f),r.kind!==void 0&&d.add(r.kind),r.role!==void 0&&!l&&u(`${f}/role`),r.previous!==void 0){l||u(`${f}/previous`),(r.role!==void 0||e.role!==void 0)&&t.push({rule:`contradictory-change`,path:`${f}/previous`,message:`an item that is ${r.role??`in a task that is ${e.role}`} has no previous dates; it is new or dropped, not moved`});let i=r.previous,s=r.type===`activity`?{first:n(i.start,`${f}/previous/start`),last:n(i.end,`${f}/previous/end`)}:(()=>{let e=n(i.date,`${f}/previous/date`);return{first:e,last:e}})();s.first!==void 0&&s.last!==void 0&&(s.first>s.last?t.push({rule:`inverted-range`,path:`${f}/previous`,message:`the previous dates start on ${i.start}, after they end on ${i.end}`}):a!==void 0&&(s.first<a.start||s.last>a.end)&&t.push({rule:`item-outside-range`,path:`${f}/previous`,message:`the previous dates fall outside the timeline's range ${o}; the range covers both plans, so widen \`time\``}))}r.role!==void 0&&e.role!==void 0&&r.role!==e.role&&t.push({rule:`contradictory-change`,path:`${f}/role`,message:`an item ${r.role} in a task that is ${e.role}`});let p,m;if(r.type===`activity`){if(p=n(r.start,`${f}/start`),m=n(r.end,`${f}/end`),p!==void 0&&m!==void 0&&p>m){t.push({rule:`inverted-range`,path:f,message:`the activity starts on ${r.start}, after it ends on ${r.end}`});return}}else p=m=n(r.date,`${f}/date`);a!==void 0&&p!==void 0&&m!==void 0&&(p<a.start||m>a.end)&&t.push({rule:`item-outside-range`,path:f,message:r.type===`activity`?`the activity runs ${r.start} to ${r.end}, outside the timeline's range ${o}; widen \`time\` or move the activity`:`the milestone falls on ${r.date}, outside the timeline's range ${o}; widen \`time\` or move the milestone`})})}),(e.periods??[]).forEach((e,r)=>{let i=`/data/periods/${r}`;e.kind!==void 0&&d.add(e.kind);let s=n(e.start,`${i}/start`),c=n(e.end,`${i}/end`);s!==void 0&&c!==void 0&&(s>c?t.push({rule:`inverted-range`,path:i,message:`the period starts on ${e.start}, after it ends on ${e.end}`}):a!==void 0&&(c<a.start||s>a.end)&&t.push({rule:`period-outside-range`,path:i,message:`the period ${e.start} to ${e.end} lies wholly outside the timeline's range ${o}, so nothing of it could be drawn`}))}),(e.references??[]).forEach((e,r)=>{let i=`/data/references/${r}`;e.kind!==void 0&&d.add(e.kind);let s=n(e.date,`${i}/date`);s!==void 0&&a!==void 0&&(s<a.start||s>a.end)&&t.push({rule:`item-outside-range`,path:i,message:`the reference date ${e.date} is outside the timeline's range ${o}; widen \`time\` or move it`})}),d.size>et.kindsPerVocabulary&&t.push({rule:`too-many-kinds`,path:`/data/rows`,message:`${d.size} distinct item types, and no more than ${et.kindsPerVocabulary} can be told apart in a rendering`,observed:d.size,limit:et.kindsPerVocabulary}),t.push(...gn(e,Ft(e))),t.push(...hn(e)),t}function hn(e){let t=new Set;for(let n of e.rows)if(n.type===`task`){n.role===`removed`&&t.add(n.id);for(let e of n.items)e.id!==void 0&&(e.role===`removed`||n.role===`removed`)&&t.add(e.id)}let n=[];return(e.dependencies??[]).forEach((e,r)=>{for(let i of[`from`,`to`])t.has(e[i])&&n.push({rule:`dependency-on-removed`,path:`/data/dependencies/${r}/${i}`,message:`"${e[i]}" was dropped from the plan, so nothing can depend on it any more; remove the dependency`})}),n}function gn(e,t){let n=[],r=e.dependencies??[],i=[],a=new Map;r.forEach((r,o)=>{let s=`/data/dependencies/${o}`,c=!0;for(let i of[`from`,`to`]){let a=r[i],o=t.get(a);if(o===void 0)c=!1,n.push({rule:`unresolved-endpoint`,path:`${s}/${i}`,message:`"${a}" is not the identifier of any task or item this timeline declares`});else if(o.type===`task`&&o.days===void 0){c=!1;let t=e.rows[o.row];if(t.type===`task`&&t.items.length>0)continue;n.push({rule:`empty-task-endpoint`,path:`${s}/${i}`,message:`task "${a}" holds no item, so it has no start or finish for a dependency to link`})}}if(!c)return;let l=t.get(r.from),u=t.get(r.to),d=(e,t)=>e.type===`task`&&t.type!==`task`&&t.row===e.row;if(l.id===u.id||d(l,u)||d(u,l)){n.push({rule:`self-dependency`,path:s,message:l.id===u.id?`"${l.id}" cannot depend on itself`:`a task and one of its own items cannot depend on each other: the task's span is made of its items`});return}let f=JSON.stringify([r.from,r.to,Lt(r)]),p=a.get(f);p===void 0?(a.set(f,o),i.push({from:r.from,to:r.to,index:o})):n.push({rule:`duplicate-dependency`,path:s,message:`the same dependency is already declared at /data/dependencies/${p}`})});let o=_n(i);return o!==void 0&&n.push({rule:`dependency-cycle`,path:`/data/dependencies/${o.index}`,message:`dependencies form a cycle, which no dates can honour: ${o.ids.join(` → `)}`}),n}function _n(e){let t=new Map;for(let n of e){let e=t.get(n.from)??[];e.push({to:n.to,index:n.index}),t.set(n.from,e)}let n=new Map,r=[];for(let e of t.keys()){if(n.has(e))continue;let i=[{id:e,next:0}];for(n.set(e,`open`),r.push({id:e,index:-1});i.length>0;){let e=i[i.length-1],a=t.get(e.id)??[];if(e.next>=a.length){n.set(e.id,`done`),i.pop(),r.pop();continue}let o=a[e.next++],s=n.get(o.to);if(s===`open`){let e=r.findIndex(e=>e.id===o.to);return{ids:[...r.slice(e).map(e=>e.id),o.to],index:o.index}}s===void 0&&(n.set(o.to,`open`),i.push({id:o.to,next:0}),r.push({id:o.to,index:o.index}))}}}function vn(e){let t=e.data;return e.kind===`graph`?Array.isArray(t.nodes)&&Array.isArray(t.edges):e.kind===`sequence`?Array.isArray(t.participants)&&Array.isArray(t.messages):e.kind===`timeline`?typeof t.time==`object`&&t.time!==null&&Array.isArray(t.rows):Array.isArray(t.columns)&&Array.isArray(t.rows)}function yn(e){return e.kind===`graph`?e.data.nodes:e.kind===`sequence`?e.data.participants:[]}function bn(e){return e.kind===`graph`?e.data.edges:e.kind===`sequence`?e.data.messages:[]}function xn(e){return e.kind===`graph`||e.kind===`sequence`?e.data.containers??[]:[]}function Sn(e){return e.kind===`graph`?`/data/nodes`:`/data/participants`}function Cn(e){return e.kind===`graph`?`/data/edges`:`/data/messages`}function wn(e){if(e.kind===`timeline`)return[];let t=e.data,n=[];for(let e of[`nodes`,`edges`,`participants`,`messages`,`rows`,`relations`]){let r=t[e];Array.isArray(r)&&r.forEach((t,r)=>{if(typeof t!=`object`||!t||Array.isArray(t))return;let i=t;n.push({at:`/data/${e}/${r}`,ref:typeof i.ref==`string`?i.ref:void 0,set:i.set,expect:i.expect,locations:i.locations})})}return n}function Tn(e){if(e.kind!==`table`)return[];let t=e.data.rows,n=[];return t.forEach((e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e;(r.ref!==void 0||r.set!==void 0)&&n.push({at:`/data/rows/${t}`,...typeof r.ref==`string`?{ref:r.ref}:{},...r.set===void 0?{}:{set:r.set}})}),n}function En(e){if(e.kind!==`table`)return[];let t=e.data.rows,n=[];return t.forEach((e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e.id;typeof r==`string`&&n.push({id:r,at:`/data/rows/${t}`})}),n}function Dn(e){if(e.kind!==`table`)return[];let t=e.data.relations;return Array.isArray(t)?t:[]}function On(e,t){return e===`timeline`?`a timeline is maintained by presenting the revised timeline again, not proposed as a change, ${t}`:`a ${e} is a projection and cannot be proposed, ${t}`}function kn(e){let t=[];if(!vn(e))return t.push({rule:`kind-data-mismatch`,path:`/data`,message:`data does not carry what kind "${e.kind}" declares`}),t;let n=Ze(e.schema).includes(e.kind);e.target!==void 0&&!n&&t.push({rule:`kind-not-proposable`,path:`/target`,message:On(e.kind,`so it carries no target`)}),e.removals!==void 0&&(n?e.target===void 0&&t.push({rule:`removal-without-target`,path:`/removals`,message:`removals need a target: an artifact that does not exist yet has nothing to remove`}):t.push({rule:`kind-not-proposable`,path:`/removals`,message:On(e.kind,`so it declares no removals`)}));let r=yn(e),i=Sn(e),a=new Map;r.forEach((e,n)=>{let r=a.get(e.id);r===void 0?a.set(e.id,n):t.push({rule:`duplicate-identifier`,path:`${i}/${n}/id`,message:`identifier "${e.id}" is already declared at ${i}/${r}`})});let o=new Map;xn(e).forEach((e,n)=>{let r=o.get(e.id);r===void 0?o.set(e.id,n):t.push({rule:`duplicate-container-identifier`,path:`/data/containers/${n}/id`,message:`container "${e.id}" is already declared at /data/containers/${r}`})}),r.forEach((e,n)=>{for(let[r,a]of[[`container`,e.container],[`set/container`,e.set?.container]])a!==void 0&&!o.has(a)&&t.push({rule:`unresolved-container`,path:`${i}/${n}/${r}`,message:`"${a}" is not a container declared in /data/containers`})});let s=Cn(e);bn(e).forEach((e,n)=>{for(let r of[`from`,`to`]){let o=e[r];a.has(o)||t.push({rule:`unresolved-endpoint`,path:`${s}/${n}/${r}`,message:`"${o}" is not an identifier declared in ${i}`})}});let c=new Map,l=(e,n,r)=>{if(n===void 0)return;let i=`${e}:${n}`,a=c.get(i);a===void 0?c.set(i,r):t.push({rule:`duplicate-reference`,path:r,message:`${e} "${n}" is already addressed at ${a}; a proposal states one intention per thing`})};r.forEach((e,t)=>l(`element`,e.ref,`${i}/${t}`)),bn(e).forEach((e,t)=>l(`relationship`,e.ref,`${s}/${t}`)),Tn(e).forEach(e=>l(`row`,e.ref,e.at)),(e.removals??[]).forEach((e,t)=>l(e.type,e.ref,`/removals/${t}`));let u=[...r.map((e,t)=>({at:`${i}/${t}`,ref:e.ref,set:e.set})),...bn(e).map((t,n)=>({at:`${Cn(e)}/${n}`,ref:t.ref,set:t.set})),...Tn(e)];for(let r of u)r.set!==void 0&&(r.ref===void 0?t.push({rule:`change-without-reference`,path:`${r.at}/set`,message:`a change names a reference to change; without one this is a new thing, and its fields are its values`}):n?e.target===void 0&&t.push({rule:`change-without-target`,path:`${r.at}/set`,message:`a change needs a target: naming what is being changed is what makes this a proposal rather than a new artifact`}):t.push({rule:`kind-not-proposable`,path:`${r.at}/set`,message:On(e.kind,`so nothing in it declares a change`)}));let d=e=>{let t=new Set;for(let n of e)n.kind!==void 0&&n.kind!==``&&t.add(n.kind);return t},f=[[e.kind===`sequence`?`participant`:`element`,i,d(r)],[e.kind===`sequence`?`message`:`relationship`,Cn(e),d(bn(e))]];for(let[e,n,r]of f)r.size>et.kindsPerVocabulary&&t.push({rule:`too-many-kinds`,path:n,message:`${r.size} distinct ${e} types, and no more than ${et.kindsPerVocabulary} can be told apart in a rendering`,observed:r.size,limit:et.kindsPerVocabulary});let p=e.viewpoints;if(Array.isArray(p)){if(e.kind!==`graph`)t.push({rule:`viewpoints-without-graph`,path:`/viewpoints`,message:`only a graph declares viewpoints; a ${e.kind} has no element and relationship kinds for one to retain`});else{let n=new Set(r.map(e=>e.kind).filter(e=>!!e)),i=new Set(bn(e).map(e=>e.kind).filter(e=>!!e)),a=new Map;p.forEach((e,r)=>{let o=`/viewpoints/${r}`,{id:s,elementKinds:c,relationshipKinds:l}=e,u=a.get(s);u===void 0?a.set(s,r):t.push({rule:`duplicate-viewpoint-identifier`,path:`${o}/id`,message:`viewpoint "${s}" is already declared at /viewpoints/${u}`}),c===void 0&&l===void 0&&t.push({rule:`empty-viewpoint`,path:o,message:`viewpoint "${s}" retains no kind, so it would show nothing it was not already showing; name elementKinds, relationshipKinds, or both`});let d=[[c,n,i,`elementKinds`,`element`,`relationship`],[l,i,n,`relationshipKinds`,`relationship`,`element`]];for(let[e,n,r,i,a,c]of d)e?.forEach((e,l)=>{n.has(e)||t.push({rule:`unresolved-viewpoint-kind`,path:`${o}/${i}/${l}`,message:`viewpoint "${s}" retains ${a} kind "${e}", and no ${a} of this document has it`+(r.has(e)?` (it is a ${c} kind here, which is a different vocabulary)`:``)})})})}}if(e.kind===`table`){let{columns:n,rows:r}=e.data;r.forEach((e,r)=>{let{cells:i,heading:a}=$e(e);a===void 0&&i.length!==n.length&&t.push({rule:`row-column-mismatch`,path:`/data/rows/${r}`,message:`row has ${i.length} values but ${n.length} columns are declared`,observed:i.length,limit:n.length})})}e.kind===`timeline`&&t.push(...mn(e.data));for(let n of wn(e)){n.expect!==void 0&&(e.target===void 0?t.push({rule:`expectation-without-target`,path:`${n.at}/expect`,message:`an expectation is checked by the authority a proposal targets; a document that targets nothing has nobody to check it`}):n.ref===void 0&&t.push({rule:`expectation-without-reference`,path:`${n.at}/expect`,message:`an expectation describes something that already exists, and this item carries no reference to one`}));let r=n.set?.removeAttributes;if(Array.isArray(r)){let e=n.set?.attributes??{},i=new Map;r.forEach((r,a)=>{if(typeof r!=`string`)return;let o=i.get(r);o===void 0?i.set(r,a):t.push({rule:`duplicate-attribute-removal`,path:`${n.at}/set/removeAttributes/${a}`,message:`"${r}" is already removed at ${n.at}/set/removeAttributes/${o}`}),Object.prototype.hasOwnProperty.call(e,r)&&t.push({rule:`attribute-set-and-removed`,path:`${n.at}/set/removeAttributes/${a}`,message:`"${r}" is both assigned and removed; a proposal states one intention per property`})})}Array.isArray(n.locations)&&n.locations.forEach((e,r)=>{if(typeof e!=`object`||!e)return;let i=e.range;i!==void 0&&(i.endLine<i.startLine||i.endLine===i.startLine&&i.endCharacter!==void 0&&i.startCharacter!==void 0&&i.endCharacter<i.startCharacter)&&t.push({rule:`location-range-reversed`,path:`${n.at}/locations/${r}/range`,message:`a range ends before it begins, so it selects nothing a reader could be taken to`})})}e.kind===`table`&&e.data.rows.forEach((e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e;r.role!==void 0&&r.set!==void 0&&t.push({rule:`role-with-change`,path:`/data/rows/${n}/role`,message:`a row states what it observed or what it asks for, not both: a declared role beside a change is a report and an instruction at once`})});let m=new Map;for(let n of En(e)){let e=m.get(n.id);e===void 0?m.set(n.id,n.at):t.push({rule:`duplicate-identifier`,path:`${n.at}/id`,message:`identifier "${n.id}" is already declared at ${e}`})}return Dn(e).forEach((e,n)=>{for(let r of[`from`,`to`]){let i=e[r];if(typeof i!=`object`||!i)continue;let a=i.id;typeof a==`string`&&(m.has(a)||t.push({rule:`unresolved-endpoint`,path:`/data/relations/${n}/${r}`,message:`"${a}" is not the identifier of any row this document declares`}))}}),t}function An(e,t){let n=t(e);if(n.length>0)return{valid:!1,issues:n};let r=e,i=kn(r);return i.length>0?{valid:!1,issues:i}:{valid:!0,envelope:r,issues:[]}}function jn(e,t,n){let r=pt(e,n);if(r!==void 0)return{valid:!1,issues:[r]};let i;try{i=JSON.parse(e)}catch{return{valid:!1,issues:[{rule:`not-json`,path:``,message:`document is not parseable JSON`}]}}let a=An(i,t);if(!a.valid)return a;let o=pt(e,n,a.envelope.schema);if(o!==void 0)return{valid:!1,issues:[o]};let s=ht(a.envelope,n);return s.length>0?{valid:!1,issues:s}:{valid:!0,envelope:a.envelope,measurement:gt(a.envelope,e),issues:[]}}function Mn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.schema;if(typeof t==`string`&&t.startsWith(`urn:structured-exchange:`))return t}function Nn(e,t,n){let r=pt(e,n);if(r!==void 0)return{status:`too-large`,issue:r};let i;try{i=JSON.parse(e)}catch{return{status:`not-a-document`,why:`unparseable`}}let a=Mn(i);if(a===void 0)return{status:`not-a-document`,why:`undeclared`};if(ot(a)===void 0)return{status:`unsupported-version`,schema:a};let o=An(i,t);if(!o.valid)return{status:`invalid`,issues:o.issues};let s=pt(e,n,o.envelope.schema);return s===void 0?{status:`valid`,envelope:o.envelope}:{status:`too-large`,issue:s}}function Pn(e){let t=e.replace(/\r\n/g,`
22
22
  `).replace(/\s+$/,``),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return`sx-${(n>>>0).toString(16).padStart(8,`0`)}-${t.length.toString(36)}`}async function Fn(e){try{return await navigator.clipboard.writeText(e),!0}catch{let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;opacity:0;pointer-events:none`,document.body.append(t);try{return t.select(),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}}}function In(e,t,n){return e>=t&&e<=n}function Ln(e){return e===8205}function Rn(e){return In(e,55296,56319)}function zn(e){return In(e,127462,127487)}function Bn(e){return In(e,65024,65039)}function Vn(e){return In(e,768,879)||In(e,6832,6911)||In(e,7616,7679)||In(e,65056,65071)}function Hn(e){return e>65535?2:1}function Un(e,t){for(;t<e.length;){let n=e.codePointAt(t);if(Vn(n)||Bn(n))t+=Hn(n);else break}return t}function Wn(e,t){let n=e.codePointAt(t),r=t+Hn(n);for(r=Un(e,r);r<e.length-1&&Ln(e.codePointAt(r));){let t=e.codePointAt(r+1);r+=1+Hn(t),r=Un(e,r)}return zn(n)&&r<e.length&&zn(e.codePointAt(r))&&(r+=Hn(e.codePointAt(r))),r}function Gn(e){return Rn(e)||Vn(e)||Bn(e)||Ln(e)}function Kn(e,t){if(t===0)return!0;let n=0,r=0;for(;r<e.length;)if(r=Wn(e,r),n++,n>=t)return!0;return!1}function qn(e,t){let n=0,r=0;for(;r<e.length;)if(r=Wn(e,r),n++,n>t)return!1;return!0}function Jn(e,t){if(t===0)return!0;let n=0;for(;n<e.length;){if(Gn(e.charCodeAt(n)))return Kn(e,t);if(n++,n>=t)return!0}return!1}function Yn(e,t){let n=0;for(;n<e.length;){if(Gn(e.charCodeAt(n)))return qn(e,t);if(n++,n>t)return!1}return!0}function Xn(e){return Array.isArray(e)}function Zn(e){return or(typeof e,`bigint`)}function Qn(e){return or(typeof e,`boolean`)}function $n(e){if(ar(e)||!er(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function er(e){return or(typeof e,`function`)}function tr(e){return or(e,null)}function nr(e){return or(typeof e,`object`)&&!tr(e)}function rr(e){return or(typeof e,`string`)}function ir(e){return or(typeof e,`symbol`)}function ar(e){return or(e,void 0)}function or(e,t){return e===t}function sr(e,t){return Yn(e,t)}function cr(e,t){return Jn(e,t)}function lr(e){return e instanceof Boolean}function ur(e){return e instanceof Number}function dr(e){return e instanceof String}function fr(e){return globalThis.ArrayBuffer.isView(e)}function pr(e){return e instanceof globalThis.RegExp}function mr(e){return e instanceof globalThis.Date}var hr=[];function gr(e){hr=e.variables}var _r=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`schema`in e&&`kind`in e&&`data`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[0].test(e)||!1)&&e.schema===`urn:structured-exchange:1`&&(e.kind===`graph`||e.kind===`sequence`||e.kind===`table`)&&(e.target===void 0||!(`target`in e)||vr(e.target))&&(e.removals===void 0||!(`removals`in e)||Array.isArray(e.removals)&&e.removals.every((e,t)=>yr(e))&&e.removals.length<=500)&&[typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`nodes`in e.data&&`edges`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>hr[2].test(e)||!1)&&Array.isArray(e.data.nodes)&&e.data.nodes.every((e,t)=>Cr(e))&&e.data.nodes.length<=500&&e.data.nodes.length>=1&&Array.isArray(e.data.edges)&&e.data.edges.every((e,t)=>Tr(e))&&e.data.edges.length<=2e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>Dr(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`participants`in e.data&&`messages`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>hr[8].test(e)||!1)&&Array.isArray(e.data.participants)&&e.data.participants.every((e,t)=>Cr(e))&&e.data.participants.length<=100&&e.data.participants.length>=1&&Array.isArray(e.data.messages)&&e.data.messages.every((e,t)=>Or(e))&&e.data.messages.length<=1e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>Dr(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`columns`in e.data&&`rows`in e.data&&Object.getOwnPropertyNames(e.data).length===2&&Array.isArray(e.data.columns)&&e.data.columns.every((e,t)=>typeof e==`string`&&sr(e,200)&&cr(e,1))&&e.data.columns.length<=50&&e.data.columns.length>=1&&Array.isArray(e.data.rows)&&e.data.rows.every((e,t)=>[Ar(e),typeof e==`object`&&!!e&&!Array.isArray(e)&&`cells`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[11].test(e)||!1)&&Ar(e.cells)&&(e.role===void 0||!(`role`in e)||e.role===`added`||e.role===`changed`||e.role===`context`||e.role===`removed`)].reduce((e,t,n)=>t===!0?++e:e,0)===1)&&e.data.rows.length<=5e3].reduce((e,t,n)=>t===!0?++e:e,0)===1),vr=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),yr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`ref`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[1].test(e)||!1)&&(e.type===`element`||e.type===`relationship`)&&vr(e.ref)&&(e.label===void 0||!(`label`in e)||br(e.label))&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))&&(e.from===void 0||!(`from`in e)||Sr(e.from))&&(e.to===void 0||!(`to`in e)||Sr(e.to))),br=(e=>typeof e==`string`&&sr(e,500)),xr=(e=>typeof e==`string`&&sr(e,100)&&cr(e,1)),Sr=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),Cr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[3].test(e)||!1)&&Sr(e.id)&&(e.ref===void 0||!(`ref`in e)||vr(e.ref))&&(e.label===void 0||!(`label`in e)||br(e.label))&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))&&(e.set===void 0||!(`set`in e)||wr(e.set))&&(e.container===void 0||!(`container`in e)||Sr(e.container))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),wr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>hr[4].test(e)||!1)&&(e.label===void 0||!(`label`in e)||br(e.label))&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))&&(e.container===void 0||!(`container`in e)||Sr(e.container))&&Object.getOwnPropertyNames(e).length>=1),Tr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[5].test(e)||!1)&&Sr(e.from)&&Sr(e.to)&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))&&(e.ref===void 0||!(`ref`in e)||vr(e.ref))&&(e.label===void 0||!(`label`in e)||br(e.label))&&(e.set===void 0||!(`set`in e)||Er(e.set))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`kind`in e)),Er=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>hr[6].test(e)||!1)&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))&&(e.label===void 0||!(`label`in e)||br(e.label))&&Object.getOwnPropertyNames(e).length>=1),Dr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&`label`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[7].test(e)||!1)&&Sr(e.id)&&br(e.label)&&(e.kind===void 0||!(`kind`in e)||xr(e.kind))),Or=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>hr[9].test(e)||!1)&&Sr(e.from)&&Sr(e.to)&&(e.ref===void 0||!(`ref`in e)||vr(e.ref))&&(e.label===void 0||!(`label`in e)||br(e.label))&&(e.set===void 0||!(`set`in e)||kr(e.set))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),kr=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>hr[10].test(e)||!1)&&(e.label===void 0||!(`label`in e)||br(e.label))&&Object.getOwnPropertyNames(e).length>=1),Ar=(e=>Array.isArray(e)&&e.every((e,t)=>(typeof e==`string`||Number.isFinite(e)||typeof e==`boolean`||e===null)&&(typeof e!=`string`||sr(e,1e3)))&&e.length<=50);function jr(e){return _r(e)}gr({variables:[RegExp(`(^schema$|^kind$|^target$|^removals$|^data$)`,`u`),RegExp(`(^type$|^ref$|^label$|^kind$|^from$|^to$)`,`u`),RegExp(`(^nodes$|^edges$|^containers$)`,`u`),RegExp(`(^id$|^ref$|^label$|^kind$|^set$|^container$)`,`u`),RegExp(`(^label$|^kind$|^container$)`,`u`),RegExp(`(^from$|^to$|^kind$|^ref$|^label$|^set$)`,`u`),RegExp(`(^kind$|^label$)`,`u`),RegExp(`(^id$|^label$|^kind$)`,`u`),RegExp(`(^participants$|^messages$|^containers$)`,`u`),RegExp(`(^from$|^to$|^ref$|^label$|^set$)`,`u`),RegExp(`(^label$)`,`u`),RegExp(`(^cells$|^role$)`,`u`)]});function Mr(){throw Error(`Unreachable`)}function Nr(e){let t=new Set,n=e;for(;n&&n!==Object.prototype;){for(let e of Reflect.ownKeys(n))e!==`constructor`&&typeof e!=`symbol`&&t.add(e);n=Object.getPrototypeOf(n)}return[...t]}function Pr(e){return typeof e==`number`}var Fr;(function(e){e[e.Array=0]=`Array`,e[e.BigInt=1]=`BigInt`,e[e.Boolean=2]=`Boolean`,e[e.Date=3]=`Date`,e[e.Constructor=4]=`Constructor`,e[e.Function=5]=`Function`,e[e.Null=6]=`Null`,e[e.Number=7]=`Number`,e[e.Object=8]=`Object`,e[e.RegExp=9]=`RegExp`,e[e.String=10]=`String`,e[e.Symbol=11]=`Symbol`,e[e.TypeArray=12]=`TypeArray`,e[e.Undefined=13]=`Undefined`})(Fr||={});var Ir=BigInt(`14695981039346656037`),[Lr,Rr]=[BigInt(`1099511628211`),BigInt(`18446744073709551616`)],zr=Array.from({length:256}).map((e,t)=>BigInt(t)),Br=new Float64Array(1),Vr=new DataView(Br.buffer),Hr=new Uint8Array(Br.buffer);function Ur(e){Ir^=zr[e],Ir=Ir*Lr%Rr}function Wr(e){Ur(Fr.Array);for(let t of e)ai(t)}function Gr(e){Ur(Fr.BigInt),Vr.setBigInt64(0,e);for(let e of Hr)Ur(e)}function Kr(e){Ur(Fr.Boolean),Ur(+!!e)}function qr(e){Ur(Fr.Constructor),ai(e.toString())}function Jr(e){Ur(Fr.Date),ai(e.getTime())}function Yr(e){Ur(Fr.Function),ai(e.toString())}function Xr(e){Ur(Fr.Null)}function Zr(e){Ur(Fr.Number),Vr.setFloat64(0,e,!0);for(let e of Hr)Ur(e)}function Qr(e){Ur(Fr.Object);for(let t of Nr(e).sort())ai(t),ai(e[t])}function $r(e){Ur(Fr.RegExp),ti(e.toString())}var ei=new TextEncoder;function ti(e){Ur(Fr.String);for(let t of ei.encode(e))Ur(t)}function ni(e){Ur(Fr.Symbol),ai(e.toString())}function ri(e){Ur(Fr.TypeArray);let t=new Uint8Array(e.buffer);for(let e=0;e<t.length;e++)Ur(t[e])}function ii(e){return Ur(Fr.Undefined)}function ai(e){return fr(e)?ri(e):mr(e)?Jr(e):pr(e)?$r(e):lr(e)?Kr(e.valueOf()):dr(e)?ti(e.valueOf()):ur(e)?Zr(e.valueOf()):Pr(e)?Zr(e):Xn(e)?Wr(e):Qn(e)?Kr(e):Zn(e)?Gr(e):$n(e)?qr(e):tr(e)?Xr(e):nr(e)?Qr(e):rr(e)?ti(e):ir(e)?ni(e):ar(e)?ii(e):er(e)?Yr(e):Mr()}function oi(e){return Ir=BigInt(`14695981039346656037`),ai(e),Ir}function si(e){return oi(e).toString(16).padStart(16,`0`)}var ci=[];function li(e){ci=e.variables}var ui=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`schema`in e&&`kind`in e&&`data`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[0].test(e)||!1)&&e.schema===`urn:structured-exchange:2`&&(e.kind===`graph`||e.kind===`sequence`||e.kind===`table`)&&(e.profile===void 0||!(`profile`in e)||typeof e.profile==`string`&&sr(e.profile,200)&&cr(e.profile,1))&&(e.target===void 0||!(`target`in e)||typeof e.target==`object`&&e.target!==null&&!Array.isArray(e.target)&&`ref`in e.target&&Object.getOwnPropertyNames(e.target).every((e,t)=>ci[1].test(e)||!1)&&di(e.target.ref)&&(e.target.revision===void 0||!(`revision`in e.target)||fi(e.target.revision)))&&(e.removals===void 0||!(`removals`in e)||Array.isArray(e.removals)&&e.removals.every((e,t)=>pi(e))&&e.removals.length<=500)&&(e.artifacts===void 0||!(`artifacts`in e)||Array.isArray(e.artifacts)&&e.artifacts.every((e,t)=>_i(e))&&e.artifacts.length<=50)&&(e.viewpoints===void 0||!(`viewpoints`in e)||Array.isArray(e.viewpoints)&&e.viewpoints.every((e,t)=>vi(e))&&e.viewpoints.length<=20)&&[typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`nodes`in e.data&&`edges`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>ci[6].test(e)||!1)&&Array.isArray(e.data.nodes)&&e.data.nodes.every((e,t)=>yi(e))&&e.data.nodes.length<=500&&e.data.nodes.length>=1&&Array.isArray(e.data.edges)&&e.data.edges.every((e,t)=>ji(e))&&e.data.edges.length<=2e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>Ni(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`participants`in e.data&&`messages`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>ci[16].test(e)||!1)&&Array.isArray(e.data.participants)&&e.data.participants.every((e,t)=>yi(e))&&e.data.participants.length<=100&&e.data.participants.length>=1&&Array.isArray(e.data.messages)&&e.data.messages.every((e,t)=>Pi(e))&&e.data.messages.length<=1e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>Ni(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`columns`in e.data&&`rows`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>ci[19].test(e)||!1)&&Array.isArray(e.data.columns)&&e.data.columns.every((e,t)=>typeof e==`string`&&sr(e,200)&&cr(e,1))&&e.data.columns.length<=50&&e.data.columns.length>=1&&Array.isArray(e.data.rows)&&e.data.rows.every((e,t)=>[Ii(e),Li(e),Bi(e)].reduce((e,t,n)=>t===!0?++e:e,0)===1)&&e.data.rows.length<=5e3&&(e.data.relations===void 0||!(`relations`in e.data)||Array.isArray(e.data.relations)&&e.data.relations.every((e,t)=>Vi(e))&&e.data.relations.length<=2e3)].reduce((e,t,n)=>t===!0?++e:e,0)===1),di=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),fi=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),pi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`ref`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[2].test(e)||!1)&&(e.type===`element`||e.type===`relationship`||e.type===`row`)&&di(e.ref)&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.from===void 0||!(`from`in e)||gi(e.from))&&(e.to===void 0||!(`to`in e)||gi(e.to))),mi=(e=>typeof e==`string`&&sr(e,500)),hi=(e=>typeof e==`string`&&sr(e,100)&&cr(e,1)),gi=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),_i=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`rel`in e&&`uri`in e&&`sha256`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[3].test(e)||!1)&&typeof e.rel==`string`&&sr(e.rel,100)&&cr(e.rel,1)&&typeof e.uri==`string`&&sr(e.uri,2e3)&&cr(e.uri,1)&&typeof e.sha256==`string`&&ci[4].test(e.sha256)&&(e.mediaType===void 0||!(`mediaType`in e)||typeof e.mediaType==`string`&&sr(e.mediaType,100)&&cr(e.mediaType,1))&&(e.label===void 0||!(`label`in e)||mi(e.label))),vi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&`label`in e&&`concern`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[5].test(e)||!1)&&gi(e.id)&&typeof e.label==`string`&&sr(e.label,500)&&cr(e.label,1)&&typeof e.concern==`string`&&sr(e.concern,500)&&cr(e.concern,1)&&(e.elementKinds===void 0||!(`elementKinds`in e)||Array.isArray(e.elementKinds)&&e.elementKinds.every((e,t)=>hi(e))&&e.elementKinds.length<=64&&e.elementKinds.length>=1&&new Set(e.elementKinds.map(si)).size===e.elementKinds.length)&&(e.relationshipKinds===void 0||!(`relationshipKinds`in e)||Array.isArray(e.relationshipKinds)&&e.relationshipKinds.every((e,t)=>hi(e))&&e.relationshipKinds.length<=64&&e.relationshipKinds.length>=1&&new Set(e.relationshipKinds.map(si)).size===e.relationshipKinds.length)),yi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[7].test(e)||!1)&&gi(e.id)&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.set===void 0||!(`set`in e)||bi(e.set))&&(e.container===void 0||!(`container`in e)||gi(e.container))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.expect===void 0||!(`expect`in e)||Ei(e.expect))&&(e.locations===void 0||!(`locations`in e)||Di(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||Ai(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),bi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[8].test(e)||!1)&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.container===void 0||!(`container`in e)||gi(e.container))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||Ti(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),xi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((t,n)=>ci[9].test(t)||Si(e[t]))&&Object.getOwnPropertyNames(e).every((e,t)=>typeof e!=`string`||sr(e,200)&&cr(e,1))&&Object.getOwnPropertyNames(e).length<=50),Si=(e=>[Ci(e),wi(e),Array.isArray(e)&&e.every((e,t)=>[Ci(e),wi(e)].reduce((e,t,n)=>t===!0?++e:e,0)===1)&&e.length<=50].reduce((e,t,n)=>t===!0?++e:e,0)===1),Ci=(e=>(typeof e==`string`||Number.isFinite(e)||typeof e==`boolean`||e===null)&&(typeof e!=`string`||sr(e,1e3))),wi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`ref`in e&&Object.getOwnPropertyNames(e).length===1&&di(e.ref)),Ti=(e=>Array.isArray(e)&&e.every((e,t)=>gi(e))&&e.length<=50),Ei=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[10].test(e)||!1)&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.container===void 0||!(`container`in e)||gi(e.container))&&(e.revision===void 0||!(`revision`in e)||fi(e.revision))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&Object.getOwnPropertyNames(e).length>=1),Di=(e=>Array.isArray(e)&&e.every((e,t)=>Oi(e))&&e.length<=10),Oi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`uri`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[11].test(e)||!1)&&typeof e.uri==`string`&&sr(e.uri,2e3)&&cr(e.uri,1)&&(e.revision===void 0||!(`revision`in e)||fi(e.revision))&&(e.range===void 0||!(`range`in e)||typeof e.range==`object`&&e.range!==null&&!Array.isArray(e.range)&&`startLine`in e.range&&`endLine`in e.range&&Object.getOwnPropertyNames(e.range).every((e,t)=>ci[12].test(e)||!1)&&ki(e.range.startLine)&&(e.range.startCharacter===void 0||!(`startCharacter`in e.range)||ki(e.range.startCharacter))&&ki(e.range.endLine)&&(e.range.endCharacter===void 0||!(`endCharacter`in e.range)||ki(e.range.endCharacter)))),ki=(e=>Number.isInteger(e)&&(!(Number.isFinite(e)||typeof e==`bigint`)||e<=1e6&&e>=0)),Ai=(e=>Array.isArray(e)&&e.every((e,t)=>_i(e))&&e.length<=20),ji=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[13].test(e)||!1)&&gi(e.from)&&gi(e.to)&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.set===void 0||!(`set`in e)||Mi(e.set))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.expect===void 0||!(`expect`in e)||Ei(e.expect))&&(e.locations===void 0||!(`locations`in e)||Di(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||Ai(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`kind`in e)),Mi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[14].test(e)||!1)&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||Ti(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),Ni=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&`label`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[15].test(e)||!1)&&gi(e.id)&&mi(e.label)&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))),Pi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[17].test(e)||!1)&&gi(e.from)&&gi(e.to)&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.set===void 0||!(`set`in e)||Fi(e.set))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.expect===void 0||!(`expect`in e)||Ei(e.expect))&&(e.locations===void 0||!(`locations`in e)||Di(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||Ai(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),Fi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[18].test(e)||!1)&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||Ti(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),Ii=(e=>Array.isArray(e)&&e.every((e,t)=>(typeof e==`string`||Number.isFinite(e)||typeof e==`boolean`||e===null)&&(typeof e!=`string`||sr(e,1e3)))&&e.length<=50),Li=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`cells`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[20].test(e)||!1)&&Ii(e.cells)&&(e.role===void 0||!(`role`in e)||Ri(e.role))&&(e.id===void 0||!(`id`in e)||gi(e.id))&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.set===void 0||!(`set`in e)||zi(e.set))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.expect===void 0||!(`expect`in e)||Ei(e.expect))&&(e.locations===void 0||!(`locations`in e)||Di(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||Ai(e.artifacts))),Ri=(e=>e===`added`||e===`changed`||e===`context`||e===`removed`),zi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[21].test(e)||!1)&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.kind===void 0||!(`kind`in e)||hi(e.kind))&&(e.cells===void 0||!(`cells`in e)||Ii(e.cells))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||Ti(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),Bi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`heading`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[22].test(e)||!1)&&typeof e.heading==`string`&&sr(e.heading,500)&&cr(e.heading,1)&&(e.depth===void 0||!(`depth`in e)||Number.isInteger(e.depth)&&(!(Number.isFinite(e.depth)||typeof e.depth==`bigint`)||e.depth<=6&&e.depth>=1))&&(e.role===void 0||!(`role`in e)||Ri(e.role))&&(e.id===void 0||!(`id`in e)||gi(e.id))&&(e.ref===void 0||!(`ref`in e)||di(e.ref))),Vi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&`kind`in e&&Object.getOwnPropertyNames(e).every((e,t)=>ci[23].test(e)||!1)&&Hi(e.from)&&Hi(e.to)&&hi(e.kind)&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&(e.label===void 0||!(`label`in e)||mi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||xi(e.attributes))),Hi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>ci[24].test(e)||!1)&&(e.id===void 0||!(`id`in e)||gi(e.id))&&(e.ref===void 0||!(`ref`in e)||di(e.ref))&&Object.getOwnPropertyNames(e).length>=1&&Object.getOwnPropertyNames(e).length<=1&&[!(typeof e==`object`&&e&&!Array.isArray(e))||`id`in e,!(typeof e==`object`&&e&&!Array.isArray(e))||`ref`in e].reduce((e,t,n)=>t===!0?++e:e,0)===1);function Ui(e){return ui(e)}li({variables:[RegExp(`(^schema$|^kind$|^profile$|^target$|^removals$|^artifacts$|^viewpoints$|^data$)`,`u`),RegExp(`(^ref$|^revision$)`,`u`),RegExp(`(^type$|^ref$|^label$|^kind$|^from$|^to$)`,`u`),RegExp(`(^rel$|^uri$|^sha256$|^mediaType$|^label$)`,`u`),RegExp(`^sha256:[0-9a-f]{64}$`,`u`),RegExp(`(^id$|^label$|^concern$|^elementKinds$|^relationshipKinds$)`,`u`),RegExp(`(^nodes$|^edges$|^containers$)`,`u`),RegExp(`(^id$|^ref$|^label$|^kind$|^set$|^container$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^kind$|^container$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(?!)`,`u`),RegExp(`(^label$|^kind$|^container$|^revision$|^attributes$)`,`u`),RegExp(`(^uri$|^revision$|^range$)`,`u`),RegExp(`(^startLine$|^startCharacter$|^endLine$|^endCharacter$)`,`u`),RegExp(`(^from$|^to$|^kind$|^ref$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^kind$|^label$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^id$|^label$|^kind$)`,`u`),RegExp(`(^participants$|^messages$|^containers$)`,`u`),RegExp(`(^from$|^to$|^ref$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^columns$|^rows$|^relations$)`,`u`),RegExp(`(^cells$|^role$|^id$|^ref$|^kind$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^kind$|^cells$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^heading$|^depth$|^role$|^id$|^ref$)`,`u`),RegExp(`(^from$|^to$|^kind$|^ref$|^label$|^attributes$)`,`u`),RegExp(`(^id$|^ref$)`,`u`)]});var Wi=[];function Gi(e){Wi=e.variables}var Ki=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`schema`in e&&`kind`in e&&`data`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[0].test(e)||!1)&&e.schema===`urn:structured-exchange:3`&&(e.kind===`graph`||e.kind===`sequence`||e.kind===`table`||e.kind===`timeline`)&&(e.profile===void 0||!(`profile`in e)||typeof e.profile==`string`&&sr(e.profile,200)&&cr(e.profile,1))&&(e.target===void 0||!(`target`in e)||typeof e.target==`object`&&e.target!==null&&!Array.isArray(e.target)&&`ref`in e.target&&Object.getOwnPropertyNames(e.target).every((e,t)=>Wi[1].test(e)||!1)&&qi(e.target.ref)&&(e.target.revision===void 0||!(`revision`in e.target)||Ji(e.target.revision)))&&(e.removals===void 0||!(`removals`in e)||Array.isArray(e.removals)&&e.removals.every((e,t)=>Yi(e))&&e.removals.length<=500)&&(e.artifacts===void 0||!(`artifacts`in e)||Array.isArray(e.artifacts)&&e.artifacts.every((e,t)=>$i(e))&&e.artifacts.length<=50)&&(e.viewpoints===void 0||!(`viewpoints`in e)||Array.isArray(e.viewpoints)&&e.viewpoints.every((e,t)=>ea(e))&&e.viewpoints.length<=20)&&[typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`nodes`in e.data&&`edges`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>Wi[6].test(e)||!1)&&Array.isArray(e.data.nodes)&&e.data.nodes.every((e,t)=>ta(e))&&e.data.nodes.length<=500&&e.data.nodes.length>=1&&Array.isArray(e.data.edges)&&e.data.edges.every((e,t)=>pa(e))&&e.data.edges.length<=2e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>ha(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`participants`in e.data&&`messages`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>Wi[16].test(e)||!1)&&Array.isArray(e.data.participants)&&e.data.participants.every((e,t)=>ta(e))&&e.data.participants.length<=100&&e.data.participants.length>=1&&Array.isArray(e.data.messages)&&e.data.messages.every((e,t)=>ga(e))&&e.data.messages.length<=1e3&&(e.data.containers===void 0||!(`containers`in e.data)||Array.isArray(e.data.containers)&&e.data.containers.every((e,t)=>ha(e))&&e.data.containers.length<=50),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`columns`in e.data&&`rows`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>Wi[19].test(e)||!1)&&Array.isArray(e.data.columns)&&e.data.columns.every((e,t)=>typeof e==`string`&&sr(e,200)&&cr(e,1))&&e.data.columns.length<=50&&e.data.columns.length>=1&&Array.isArray(e.data.rows)&&e.data.rows.every((e,t)=>[va(e),ya(e),Sa(e)].reduce((e,t,n)=>t===!0?++e:e,0)===1)&&e.data.rows.length<=5e3&&(e.data.relations===void 0||!(`relations`in e.data)||Array.isArray(e.data.relations)&&e.data.relations.every((e,t)=>Ca(e))&&e.data.relations.length<=2e3),typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)&&`time`in e.data&&`rows`in e.data&&Object.getOwnPropertyNames(e.data).every((e,t)=>Wi[25].test(e)||!1)&&(e.data.title===void 0||!(`title`in e.data)||Xi(e.data.title))&&typeof e.data.time==`object`&&e.data.time!==null&&!Array.isArray(e.data.time)&&`start`in e.data.time&&`end`in e.data.time&&`scale`in e.data.time&&Object.getOwnPropertyNames(e.data.time).length===3&&Ta(e.data.time.start)&&Ta(e.data.time.end)&&(e.data.time.scale===`week`||e.data.time.scale===`month`||e.data.time.scale===`quarter`)&&Array.isArray(e.data.rows)&&e.data.rows.every((e,t)=>Ea(e))&&e.data.rows.length<=500&&(e.data.dependencies===void 0||!(`dependencies`in e.data)||Array.isArray(e.data.dependencies)&&e.data.dependencies.every((e,t)=>Na(e))&&e.data.dependencies.length<=2e3)&&(e.data.comparedTo===void 0||!(`comparedTo`in e.data)||typeof e.data.comparedTo==`object`&&e.data.comparedTo!==null&&!Array.isArray(e.data.comparedTo)&&`label`in e.data.comparedTo&&Object.getOwnPropertyNames(e.data.comparedTo).every((e,t)=>Wi[32].test(e)||!1)&&typeof e.data.comparedTo.label==`string`&&sr(e.data.comparedTo.label,500)&&cr(e.data.comparedTo.label,1)&&(e.data.comparedTo.date===void 0||!(`date`in e.data.comparedTo)||Ta(e.data.comparedTo.date)))&&(e.data.periods===void 0||!(`periods`in e.data)||Array.isArray(e.data.periods)&&e.data.periods.every((e,t)=>Pa(e))&&e.data.periods.length<=100)&&(e.data.references===void 0||!(`references`in e.data)||Array.isArray(e.data.references)&&e.data.references.every((e,t)=>Fa(e))&&e.data.references.length<=50)].reduce((e,t,n)=>t===!0?++e:e,0)===1),qi=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),Ji=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),Yi=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`ref`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[2].test(e)||!1)&&(e.type===`element`||e.type===`relationship`||e.type===`row`)&&qi(e.ref)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.from===void 0||!(`from`in e)||Qi(e.from))&&(e.to===void 0||!(`to`in e)||Qi(e.to))),Xi=(e=>typeof e==`string`&&sr(e,500)),Zi=(e=>typeof e==`string`&&sr(e,100)&&cr(e,1)),Qi=(e=>typeof e==`string`&&sr(e,200)&&cr(e,1)),$i=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`rel`in e&&`uri`in e&&`sha256`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[3].test(e)||!1)&&typeof e.rel==`string`&&sr(e.rel,100)&&cr(e.rel,1)&&typeof e.uri==`string`&&sr(e.uri,2e3)&&cr(e.uri,1)&&typeof e.sha256==`string`&&Wi[4].test(e.sha256)&&(e.mediaType===void 0||!(`mediaType`in e)||typeof e.mediaType==`string`&&sr(e.mediaType,100)&&cr(e.mediaType,1))&&(e.label===void 0||!(`label`in e)||Xi(e.label))),ea=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&`label`in e&&`concern`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[5].test(e)||!1)&&Qi(e.id)&&typeof e.label==`string`&&sr(e.label,500)&&cr(e.label,1)&&typeof e.concern==`string`&&sr(e.concern,500)&&cr(e.concern,1)&&(e.elementKinds===void 0||!(`elementKinds`in e)||Array.isArray(e.elementKinds)&&e.elementKinds.every((e,t)=>Zi(e))&&e.elementKinds.length<=64&&e.elementKinds.length>=1&&new Set(e.elementKinds.map(si)).size===e.elementKinds.length)&&(e.relationshipKinds===void 0||!(`relationshipKinds`in e)||Array.isArray(e.relationshipKinds)&&e.relationshipKinds.every((e,t)=>Zi(e))&&e.relationshipKinds.length<=64&&e.relationshipKinds.length>=1&&new Set(e.relationshipKinds.map(si)).size===e.relationshipKinds.length)),ta=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[7].test(e)||!1)&&Qi(e.id)&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.set===void 0||!(`set`in e)||na(e.set))&&(e.container===void 0||!(`container`in e)||Qi(e.container))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.expect===void 0||!(`expect`in e)||ca(e.expect))&&(e.locations===void 0||!(`locations`in e)||la(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||fa(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),na=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[8].test(e)||!1)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.container===void 0||!(`container`in e)||Qi(e.container))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||sa(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),ra=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((t,n)=>Wi[9].test(t)||ia(e[t]))&&Object.getOwnPropertyNames(e).every((e,t)=>typeof e!=`string`||sr(e,200)&&cr(e,1))&&Object.getOwnPropertyNames(e).length<=50),ia=(e=>[aa(e),oa(e),Array.isArray(e)&&e.every((e,t)=>[aa(e),oa(e)].reduce((e,t,n)=>t===!0?++e:e,0)===1)&&e.length<=50].reduce((e,t,n)=>t===!0?++e:e,0)===1),aa=(e=>(typeof e==`string`||Number.isFinite(e)||typeof e==`boolean`||e===null)&&(typeof e!=`string`||sr(e,1e3))),oa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`ref`in e&&Object.getOwnPropertyNames(e).length===1&&qi(e.ref)),sa=(e=>Array.isArray(e)&&e.every((e,t)=>Qi(e))&&e.length<=50),ca=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[10].test(e)||!1)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.container===void 0||!(`container`in e)||Qi(e.container))&&(e.revision===void 0||!(`revision`in e)||Ji(e.revision))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&Object.getOwnPropertyNames(e).length>=1),la=(e=>Array.isArray(e)&&e.every((e,t)=>ua(e))&&e.length<=10),ua=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`uri`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[11].test(e)||!1)&&typeof e.uri==`string`&&sr(e.uri,2e3)&&cr(e.uri,1)&&(e.revision===void 0||!(`revision`in e)||Ji(e.revision))&&(e.range===void 0||!(`range`in e)||typeof e.range==`object`&&e.range!==null&&!Array.isArray(e.range)&&`startLine`in e.range&&`endLine`in e.range&&Object.getOwnPropertyNames(e.range).every((e,t)=>Wi[12].test(e)||!1)&&da(e.range.startLine)&&(e.range.startCharacter===void 0||!(`startCharacter`in e.range)||da(e.range.startCharacter))&&da(e.range.endLine)&&(e.range.endCharacter===void 0||!(`endCharacter`in e.range)||da(e.range.endCharacter)))),da=(e=>Number.isInteger(e)&&(!(Number.isFinite(e)||typeof e==`bigint`)||e<=1e6&&e>=0)),fa=(e=>Array.isArray(e)&&e.every((e,t)=>$i(e))&&e.length<=20),pa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[13].test(e)||!1)&&Qi(e.from)&&Qi(e.to)&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.set===void 0||!(`set`in e)||ma(e.set))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.expect===void 0||!(`expect`in e)||ca(e.expect))&&(e.locations===void 0||!(`locations`in e)||la(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||fa(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`kind`in e)),ma=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[14].test(e)||!1)&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||sa(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),ha=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`id`in e&&`label`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[15].test(e)||!1)&&Qi(e.id)&&Xi(e.label)&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))),ga=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[17].test(e)||!1)&&Qi(e.from)&&Qi(e.to)&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.set===void 0||!(`set`in e)||_a(e.set))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.expect===void 0||!(`expect`in e)||ca(e.expect))&&(e.locations===void 0||!(`locations`in e)||la(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||fa(e.artifacts))&&(typeof e!=`object`||!e||Array.isArray(e)||`ref`in e?!0:!(typeof e==`object`&&e&&!Array.isArray(e))||`label`in e)),_a=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[18].test(e)||!1)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||sa(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),va=(e=>Array.isArray(e)&&e.every((e,t)=>(typeof e==`string`||Number.isFinite(e)||typeof e==`boolean`||e===null)&&(typeof e!=`string`||sr(e,1e3)))&&e.length<=50),ya=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`cells`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[20].test(e)||!1)&&va(e.cells)&&(e.role===void 0||!(`role`in e)||ba(e.role))&&(e.id===void 0||!(`id`in e)||Qi(e.id))&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.set===void 0||!(`set`in e)||xa(e.set))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.expect===void 0||!(`expect`in e)||ca(e.expect))&&(e.locations===void 0||!(`locations`in e)||la(e.locations))&&(e.artifacts===void 0||!(`artifacts`in e)||fa(e.artifacts))),ba=(e=>e===`added`||e===`changed`||e===`context`||e===`removed`),xa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[21].test(e)||!1)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.cells===void 0||!(`cells`in e)||va(e.cells))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))&&(e.removeAttributes===void 0||!(`removeAttributes`in e)||sa(e.removeAttributes))&&Object.getOwnPropertyNames(e).length>=1),Sa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`heading`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[22].test(e)||!1)&&typeof e.heading==`string`&&sr(e.heading,500)&&cr(e.heading,1)&&(e.depth===void 0||!(`depth`in e)||Number.isInteger(e.depth)&&(!(Number.isFinite(e.depth)||typeof e.depth==`bigint`)||e.depth<=6&&e.depth>=1))&&(e.role===void 0||!(`role`in e)||ba(e.role))&&(e.id===void 0||!(`id`in e)||Qi(e.id))&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))),Ca=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&`kind`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[23].test(e)||!1)&&wa(e.from)&&wa(e.to)&&Zi(e.kind)&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.attributes===void 0||!(`attributes`in e)||ra(e.attributes))),wa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[24].test(e)||!1)&&(e.id===void 0||!(`id`in e)||Qi(e.id))&&(e.ref===void 0||!(`ref`in e)||qi(e.ref))&&Object.getOwnPropertyNames(e).length>=1&&Object.getOwnPropertyNames(e).length<=1&&[!(typeof e==`object`&&e&&!Array.isArray(e))||`id`in e,!(typeof e==`object`&&e&&!Array.isArray(e))||`ref`in e].reduce((e,t,n)=>t===!0?++e:e,0)===1),Ta=(e=>typeof e==`string`&&Wi[26].test(e)),Ea=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&(e.type===`task`||e.type===`separator`)&&(typeof e!=`object`||!e||Array.isArray(e)||e.type===void 0||!(`type`in e)||e.type===`task`?Da(e):!0)&&(typeof e!=`object`||!e||Array.isArray(e)||e.type===void 0||!(`type`in e)||e.type===`separator`?Ma(e):!0)),Da=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`id`in e&&`label`in e&&`items`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[27].test(e)||!1)&&e.type===`task`&&Qi(e.id)&&Xi(e.label)&&Array.isArray(e.items)&&e.items.every((e,t)=>Oa(e))&&e.items.length<=100&&(e.role===void 0||!(`role`in e)||Aa(e.role))),Oa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&(e.type===`activity`||e.type===`milestone`)&&(typeof e!=`object`||!e||Array.isArray(e)||e.type===void 0||!(`type`in e)||e.type===`activity`?ka(e):!0)&&(typeof e!=`object`||!e||Array.isArray(e)||e.type===void 0||!(`type`in e)||e.type===`milestone`?ja(e):!0)),ka=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`start`in e&&`end`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[28].test(e)||!1)&&e.type===`activity`&&Ta(e.start)&&Ta(e.end)&&(e.id===void 0||!(`id`in e)||Qi(e.id))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.previous===void 0||!(`previous`in e)||typeof e.previous==`object`&&e.previous!==null&&!Array.isArray(e.previous)&&`start`in e.previous&&`end`in e.previous&&Object.getOwnPropertyNames(e.previous).length===2&&Ta(e.previous.start)&&Ta(e.previous.end))&&(e.role===void 0||!(`role`in e)||Aa(e.role))),Aa=(e=>e===`added`||e===`removed`),ja=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&`date`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[29].test(e)||!1)&&e.type===`milestone`&&Ta(e.date)&&(e.id===void 0||!(`id`in e)||Qi(e.id))&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))&&(e.previous===void 0||!(`previous`in e)||typeof e.previous==`object`&&e.previous!==null&&!Array.isArray(e.previous)&&`date`in e.previous&&Object.getOwnPropertyNames(e.previous).length===1&&Ta(e.previous.date))&&(e.role===void 0||!(`role`in e)||Aa(e.role))),Ma=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`type`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[30].test(e)||!1)&&e.type===`separator`&&(e.label===void 0||!(`label`in e)||Xi(e.label))),Na=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`from`in e&&`to`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[31].test(e)||!1)&&Qi(e.from)&&Qi(e.to)&&(e.type===void 0||!(`type`in e)||e.type===`finish-to-start`||e.type===`start-to-start`||e.type===`finish-to-finish`||e.type===`start-to-finish`)),Pa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`start`in e&&`end`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[33].test(e)||!1)&&Ta(e.start)&&Ta(e.end)&&(e.label===void 0||!(`label`in e)||Xi(e.label))&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind))),Fa=(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`date`in e&&`label`in e&&Object.getOwnPropertyNames(e).every((e,t)=>Wi[34].test(e)||!1)&&Ta(e.date)&&typeof e.label==`string`&&sr(e.label,500)&&cr(e.label,1)&&(e.kind===void 0||!(`kind`in e)||Zi(e.kind)));function Ia(e){return Ki(e)}Gi({variables:[RegExp(`(^schema$|^kind$|^profile$|^target$|^removals$|^artifacts$|^viewpoints$|^data$)`,`u`),RegExp(`(^ref$|^revision$)`,`u`),RegExp(`(^type$|^ref$|^label$|^kind$|^from$|^to$)`,`u`),RegExp(`(^rel$|^uri$|^sha256$|^mediaType$|^label$)`,`u`),RegExp(`^sha256:[0-9a-f]{64}$`,`u`),RegExp(`(^id$|^label$|^concern$|^elementKinds$|^relationshipKinds$)`,`u`),RegExp(`(^nodes$|^edges$|^containers$)`,`u`),RegExp(`(^id$|^ref$|^label$|^kind$|^set$|^container$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^kind$|^container$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(?!)`,`u`),RegExp(`(^label$|^kind$|^container$|^revision$|^attributes$)`,`u`),RegExp(`(^uri$|^revision$|^range$)`,`u`),RegExp(`(^startLine$|^startCharacter$|^endLine$|^endCharacter$)`,`u`),RegExp(`(^from$|^to$|^kind$|^ref$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^kind$|^label$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^id$|^label$|^kind$)`,`u`),RegExp(`(^participants$|^messages$|^containers$)`,`u`),RegExp(`(^from$|^to$|^ref$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^columns$|^rows$|^relations$)`,`u`),RegExp(`(^cells$|^role$|^id$|^ref$|^kind$|^label$|^set$|^attributes$|^expect$|^locations$|^artifacts$)`,`u`),RegExp(`(^label$|^kind$|^cells$|^attributes$|^removeAttributes$)`,`u`),RegExp(`(^heading$|^depth$|^role$|^id$|^ref$)`,`u`),RegExp(`(^from$|^to$|^kind$|^ref$|^label$|^attributes$)`,`u`),RegExp(`(^id$|^ref$)`,`u`),RegExp(`(^title$|^time$|^rows$|^dependencies$|^comparedTo$|^periods$|^references$)`,`u`),RegExp(`^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$`,`u`),RegExp(`(^type$|^id$|^label$|^items$|^role$)`,`u`),RegExp(`(^type$|^start$|^end$|^id$|^label$|^kind$|^previous$|^role$)`,`u`),RegExp(`(^type$|^date$|^id$|^label$|^kind$|^previous$|^role$)`,`u`),RegExp(`(^type$|^label$)`,`u`),RegExp(`(^from$|^to$|^type$)`,`u`),RegExp(`(^label$|^date$)`,`u`),RegExp(`(^start$|^end$|^label$|^kind$)`,`u`),RegExp(`(^date$|^label$|^kind$)`,`u`)]});var La={[Ye]:jr,[tt]:Ui,[it]:Ia},Ra=e=>{let t=Mn(e),n=ot(t);return n===void 0&&t!==void 0?[{rule:`unsupported-version`,path:`/schema`,message:`this build validates ${at.join(` and `)}`}]:La[n??`urn:structured-exchange:1`](e)?[]:[{rule:`schema/invalid`,path:``,message:`does not conform to the published structured-exchange schema`}]},za=Object.defineProperty,Ba=(e,t,n)=>t in e?za(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Va=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},Ha=(e,t,n)=>Ba(e,typeof t==`symbol`?t:t+``,n),Ua={};Va(Ua,{Graph:()=>ko,alg:()=>no});var Wa=Object.defineProperty,Ga=(e,t)=>{for(var n in t)Wa(e,n,{get:t[n],enumerable:!0})},Ka=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected=`directed`in e?e.directed:!0,this._isMultigraph=`multigraph`in e&&e.multigraph,this._isCompound=`compound`in e&&e.compound),this._isCompound&&(this._parent={},this._children={},this._children[`\0`]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return this._defaultNodeLabelFn=typeof e==`function`?e:()=>e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,t){return e.forEach(e=>{t===void 0?this.setNode(e):this.setNode(e,t)}),this}setNode(e,t){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=`\0`,this._children[e]={},this._children[`\0`][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let t=e=>this.removeEdge(this._edgeObjs[e]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(e=>{this.setParent(e)}),delete this._children[e]),Object.keys(this._in[e]).forEach(t),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw Error(`Cannot set parent in a non-compound graph`);if(t===void 0)t=`\0`;else{t+=``;for(let n=t;n!==void 0;n=this.parent(n))if(n===e)throw Error(`Setting `+t+` as parent of `+e+` would create a cycle`);this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}parent(e){if(this._isCompound){let t=this._parent[e];if(t!==`\0`)return t}}children(e=`\0`){if(this._isCompound){let t=this._children[e];if(t)return Object.keys(t)}else{if(e===`\0`)return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let t=this._preds[e];if(t)return Object.keys(t)}successors(e){let t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){let t=this.predecessors(e);if(t){let n=new Set(t),r=this.successors(e);if(r)for(let e of r)n.add(e);return Array.from(n.values())}}isLeaf(e){let t;return t=this.isDirected()?this.successors(e):this.neighbors(e),(t?.length??0)===0}filterNodes(e){let t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph()),Object.entries(this._nodes).forEach(([n,r])=>{e(n)&&t.setNode(n,r)}),Object.values(this._edgeObjs).forEach(e=>{t.hasNode(e.v)&&t.hasNode(e.w)&&t.setEdge(e,this.edge(e))});let n={},r=e=>{let i=this.parent(e);return!i||t.hasNode(i)?(n[e]=i,i):i in n?n[i]:r(i)};return this._isCompound&&t.nodes().forEach(e=>t.setParent(e,r(e))),t}setDefaultEdgeLabel(e){return this._defaultEdgeLabelFn=typeof e==`function`?e:()=>e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){return e.reduce((e,n)=>(t===void 0?this.setEdge(e,n):this.setEdge(e,n,t),n)),this}setEdge(e,t,n,r){let i,a,o,s,c=!1;typeof e==`object`&&e&&`v`in e?(i=e.v,a=e.w,o=e.name,arguments.length===2&&(s=t,c=!0)):(i=e,a=t,o=r,arguments.length>2&&(s=n,c=!0)),i=``+i,a=``+a,o!==void 0&&(o=``+o);let l=Ya(this._isDirected,i,a,o);if(l in this._edgeLabels)return c&&(this._edgeLabels[l]=s),this;if(o!==void 0&&!this._isMultigraph)throw Error(`Cannot set a named edge when isMultigraph = false`);this.setNode(i),this.setNode(a),this._edgeLabels[l]=c?s:this._defaultEdgeLabelFn(i,a,o);let u=Xa(this._isDirected,i,a,o);return i=u.v,a=u.w,Object.freeze(u),this._edgeObjs[l]=u,qa(this._preds[a],i),qa(this._sucs[i],a),this._in[a][l]=u,this._out[i][l]=u,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?Za(this._isDirected,e):Ya(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(e,t,n){let r=arguments.length===1?this.edge(e):this.edge(e,t,n);return typeof r!=`object`||!r?{label:r}:r}hasEdge(e,t,n){return(arguments.length===1?Za(this._isDirected,e):Ya(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?Za(this._isDirected,e):Ya(this._isDirected,e,t,n),i=this._edgeObjs[r];if(i){let e=i.v,t=i.w;delete this._edgeLabels[r],delete this._edgeObjs[r],Ja(this._preds[t],e),Ja(this._sucs[e],t),delete this._in[t][r],delete this._out[e][r],this._edgeCount--}return this}inEdges(e,t){return this.isDirected()?this.filterEdges(this._in[e],e,t):this.nodeEdges(e,t)}outEdges(e,t){return this.isDirected()?this.filterEdges(this._out[e],e,t):this.nodeEdges(e,t)}nodeEdges(e,t){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,t)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,t,n){if(!e)return;let r=Object.values(e);return n?r.filter(e=>e.v===t&&e.w===n||e.v===n&&e.w===t):r}};function qa(e,t){e[t]?e[t]++:e[t]=1}function Ja(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function Ya(e,t,n,r){let i=``+t,a=``+n;if(!e&&i>a){let e=i;i=a,a=e}return i+``+a+``+(r===void 0?`\0`:r)}function Xa(e,t,n,r){let i=``+t,a=``+n;if(!e&&i>a){let e=i;i=a,a=e}let o={v:i,w:a};return r&&(o.name=r),o}function Za(e,t){return Ya(e,t.v,t.w,t.name)}Ga({},{read:()=>to,write:()=>Qa});function Qa(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:$a(e),edges:eo(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function $a(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),i={v:t};return n!==void 0&&(i.value=n),r!==void 0&&(i.parent=r),i})}function eo(e){return e.edges().map(t=>{let n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function to(e){let t=new Ka(e.options);return e.value!==void 0&&t.setGraph(e.value),e.nodes.forEach(e=>{t.setNode(e.v,e.value),e.parent&&t.setParent(e.v,e.parent)}),e.edges.forEach(e=>{t.setEdge({v:e.v,w:e.w,name:e.name},e.value)}),t}var no={};Ga(no,{CycleException:()=>vo,bellmanFord:()=>io,components:()=>oo,dijkstra:()=>lo,dijkstraAll:()=>fo,findCycles:()=>mo,floydWarshall:()=>go,isAcyclic:()=>bo,postorder:()=>wo,preorder:()=>To,prim:()=>Eo,shortestPaths:()=>Do,tarjan:()=>po,topsort:()=>yo});var ro=()=>1;function io(e,t,n,r){return ao(e,String(t),n||ro,r||function(t){return e.outEdges(t)??[]})}function ao(e,t,n,r){let i={},a,o=0,s=e.nodes(),c=function(e){let t=i[e.v],r=i[e.w];if(!t||!r)return;let o=n(e);t.distance+o<r.distance&&(i[e.w]={distance:t.distance+o,predecessor:e.v},a=!0)},l=function(){s.forEach(function(e){r(e).forEach(function(t){let n=t.v===e?t.v:t.w,r=n===t.v?t.w:t.v;c({v:n,w:r})})})};s.forEach(function(e){i[e]={distance:e===t?0:1/0,predecessor:``}});let u=s.length;for(let e=1;e<u&&(a=!1,o++,l(),a);e++);if(o===u-1&&(a=!1,l(),a))throw Error(`The graph contains a negative weight cycle`);return i}function oo(e){let t={},n=[],r;function i(n){var a,o;n in t||(t[n]=!0,r.push(n),(a=e.successors(n))==null||a.forEach(i),(o=e.predecessors(n))==null||o.forEach(i))}return e.nodes().forEach(function(e){r=[],i(e),r.length&&n.push(r)}),n}var so=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw Error(`Queue underflow`);return this._arr[0].key}add(e,t){let n=this._keyIndices,r=String(e);if(!(r in n)){let e=this._arr,i=e.length;return n[r]=i,e.push({key:r,priority:t}),this._decrease(i),!0}return!1}removeMin(){if(this.size()===0)throw Error(`Queue underflow`);this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){let n=this._keyIndices[e];if(n===void 0)throw Error(`Key not found: ${e}`);let r=this._arr[n].priority;if(t>r)throw Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${t}`);this._arr[n].priority=t,this._decrease(n)}_heapify(e){let t=this._arr,n=2*e,r=n+1,i=e;n<t.length&&(i=t[n].priority<t[i].priority?n:i,r<t.length&&(i=t[r].priority<t[i].priority?r:i),i!==e&&(this._swap(e,i),this._heapify(i)))}_decrease(e){let t=this._arr,n=t[e].priority,r;for(;e!==0&&(r=e>>1,!(t[r].priority<n));)this._swap(e,r),e=r}_swap(e,t){let n=this._arr,r=this._keyIndices,i=n[e],a=n[t];n[e]=a,n[t]=i,r[a.key]=e,r[i.key]=t}},co=()=>1;function lo(e,t,n,r){return uo(e,String(t),n||co,r||function(t){return e.outEdges(t)??[]})}function uo(e,t,n,r){let i={},a=new so,o,s,c=function(e){let t=e.v===o?e.w:e.v,r=i[t];if(!r)return;let c=n(e),l=s.distance+c;if(c<0)throw Error(`dijkstra does not allow negative edge weights. Bad edge: `+e+` Weight: `+c);l<r.distance&&(r.distance=l,r.predecessor=o,a.decrease(t,l))};for(e.nodes().forEach(function(e){let n=e===t?0:1/0;i[e]={distance:n,predecessor:``},a.add(e,n)});a.size()>0;){o=a.removeMin();let e=i[o];if(!e||e.distance===1/0)break;s=e,r(o).forEach(c)}return i}function fo(e,t,n){return e.nodes().reduce(function(r,i){return r[i]=lo(e,i,t,n),r},{})}function po(e){let t=0,n=[],r={},i=[];function a(o){var s;let c=r[o]={onStack:!0,lowlink:t,index:t++};if(n.push(o),(s=e.successors(o))==null||s.forEach(function(e){if(e in r){let t=r[e];t!=null&&t.onStack&&(c.lowlink=Math.min(c.lowlink,t.index))}else{a(e);let t=r[e];t&&(c.lowlink=Math.min(c.lowlink,t.lowlink))}}),c.lowlink===c.index){let e=[],t;do{t=n.pop();let i=r[t];i&&(i.onStack=!1),e.push(t)}while(o!==t);i.push(e)}}return e.nodes().forEach(function(e){e in r||a(e)}),i}function mo(e){return po(e).filter(function(t){let n=t[0];return n?t.length>1||t.length===1&&(e.outEdges(n,n)??[]).length>0:!1})}var ho=()=>1;function go(e,t,n){return _o(e,t||ho,n||function(t){return e.outEdges(t)??[]})}function _o(e,t,n){let r={},i=e.nodes();return i.forEach(function(e){let a={};r[e]=a,a[e]={distance:0,predecessor:``},i.forEach(function(t){e!==t&&(a[t]={distance:1/0,predecessor:``})}),n(e).forEach(function(n){let r=n.v===e?n.w:n.v,i=t(n);a[r]={distance:i,predecessor:e}})}),i.forEach(function(e){let t=r[e];t&&i.forEach(function(n){let a=r[n];a&&i.forEach(function(n){let r=a[e],i=t[n],o=a[n];if(r&&i&&o){let e=r.distance+i.distance;e<o.distance&&(o.distance=e,o.predecessor=i.predecessor)}})})}),r}var vo=class extends Error{constructor(e){super(e),this.name=`CycleException`}};function yo(e){let t={},n={},r=[];function i(a){var o;if(a in n)throw new vo;a in t||(n[a]=!0,t[a]=!0,(o=e.predecessors(a))==null||o.forEach(i),delete n[a],r.push(a))}if(e.sinks().forEach(i),Object.keys(t).length!==e.nodeCount())throw new vo;return r}function bo(e){try{yo(e)}catch(e){if(e instanceof vo)return!1;throw e}return!0}function xo(e,t,n,r,i){Array.isArray(t)||(t=[t]);let a=(t=>(e.isDirected()?e.successors(t):e.neighbors(t))??[]),o={};return t.forEach(function(t){if(!e.hasNode(t))throw Error(`Graph does not have node: `+t);i=So(e,t,n===`post`,o,a,r,i)}),i}function So(e,t,n,r,i,a,o){return t in r||(r[t]=!0,n||(o=a(o,t)),i(t).forEach(function(t){o=So(e,t,n,r,i,a,o)}),n&&(o=a(o,t))),o}function Co(e,t,n){return xo(e,t,n,function(e,t){return e.push(t),e},[])}function wo(e,t){return Co(e,t,`post`)}function To(e,t){return Co(e,t,`pre`)}function Eo(e,t){var n;let r=new Ka,i={},a=new so,o;function s(e){let n=e.v===o?e.w:e.v,r=a.priority(n);if(r!==void 0){let s=t(e);s<r&&(i[n]=o,a.decrease(n,s))}}if(e.nodeCount()===0)return r;e.nodes().forEach(function(e){a.add(e,1/0),r.setNode(e)});let c=e.nodes()[0];c!==void 0&&a.decrease(c,0);let l=!1;for(;a.size()>0;){if(o=a.removeMin(),o in i)r.setEdge(o,i[o]);else{if(l)throw Error(`Input graph is not connected: `+e);l=!0}(n=e.nodeEdges(o))==null||n.forEach(s)}return r}function Do(e,t,n,r){return Oo(e,t,n,r??(t=>e.outEdges(t)??[]))}function Oo(e,t,n,r){if(n===void 0)return lo(e,t,n,r);let i=!1,a=e.nodes();for(let o=0;o<a.length;o++){let s=a[o];if(s===void 0)continue;let c=r(s);for(let e=0;e<c.length;e++){let t=c[e];if(!t)continue;let r=t.v===s?t.v:t.w;n({v:r,w:r===t.v?t.w:t.v})<0&&(i=!0)}if(i)return io(e,t,n,r)}return lo(e,t,n,r)}var ko=Ka;function Ao(e,t,n,r){let i=r;for(;e.hasNode(i);)i=Ko(r);return n.dummy=t,e.setNode(i,n),i}function jo(e){let t=new ko().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},i=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})}),t}function Mo(e){let t=new ko({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function No(e,t){let n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2;if(!i&&!a)throw Error(`Not possible to find intersection inside of the rectangle`);let c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=s*i/a,l=s):(i<0&&(o=-o),c=o,l=o*a/i),{x:n+c,y:r+l}}function Po(e){let t=qo(Vo(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),i=r.rank;i!==void 0&&(t[i]||(t[i]=[]),t[i][r.order]=n)}),t}function Fo(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MAX_VALUE:n}),n=Bo(Math.min,t);e.nodes().forEach(t=>{let r=e.node(t);Object.hasOwn(r,`rank`)&&(r.rank-=n)})}function Io(e){let t=e.nodes().map(t=>e.node(t).rank).filter(e=>e!==void 0),n=Bo(Math.min,t),r=[];e.nodes().forEach(t=>{let i=e.node(t).rank-n;r[i]||(r[i]=[]),r[i].push(t)});let i=0,a=e.graph().nodeRankFactor;Array.from(r).forEach((t,n)=>{t===void 0&&n%a!==0?--i:t!==void 0&&i&&t.forEach(t=>e.node(t).rank+=i)})}function Lo(e,t,n,r){let i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),Ao(e,`border`,i,t)}function Ro(e,t=zo){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);n.push(i)}return n}var zo=65535;function Bo(e,t){return t.length>zo?e(...Ro(t).map(t=>e(...t))):e(...t)}function Vo(e){let t=e.nodes().map(t=>{let n=e.node(t).rank;return n===void 0?Number.MIN_VALUE:n});return Bo(Math.max,t)}function Ho(e,t){let n={lhs:[],rhs:[]};return e.forEach(e=>{t(e)?n.lhs.push(e):n.rhs.push(e)}),n}function Uo(e,t){let n=Date.now();try{return t()}finally{console.log(e+` time: `+(Date.now()-n)+`ms`)}}function Wo(e,t){return t()}var Go=0;function Ko(e){return e+(``+ ++Go)}function qo(e,t,n=1){t??(t=e,e=0);let r=e=>e<t;n<0&&(r=e=>t<e);let i=[];for(let t=e;r(t);t+=n)i.push(t);return i}function Jo(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function Yo(e,t){let n;return n=typeof t==`string`?e=>e[t]:t,Object.entries(e).reduce((e,[t,r])=>(e[t]=n(r,t),e),{})}function Xo(e,t){return e.reduce((e,n,r)=>(e[n]=t[r],e),{})}var Zo=`\0`;function Qo(e,t,n){if(!(e&&t&&n&&t.dummy===`edge`&&n.dummy===`edge`&&t.edgeObj&&n.edgeObj&&e[t.edgeObj.v]&&e[n.edgeObj.v]&&e[t.edgeObj.w]&&e[n.edgeObj.w]))return 0;let r=!0;t.edgeObj.w===n.edgeObj.w&&(r=!1);let i=r?e[t.edgeObj.v]?.rank??NaN:e[t.edgeObj.w]?.rank??NaN,a=Object.entries(e).find(e=>e[1].edgeObj?.v===t.edgeObj.v&&e[1].edgeObj?.w===t.edgeObj.w&&e[1].rank===i),o=Object.entries(e).find(e=>e[1].edgeObj?.v===n.edgeObj.v&&e[1].edgeObj?.w===n.edgeObj.w&&e[1].rank===i);if(!a||!o)return 0;let s=a[1].order??NaN,c=o[1].order??NaN;return isNaN(s-c)?0:s-c}var $o=`3.1.1`,es=class{constructor(){Ha(this,`_sentinel`);let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return ts(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&ts(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,ns)),n=n._prev;return`[`+e.join(`, `)+`]`}};function ts(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function ns(e,t){if(e!==`_next`&&e!==`_prev`)return t}var rs=es,is=()=>1;function as(e,t){if(e.nodeCount()<=1)return[];let n=cs(e,t||is);return os(n.graph,n.buckets,n.zeroIdx).flatMap(t=>e.outEdges(t.v,t.w)||[])}function os(e,t,n){let r=[],i=t[t.length-1],a=t[0],o;for(;e.nodeCount();){for(;o=a.dequeue();)ss(e,t,n,o);for(;o=i.dequeue();)ss(e,t,n,o);if(e.nodeCount()){for(let i=t.length-2;i>0;--i)if(o=t[i]?.dequeue(),o){r=r.concat(ss(e,t,n,o,!0)||[]);break}}}return r}function ss(e,t,n,r,i){let a=[],o=i?a:void 0;return(e.inEdges(r.v)||[]).forEach(r=>{let o=e.edge(r),s=e.node(r.v);i&&a.push({v:r.v,w:r.w}),s.out-=o,ls(t,n,s)}),(e.outEdges(r.v)||[]).forEach(r=>{let i=e.edge(r),a=r.w,o=e.node(a);o.in-=i,ls(t,n,o)}),e.removeNode(r.v),o}function cs(e,t){let n=new ko,r=0,i=0;e.nodes().forEach(e=>{n.setNode(e,{v:e,in:0,out:0})}),e.edges().forEach(e=>{let a=n.edge(e.v,e.w)||0,o=t(e),s=a+o;n.setEdge(e.v,e.w,s);let c=n.node(e.v),l=n.node(e.w);i=Math.max(i,c.out+=o),r=Math.max(r,l.in+=o)});let a=us(i+r+3).map(()=>new rs),o=r+1;return n.nodes().forEach(e=>{ls(a,o,n.node(e))}),{graph:n,buckets:a,zeroIdx:o}}function ls(e,t,n){var r,i,a;n.out?n.in?(a=e[n.out-n.in+t])==null||a.enqueue(n):(i=e[e.length-1])==null||i.enqueue(n):(r=e[0])==null||r.enqueue(n)}function us(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function ds(e,t){(e.graph().acyclicer===`greedy`?as(e,n(e)):fs(e,t??null)).forEach(t=>{let n=e.edge(t);e.removeEdge(t),n.forwardName=t.name,n.reversed=!0,e.setEdge(t.w,t.v,n,Ko(`rev`))});function n(e){return t=>e.edge(t).weight}}function fs(e,t){let n=[],r={},i={};function a(t){Object.hasOwn(i,t)||(i[t]=!0,r[t]=!0,e.outEdges(t).forEach(e=>{Object.hasOwn(r,e.w)?n.push(e):a(e.w)}),delete r[t])}function o(a){var s;Object.hasOwn(i,a)||(i[a]=!0,r[a]=!0,(s=e.outEdges(a))==null||s.forEach(i=>{Object.hasOwn(r,i.w)||t.node(a)?.rank>t.node(i.w)?.rank&&ms(e,i.w,i)?n.push(i):o(i.w)}),delete r[a])}let s=a;return t&&typeof t.node==`function`&&(s=o),e.sources().forEach(s),e.nodes().forEach(s),n}function ps(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}function ms(e,t,n){let r=new Set;function i(t){if(e.sources().includes(t))return!0;r.add(t);for(let a of e.inEdges(t)??[])if((a.v!==n.v||a.w!==n.w)&&!r.has(a.v)&&i(a.v))return!0;return!1}return i(t)}function hs(e){e.graph().dummyChains=[],e.edges().forEach(t=>gs(e,t))}function gs(e,t){let n=t.v,r=e.node(n).rank,i=t.w,a=e.node(i).rank,o=t.name,s=e.edge(t),c=s.labelRank;if(a===r+1)return;e.removeEdge(t);let l,u,d=0;for(++r;r<a;++d,++r)s.points=[],u={width:0,height:0,edgeLabel:s,edgeObj:t,rank:r},l=Ao(e,`edge`,u,`_d`),r===c&&(u.width=s.width,u.height=s.height,u.dummy=`edge-label`,u.labelpos=s.labelpos),e.setEdge(n,l,{weight:s.weight},o),d===0&&e.graph().dummyChains.push(l),n=l;e.setEdge(n,i,{weight:s.weight},o)}function _s(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,i;for(e.setEdge(n.edgeObj,r);n.dummy;)i=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy===`edge-label`&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=i,n=e.node(t)})}function vs(e){let t={};function n(r){let i=e.node(r);if(Object.hasOwn(t,r))return i.rank;t[r]=!0;let a=e.outEdges(r),o=a?a.map(t=>t==null?1/0:n(t.w)-e.edge(t).minlen):[],s=Bo(Math.min,o);return s===1/0&&(s=0),i.rank=s}e.sources().forEach(n)}function ys(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var bs=xs;function xs(e){let t=new ko({directed:!1}),n=e.nodes();if(n.length===0)throw Error(`Graph must have at least one node`);let r=n[0],i=e.nodeCount();t.setNode(r,{});let a,o;for(;Ss(t,e)<i&&(a=Cs(t,e),a);)o=t.hasNode(a.v)?ys(e,a):-ys(e,a),ws(t,e,o);return t}function Ss(e,t){function n(r){let i=t.nodeEdges(r);i&&i.forEach(i=>{let a=i.v,o=r===a?i.w:a;!e.hasNode(o)&&!ys(t,i)&&(e.setNode(o,{}),e.setEdge(r,o,{}),n(o))})}return e.nodes().forEach(n),e.nodeCount()}function Cs(e,t){return t.edges().reduce((n,r)=>{let i=1/0;return e.hasNode(r.v)!==e.hasNode(r.w)&&(i=ys(t,r)),i<n[0]?[i,r]:n},[1/0,null])[1]}function ws(e,t,n){e.nodes().forEach(e=>t.node(e).rank+=n)}var{preorder:Ts,postorder:Es}=no,Ds=Os;Os.initLowLimValues=Ms,Os.initCutValues=ks,Os.calcCutValue=js,Os.leaveEdge=Ps,Os.enterEdge=Fs,Os.exchangeEdges=Is;function Os(e){e=jo(e),vs(e);let t=bs(e);Ms(t),ks(t,e);let n,r;for(;n=Ps(t);)r=Fs(t,e,n),Is(t,e,n,r)}function ks(e,t){let n=Es(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(n=>As(e,t,n))}function As(e,t,n){let r=e.node(n).parent,i=e.edge(n,r);i.cutvalue=js(e,t,n)}function js(e,t,n){let r=e.node(n).parent,i=!0,a=t.edge(n,r),o=0;a||=(i=!1,t.edge(r,n)),o=a.weight;let s=t.nodeEdges(n);return s&&s.forEach(a=>{let s=a.v===n,c=s?a.w:a.v;if(c!==r){let r=s===i,l=t.edge(a).weight;if(o+=r?l:-l,Rs(e,n,c)){let t=e.edge(n,c).cutvalue;o+=r?-t:t}}}),o}function Ms(e,t){arguments.length<2&&(t=e.nodes()[0]),Ns(e,{},1,t)}function Ns(e,t,n,r,i){let a=n,o=e.node(r);t[r]=!0;let s=e.neighbors(r);return s&&s.forEach(i=>{Object.hasOwn(t,i)||(n=Ns(e,t,n,i,r))}),o.low=a,o.lim=n++,i?o.parent=i:delete o.parent,n}function Ps(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function Fs(e,t,n){let r=n.v,i=n.w;t.hasEdge(r,i)||(r=n.w,i=n.v);let a=e.node(r),o=e.node(i),s=a,c=!1;return a.lim>o.lim&&(s=o,c=!0),t.edges().filter(t=>c===zs(e,e.node(t.v),s)&&c!==zs(e,e.node(t.w),s)).reduce((e,n)=>ys(t,n)<ys(t,e)?n:e)}function Is(e,t,n,r){let i=n.v,a=n.w;e.removeEdge(i,a),e.setEdge(r.v,r.w,{}),Ms(e),ks(e,t),Ls(e,t)}function Ls(e,t){let n=e.nodes().find(t=>!e.node(t).parent);if(!n)return;let r=Ts(e,[n]);r=r.slice(1),r.forEach(n=>{let r=e.node(n).parent,i=t.edge(n,r),a=!1;i||(i=t.edge(r,n),a=!0),t.node(n).rank=t.node(r).rank+(a?i.minlen:-i.minlen)})}function Rs(e,t,n){return e.hasEdge(t,n)}function zs(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var Bs=Vs;function Vs(e){let t=e.graph().ranker;if(typeof t==`function`)return t(e);switch(t){case`network-simplex`:Ws(e);break;case`tight-tree`:Us(e);break;case`longest-path`:Hs(e);break;case`none`:break;default:Ws(e)}}var Hs=vs;function Us(e){vs(e),bs(e)}function Ws(e){Ds(e)}var Gs=Ks;function Ks(e){let t=Js(e),n=e.graph();Array.isArray(n.dummyChains)&&n.dummyChains.forEach(n=>{let r=e.node(n),i=r.edgeObj,a=qs(e,t,i.v,i.w),o=a.path,s=a.lca,c=0,l=o[c],u=!0;for(;n!==i.w;){if(r=e.node(n),u){for(;(l=o[c])!==s&&e.node(l).maxRank<r.rank;)c++;l===s&&(u=!1)}if(!u){for(;c<o.length-1&&e.node(o[c+1]).minRank<=r.rank;)c++;l=o[c]}l!==void 0&&e.setParent(n,l),n=e.successors(n)[0]}})}function qs(e,t,n,r){let i=[],a=[],o=Math.min(t[n].low,t[r].low),s=Math.max(t[n].lim,t[r].lim),c;c=n;do c=e.parent(c),i.push(c);while(c&&(t[c].low>o||s>t[c].lim));let l=c,u=r;for(;(u=e.parent(u))!==l;)a.push(u);return{path:i.concat(a.reverse()),lca:l}}function Js(e){let t={},n=0;function r(i){let a=n;e.children(i).forEach(r),t[i]={low:a,lim:n++}}return e.children(Zo).forEach(r),t}function Ys(e){let t=Ao(e,`root`,{},`_root`),n=Zs(e),r=Object.values(n),i=Bo(Math.max,r)-1,a=2*i+1;e.graph().nestingRoot=t,e.edges().forEach(t=>e.edge(t).minlen*=a);let o=Qs(e)+1;e.children(Zo).forEach(r=>{Xs(e,t,a,o,i,n,r)}),e.graph().nodeRankFactor=a}function Xs(e,t,n,r,i,a,o){let s=e.children(o);if(!s.length){o!==t&&e.setEdge(t,o,{weight:0,minlen:n});return}let c=Lo(e,`_bt`),l=Lo(e,`_bb`),u=e.node(o);e.setParent(c,o),u.borderTop=c,e.setParent(l,o),u.borderBottom=l,s.forEach(s=>{Xs(e,t,n,r,i,a,s);let u=e.node(s),d=u.borderTop?u.borderTop:s,f=u.borderBottom?u.borderBottom:s,p=u.borderTop?r:2*r,m=d===f?i-(a[o]??0)+1:1;e.setEdge(c,d,{weight:p,minlen:m,nestingEdge:!0}),e.setEdge(f,l,{weight:p,minlen:m,nestingEdge:!0})}),e.parent(o)||e.setEdge(t,c,{weight:0,minlen:i+(a[o]??0)})}function Zs(e){let t={};function n(r,i){let a=e.children(r);a&&a.length&&a.forEach(e=>n(e,i+1)),t[r]=i}return e.children(Zo).forEach(e=>n(e,1)),t}function Qs(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function $s(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(t=>{e.edge(t).nestingEdge&&e.removeEdge(t)})}var ec=tc;function tc(e){function t(n){let r=e.children(n),i=e.node(n);if(r.length&&r.forEach(t),i&&Object.hasOwn(i,`minRank`)){i.borderLeft=[],i.borderRight=[];for(let t=i.minRank,r=i.maxRank+1;t<r;++t)nc(e,`borderLeft`,`_bl`,n,i,t),nc(e,`borderRight`,`_br`,n,i,t)}}e.children(Zo).forEach(t)}function nc(e,t,n,r,i,a){let o={width:0,height:0,rank:a,borderType:t},s=i[t][a-1],c=Ao(e,`border`,o,n);i[t][a]=c,e.setParent(c,r),s&&e.setEdge(s,c,{weight:1})}function rc(e){let t=e.graph().rankdir?.toLowerCase();(t===`lr`||t===`rl`)&&ac(e)}function ic(e){let t=e.graph().rankdir?.toLowerCase();(t===`bt`||t===`rl`)&&sc(e),(t===`lr`||t===`rl`)&&(lc(e),ac(e))}function ac(e){e.nodes().forEach(t=>oc(e.node(t))),e.edges().forEach(t=>oc(e.edge(t)))}function oc(e){let t=e.width;e.width=e.height,e.height=t}function sc(e){e.nodes().forEach(t=>cc(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(cc),Object.hasOwn(r,`y`)&&cc(r)})}function cc(e){e.y=-e.y}function lc(e){e.nodes().forEach(t=>uc(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(uc),Object.hasOwn(r,`x`)&&uc(r)})}function uc(e){let t=e.x;e.x=e.y,e.y=t}function dc(e,t=null){let n={},r=e.nodes().filter(t=>!e.children(t).length),i=r.map(t=>e.node(t).rank),a=qo(Bo(Math.max,i)+1).map(()=>[]);function o(t){if(n[t])return;n[t]=!0;let r=e.node(t);a[r.rank].push(t);let i=e.successors(t);i&&[...i].sort((e,t)=>s(e,t)).forEach(o)}r.sort((t,n)=>e.node(t).rank-e.node(n).rank).forEach(o);function s(n,r){return Qo(t,e.node(n),e.node(r))}return a}function fc(e,t){let n=0;for(let r=1;r<t.length;++r)n+=pc(e,t[r-1],t[r]);return n}function pc(e,t,n){let r=Xo(n,n.map((e,t)=>t)),i=t.flatMap(t=>{let n=e.outEdges(t);return n?n.map(t=>({pos:r[t.w],weight:e.edge(t).weight})).sort((e,t)=>e.pos-t.pos):[]}),a=1;for(;a<n.length;)a<<=1;let o=2*a-1;--a;let s=Array(o).fill(0),c=0;return i.forEach(e=>{let t=e.pos+a;s[t]+=e.weight;let n=0;for(;t>0;)t%2&&(n+=s[t+1]),t=t-1>>1,s[t]+=e.weight;c+=e.weight*n}),c}function mc(e,t=[]){return t.map(t=>{let n=e.inEdges(t);if(!n||!n.length)return{v:t};{let r=n.reduce((t,n)=>{let r=e.edge(n),i=e.node(n.v);return{sum:t.sum+r.weight*i.order,weight:t.weight+r.weight}},{sum:0,weight:0});return{v:t,barycenter:r.sum/r.weight,weight:r.weight}}})}function hc(e,t){let n={};return e.forEach((e,t)=>{let r={indegree:0,in:[],out:[],vs:[e.v],i:t};e.barycenter!==void 0&&(r.barycenter=e.barycenter,r.weight=e.weight),n[e.v]=r}),t.edges().forEach(e=>{let t=n[e.v],r=n[e.w];t!==void 0&&r!==void 0&&(r.indegree++,t.out.push(r))}),gc(Object.values(n).filter(e=>!e.indegree))}function gc(e){let t=[];function n(e){return t=>{t.merged||(t.barycenter===void 0||e.barycenter===void 0||t.barycenter>=e.barycenter)&&_c(e,t)}}function r(t){return n=>{n.in.push(t),--n.indegree===0&&e.push(n)}}for(;e.length;){let i=e.pop();t.push(i),i.in.reverse().forEach(n(i)),i.out.forEach(r(i))}return t.filter(e=>!e.merged).map(e=>Jo(e,[`vs`,`i`,`barycenter`,`weight`]))}function _c(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}function vc(e,t,n,r,i){let a={},o=null,s=null,c=i;typeof t==`boolean`?(c=t,a={}):t&&(a=t,o=n??null,s=r??null);let l=Ho(e,e=>Object.hasOwn(e,`barycenter`)),u=l.lhs,d=l.rhs.sort((e,t)=>t.i-e.i),f=[],p=0,m=0,h=0;u.sort(bc(s,o,!!c));for(let[e,t]of Object.entries(a)){let n=u.findIndex(t=>t.vs[0]===e);u.splice(n+1,0,t)}h=yc(f,d,h),u.forEach(e=>{h+=e.vs.length,f.push(e.vs),p+=e.barycenter*e.weight,m+=e.weight,h=yc(f,d,h)});let g={vs:f.flat(1)};return m&&(g.barycenter=p/m,g.weight=m),g}function yc(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function bc(e,t,n){return(r,i)=>{if(r.barycenter<i.barycenter)return-1;if(r.barycenter>i.barycenter)return 1;if(e&&(typeof r.vs[0]==`string`||typeof i.vs[0]==`string`)){let n=Qo(t,e.node(r.vs[0]),e.node(i.vs[0]));if(n!==0)return n}return n?i.i-r.i:r.i-i.i}}function xc(e,t,n,r,i){var a,o;let s=null,c=i;typeof r==`boolean`?(c=r,s=null):r!==void 0&&(s=r);let l=e.children(t),u=e.node(t),d=u?u.borderLeft:void 0,f=u?u.borderRight:void 0,p={};d&&(l=l.filter(e=>e!==d&&e!==f));let m=mc(e,l);m.forEach(t=>{if(e.children(t.v).length){let{result:r}=xc(e,t.v,n,s,c);p[t.v]=r,Object.hasOwn(r,`barycenter`)&&Cc(t,r)}});let h=hc(m,n);Sc(h,p);let g={},_=!1;for(let t=0;t<h.length;t++)for(let n=t+1;n<h.length;n++)if(h[t]&&h[n]&&(a=h[t])!=null&&a.barycenter&&(o=h[n])!=null&&o.barycenter&&h[t]?.barycenter===h[n].barycenter){let r=h[t]?.vs[0]??``,i=h[n]?.vs[0]??``,a=e.node(r),o=e.node(i);if(a.dummy===`edge`&&o.dummy===`edge`&&a.edgeObj?.v===o.edgeObj?.v&&a.edgeObj?.w===o.edgeObj?.w){if(a.edgeLabel.reversed){g[i]=h[t],h.splice(t,1),t--;break}g[r]=h[n],h.splice(n,1),n--}else _=!0}let v=vc(h,g,s,e,c);if(d&&f){v.vs=[d,v.vs,f].flat(1);let t=e.predecessors(d);if(t&&t.length){let n=e.node(t[0]),r=e.predecessors(f),i=e.node(r[0]);Object.hasOwn(v,`barycenter`)||(v.barycenter=0,v.weight=0),v.barycenter=(v.barycenter*v.weight+n.order+i.order)/(v.weight+2),v.weight+=2}}return Object.defineProperty(v,"result",{value:v,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(v,"usedBias",{value:_,enumerable:!1,configurable:!0,writable:!0}),v}function Sc(e,t){e.forEach(e=>{e.vs=e.vs.flatMap(e=>t[e]?t[e].vs:e)})}function Cc(e,t){e.barycenter===void 0?(e.barycenter=t.barycenter,e.weight=t.weight):(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight)}function wc(e,t,n,r){r||=e.nodes();let i=Tc(e),a=new ko({compound:!0}).setGraph({root:i}).setDefaultNodeLabel(t=>e.node(t));return r.forEach(r=>{let o=e.node(r),s=e.parent(r);if(o.rank===t||o.minRank<=t&&t<=o.maxRank){a.setNode(r),a.setParent(r,s||i);let c=e[n](r);c&&c.forEach(t=>{let n=t.v===r?t.w:t.v,i=a.edge(n,r),o=i===void 0?0:i.weight;a.setEdge(n,r,{weight:e.edge(t).weight+o})}),Object.hasOwn(o,`minRank`)&&a.setNode(r,{borderLeft:o.borderLeft[t],borderRight:o.borderRight[t]})}}),a}function Tc(e){let t;for(;e.hasNode(t=Ko(`_root`)););return t}function Ec(e,t,n){let r={},i;n.forEach(n=>{let a=e.parent(n),o,s;for(;a;){if(o=e.parent(a),o?(s=r[o],r[o]=a):(s=i,i=a),s&&s!==a){t.setEdge(s,a);return}a=o}})}function Dc(e,t={},n=null){if(typeof t.customOrder==`function`){t.customOrder(e,Dc);return}let r=Vo(e),i=Oc(e,qo(1,r+1),`inEdges`),a=Oc(e,qo(r-1,-1,-1),`outEdges`),o=dc(e,n);if(Ac(e,o),t.disableOptimalOrderHeuristic)return;let s=1/0,c,l=t.constraints||[];for(let t=0,r=0;r<4;++t,++r){kc(t%2?i:a,t%4>=2,l,n),o=Po(e);let u=fc(e,o);u<s?(r=0,c=Object.assign({},o),s=u):u===s&&(c=structuredClone(o))}Ac(e,c)}function Oc(e,t,n){let r=new Map,i=(e,t)=>{r.has(e)||r.set(e,[]),r.get(e).push(t)};for(let t of e.nodes()){let n=e.node(t);if(typeof n.rank==`number`&&i(n.rank,t),typeof n.minRank==`number`&&typeof n.maxRank==`number`)for(let e=n.minRank;e<=n.maxRank;e++)e!==n.rank&&i(e,t)}return t.map(function(t){return wc(e,t,n,r.get(t)||[])})}function kc(e,t,n,r){let i=!0,a=new ko;e.forEach(function(e){n.forEach(e=>a.setEdge(e.left,e.right));let o=e.graph().root,{result:s,usedBias:c}=xc(e,o,a,r,i);t&&c&&(i=!i),s.vs.forEach((t,n)=>e.node(t).order=n),Ec(e,a,s.vs)})}function Ac(e,t){Object.values(t).forEach(t=>t.forEach((t,n)=>e.node(t).order=n))}function jc(e,t){let n={};function r(t,r){let i=0,a=0,o=t.length,s=r[r.length-1];return r.forEach((t,c)=>{let l=Nc(e,t),u=l?e.node(l).order:o;(l||t===s)&&(r.slice(a,c+1).forEach(t=>{let r=e.predecessors(t);r&&r.forEach(r=>{let a=e.node(r),o=a.order;(o<i||u<o)&&!(a.dummy&&e.node(t).dummy)&&Pc(n,r,t)})}),a=c+1,i=u)}),r}return t.length&&t.reduce(r),n}function Mc(e,t){let n={};function r(t,r,i,a,o){qo(r,i).forEach(r=>{let i=t[r];if(i!==void 0&&e.node(i).dummy){let t=e.predecessors(i);t&&t.forEach(t=>{if(t===void 0)return;let r=e.node(t);r.dummy&&(r.order<a||r.order>o)&&Pc(n,t,i)})}})}function i(t,n){let i=-1,a=-1,o=0;return n.forEach((s,c)=>{if(e.node(s).dummy===`border`){let t=e.predecessors(s);if(t&&t.length){let s=t[0];if(s===void 0)return;a=e.node(s).order,r(n,o,c,i,a),o=c,i=a}}r(n,o,n.length,a,t.length)}),n}return t.length&&t.reduce(i),n}function Nc(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(t=>e.node(t).dummy)}}function Pc(e,t,n){if(t>n){let e=t;t=n,n=e}let r=e[t];r||(e[t]=r={}),r[n]=!0}function Fc(e,t,n){if(t>n){let e=t;t=n,n=e}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function Ic(e,t,n,r,i){let a={},o={},s={};return t.forEach(e=>{e.forEach((e,t)=>{a[e]=e,o[e]=e,s[e]=t})}),t.forEach(t=>{let c=-1,l=-1,u=!1,d=t,f=t.findIndex(t=>i?.includes(t)||Gc(t,e,i));f>0&&(d=[t[f],...t.slice(0,f),...t.slice(f+1)],u=!0),d.forEach(t=>{let d=r(t);if(d&&d.length){i!=null&&i.includes(t)&&(d=d.filter(t=>Gc(t,e,i)));let r=d.sort((e,t)=>{let n=s[e],r=s[t];return(n===void 0?0:n)-(r===void 0?0:r)}),f=(r.length-1)/2;for(let e=Math.floor(f),i=Math.ceil(f);e<=i;++e){let i=r[e];if(i===void 0)continue;let d=s[i];if(d!==void 0&&o[t]===t&&c<d&&s[i]!==l&&!Fc(n,t,i)){let e=a[i];e!==void 0&&(o[i]=t,o[t]=a[t]=e,c=d,u&&=(c=-1,l=s[i]??-1,!1))}}}})}),{root:a,align:o}}function Lc(e,t,n,r,i=!1){let a={},o=Rc(e,t,n,i),s=i?`borderLeft`:`borderRight`;function c(e,t){let n=o.nodes().slice(),r={},i=n.pop();for(;i;){if(r[i])e(i);else{r[i]=!0,n.push(i);for(let e of t(i))n.push(e)}i=n.pop()}}function l(e){let t=o.inEdges(e);t?a[e]=t.reduce((e,t)=>{let n=a[t.v]??0,r=o.edge(t);return Math.max(e,n+(r===void 0?0:r))},0):a[e]=0}function u(t){let n=o.outEdges(t),r=1/0;n&&(r=n.reduce((e,t)=>{let n=a[t.w],r=o.edge(t);return Math.min(e,(n===void 0?0:n)-(r===void 0?0:r))},1/0));let i=e.node(t);r!==1/0&&i.borderType!==s&&(a[t]=Math.max(a[t]===void 0?0:a[t],r))}function d(e){return o.predecessors(e)||[]}function f(e){return o.successors(e)||[]}return c(l,d),c(u,f),Object.keys(r).forEach(e=>{let t=n[e];t!==void 0&&(a[e]=a[t]??0)}),a}function Rc(e,t,n,r){let i=new ko,a=e.graph(),o=Uc(a.nodesep,a.edgesep,r);return t.forEach(t=>{let r;t.forEach(t=>{let a=n[t];if(a!==void 0){if(i.setNode(a),r!==void 0){let s=n[r];if(s!==void 0){let n=i.edge(s,a);i.setEdge(s,a,Math.max(o(e,t,r),n||0))}}r=t}})}),i}function zc(e,t){return Object.values(t).reduce((t,n)=>{let r=-1/0,i=1/0;Object.entries(n).forEach(([t,n])=>{let a=Wc(e,t)/2;r=Math.max(n+a,r),i=Math.min(n-a,i)});let a=r-i;return a<t[0]&&(t=[a,n]),t},[1/0,null])[1]}function Bc(e,t){let n=Object.values(t),r=Bo(Math.min,n),i=Bo(Math.max,n);[`u`,`d`].forEach(n=>{[`l`,`r`].forEach(a=>{let o=n+a,s=e[o];if(!s||s===t)return;let c=Object.values(s),l=r-Bo(Math.min,c);a!==`l`&&(l=i-Bo(Math.max,c)),l&&(e[o]=Yo(s,e=>e+l))})})}function Vc(e,t=void 0){let n=e.ul;return n?Yo(n,(n,r)=>{if(t){let n=e[t.toLowerCase()];if(n&&n[r]!==void 0)return n[r]}let i=Object.values(e).map(e=>{let t=e[r];return t===void 0?0:t}).sort((e,t)=>e-t);return((i[1]??0)+(i[2]??0))/2}):{}}function Hc(e,t){let n=Po(e),r=Object.assign(jc(e,n),Mc(e,n)),i={},a;return[`u`,`d`].forEach(o=>{a=o===`u`?n:Object.values(n).reverse(),[`l`,`r`].forEach(n=>{n===`r`&&(a=a.map(e=>Object.values(e).reverse()));let s=Ic(e,a,r,t=>(o===`u`?e.predecessors(t):e.successors(t))||[],t),c=Lc(e,a,s.root,s.align,n===`r`);n===`r`&&(c=Yo(c,e=>-e)),i[o+n]=c})}),Bc(i,zc(e,i)),Vc(i,e.graph().align)}function Uc(e,t,n){return(r,i,a)=>{let o=r.node(i),s=r.node(a),c=0,l;if(c+=o.width/2,Object.hasOwn(o,`labelpos`))switch(o.labelpos.toLowerCase()){case`l`:l=-o.width/2;break;case`r`:l=o.width/2}if(l&&(c+=n?l:-l),l=void 0,c+=(o.dummy?t:e)/2,c+=(s.dummy?t:e)/2,c+=s.width/2,Object.hasOwn(s,`labelpos`))switch(s.labelpos.toLowerCase()){case`l`:l=s.width/2;break;case`r`:l=-s.width/2}return l&&(c+=n?l:-l),c}}function Wc(e,t){return e.node(t).width}function Gc(e,t,n){if(!n)return!1;let r=t.node(e)?.edgeObj;if(!r||t.node(e).edgeLabel.reversed)return!1;let i=n.indexOf(r?.v),a=n.indexOf(r?.w);return i!==-1&&a!==-1&&i===(a+1)%n.length||i===(a-1)%n.length}function Kc(e,t){e=Mo(e),qc(e),Object.entries(Hc(e,t)).forEach(([t,n])=>e.node(t).x=n)}function qc(e){let t=Po(e),n=e.graph(),r=n.ranksep,i=n.rankalign,a=0;t.forEach(t=>{let n=t.reduce((t,n)=>{let r=e.node(n).height??0;return t>r?t:r},0);t.forEach(t=>{let r=e.node(t);r.y=i===`top`?a+r.height/2:i===`bottom`?a+n-r.height/2:a+n/2}),a+=n+r})}var Jc=new WeakMap;function Yc(e,t={}){return Zc(e,Wo,t),e}function Xc(e,t,n){let r=t;for(;r!==void 0;){let t=e.parent(r);if(t===n)return r;r=t}}function Zc(e,t,n){let r=e.nodes().filter(t=>e.children(t).length),i={};r.forEach(r=>{let a=e.node(r);if(a&&a.rankdir){let o=new ko({multigraph:!0,compound:!0});o.setGraph({rankdir:a.rankdir});let s=e.children(r);s.forEach(t=>{let n={...e.node(t)};o.setNode(t,n);let i=e.parent(t);i&&i!==r&&s.includes(i)&&o.setParent(t,i)});let c=new Set;e.edges().forEach(t=>{let n=Xc(e,t.v,r),i=Xc(e,t.w,r);if(n&&i&&n!==i){let r=`${n}\0${i}`;c.has(r)||(c.add(r),o.setEdge(n,i,{...e.edge(t)}))}}),Zc(o,t,n);let l=cl(o);Qc(l,t,n,null),$c(o,l);let u=1/0,d=1/0,f=-1/0,p=-1/0;o.nodes().forEach(e=>{if(e===r)return;let t=o.node(e);t&&typeof t.x==`number`&&typeof t.y==`number`&&typeof t.width==`number`&&typeof t.height==`number`&&(u=Math.min(u,t.x-t.width/2),f=Math.max(f,t.x+t.width/2),d=Math.min(d,t.y-t.height/2),p=Math.max(p,t.y+t.height/2))}),(!isFinite(u)||!isFinite(d)||!isFinite(f)||!isFinite(p))&&(u=d=0,f=p=0);let m=f-u,h=p-d;i[r]={minX:u,minY:d,maxX:f,maxY:p,width:m,height:h,offsetX:u,offsetY:d},a._dagreClusterSubgraph=o}});let a=[],o=t=>{let n=[],r=(e.children(t)||[]).filter(e=>e!==t);for(;r.length>0;){let t=r.shift();n.push(t),(e.children(t)||[]).filter(e=>e!==t).forEach(e=>r.push(e))}return n},s=new Map;r.forEach(t=>{let n=e.node(t);n&&n.rankdir&&i[t]&&s.set(t,(e.children(t)||[]).filter(e=>e!==t))});let c=new Set([...s.values()].flat()),l=new Map;s.forEach((e,t)=>{c.has(t)||l.set(t,o(t))});let u=new Set([...l.values()].flat()),d=e=>{for(let[t,n]of l)if(n.includes(e))return t;return e},f=[];e.edges().forEach(t=>{(u.has(t.v)||u.has(t.w))&&f.push({edge:t,label:e.edge(t)})});let p=new Map;u.forEach(t=>{let n=e.parent(t);p.set(t,typeof n==`string`?n:void 0)}),l.forEach((t,n)=>{let r=e.node(n),o=[];t.forEach(t=>{let n=e.node(t);n&&(o.push({id:t,node:n,parent:p.get(t)}),e.removeNode(t))});let s=f.filter(({edge:e})=>t.includes(e.v)||t.includes(e.w)),c=i[n];r&&(a.push({clusterId:n,subgraph:r._dagreClusterSubgraph,bounds:c,children:t,removedNodes:o,removedEdges:s}),r.width=c.width,r.height=c.height)});let m=new Set;f.forEach(({edge:t,label:n})=>{let r=d(t.v),i=d(t.w);if(r!==i&&e.hasNode(r)&&e.hasNode(i)){let t=`${r}\0${i}`;m.has(t)||(m.add(t),e.setEdge(r,i,{...n,width:0,height:0}))}});let h=cl(e),g=Qc(h,t,n,Jc.get(e)??null);Jc.set(e,g),$c(e,h),m.forEach(t=>{let n=t.indexOf(`\0`),r=t.slice(0,n),i=t.slice(n+1);e.hasEdge(r,i)&&e.removeEdge(r,i)}),a.forEach(({clusterId:t,subgraph:n,bounds:r,removedNodes:i,removedEdges:a})=>{let o=e.node(t),s=o?.x??0,c=o?.y??0,l=(r.minX+r.maxX)/2,u=(r.minY+r.maxY)/2;i.forEach(({id:t,node:n,parent:r})=>{e.setNode(t,n),r!==void 0&&e.setParent(t,r)}),a.forEach(({edge:t,label:n})=>{e.setEdge(t,n)}),n.nodes().forEach(r=>{if(r===t)return;let i=n.node(r),a=e.node(r);a&&i&&typeof i.x==`number`&&typeof i.y==`number`&&(a.x=s+(i.x-l),a.y=c+(i.y-u))}),delete o._dagreClusterSubgraph}),r.forEach(t=>{let n=e.node(t),r=i[t];if(n&&n.rankdir&&n._dagreClusterSubgraph&&r){let i=n._dagreClusterSubgraph,a=n.x??0,o=n.y??0,s=(r.minX+r.maxX)/2,c=(r.minY+r.maxY)/2;i.nodes().forEach(n=>{if(n===t)return;let r=i.node(n),l=e.node(n);if(l&&r&&typeof r.x==`number`&&typeof r.y==`number`){let e=r.x-s,t=r.y-c;l.x=a+e,l.y=o+t}}),delete n._dagreClusterSubgraph}})}function Qc(e,t,n,r=null){var i,a;let o=n?.useDynamic!==!1,s=o&&(i=r?.graph)!=null?i:null,c=o&&(a=r?.rawNodes)!=null?a:null;t(` makeSpaceForEdgeLabels`,()=>ll(e)),t(` removeSelfEdges`,()=>vl(e)),t(` acyclic`,()=>ds(e,s)),t(` nestingGraph.run`,()=>Ys(e)),t(` rank`,()=>Bs(Mo(e))),t(` injectEdgeLabelProxies`,()=>ul(e)),t(` removeEmptyRanks`,()=>Io(e)),t(` nestingGraph.cleanup`,()=>$s(e)),t(` normalizeRanks`,()=>Fo(e)),t(` assignRankMinMax`,()=>dl(e)),t(` removeEdgeLabelProxies`,()=>fl(e)),t(` normalize.run`,()=>hs(e)),t(` parentDummyChains`,()=>Gs(e)),t(` addBorderSegments`,()=>ec(e)),t(` order`,()=>Dc(e,n,c)),t(` insertSelfEdges`,()=>yl(e)),t(` adjustCoordinateSystem`,()=>rc(e)),t(` position`,()=>Kc(e,n.corePath)),t(` positionSelfEdges`,()=>bl(e));let l=JSON.parse(JSON.stringify(e._nodes));return t(` removeBorderNodes`,()=>_l(e)),t(` normalize.undo`,()=>_s(e)),t(` fixupEdgeLabelCoords`,()=>hl(e)),t(` undoCoordinateSystem`,()=>ic(e)),t(` translateGraph`,()=>pl(e)),t(` assignNodeIntersects`,()=>ml(e)),t(` reversePoints`,()=>gl(e)),t(` acyclic.undo`,()=>ps(e)),{graph:e,rawNodes:l}}function $c(e,t){e.nodes().forEach(n=>{let r=e.node(n),i=t.node(n);r&&(r.x=i.x,r.y=i.y,r.order=i.order,r.rank=i.rank,t.children(n).length&&(r.width=i.width,r.height=i.height))}),e.edges().forEach(n=>{let r=e.edge(n),i=t.edge(n);r.points=i.points,Object.hasOwn(i,`x`)&&(r.x=i.x,r.y=i.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var el=[`nodesep`,`edgesep`,`ranksep`,`marginx`,`marginy`],tl={ranksep:50,edgesep:20,nodesep:50,rankdir:`TB`,rankalign:`center`},nl=[`acyclicer`,`ranker`,`rankdir`,`align`,`rankalign`],rl=[`width`,`height`,`rank`],il={width:0,height:0},al=[`minlen`,`weight`,`width`,`height`,`labeloffset`],ol={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:`r`},sl=[`labelpos`];function cl(e){let t=new ko({multigraph:!0,compound:!0}),n=Sl(e.graph());return t.setGraph(Object.assign({},tl,xl(n,el),Jo(n,nl))),e.nodes().forEach(n=>{let r=xl(Sl(e.node(n)),rl);Object.keys(il).forEach(e=>{r[e]===void 0&&(r[e]=il[e])}),t.setNode(n,r);let i=e.parent(n);i!==void 0&&t.setParent(n,i)}),e.edges().forEach(n=>{let r=Sl(e.edge(n));t.setEdge(n,Object.assign({},ol,xl(r,al),Jo(r,sl)))}),t}function ll(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,(r.labelpos??`r`).toLowerCase()!==`c`&&(t.rankdir===`TB`||t.rankdir===`BT`?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function ul(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let n=e.node(t.v);Ao(e,`edge-proxy`,{rank:(e.node(t.w).rank-n.rank)/2+n.rank,e:t},`_ep`)}})}function dl(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function fl(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy===`edge-proxy`){let r=n;e.edge(r.e).labelRank=n.rank,e.removeNode(t)}})}function pl(e){let t=1/0,n=0,r=1/0,i=0,a=e.graph(),o=a.marginx||0,s=a.marginy||0;function c(e){let a=e.x,o=e.y,s=e.width,c=e.height;t=Math.min(t,a-s/2),n=Math.max(n,a+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}e.nodes().forEach(t=>c(e.node(t))),e.edges().forEach(t=>{let n=e.edge(t);Object.hasOwn(n,`x`)&&c(n)}),t-=o,r-=s,e.nodes().forEach(n=>{let i=e.node(n);i.x-=t,i.y-=r}),e.edges().forEach(n=>{let i=e.edge(n);i.points.forEach(e=>{e.x-=t,e.y-=r}),Object.hasOwn(i,`x`)&&(i.x-=t),Object.hasOwn(i,`y`)&&(i.y-=r)}),a.width=n-t+o,a.height=i-r+s}function ml(e){e.edges().forEach(t=>{if(t.v===t.w)return;let n=e.edge(t),r=e.node(t.v),i=e.node(t.w),a,o;n.points?(a=n.points[0],o=n.points[n.points.length-1]):(n.points=[],a=i,o=r),n.points.unshift(No(r,a)),n.points.push(No(i,o))})}function hl(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,`x`))switch((n.labelpos===`l`||n.labelpos===`r`)&&(n.width-=n.labeloffset),n.labelpos){case`l`:n.x-=n.width/2+n.labeloffset;break;case`r`:n.x+=n.width/2+n.labeloffset}})}function gl(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function _l(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),i=e.node(n.borderBottom),a=e.node(n.borderLeft[n.borderLeft.length-1]),o=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(o.x-a.x),n.height=Math.abs(i.y-r.y),n.x=a.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy===`border`&&e.removeNode(t)})}function vl(e){e.edges().forEach(t=>{if(t.v===t.w){let n=e.node(t.v);n.selfEdges||=[],n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function yl(e){Po(e).forEach(t=>{let n=0;t.forEach((t,r)=>{let i=e.node(t);typeof i.rank!=`number`&&(i.rank=0),i.order=r+n,(i.selfEdges||[]).forEach(t=>{Ao(e,`selfedge`,{width:t.label.width,height:t.label.height,rank:i.rank,order:r+ ++n,e:t.e,edgeLabel:t.label},`_se`),(!Array.isArray(t.label.points)||t.label.points.length!==7)&&(t.label.points=[{x:0,y:-10},{x:0,y:-10},{x:0,y:0},{x:0,y:10},{x:0,y:10},{x:0,y:0},{x:0,y:0}])}),delete i.selfEdges})})}function bl(e){e.nodes().forEach(t=>{let n=e.node(t),r=e=>typeof e==`number`&&isFinite(e);if(n.dummy===`selfedge`){let i=n,a=e.node(i.e.v),o=r(a?.x)?a.x:0,s=r(a?.y)?a.y:0,c=r(a?.width)?a.width:0,l=r(a?.height)?a.height:0,u=r(n.x)?n.x:o,d=r(n.y)?n.y:s,f=c/2,p=l/2;i.edgeLabel.points=[{x:u+f,y:d-p},{x:u+f,y:d-p},{x:u,y:d},{x:u-f,y:d+p},{x:u-f,y:d+p},{x:u,y:d},{x:u,y:d}],i.edgeLabel.x=u,i.edgeLabel.y=d,e.setEdge(i.e,i.edgeLabel),e.removeNode(t)}else n&&Array.isArray(n.selfEdges)&&n.selfEdges.forEach(e=>{if(!Array.isArray(e.label.points)||e.label.points.length!==7){let t=r(n.x)?n.x:0,i=r(n.y)?n.y:0,a=r(n.width)?n.width:0,o=r(n.height)?n.height:0,s=a/2,c=o/2;e.label.points=[{x:t+s,y:i-c},{x:t+s,y:i-c},{x:t,y:i},{x:t-s,y:i+c},{x:t-s,y:i+c},{x:t,y:i},{x:t,y:i}]}})})}function xl(e,t){return Yo(Jo(e,t),Number)}function Sl(e){let t={};return e&&Object.entries(e).forEach(([e,n])=>{typeof e==`string`&&(e=e.toLowerCase()),t[e]=n}),t}function Cl(e){let t=Po(e),n=new ko({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(t=>{n.setNode(t,{label:t}),n.setParent(t,`layer`+e.node(t).rank)}),e.edges().forEach(e=>n.setEdge(e.v,e.w,{},e.name)),t.forEach((e,t)=>{let r=`layer`+t;n.setNode(r,{rank:`same`}),e.reduce((e,t)=>(n.setEdge(e,t,{style:`invis`}),t))}),n}var wl={graphlib:Ua,version:$o,layout:Yc,debug:Cl,util:{time:Uo,notime:Wo}};function Tl(e,t){return t?e.ref===void 0?`added`:e.set===void 0?`context`:`changed`:`unchanged`}function El(e,t){if(t&&e.heading===void 0)return e.ref===void 0?`added`:e.set===void 0?`context`:`changed`}function Dl(e,t){return t?e.ref===void 0?`added`:e.set===void 0?`context`:`changed`:`unchanged`}function Ol(e){let t=e.set;if(t===void 0)return[];let n=e;return Object.entries(t).filter(([e])=>e!==`attributes`&&e!==`removeAttributes`).map(([e,t])=>{let r=n[e];return{field:e,...typeof r==`string`?{from:r}:{},to:String(t)}})}var kl={added:`added`,changed:`changed`,context:`existing`,unchanged:``},Al={added:`added`,changed:`changed`,context:`existing`,removed:`removed`},jl=[`added`,`changed`,`context`,`removed`];function Ml(e){return e.rows.some(e=>$e(e).role!==void 0)}function Nl(e,t){if(t)return $e(e).role??`context`}function Pl(e){if(e.length===0)return;let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));return{x:t-Rl,y:n-Rl-zl,width:r-t+Rl*2,height:i-n+Rl*2+zl}}var Fl=64,Il=24,Ll=12,Rl=10,zl=16,Bl=16,Vl=160,Hl=52;function Ul(e,t,n=`landscape`){let r=new wl.graphlib.Graph({compound:!0,multigraph:!0});r.setGraph({rankdir:n===`portrait`?`TB`:`LR`,ranksep:Fl,nodesep:Il,marginx:Ll,marginy:Ll}),r.setDefaultEdgeLabel(()=>({}));for(let n of e.nodes)r.setNode(n.id,t(n));let i=e.containers??[],a=new Map;for(let t of e.nodes)t.container!==void 0&&i.some(e=>e.id===t.container)&&(r.setNode(t.container,{label:t.container}),r.setParent(t.id,t.container),a.set(t.container,[...a.get(t.container)??[],t.id]));e.edges.forEach((e,t)=>{e.from!==e.to&&r.hasNode(e.from)&&r.hasNode(e.to)&&r.setEdge(e.from,e.to,{},String(t))}),wl.layout(r);let o=e.nodes.map(e=>{let n=r.node(e.id),{width:i,height:a}=t(e);return{id:e.id,x:(n?.x??Ll+i/2)-i/2,y:(n?.y??Ll+a/2)-a/2,width:i,height:a}}),s=[];e.edges.forEach((e,t)=>{if(e.from===e.to)return;let n=r.edge(e.from,e.to,String(t));n?.points!==void 0&&n.points.length>0&&s.push({index:t,points:n.points.map(e=>({x:e.x,y:e.y}))})});let c=[],l=o.reduce((e,t)=>Math.max(e,t.y+t.height),Ll)+Bl,u=new Map(o.map(e=>[e.id,e]));for(let e of i){let t=Pl((a.get(e.id)??[]).flatMap(e=>{let t=u.get(e);return t===void 0?[]:[t]}));t===void 0?(c.push({id:e.id,label:e.label,x:Ll,y:l,width:Vl,height:Hl}),l+=68):c.push({id:e.id,label:e.label,...t})}let d=[...o.map(e=>({x:e.x,y:e.y,width:e.width,height:e.height})),...c],f=Math.min(0,...d.map(e=>e.x))-Ll,p=Math.min(0,...d.map(e=>e.y))-Ll;if(f<0||p<0){for(let e of o)e.x-=f,e.y-=p;for(let e of c)e.x-=f,e.y-=p;for(let e of s)for(let t of e.points)t.x-=f,t.y-=p}let m=[...o.map(e=>({x:e.x,y:e.y,width:e.width,height:e.height})),...c].reduce((e,t)=>({width:Math.max(e.width,t.x+t.width),height:Math.max(e.height,t.y+t.height)}),{width:0,height:0});return{nodes:o,edges:s,containers:c,width:m.width+Ll,height:m.height+Ll}}var Wl={attributes:[],expectations:[],assignments:[],removedAttributes:[],locations:[],artifacts:[]};function Gl(e){if(typeof e!=`object`||!e)return Wl;let t=e,n=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.entries(e):[],r=t.set,i=r?.removeAttributes;return{attributes:n(t.attributes),expectations:n(t.expect?.attributes),assignments:n(r?.attributes),removedAttributes:Array.isArray(i)?i.filter(e=>typeof e==`string`):[],locations:Array.isArray(t.locations)?t.locations:[],artifacts:Array.isArray(t.artifacts)?t.artifacts:[]}}function Kl(e){let t=e.target;if(typeof t==`string`)return{ref:t};if(typeof t!=`object`||!t)return;let n=t;if(typeof n.ref==`string`)return{ref:n.ref,...typeof n.revision==`string`?{revision:n.revision}:{}}}function ql(e,t){let n=(e.removals??[]).map(e=>({type:e.type,ref:e.ref})),r=e.profile,i=e.artifacts,a={...typeof r==`string`?{profile:r}:{},...(()=>{let t=Kl(e);return t===void 0?{}:{target:t}})(),artifacts:Array.isArray(i)?i:[]};if(e.kind===`table`){let r=e.data,i=Ml(r),o=r.rows.map(e=>{let n=Array.isArray(e)?{}:e,r=(Array.isArray(e)?void 0:e.role)??El({ref:typeof n.ref==`string`?n.ref:void 0,set:n.set,heading:typeof n.heading==`string`?n.heading:void 0},t)??Nl(e,i),{cells:a,heading:o}=$e(e),s=Array.isArray(e)?{}:e;return{cells:a,...r===void 0?{}:{role:r},...o===void 0?{}:{heading:o},...typeof s.depth==`number`?{depth:s.depth}:{},...typeof s.id==`string`?{id:s.id}:{},...typeof s.ref==`string`?{ref:s.ref}:{},...typeof s.kind==`string`?{kind:s.kind}:{},changes:Ol(s),...Gl(e)}}),s=new Map;for(let e of o){if(e.id===void 0)continue;let t=e.cells.find(e=>typeof e==`string`&&e!==``);s.set(e.id,(typeof t==`string`?t:void 0)??e.ref??e.id)}let c=r.relations,l=(Array.isArray(c)?c:[]).map(e=>{let t=e,n=e=>{let t=typeof e?.id==`string`?e.id:void 0,n=typeof e?.ref==`string`?e.ref:void 0;return{id:t,ref:n,label:(t===void 0?void 0:s.get(t))??n??t??``}},r=n(t.from),i=n(t.to);return{kind:t.kind??``,...typeof t.label==`string`?{label:t.label}:{},...r.id===void 0?{}:{fromRow:r.id},...i.id===void 0?{}:{toRow:i.id},...r.ref===void 0?{}:{fromRef:r.ref},...i.ref===void 0?{}:{toRef:i.ref},fromLabel:r.label,toLabel:i.label}});return{thingNoun:`column`,linkNoun:`row`,things:[],links:[],columns:r.columns,rows:o,containers:[],removals:n,traces:l,...a}}if(e.kind===`timeline`)return{thingNoun:`task`,linkNoun:`dependency`,things:[],links:[],containers:[],removals:n,traces:[],...a};let o=e.kind===`graph`,s=o?e.data.nodes:e.data.participants,c=o?e.data.edges:e.data.messages,l=new Map(s.map(e=>[e.id,Jl(e)]));return{thingNoun:o?`element`:`participant`,linkNoun:o?`relationship`:`message`,things:s.map(e=>({id:e.id,label:Jl(e),kind:e.kind,role:Tl(e,t),changes:Ol(e),container:e.container,...Gl(e)})),links:c.map(e=>({from:e.from,to:e.to,fromLabel:l.get(e.from)??e.from,toLabel:l.get(e.to)??e.to,label:e.label,kind:`kind`in e?e.kind:void 0,role:Dl(e,t),changes:Ol(e),isLoop:e.from===e.to,...Gl(e)})),containers:e.data.containers??[],removals:n,traces:[],...a}}function Jl(e){return e.label??e.ref??e.id}function Yl(e){if(e.kind===`graph`){let t=e.data,n=[`flowchart TD`],r=t.containers??[],i=new Set(r.map(e=>e.id)),a=e=>t.nodes.filter(t=>t.container===e);for(let e of r){n.push(` subgraph ${Xl(e.id)}["${Ql(e.label)}"]`);for(let t of a(e.id))n.push(` ${Xl(t.id)}["${Ql(Jl(t))}"]`);n.push(` end`)}for(let e of t.nodes)e.container!==void 0&&i.has(e.container)||n.push(` ${Xl(e.id)}["${Ql(Jl(e))}"]`);for(let e of t.edges){let t=e.label??e.kind,r=t===void 0?`-->`:`-- "${Ql(t)}" -->`;n.push(` ${Xl(e.from)} ${r} ${Xl(e.to)}`)}return n.join(`
23
23
  `)}if(e.kind===`sequence`){let t=e.data,n=[`sequenceDiagram`],r=t.containers??[],i=new Set(r.map(e=>e.id)),a=(e,t)=>`${t}participant ${Xl(e.id)} as "${Ql(Jl(e))}"`;for(let e of r){n.push(` box ${Ql(e.label)}`);for(let r of t.participants.filter(t=>t.container===e.id))n.push(a(r,` `));n.push(` end`)}for(let e of t.participants)e.container!==void 0&&i.has(e.container)||n.push(a(e,` `));for(let e of t.messages)n.push(` ${Xl(e.from)}->>${Xl(e.to)}: ${Ql(e.label??``)}`);return n.join(`
@@ -325,12 +325,12 @@ l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
325
325
  `).trim();return r===``?void 0:r}function YF({text:e}){let t=(0,d.useMemo)(()=>[xF,NF],[]),n=(0,d.useMemo)(()=>[eD],[]);return(0,A.jsx)(`div`,{className:`prose-chat max-h-96 overflow-auto text-zinc-700 dark:text-zinc-300`,children:(0,A.jsx)(Py,{remarkPlugins:t,rehypePlugins:n,children:E(e)})})}function XF({item:e}){return(0,A.jsx)(`pre`,{className:`max-h-96 overflow-auto whitespace-pre-wrap font-mono text-xs text-zinc-700 dark:text-zinc-300`,children:e.output?e.output:e.running?`running…`:`(no output)`})}var ZF={id:`raw`,match:()=>!0,stable:!1,Expanded:XF},QF={id:`codemode`,match:e=>e.toolName===`codemode`,stable:!0,extensionOwned:!0,compactHeader:!0,showsRawReveal:!0,Expanded:({item:e})=>(0,A.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,A.jsxs)(`section`,{"aria-label":`Script`,children:[(0,A.jsx)(`h4`,{className:`mb-1 text-xs font-medium text-zinc-500`,children:`Script`}),e.callHtml?(0,A.jsx)(Ge,{html:e.callHtml,className:`max-h-64 text-zinc-700 dark:text-zinc-300`}):(0,A.jsx)(`pre`,{className:`max-h-64 overflow-auto whitespace-pre-wrap font-mono text-xs`,children:typeof e.args?.code==`string`?e.args.code:JSON.stringify(e.args)})]}),(0,A.jsxs)(`section`,{"aria-label":`Calls and result`,children:[(0,A.jsx)(`h4`,{className:`mb-1 text-xs font-medium text-zinc-500`,children:`Calls and result`}),e.outputHtml?(0,A.jsx)(Ge,{html:e.outputHtml,className:`max-h-96 text-zinc-700 dark:text-zinc-300`}):(0,A.jsx)(XF,{item:e})]})]})},$F={id:`extension-html`,match:e=>!!e.outputHtml,stable:!1,extensionOwned:!0,showsRawReveal:!0,hasCollapsed:e=>!!e.outputHtmlCollapsed,Collapsed:({item:e})=>(0,A.jsx)(Ge,{html:e.outputHtmlCollapsed??``,className:`max-h-96 text-zinc-700 dark:text-zinc-300`}),Expanded:({item:e})=>(0,A.jsx)(Ge,{html:e.outputHtml??``,className:`max-h-96 text-zinc-700 dark:text-zinc-300`})};function eI(e){if(e.toolName!==`edit`||e.args===null||typeof e.args!=`object`)return null;let t=e.args.edits;if(!Array.isArray(t))return null;let n=t.filter(e=>typeof e==`object`&&!!e&&typeof e.oldText==`string`&&typeof e.newText==`string`);return n.length>0?n:null}var tI={id:`file-edit`,match:e=>eI(e)!==null,stable:!0,startsExpanded:!0,showsRawReveal:!0,Expanded:({item:e})=>(0,A.jsx)(`div`,{className:`flex flex-col gap-2`,children:(eI(e)??[]).map((e,t)=>(0,A.jsx)(Ke,{lines:S(e.oldText,e.newText)},t))})};function nI(e){if(e.toolName!==`write`||e.args===null||typeof e.args!=`object`)return null;let t=e.args.content;return typeof t==`string`?t:null}var rI={id:`file-write`,match:e=>nI(e)!==null,stable:!0,startsExpanded:!0,showsRawReveal:!0,Expanded:({item:e})=>(0,A.jsx)(qe,{lines:(nI(e)??``).split(`
326
326
  `).map(e=>({type:`add`,text:e}))})},iI={id:`pi-render`,match:e=>e.output?D(e.output)!==void 0:!1,stable:!1,Collapsed:({item:e})=>(0,A.jsx)(YF,{text:D(e.output??``)??``}),Expanded:XF},aI={id:`orient-summary`,match:e=>e.output?JF(te(e.output))!==void 0:!1,stable:!1,Collapsed:({item:e})=>(0,A.jsx)(YF,{text:JF(te(e.output??``))??``}),Expanded:XF};function oI(e){let t=e.trim();return t===`/dev/null`||t===``?null:t.replace(/^[ab]\//,``)}function sI(e){let t=[],n=null,r=null,i=!1,a=()=>{n&&n.lines.length>0&&t.push(n),n=null};for(let t of e.split(`
327
327
  `))if(t.startsWith(`diff --git `)){a(),i=!1,r=null;let e=/^diff --git (.+?) (.+)$/.exec(t),o=e?oI(e[2])??oI(e[1]):null;n=o===null?null:{path:o,lines:[],added:0,removed:0}}else if(t.startsWith(`--- `))i=!1,r=oI(t.slice(4));else if(t.startsWith(`+++ `)){i=!1;let e=oI(t.slice(4))??r;e!==null&&(n===null||n.lines.length>0)?(a(),n={path:e,lines:[],added:0,removed:0}):e!==null&&n!==null&&(n.path=e)}else if(t.startsWith(`@@`))i=n!==null;else if(i&&n!==null){if(t.startsWith(`+`))n.lines.push({type:`add`,text:t.slice(1)}),n.added++;else if(t.startsWith(`-`))n.lines.push({type:`del`,text:t.slice(1)}),n.removed++;else if(t.startsWith(` `))n.lines.push({type:`same`,text:t.slice(1)});else if(t.startsWith(`\\`))continue;else i=!1}return a(),t}var cI=/^\s*git\s+(diff|show)\b/;function lI(e){if(e.toolName!==`bash`||e.args===null||typeof e.args!=`object`)return null;let t=e.args.command;return typeof t!=`string`||!cI.test(t)?null:t}var uI=6;function dI({onClick:e,children:t}){return(0,A.jsx)(`button`,{type:`button`,onClick:e,className:`rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`,children:t})}function fI({item:e,dispatch:t}){let n=sI(e.output??``),[r,i]=(0,d.useState)(!1);if(n.length===0)return(0,A.jsx)(XF,{item:e});let a=r?n:n.slice(0,uI);return(0,A.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[a.map(e=>(0,A.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`truncate font-mono text-xs text-zinc-600 dark:text-zinc-400`,children:e.path}),(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[(0,A.jsxs)(`span`,{className:`text-emerald-600 dark:text-emerald-400`,children:[`+`,e.added]}),` `,(0,A.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,e.removed]})]}),(0,A.jsxs)(`span`,{className:`ml-auto flex shrink-0 items-center`,children:[(0,A.jsx)(dI,{onClick:()=>t({kind:`openFile`,path:e.path}),children:`open`}),(0,A.jsx)(dI,{onClick:()=>t({kind:`openFileHistory`,path:e.path}),children:`history`})]})]}),(0,A.jsx)(qe,{lines:e.lines})]},e.path)),!r&&n.length>uI&&(0,A.jsxs)(`button`,{type:`button`,onClick:()=>i(!0),className:`self-start text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300`,children:[`show `,n.length-uI,` more file`,n.length-uI===1?``:`s`]})]})}var pI={id:`git-diff`,match:e=>lI(e)!==null,stable:!0,showsRawReveal:!0,Expanded:fI},mI=/^(.*?):(\d+):(.*)$/;function hI(e){let t=[],n=new Map;for(let r of e.split(`
328
- `)){let e=mI.exec(r);if(e===null)continue;let[,i,a,o]=e;if(i===``)continue;let s=n.get(i);s===void 0&&(s={path:i,hits:[]},n.set(i,s),t.push(s)),s.hits.push({line:Number(a),text:o})}return t}function gI(e){return e.reduce((e,t)=>e+t.hits.length,0)}var _I=8,vI=5;function yI({item:e,dispatch:t}){let n=hI(e.output??``),[r,i]=(0,d.useState)(!1);if(n.length===0)return(0,A.jsx)(XF,{item:e});let a=r?n:n.slice(0,_I);return(0,A.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,A.jsxs)(`div`,{className:`text-xs text-zinc-500`,children:[gI(n),` match`,gI(n)===1?``:`es`,` in `,n.length,` file`,n.length===1?``:`s`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`flex flex-col`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({kind:`openFile`,path:e.path}),className:`flex items-center gap-2 truncate text-left font-mono text-xs text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100`,children:[(0,A.jsx)(`span`,{className:`truncate`,children:e.path}),(0,A.jsx)(`span`,{className:`shrink-0 text-zinc-400 dark:text-zinc-600`,children:e.hits.length})]}),(0,A.jsxs)(`div`,{className:`overflow-x-auto rounded border border-zinc-200 font-mono text-xs dark:border-zinc-800`,children:[e.hits.slice(0,vI).map((e,t)=>(0,A.jsxs)(`div`,{className:`flex gap-2 px-2`,children:[(0,A.jsx)(`span`,{className:`shrink-0 select-none text-zinc-400 dark:text-zinc-600`,children:e.line}),(0,A.jsx)(`span`,{className:`whitespace-pre text-zinc-700 dark:text-zinc-300`,children:e.text})]},t)),e.hits.length>vI&&(0,A.jsxs)(`div`,{className:`px-2 text-zinc-400 dark:text-zinc-600`,children:[`+`,e.hits.length-vI,` more in this file`]})]})]},e.path)),!r&&n.length>_I&&(0,A.jsxs)(`button`,{type:`button`,onClick:()=>i(!0),className:`self-start text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300`,children:[`show `,n.length-_I,` more file`,n.length-_I===1?``:`s`]})]})}var bI=[QF,$F,Bf,tI,rI,pI,{id:`code-search`,match:e=>e.toolName===`grep`,stable:!0,showsRawReveal:!0,Expanded:yI},iI,aI,ZF];function xI(e){for(let t of bI){let n=!1;try{n=t.match(e)}catch{n=!1}if(n)return t}return ZF}function SI(e,t){let n=xI(e);if(t===void 0||t===n.id)return n;let r=bI.find(e=>e.id===t);if(r===void 0||r.id===ZF.id||n.extensionOwned===!0)return n;let i=!1;try{i=r.match(e)}catch{i=!1}return i?r:n}function CI(e){if(typeof e!=`object`||!e)return``;let t=e,n=[`command`,`path`,`file_path`,`pattern`,`query`].find(e=>typeof t[e]==`string`);if(n)return t[n];let r=JSON.stringify(t);return r===`{}`?``:r}function wI({item:e,dispatch:t=WF}){let n=(0,d.useRef)(void 0),r=SI(e,n.current);n.current=r.id;let i=r.startsExpanded===!0,[a,o]=(0,d.useState)(i);(0,d.useEffect)(()=>{o(i)},[i]);let[s,c]=(0,d.useState)(!1),l=(0,d.useRef)(null),u=r.compactHeader?void 0:e.callHtml,f=r.compactHeader?``:CI(e.args),p=r.Collapsed,m=!a&&p!==void 0&&(r.hasCollapsed?.(e)??!0);return(0,A.jsxs)(`div`,{className:`rounded-lg border text-sm ${e.isError?`border-red-300 bg-red-50 dark:border-red-900/60 dark:bg-red-950/20`:`border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900/60`}`,children:[(0,A.jsxs)(`div`,{onMouseDown:e=>{l.current={x:e.clientX,y:e.clientY}},onClick:e=>{let t=l.current;l.current=null,!(e.detail>0&&t&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)&&o(!a)},className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,A.jsxs)(`button`,{type:`button`,"aria-expanded":a,"aria-label":u?e.toolName:void 0,className:`flex shrink-0 items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full ${e.running?`animate-pulse motion-reduce:animate-none bg-amber-400`:e.isError?`bg-red-500`:`bg-emerald-500`}`}),!u&&(0,A.jsx)(`span`,{className:`font-mono font-medium text-zinc-700 dark:text-zinc-300`,children:e.toolName})]}),u?(0,A.jsx)(Ge,{as:`span`,html:u,className:`min-w-0 flex-1 text-zinc-700 dark:text-zinc-300`}):f&&(0,A.jsx)(`span`,{className:`min-w-0 overflow-x-auto whitespace-nowrap font-mono text-xs text-zinc-500 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden`,children:f}),(0,A.jsx)(`span`,{className:`ml-auto text-xs text-zinc-400 dark:text-zinc-600`,children:a?`▾`:`▸`})]}),e.running&&e.progress!=null&&(0,A.jsx)(`div`,{className:`border-t border-zinc-200 px-3 py-1.5 dark:border-zinc-800`,children:(0,A.jsx)(`progress`,{value:e.progress,max:1,"aria-label":`${e.toolName} progress`,className:`h-1.5 w-full appearance-none overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800 [&::-moz-progress-bar]:bg-emerald-500 [&::-webkit-progress-bar]:bg-transparent [&::-webkit-progress-value]:rounded-full [&::-webkit-progress-value]:bg-emerald-500`})}),m&&p!==void 0&&(0,A.jsx)(`div`,{className:`border-t border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:(0,A.jsx)(p,{item:e,dispatch:t})}),a&&(0,A.jsxs)(`div`,{className:`border-t border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(r.Expanded,{item:e,dispatch:t}),r.showsRawReveal===!0&&(0,A.jsxs)(`div`,{className:`mt-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>c(!s),className:`text-xs text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-400`,children:s?`hide raw output`:`raw output`}),s&&(0,A.jsx)(`div`,{className:`mt-1`,children:(0,A.jsx)(XF,{item:e})})]})]})]})}function TI({item:e}){let[t,n]=(0,d.useState)(!1),r=e.details!==void 0,i=!!e.contentHtml,a=e.contentHtmlCollapsed??e.contentHtml,o=r||i&&!!e.contentHtmlCollapsed;return(0,A.jsxs)(`div`,{className:`rounded-lg border border-violet-200 bg-violet-50 px-3 py-2 text-sm dark:border-violet-900/60 dark:bg-violet-950/30`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-xs font-bold text-violet-700 dark:text-violet-300`,children:[`[`,e.customType,`]`]}),o&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>n(!t),title:`Show details`,className:`ml-auto text-xs text-violet-500 hover:text-violet-700 dark:text-violet-500 dark:hover:text-violet-300`,children:t?`▾`:`▸`})]}),i&&a?(0,A.jsx)(Ge,{html:t||!e.contentHtmlCollapsed?e.contentHtml??a:a,className:`mt-1 text-violet-950 dark:text-violet-100`}):(0,A.jsx)(`div`,{className:`prose-chat mt-1 text-violet-950 dark:text-violet-100`,children:(0,A.jsx)(Py,{remarkPlugins:[xF,NF],rehypePlugins:[eD],children:E(e.text)})}),t&&r&&(0,A.jsx)(`pre`,{className:`mt-2 max-h-96 overflow-auto border-t border-violet-200 pt-2 font-mono text-xs text-violet-600 dark:border-violet-900/60 dark:text-violet-400`,children:JSON.stringify(e.details,null,2)})]})}var EI=`pi-outpost:update-notice-dismissed`;function DI(){try{return window.localStorage.getItem(EI)}catch{return null}}function OI({notice:e}){let[t,n]=(0,d.useState)(()=>DI());return t===e.latest?null:(0,A.jsxs)(`div`,{role:`status`,"data-testid":`update-notice`,className:`flex items-center gap-2 border-b border-sky-200 bg-sky-50 px-4 py-1.5 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,children:[(0,A.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[`pi-outpost `,e.latest,` is available (you have `,e.running,`). `,e.instruction]}),(0,A.jsx)(`code`,{className:`shrink-0 rounded bg-white/70 px-1.5 py-0.5 font-mono dark:bg-sky-900/40`,children:e.copy}),(0,A.jsx)(le,{text:e.copy}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Dismiss the update notice`,onClick:()=>{try{window.localStorage.setItem(EI,e.latest)}catch{}n(e.latest)},className:`shrink-0 rounded px-1.5 text-sky-700 hover:bg-sky-100 dark:text-sky-300 dark:hover:bg-sky-900/50`,children:`×`})]})}function kI(e){return e.id??e.root}function AI(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e)}function jI({item:e}){let[t,n]=(0,d.useState)(!1),r=e.tokensBefore?`Conversation compacted here — ${AI(e.tokensBefore)} tokens summarised`:`Conversation compacted here`;return(0,A.jsxs)(`div`,{className:`my-1`,"data-compaction-boundary":!0,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`h-px flex-1 bg-amber-300 dark:bg-amber-900`}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>n(!t),"aria-expanded":t,className:`rounded-full border border-amber-300 bg-amber-50 px-2 py-0.5 text-xs text-amber-800 hover:bg-amber-100 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-300 dark:hover:bg-amber-950/70`,children:[r,` `,t?`▾`:`▸`]}),(0,A.jsx)(`span`,{className:`h-px flex-1 bg-amber-300 dark:bg-amber-900`})]}),t&&(0,A.jsxs)(`div`,{className:`mt-2 whitespace-pre-wrap rounded-lg border border-amber-200 bg-amber-50/60 px-3 py-2 text-sm text-zinc-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-zinc-300`,children:[(0,A.jsx)(`p`,{className:`mb-1 text-xs font-medium text-amber-800 dark:text-amber-300`,children:`What the agent kept of everything above:`}),e.summary||`(the runtime recorded no summary)`]})]})}function MI({older:e,onLoad:t}){if(e.remaining<=0&&!e.error)return null;let n=e.remaining,r=e.loading?`Loading earlier messages…`:`Load ${n} earlier message${n===1?``:`s`}`;return(0,A.jsxs)(`div`,{className:`flex flex-col items-center gap-1 pb-2`,"data-older-messages":!0,children:[(0,A.jsx)(`button`,{type:`button`,onClick:t,disabled:e.loading,"aria-busy":e.loading,"aria-label":e.loading?`Loading earlier messages`:`Load ${n} earlier messages`,className:`rounded-full border border-zinc-300 bg-white px-3 py-1 text-xs text-zinc-600 hover:bg-zinc-50 disabled:cursor-progress disabled:opacity-60 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:r}),e.error&&(0,A.jsxs)(`p`,{role:`status`,className:`text-xs text-red-600 dark:text-red-400`,children:[e.error,` — try again`]})]})}var NI={cost:0,unpriced:0,turns:0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0};function PI(e){let t={...NI};for(let n of e){if(n.kind!==`assistant`||!n.usage)continue;let e=n.usage;t.turns+=1,t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.totalTokens+=e.totalTokens,e.cost===void 0?t.unpriced+=1:t.cost+=e.cost}return t}function FI(e){let t=e>0&&e<.01?4:2;return`$${e.toFixed(t)}`}function II(e){return e<1e3?String(e):e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1)}M`}var LI=80,RI=new WeakMap;function zI(e){let t=typeof e==`object`&&!!e;if(t){let t=RI.get(e);if(t!==void 0)return t}let n=0;try{n=JSON.stringify(e)?.length??0}catch{n=0}return t&&RI.set(e,n),n}function BI(e){let t=e.replace(/\s+/g,` `).trim();return t.length>LI?`${t.slice(0,79)}…`:t}function VI(e,t){return{index:e,title:t,turns:0,toolCalls:0,failedToolCalls:0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,unpriced:0}}function HI(e,t){e.turns+=1,e.input+=t.input,e.output+=t.output,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.totalTokens+=t.totalTokens,t.cost===void 0?e.unpriced+=1:e.cost=(e.cost??0)+t.cost}function UI(e){if(e.length===0)return 0;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==1?t[n]:(t[n-1]+t[n])/2}function WI(e){let t=[],n=[],r=[],i=new Map,a=VI(-1,``),o=a;e.forEach((e,a)=>{if(e.kind===`user`){o=VI(a,BI(e.text)),r.push(o);return}if(e.kind===`assistant`){if(!e.usage)return;t.push({index:a,number:t.length+1,requestIndex:o.index,usage:e.usage}),HI(o,e.usage);return}if(e.kind!==`tool`)return;let s={index:a,toolCallId:e.toolCallId,name:e.toolName,inputSize:zI(e.args),outputSize:e.output.length,isError:e.isError===!0,running:e.running===!0,requestIndex:o.index};n.push(s),o.toolCalls+=1,s.isError&&(o.failedToolCalls+=1);let c=i.get(s.name)??{name:s.name,calls:0,failures:0,inputSize:0,outputSize:0};c.calls+=1,s.isError&&(c.failures+=1),c.inputSize+=s.inputSize,c.outputSize+=s.outputSize,i.set(s.name,c)}),(a.turns>0||a.toolCalls>0)&&r.unshift(a);let s=PI(e),c=t.map(e=>e.usage.cost).filter(e=>e!==void 0),l=n.filter(e=>e.isError).length;return{turns:t,requests:r,toolCalls:n,tools:[...i.values()],totals:s,pricedTurns:c.length,averageTurnCost:c.length===0?0:s.cost/c.length,medianTurnCost:UI(c),totalToolCalls:n.length,failedToolCalls:l,toolCallsPerTurn:t.length===0?0:n.length/t.length}}function GI(e,t){let n=[...e];return t===`input`?n.sort((e,t)=>t.inputSize-e.inputSize):t===`failure`?n.sort((e,t)=>Number(t.isError)-Number(e.isError)||t.outputSize-e.outputSize):n.sort((e,t)=>t.outputSize-e.outputSize)}function KI(e){return e.filter(e=>e.index>=0).sort((e,t)=>t.totalTokens-e.totalTokens||(t.cost??0)-(e.cost??0))}function qI(e){return e<1e3?`${e} B`:e<1e6?`${Math.round(e/1e3)} kB`:`${(e/1e6).toFixed(1)} MB`}var JI=768,YI=26,XI=132,ZI=12,QI=96,$I=124,eL=[{key:`input`,label:`input`,className:`text-emerald-500`,value:e=>e.usage.input},{key:`output`,label:`output`,className:`text-blue-500`,value:e=>e.usage.output},{key:`cacheRead`,label:`cache read`,className:`text-violet-500`,value:e=>e.usage.cacheRead},{key:`cacheWrite`,label:`cache write`,className:`text-amber-500`,value:e=>e.usage.cacheWrite}],tL=[{key:`cost`,label:`cost`,className:`text-rose-500`,value:e=>e.usage.cost??0}];function nL({title:e,children:t}){return(0,A.jsxs)(`section`,{className:`border-t border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:[(0,A.jsx)(`h3`,{className:`mb-2 font-mono text-[11px] uppercase tracking-wide text-zinc-400 dark:text-zinc-500`,children:e}),t]})}function rL({children:e}){return(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:e})}function iL({label:e,value:t,hint:n}){return(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-200 px-2 py-1.5 dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{"aria-label":`${e}: ${t}`,className:`font-mono text-sm text-zinc-700 dark:text-zinc-200`,children:t}),(0,A.jsx)(`div`,{className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:e}),n&&(0,A.jsx)(`div`,{className:`text-[10px] text-zinc-400 dark:text-zinc-500`,children:n})]})}function aL({turns:e,series:t,format:n,onJump:r,describe:i}){let a=Math.max(1,...e.flatMap(e=>t.map(t=>t.value(e)))),o=Math.max(e.length*YI,YI),s=e=>YI/2+e*YI,c=e=>ZI+QI*(1-e/a);return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`mb-1 flex flex-wrap gap-x-3 gap-y-1`,children:t.map(e=>(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-zinc-500 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{className:`inline-block h-0.5 w-3 bg-current ${e.className}`}),e.label]},e.key))}),(0,A.jsxs)(`div`,{className:`flex`,children:[(0,A.jsxs)(`div`,{"aria-hidden":!0,className:`flex w-12 shrink-0 flex-col justify-between py-2 pr-1 text-right font-mono text-[9px] text-zinc-400 dark:text-zinc-600`,style:{height:XI},children:[(0,A.jsx)(`span`,{children:n(a)}),(0,A.jsx)(`span`,{children:`0`})]}),(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,A.jsxs)(`svg`,{width:o,height:XI,role:`group`,"aria-label":`Per-turn chart`,children:[(0,A.jsx)(`line`,{x1:0,x2:o,y1:108,y2:108,stroke:`currentColor`,className:`text-zinc-200 dark:text-zinc-800`}),t.map(t=>(0,A.jsx)(`polyline`,{fill:`none`,stroke:`currentColor`,strokeWidth:1.5,className:t.className,points:e.map((e,n)=>`${s(n)},${c(t.value(e))}`).join(` `)},t.key)),e.map((n,a)=>(0,A.jsxs)(`g`,{children:[t.map(e=>(0,A.jsx)(`circle`,{cx:s(a),cy:c(e.value(n)),r:2,fill:`currentColor`,className:e.className},e.key)),(0,A.jsx)(`rect`,{x:s(a)-YI/2,y:0,width:YI,height:XI,fill:`transparent`,role:`button`,tabIndex:0,"aria-label":`Turn ${n.number}: ${i(n)} — jump to it`,className:`cursor-pointer outline-none focus-visible:fill-zinc-500/10`,onClick:()=>r(n.index),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(n.index))},children:(0,A.jsx)(`title`,{children:`turn ${n.number} · ${i(n)}`})}),(e.length<=12||n.number%5==0)&&(0,A.jsx)(`text`,{x:s(a),y:$I,textAnchor:`middle`,className:`fill-zinc-400 text-[9px] dark:fill-zinc-600`,children:n.number})]},n.index))]})})]})]})}function oL({onJump:e,label:t,children:n}){return(0,A.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,className:`flex w-full items-baseline gap-2 rounded-md px-2 py-1 text-left text-xs hover:bg-zinc-100 dark:hover:bg-zinc-900`,children:n})}function sL({analysis:e,onJump:t,onClose:n}){let[r,i]=(0,d.useState)(`output`),{totals:a}=e;function o(e){t(e),window.innerWidth<JI&&n()}let s=e.turns.length===0&&e.toolCalls.length===0,c=GI(e.toolCalls,r),l=KI(e.requests);return(0,A.jsxs)(`aside`,{"aria-label":`Session analysis`,className:`absolute inset-y-0 right-0 z-10 w-full overflow-y-auto border-l border-zinc-200 bg-white shadow-xl md:w-[26rem] dark:border-zinc-800 dark:bg-zinc-950`,children:[(0,A.jsxs)(`header`,{className:`sticky top-0 flex items-center gap-2 border-b border-zinc-200 bg-white px-4 py-2 dark:border-zinc-800 dark:bg-zinc-950`,children:[(0,A.jsx)(`h2`,{className:`font-mono text-xs text-zinc-600 dark:text-zinc-300`,children:`session analysis`}),(0,A.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close session analysis`,className:`ml-auto rounded-md px-2 py-1 text-sm text-zinc-500 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-900`,children:`×`})]}),s?(0,A.jsx)(`div`,{className:`px-4 py-6`,children:(0,A.jsx)(rL,{children:`Nothing to analyse yet — no turn has reported figures and no tool has been called.`})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nL,{title:`tokens`,children:(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(iL,{label:`total`,value:II(a.totalTokens)}),(0,A.jsx)(iL,{label:`fresh input`,value:II(a.input)}),(0,A.jsx)(iL,{label:`output`,value:II(a.output)}),(0,A.jsx)(iL,{label:`cache read`,value:II(a.cacheRead)}),(0,A.jsx)(iL,{label:`cache write`,value:II(a.cacheWrite)}),(0,A.jsx)(iL,{label:`turns`,value:String(e.turns.length)})]})}),(0,A.jsx)(nL,{title:`cost`,children:e.pricedTurns===0?(0,A.jsx)(rL,{children:`No turn was priced — this provider reports tokens only.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(iL,{label:`total`,value:FI(a.cost)}),(0,A.jsx)(iL,{label:`average turn`,value:FI(e.averageTurnCost)}),(0,A.jsx)(iL,{label:`median turn`,value:FI(e.medianTurnCost)})]}),(0,A.jsxs)(`p`,{className:`mt-1 text-[11px] text-zinc-400 dark:text-zinc-500`,children:[`over `,e.pricedTurns,` priced turn`,e.pricedTurns===1?``:`s`,a.unpriced>0&&`, ${a.unpriced} unpriced`]})]})}),(0,A.jsx)(nL,{title:`tool calls`,children:e.totalToolCalls===0?(0,A.jsx)(rL,{children:`No tool call recorded in this session.`}):(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(iL,{label:`calls`,value:String(e.totalToolCalls)}),(0,A.jsx)(iL,{label:`per turn`,value:e.toolCallsPerTurn.toFixed(1)}),(0,A.jsx)(iL,{label:`failed`,value:String(e.failedToolCalls)})]})}),(0,A.jsx)(nL,{title:`tokens per turn`,children:e.turns.length===0?(0,A.jsx)(rL,{children:`No turn has reported figures yet.`}):(0,A.jsx)(aL,{turns:e.turns,series:eL,format:II,onJump:o,describe:e=>`${II(e.usage.totalTokens)} tokens (input ${e.usage.input}, output ${e.usage.output}, cache read ${e.usage.cacheRead}, cache write ${e.usage.cacheWrite})`})}),(0,A.jsx)(nL,{title:`cost per turn`,children:e.pricedTurns===0?(0,A.jsx)(rL,{children:`No turn was priced, so there is no cost to plot.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(aL,{turns:e.turns.filter(e=>e.usage.cost!==void 0),series:tL,format:FI,onJump:o,describe:e=>FI(e.usage.cost??0)}),a.unpriced>0&&(0,A.jsxs)(`p`,{className:`mt-1 text-[10px] text-zinc-400 dark:text-zinc-500`,children:[a.unpriced,` unpriced turn`,a.unpriced===1?``:`s`,` left out — they carry no price to plot`]})]})}),(0,A.jsx)(nL,{title:`costliest tool calls`,children:c.length===0?(0,A.jsx)(rL,{children:`No tool call recorded in this session.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,A.jsx)(`label`,{htmlFor:`tool-ranking`,className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:`rank by`}),(0,A.jsxs)(`select`,{id:`tool-ranking`,value:r,onChange:e=>i(e.target.value),className:`rounded-md border border-zinc-300 bg-white px-1.5 py-0.5 font-mono text-[11px] text-zinc-600 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300`,children:[(0,A.jsx)(`option`,{value:`output`,children:`output size`}),(0,A.jsx)(`option`,{value:`input`,children:`input size`}),(0,A.jsx)(`option`,{value:`failure`,children:`failure`})]})]}),(0,A.jsx)(`p`,{className:`mb-1 text-[10px] text-zinc-400 dark:text-zinc-500`,children:`measured content size, not tokens — a tool call carries no price`}),c.slice(0,10).map(e=>(0,A.jsxs)(oL,{onJump:()=>o(e.index),label:`Jump to the ${e.name} call, output ${qI(e.outputSize)}`,children:[(0,A.jsx)(`span`,{className:`font-mono text-zinc-600 dark:text-zinc-300`,children:e.name}),e.isError&&(0,A.jsx)(`span`,{className:`text-red-500`,children:`failed`}),e.running&&(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`running`}),(0,A.jsxs)(`span`,{className:`ml-auto font-mono text-zinc-500 dark:text-zinc-400`,children:[`in `,qI(e.inputSize),` · out `,qI(e.outputSize)]})]},e.toolCallId||`${e.index}`))]})}),(0,A.jsx)(nL,{title:`tools`,children:e.tools.length===0?(0,A.jsx)(rL,{children:`No tool has been called yet.`}):(0,A.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,A.jsx)(`thead`,{children:(0,A.jsxs)(`tr`,{className:`text-left text-[10px] uppercase text-zinc-400 dark:text-zinc-500`,children:[(0,A.jsx)(`th`,{className:`font-normal`,children:`tool`}),(0,A.jsx)(`th`,{className:`font-normal`,children:`calls`}),(0,A.jsx)(`th`,{className:`font-normal`,children:`failed`}),(0,A.jsx)(`th`,{className:`text-right font-normal`,children:`in / out`})]})}),(0,A.jsx)(`tbody`,{className:`font-mono text-zinc-600 dark:text-zinc-300`,children:[...e.tools].sort((e,t)=>t.outputSize-e.outputSize).map(e=>(0,A.jsxs)(`tr`,{children:[(0,A.jsx)(`td`,{children:e.name}),(0,A.jsx)(`td`,{children:e.calls}),(0,A.jsx)(`td`,{className:e.failures>0?`text-red-500`:``,children:e.failures}),(0,A.jsxs)(`td`,{className:`text-right`,children:[qI(e.inputSize),` / `,qI(e.outputSize)]})]},e.name))})]})}),(0,A.jsx)(nL,{title:`costliest requests`,children:l.length===0?(0,A.jsx)(rL,{children:`No request has consumed anything yet.`}):l.slice(0,10).map(e=>(0,A.jsxs)(oL,{onJump:()=>o(e.index),label:`Jump to the request "${e.title}"`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-zinc-600 dark:text-zinc-300`,children:e.title}),(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-zinc-500 dark:text-zinc-400`,children:[II(e.totalTokens),` tok`,e.cost!==void 0&&` · ${FI(e.cost)}`]}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[10px] text-zinc-400 dark:text-zinc-500`,children:[e.turns,`t / `,e.toolCalls,`c`,e.failedToolCalls>0&&` · ${e.failedToolCalls}✗`]})]},e.index))})]})]})}var cL=2e3;function lL({items:e,scrollerRef:t,hideTools:n,onShowTools:r,onJump:i}){let[a,o]=(0,d.useState)(null),s=(0,d.useRef)(null),[c,l]=(0,d.useState)(0),u=(0,d.useRef)(null);(0,d.useEffect)(()=>()=>{u.current&&clearTimeout(u.current)},[]);let f=(0,d.useCallback)(t=>{let i=e[t];i&&(i.kind===`tool`&&n&&r(),s.current=t,l(e=>e+1))},[e,n,r]);return(0,d.useEffect)(()=>{let e=s.current;if(e===null)return;s.current=null;let n=t.current?.querySelector(`[data-item-index="${e}"]`);n&&(i(n),n.scrollIntoView?.({behavior:`smooth`,block:`center`}),o(e),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>o(null),cL))},[c,n,t,i]),{jumpToItem:f,highlightIndex:a}}var uL={tools:`pi-outpost:hide-tools`,reasoning:`pi-outpost:hide-reasoning`},dL=[`tools`,`reasoning`],fL={tools:`Tool calls`,reasoning:`Reasoning`};function pL(e){try{return localStorage.getItem(uL[e])===`1`}catch{return!1}}function mL(){return{tools:!pL(`tools`),reasoning:!pL(`reasoning`)}}function hL(e,t){try{localStorage.setItem(uL[e],t?`0`:`1`)}catch{}}function gL(e){return dL.filter(t=>!e[t]).length}function _L(e,t){let n=null;for(let r of e)(r.repo===``||t===r.repo||t.startsWith(`${r.repo}/`))&&(n===null||r.repo.length>n.repo.length)&&(n=r);return n}var vL=/(?:^|\s)@([^\s@]+)/g,yL=new Set([`,`,`.`,`;`,`:`,`!`,`?`,`)`,`]`]);function bL(e){let t=e.length;for(;t>0&&yL.has(e[t-1]);)t--;return e.slice(0,t)}function xL(e){return[...e.matchAll(vL)].map(([,e])=>bL(e??``)).filter(e=>e.length>0)}var SL=`uploads`,CL=class extends Error{reason;constructor(e,t){super(e),this.name=`UploadError`,this.reason=t}};function wL(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result.split(`,`,2)[1]??``),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function TL(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function EL(e){return e.type.startsWith(`image/`)?`image`:e.type===`application/pdf`||O(e.name)||k(e.name)?`extraction-tool`:e.size<=524288?`inline-text`:kL(e)&&e.size<=26214400?`extraction-tool`:`unsupported`}function DL(e){let t=EL(e);return t===`extraction-tool`||t===`image`&&e.size>7340032}var OL=new Set([`application/json`,`application/xml`,`application/javascript`,`application/x-yaml`,`application/yaml`,`application/sql`]);function kL(e){return e.type.startsWith(`text/`)||OL.has(e.type)}function AL(e){return kL(e)?`${e.name}: file too large to upload (max 25 MB)`:`${e.name}: unsupported file type${e.type?` (${e.type})`:``}`}function jL(e,t){return t instanceof CL?t.reason===`denied`?`${e.name}: cannot upload — the workspace is read-only`:t.reason===`too-large`?`${e.name}: file too large to upload (max 25 MB)`:t.reason===`invalid`?`${e.name}: ${t.message}`:`${e.name}: upload failed — ${t.message}`:`${e.name}: upload failed`}async function ML(e){let t;try{t=await e.text()}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}return t.includes(`\0`)?{attachments:[],errors:[`${e.name}: unsupported binary file`]}:{attachments:[{name:e.name,kind:`text`,data:t,mimeType:e.type||`text/plain`,source:`manual`}],errors:[]}}async function NL(e){try{let t=await wL(e);return{attachments:[{name:e.name,kind:`image`,data:t,mimeType:e.type,source:`manual`}],errors:[]}}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}}async function PL(e,t){if(e.size>26214400)return{attachments:[],errors:[`${e.name}: file too large to upload (max 25 MB)`]};let n;try{n=await wL(e)}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}try{return{attachments:[HL(await t(e.name,n))],errors:[]}}catch(t){return{attachments:[],errors:[jL(e,t)]}}}async function FL(e,t){let n=await Promise.all([...e].map(e=>{let n=EL(e);return n===`unsupported`?Promise.resolve({attachments:[],errors:[AL(e)]}):n===`inline-text`?ML(e):n===`image`&&e.size<=7340032?NL(e):PL(e,t)}));return{attachments:n.flatMap(e=>e.attachments),errors:n.flatMap(e=>e.errors)}}function IL(e){return{...HL(e),source:`preview`,previewPath:e}}function LL(e){return IL(e)}function RL(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|\\s)@${n}[,.;:!?)\\]]*(\\s|$)`).test(e)}var zL=xL;function BL(e,t){let n=e.trim(),r=e=>{n+=`${n?`
328
+ `)){let e=mI.exec(r);if(e===null)continue;let[,i,a,o]=e;if(i===``)continue;let s=n.get(i);s===void 0&&(s={path:i,hits:[]},n.set(i,s),t.push(s)),s.hits.push({line:Number(a),text:o})}return t}function gI(e){return e.reduce((e,t)=>e+t.hits.length,0)}var _I=8,vI=5;function yI({item:e,dispatch:t}){let n=hI(e.output??``),[r,i]=(0,d.useState)(!1);if(n.length===0)return(0,A.jsx)(XF,{item:e});let a=r?n:n.slice(0,_I);return(0,A.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,A.jsxs)(`div`,{className:`text-xs text-zinc-500`,children:[gI(n),` match`,gI(n)===1?``:`es`,` in `,n.length,` file`,n.length===1?``:`s`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`flex flex-col`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({kind:`openFile`,path:e.path}),className:`flex items-center gap-2 truncate text-left font-mono text-xs text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100`,children:[(0,A.jsx)(`span`,{className:`truncate`,children:e.path}),(0,A.jsx)(`span`,{className:`shrink-0 text-zinc-400 dark:text-zinc-600`,children:e.hits.length})]}),(0,A.jsxs)(`div`,{className:`overflow-x-auto rounded border border-zinc-200 font-mono text-xs dark:border-zinc-800`,children:[e.hits.slice(0,vI).map((e,t)=>(0,A.jsxs)(`div`,{className:`flex gap-2 px-2`,children:[(0,A.jsx)(`span`,{className:`shrink-0 select-none text-zinc-400 dark:text-zinc-600`,children:e.line}),(0,A.jsx)(`span`,{className:`whitespace-pre text-zinc-700 dark:text-zinc-300`,children:e.text})]},t)),e.hits.length>vI&&(0,A.jsxs)(`div`,{className:`px-2 text-zinc-400 dark:text-zinc-600`,children:[`+`,e.hits.length-vI,` more in this file`]})]})]},e.path)),!r&&n.length>_I&&(0,A.jsxs)(`button`,{type:`button`,onClick:()=>i(!0),className:`self-start text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300`,children:[`show `,n.length-_I,` more file`,n.length-_I===1?``:`s`]})]})}var bI=[QF,$F,Bf,tI,rI,pI,{id:`code-search`,match:e=>e.toolName===`grep`,stable:!0,showsRawReveal:!0,Expanded:yI},iI,aI,ZF];function xI(e){for(let t of bI){let n=!1;try{n=t.match(e)}catch{n=!1}if(n)return t}return ZF}function SI(e,t){let n=xI(e);if(t===void 0||t===n.id)return n;let r=bI.find(e=>e.id===t);if(r===void 0||r.id===ZF.id||n.extensionOwned===!0)return n;let i=!1;try{i=r.match(e)}catch{i=!1}return i?r:n}function CI(e){if(typeof e!=`object`||!e)return``;let t=e,n=[`command`,`path`,`file_path`,`pattern`,`query`].find(e=>typeof t[e]==`string`);if(n)return t[n];let r=JSON.stringify(t);return r===`{}`?``:r}function wI({item:e,dispatch:t=WF}){let n=(0,d.useRef)(void 0),r=SI(e,n.current);n.current=r.id;let i=r.startsExpanded===!0,[a,o]=(0,d.useState)(i);(0,d.useEffect)(()=>{o(i)},[i]);let[s,c]=(0,d.useState)(!1),l=(0,d.useRef)(null),u=r.compactHeader?void 0:e.callHtml,f=r.compactHeader?``:CI(e.args),p=r.Collapsed,m=!a&&p!==void 0&&(r.hasCollapsed?.(e)??!0);return(0,A.jsxs)(`div`,{className:`rounded-lg border text-sm ${e.isError?`border-red-300 bg-red-50 dark:border-red-900/60 dark:bg-red-950/20`:`border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900/60`}`,children:[(0,A.jsxs)(`div`,{onMouseDown:e=>{l.current={x:e.clientX,y:e.clientY}},onClick:e=>{let t=l.current;l.current=null,!(e.detail>0&&t&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)&&o(!a)},className:`flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left`,children:[(0,A.jsxs)(`button`,{type:`button`,"aria-expanded":a,"aria-label":u?e.toolName:void 0,className:`flex shrink-0 items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full ${e.running?`animate-pulse motion-reduce:animate-none bg-amber-400`:e.isError?`bg-red-500`:`bg-emerald-500`}`}),!u&&(0,A.jsx)(`span`,{className:`font-mono font-medium text-zinc-700 dark:text-zinc-300`,children:e.toolName})]}),u?(0,A.jsx)(Ge,{as:`span`,html:u,className:`min-w-0 flex-1 text-zinc-700 dark:text-zinc-300`}):f&&(0,A.jsx)(`span`,{className:`min-w-0 overflow-x-auto whitespace-nowrap font-mono text-xs text-zinc-500 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden`,children:f}),(0,A.jsx)(`span`,{className:`ml-auto text-xs text-zinc-400 dark:text-zinc-600`,children:a?`▾`:`▸`})]}),e.running&&e.progress!=null&&(0,A.jsx)(`div`,{className:`border-t border-zinc-200 px-3 py-1.5 dark:border-zinc-800`,children:(0,A.jsx)(`progress`,{value:e.progress,max:1,"aria-label":`${e.toolName} progress`,className:`h-1.5 w-full appearance-none overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800 [&::-moz-progress-bar]:bg-emerald-500 [&::-webkit-progress-bar]:bg-transparent [&::-webkit-progress-value]:rounded-full [&::-webkit-progress-value]:bg-emerald-500`})}),m&&p!==void 0&&(0,A.jsx)(`div`,{className:`border-t border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:(0,A.jsx)(p,{item:e,dispatch:t})}),a&&(0,A.jsxs)(`div`,{className:`border-t border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(r.Expanded,{item:e,dispatch:t}),r.showsRawReveal===!0&&(0,A.jsxs)(`div`,{className:`mt-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>c(!s),className:`text-xs text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-400`,children:s?`hide raw output`:`raw output`}),s&&(0,A.jsx)(`div`,{className:`mt-1`,children:(0,A.jsx)(XF,{item:e})})]})]})]})}function TI({item:e}){let[t,n]=(0,d.useState)(!1),r=e.details!==void 0,i=!!e.contentHtml,a=e.contentHtmlCollapsed??e.contentHtml,o=r||i&&!!e.contentHtmlCollapsed;return(0,A.jsxs)(`div`,{className:`rounded-lg border border-violet-200 bg-violet-50 px-3 py-2 text-sm dark:border-violet-900/60 dark:bg-violet-950/30`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-xs font-bold text-violet-700 dark:text-violet-300`,children:[`[`,e.customType,`]`]}),o&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>n(!t),title:`Show details`,className:`ml-auto text-xs text-violet-500 hover:text-violet-700 dark:text-violet-500 dark:hover:text-violet-300`,children:t?`▾`:`▸`})]}),i&&a?(0,A.jsx)(Ge,{html:t||!e.contentHtmlCollapsed?e.contentHtml??a:a,className:`mt-1 text-violet-950 dark:text-violet-100`}):(0,A.jsx)(`div`,{className:`prose-chat mt-1 text-violet-950 dark:text-violet-100`,children:(0,A.jsx)(Py,{remarkPlugins:[xF,NF],rehypePlugins:[eD],children:E(e.text)})}),t&&r&&(0,A.jsx)(`pre`,{className:`mt-2 max-h-96 overflow-auto border-t border-violet-200 pt-2 font-mono text-xs text-violet-600 dark:border-violet-900/60 dark:text-violet-400`,children:JSON.stringify(e.details,null,2)})]})}var EI=`pi-outpost:update-notice-dismissed`;function DI(){try{return window.localStorage.getItem(EI)}catch{return null}}function OI({notice:e}){let[t,n]=(0,d.useState)(()=>DI());return t===e.latest?null:(0,A.jsxs)(`div`,{role:`status`,"data-testid":`update-notice`,className:`flex items-center gap-2 border-b border-sky-200 bg-sky-50 px-4 py-1.5 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,children:[(0,A.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[`pi-outpost `,e.latest,` is available (you have `,e.running,`). `,e.instruction,` `,(0,A.jsx)(`a`,{href:e.releaseNotes,target:`_blank`,rel:`noreferrer`,className:`font-medium underline underline-offset-2`,children:`What's new`})]}),(0,A.jsx)(`code`,{className:`shrink-0 rounded bg-white/70 px-1.5 py-0.5 font-mono dark:bg-sky-900/40`,children:e.copy}),(0,A.jsx)(le,{text:e.copy}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Dismiss the update notice`,onClick:()=>{try{window.localStorage.setItem(EI,e.latest)}catch{}n(e.latest)},className:`shrink-0 rounded px-1.5 text-sky-700 hover:bg-sky-100 dark:text-sky-300 dark:hover:bg-sky-900/50`,children:`×`})]})}var kI=`pi-outpost:changes-notice-dismissed`;function AI(){try{return window.localStorage.getItem(kI)}catch{return null}}function jI(e){return(0,A.jsx)(`a`,{...e,target:`_blank`,rel:`noreferrer`})}function MI({changes:e}){let[t,n]=(0,d.useState)(()=>AI()),[r,i]=(0,d.useState)(!1);if(t===e.to)return null;let a=e.entries.length>0;return(0,A.jsxs)(`div`,{role:`status`,"data-testid":`changes-notice`,className:`border-b border-zinc-200 bg-zinc-50 text-xs text-zinc-700 dark:border-zinc-800 dark:bg-zinc-900/60 dark:text-zinc-300`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-1.5`,children:[(0,A.jsx)(`span`,{className:`shrink-0 rounded-full bg-sky-100 px-1.5 font-medium leading-4 text-sky-800 dark:bg-sky-900/50 dark:text-sky-200`,children:`New`}),(0,A.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[`pi-outpost was updated to `,e.to,` (from `,e.from,`).`]}),a?(0,A.jsx)(`button`,{type:`button`,"aria-expanded":r,onClick:()=>i(!r),className:`shrink-0 rounded px-1.5 font-medium text-zinc-900 underline-offset-2 hover:underline dark:text-zinc-100`,children:r?`Hide what changed`:`What's changed`}):(0,A.jsx)(jI,{href:e.releaseNotes,className:`shrink-0 font-medium text-zinc-900 underline-offset-2 hover:underline dark:text-zinc-100`,children:`Release notes`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Dismiss the update news`,onClick:()=>{try{window.localStorage.setItem(kI,e.to)}catch{}n(e.to)},className:`shrink-0 rounded px-1.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-zinc-100`,children:`×`})]}),r&&a&&(0,A.jsx)(`div`,{"data-testid":`changes-notice-body`,className:`max-h-[50vh] overflow-y-auto border-t border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:(0,A.jsxs)(`div`,{className:`mx-auto max-w-3xl`,children:[e.entries.map(e=>(0,A.jsxs)(`section`,{className:`mb-4`,children:[(0,A.jsxs)(`h2`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[e.version,e.date&&(0,A.jsx)(`span`,{className:`ml-2 font-normal text-zinc-500 dark:text-zinc-400`,children:e.date})]}),(0,A.jsx)(`div`,{className:`prose-chat text-zinc-800 dark:text-zinc-200`,children:(0,A.jsx)(Py,{remarkPlugins:[xF],components:{a:jI},children:e.markdown})})]},e.version)),(0,A.jsx)(jI,{href:e.releaseNotes,className:`font-medium text-zinc-900 underline-offset-2 hover:underline dark:text-zinc-100`,children:`Release notes on GitHub`})]})})]})}function NI(e){return e.id??e.root}function PI(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(e)}function FI({item:e}){let[t,n]=(0,d.useState)(!1),r=e.tokensBefore?`Conversation compacted here — ${PI(e.tokensBefore)} tokens summarised`:`Conversation compacted here`;return(0,A.jsxs)(`div`,{className:`my-1`,"data-compaction-boundary":!0,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`h-px flex-1 bg-amber-300 dark:bg-amber-900`}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>n(!t),"aria-expanded":t,className:`rounded-full border border-amber-300 bg-amber-50 px-2 py-0.5 text-xs text-amber-800 hover:bg-amber-100 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-300 dark:hover:bg-amber-950/70`,children:[r,` `,t?`▾`:`▸`]}),(0,A.jsx)(`span`,{className:`h-px flex-1 bg-amber-300 dark:bg-amber-900`})]}),t&&(0,A.jsxs)(`div`,{className:`mt-2 whitespace-pre-wrap rounded-lg border border-amber-200 bg-amber-50/60 px-3 py-2 text-sm text-zinc-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-zinc-300`,children:[(0,A.jsx)(`p`,{className:`mb-1 text-xs font-medium text-amber-800 dark:text-amber-300`,children:`What the agent kept of everything above:`}),e.summary||`(the runtime recorded no summary)`]})]})}function II({older:e,onLoad:t}){if(e.remaining<=0&&!e.error)return null;let n=e.remaining,r=e.loading?`Loading earlier messages…`:`Load ${n} earlier message${n===1?``:`s`}`;return(0,A.jsxs)(`div`,{className:`flex flex-col items-center gap-1 pb-2`,"data-older-messages":!0,children:[(0,A.jsx)(`button`,{type:`button`,onClick:t,disabled:e.loading,"aria-busy":e.loading,"aria-label":e.loading?`Loading earlier messages`:`Load ${n} earlier messages`,className:`rounded-full border border-zinc-300 bg-white px-3 py-1 text-xs text-zinc-600 hover:bg-zinc-50 disabled:cursor-progress disabled:opacity-60 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:r}),e.error&&(0,A.jsxs)(`p`,{role:`status`,className:`text-xs text-red-600 dark:text-red-400`,children:[e.error,` — try again`]})]})}var LI={cost:0,unpriced:0,turns:0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0};function RI(e){let t={...LI};for(let n of e){if(n.kind!==`assistant`||!n.usage)continue;let e=n.usage;t.turns+=1,t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.totalTokens+=e.totalTokens,e.cost===void 0?t.unpriced+=1:t.cost+=e.cost}return t}function zI(e){let t=e>0&&e<.01?4:2;return`$${e.toFixed(t)}`}function BI(e){return e<1e3?String(e):e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1)}M`}var VI=80,HI=new WeakMap;function UI(e){let t=typeof e==`object`&&!!e;if(t){let t=HI.get(e);if(t!==void 0)return t}let n=0;try{n=JSON.stringify(e)?.length??0}catch{n=0}return t&&HI.set(e,n),n}function WI(e){let t=e.replace(/\s+/g,` `).trim();return t.length>VI?`${t.slice(0,79)}…`:t}function GI(e,t){return{index:e,title:t,turns:0,toolCalls:0,failedToolCalls:0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,unpriced:0}}function KI(e,t){e.turns+=1,e.input+=t.input,e.output+=t.output,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.totalTokens+=t.totalTokens,t.cost===void 0?e.unpriced+=1:e.cost=(e.cost??0)+t.cost}function qI(e){if(e.length===0)return 0;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==1?t[n]:(t[n-1]+t[n])/2}function JI(e){let t=[],n=[],r=[],i=new Map,a=GI(-1,``),o=a;e.forEach((e,a)=>{if(e.kind===`user`){o=GI(a,WI(e.text)),r.push(o);return}if(e.kind===`assistant`){if(!e.usage)return;t.push({index:a,number:t.length+1,requestIndex:o.index,usage:e.usage}),KI(o,e.usage);return}if(e.kind!==`tool`)return;let s={index:a,toolCallId:e.toolCallId,name:e.toolName,inputSize:UI(e.args),outputSize:e.output.length,isError:e.isError===!0,running:e.running===!0,requestIndex:o.index};n.push(s),o.toolCalls+=1,s.isError&&(o.failedToolCalls+=1);let c=i.get(s.name)??{name:s.name,calls:0,failures:0,inputSize:0,outputSize:0};c.calls+=1,s.isError&&(c.failures+=1),c.inputSize+=s.inputSize,c.outputSize+=s.outputSize,i.set(s.name,c)}),(a.turns>0||a.toolCalls>0)&&r.unshift(a);let s=RI(e),c=t.map(e=>e.usage.cost).filter(e=>e!==void 0),l=n.filter(e=>e.isError).length;return{turns:t,requests:r,toolCalls:n,tools:[...i.values()],totals:s,pricedTurns:c.length,averageTurnCost:c.length===0?0:s.cost/c.length,medianTurnCost:qI(c),totalToolCalls:n.length,failedToolCalls:l,toolCallsPerTurn:t.length===0?0:n.length/t.length}}function YI(e,t){let n=[...e];return t===`input`?n.sort((e,t)=>t.inputSize-e.inputSize):t===`failure`?n.sort((e,t)=>Number(t.isError)-Number(e.isError)||t.outputSize-e.outputSize):n.sort((e,t)=>t.outputSize-e.outputSize)}function XI(e){return e.filter(e=>e.index>=0).sort((e,t)=>t.totalTokens-e.totalTokens||(t.cost??0)-(e.cost??0))}function ZI(e){return e<1e3?`${e} B`:e<1e6?`${Math.round(e/1e3)} kB`:`${(e/1e6).toFixed(1)} MB`}var QI=768,$I=26,eL=132,tL=12,nL=96,rL=124,iL=[{key:`input`,label:`input`,className:`text-emerald-500`,value:e=>e.usage.input},{key:`output`,label:`output`,className:`text-blue-500`,value:e=>e.usage.output},{key:`cacheRead`,label:`cache read`,className:`text-violet-500`,value:e=>e.usage.cacheRead},{key:`cacheWrite`,label:`cache write`,className:`text-amber-500`,value:e=>e.usage.cacheWrite}],aL=[{key:`cost`,label:`cost`,className:`text-rose-500`,value:e=>e.usage.cost??0}];function oL({title:e,children:t}){return(0,A.jsxs)(`section`,{className:`border-t border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:[(0,A.jsx)(`h3`,{className:`mb-2 font-mono text-[11px] uppercase tracking-wide text-zinc-400 dark:text-zinc-500`,children:e}),t]})}function sL({children:e}){return(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:e})}function cL({label:e,value:t,hint:n}){return(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-200 px-2 py-1.5 dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{"aria-label":`${e}: ${t}`,className:`font-mono text-sm text-zinc-700 dark:text-zinc-200`,children:t}),(0,A.jsx)(`div`,{className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:e}),n&&(0,A.jsx)(`div`,{className:`text-[10px] text-zinc-400 dark:text-zinc-500`,children:n})]})}function lL({turns:e,series:t,format:n,onJump:r,describe:i}){let a=Math.max(1,...e.flatMap(e=>t.map(t=>t.value(e)))),o=Math.max(e.length*$I,$I),s=e=>$I/2+e*$I,c=e=>tL+nL*(1-e/a);return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`mb-1 flex flex-wrap gap-x-3 gap-y-1`,children:t.map(e=>(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-zinc-500 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{className:`inline-block h-0.5 w-3 bg-current ${e.className}`}),e.label]},e.key))}),(0,A.jsxs)(`div`,{className:`flex`,children:[(0,A.jsxs)(`div`,{"aria-hidden":!0,className:`flex w-12 shrink-0 flex-col justify-between py-2 pr-1 text-right font-mono text-[9px] text-zinc-400 dark:text-zinc-600`,style:{height:eL},children:[(0,A.jsx)(`span`,{children:n(a)}),(0,A.jsx)(`span`,{children:`0`})]}),(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,A.jsxs)(`svg`,{width:o,height:eL,role:`group`,"aria-label":`Per-turn chart`,children:[(0,A.jsx)(`line`,{x1:0,x2:o,y1:108,y2:108,stroke:`currentColor`,className:`text-zinc-200 dark:text-zinc-800`}),t.map(t=>(0,A.jsx)(`polyline`,{fill:`none`,stroke:`currentColor`,strokeWidth:1.5,className:t.className,points:e.map((e,n)=>`${s(n)},${c(t.value(e))}`).join(` `)},t.key)),e.map((n,a)=>(0,A.jsxs)(`g`,{children:[t.map(e=>(0,A.jsx)(`circle`,{cx:s(a),cy:c(e.value(n)),r:2,fill:`currentColor`,className:e.className},e.key)),(0,A.jsx)(`rect`,{x:s(a)-$I/2,y:0,width:$I,height:eL,fill:`transparent`,role:`button`,tabIndex:0,"aria-label":`Turn ${n.number}: ${i(n)} — jump to it`,className:`cursor-pointer outline-none focus-visible:fill-zinc-500/10`,onClick:()=>r(n.index),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(n.index))},children:(0,A.jsx)(`title`,{children:`turn ${n.number} · ${i(n)}`})}),(e.length<=12||n.number%5==0)&&(0,A.jsx)(`text`,{x:s(a),y:rL,textAnchor:`middle`,className:`fill-zinc-400 text-[9px] dark:fill-zinc-600`,children:n.number})]},n.index))]})})]})]})}function uL({onJump:e,label:t,children:n}){return(0,A.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,className:`flex w-full items-baseline gap-2 rounded-md px-2 py-1 text-left text-xs hover:bg-zinc-100 dark:hover:bg-zinc-900`,children:n})}function dL({analysis:e,onJump:t,onClose:n}){let[r,i]=(0,d.useState)(`output`),{totals:a}=e;function o(e){t(e),window.innerWidth<QI&&n()}let s=e.turns.length===0&&e.toolCalls.length===0,c=YI(e.toolCalls,r),l=XI(e.requests);return(0,A.jsxs)(`aside`,{"aria-label":`Session analysis`,className:`absolute inset-y-0 right-0 z-10 w-full overflow-y-auto border-l border-zinc-200 bg-white shadow-xl md:w-[26rem] dark:border-zinc-800 dark:bg-zinc-950`,children:[(0,A.jsxs)(`header`,{className:`sticky top-0 flex items-center gap-2 border-b border-zinc-200 bg-white px-4 py-2 dark:border-zinc-800 dark:bg-zinc-950`,children:[(0,A.jsx)(`h2`,{className:`font-mono text-xs text-zinc-600 dark:text-zinc-300`,children:`session analysis`}),(0,A.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close session analysis`,className:`ml-auto rounded-md px-2 py-1 text-sm text-zinc-500 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-900`,children:`×`})]}),s?(0,A.jsx)(`div`,{className:`px-4 py-6`,children:(0,A.jsx)(sL,{children:`Nothing to analyse yet — no turn has reported figures and no tool has been called.`})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(oL,{title:`tokens`,children:(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(cL,{label:`total`,value:BI(a.totalTokens)}),(0,A.jsx)(cL,{label:`fresh input`,value:BI(a.input)}),(0,A.jsx)(cL,{label:`output`,value:BI(a.output)}),(0,A.jsx)(cL,{label:`cache read`,value:BI(a.cacheRead)}),(0,A.jsx)(cL,{label:`cache write`,value:BI(a.cacheWrite)}),(0,A.jsx)(cL,{label:`turns`,value:String(e.turns.length)})]})}),(0,A.jsx)(oL,{title:`cost`,children:e.pricedTurns===0?(0,A.jsx)(sL,{children:`No turn was priced — this provider reports tokens only.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(cL,{label:`total`,value:zI(a.cost)}),(0,A.jsx)(cL,{label:`average turn`,value:zI(e.averageTurnCost)}),(0,A.jsx)(cL,{label:`median turn`,value:zI(e.medianTurnCost)})]}),(0,A.jsxs)(`p`,{className:`mt-1 text-[11px] text-zinc-400 dark:text-zinc-500`,children:[`over `,e.pricedTurns,` priced turn`,e.pricedTurns===1?``:`s`,a.unpriced>0&&`, ${a.unpriced} unpriced`]})]})}),(0,A.jsx)(oL,{title:`tool calls`,children:e.totalToolCalls===0?(0,A.jsx)(sL,{children:`No tool call recorded in this session.`}):(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-2`,children:[(0,A.jsx)(cL,{label:`calls`,value:String(e.totalToolCalls)}),(0,A.jsx)(cL,{label:`per turn`,value:e.toolCallsPerTurn.toFixed(1)}),(0,A.jsx)(cL,{label:`failed`,value:String(e.failedToolCalls)})]})}),(0,A.jsx)(oL,{title:`tokens per turn`,children:e.turns.length===0?(0,A.jsx)(sL,{children:`No turn has reported figures yet.`}):(0,A.jsx)(lL,{turns:e.turns,series:iL,format:BI,onJump:o,describe:e=>`${BI(e.usage.totalTokens)} tokens (input ${e.usage.input}, output ${e.usage.output}, cache read ${e.usage.cacheRead}, cache write ${e.usage.cacheWrite})`})}),(0,A.jsx)(oL,{title:`cost per turn`,children:e.pricedTurns===0?(0,A.jsx)(sL,{children:`No turn was priced, so there is no cost to plot.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(lL,{turns:e.turns.filter(e=>e.usage.cost!==void 0),series:aL,format:zI,onJump:o,describe:e=>zI(e.usage.cost??0)}),a.unpriced>0&&(0,A.jsxs)(`p`,{className:`mt-1 text-[10px] text-zinc-400 dark:text-zinc-500`,children:[a.unpriced,` unpriced turn`,a.unpriced===1?``:`s`,` left out — they carry no price to plot`]})]})}),(0,A.jsx)(oL,{title:`costliest tool calls`,children:c.length===0?(0,A.jsx)(sL,{children:`No tool call recorded in this session.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,A.jsx)(`label`,{htmlFor:`tool-ranking`,className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:`rank by`}),(0,A.jsxs)(`select`,{id:`tool-ranking`,value:r,onChange:e=>i(e.target.value),className:`rounded-md border border-zinc-300 bg-white px-1.5 py-0.5 font-mono text-[11px] text-zinc-600 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300`,children:[(0,A.jsx)(`option`,{value:`output`,children:`output size`}),(0,A.jsx)(`option`,{value:`input`,children:`input size`}),(0,A.jsx)(`option`,{value:`failure`,children:`failure`})]})]}),(0,A.jsx)(`p`,{className:`mb-1 text-[10px] text-zinc-400 dark:text-zinc-500`,children:`measured content size, not tokens — a tool call carries no price`}),c.slice(0,10).map(e=>(0,A.jsxs)(uL,{onJump:()=>o(e.index),label:`Jump to the ${e.name} call, output ${ZI(e.outputSize)}`,children:[(0,A.jsx)(`span`,{className:`font-mono text-zinc-600 dark:text-zinc-300`,children:e.name}),e.isError&&(0,A.jsx)(`span`,{className:`text-red-500`,children:`failed`}),e.running&&(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`running`}),(0,A.jsxs)(`span`,{className:`ml-auto font-mono text-zinc-500 dark:text-zinc-400`,children:[`in `,ZI(e.inputSize),` · out `,ZI(e.outputSize)]})]},e.toolCallId||`${e.index}`))]})}),(0,A.jsx)(oL,{title:`tools`,children:e.tools.length===0?(0,A.jsx)(sL,{children:`No tool has been called yet.`}):(0,A.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,A.jsx)(`thead`,{children:(0,A.jsxs)(`tr`,{className:`text-left text-[10px] uppercase text-zinc-400 dark:text-zinc-500`,children:[(0,A.jsx)(`th`,{className:`font-normal`,children:`tool`}),(0,A.jsx)(`th`,{className:`font-normal`,children:`calls`}),(0,A.jsx)(`th`,{className:`font-normal`,children:`failed`}),(0,A.jsx)(`th`,{className:`text-right font-normal`,children:`in / out`})]})}),(0,A.jsx)(`tbody`,{className:`font-mono text-zinc-600 dark:text-zinc-300`,children:[...e.tools].sort((e,t)=>t.outputSize-e.outputSize).map(e=>(0,A.jsxs)(`tr`,{children:[(0,A.jsx)(`td`,{children:e.name}),(0,A.jsx)(`td`,{children:e.calls}),(0,A.jsx)(`td`,{className:e.failures>0?`text-red-500`:``,children:e.failures}),(0,A.jsxs)(`td`,{className:`text-right`,children:[ZI(e.inputSize),` / `,ZI(e.outputSize)]})]},e.name))})]})}),(0,A.jsx)(oL,{title:`costliest requests`,children:l.length===0?(0,A.jsx)(sL,{children:`No request has consumed anything yet.`}):l.slice(0,10).map(e=>(0,A.jsxs)(uL,{onJump:()=>o(e.index),label:`Jump to the request "${e.title}"`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-zinc-600 dark:text-zinc-300`,children:e.title}),(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-zinc-500 dark:text-zinc-400`,children:[BI(e.totalTokens),` tok`,e.cost!==void 0&&` · ${zI(e.cost)}`]}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[10px] text-zinc-400 dark:text-zinc-500`,children:[e.turns,`t / `,e.toolCalls,`c`,e.failedToolCalls>0&&` · ${e.failedToolCalls}✗`]})]},e.index))})]})]})}var fL=2e3;function pL({items:e,scrollerRef:t,hideTools:n,onShowTools:r,onJump:i}){let[a,o]=(0,d.useState)(null),s=(0,d.useRef)(null),[c,l]=(0,d.useState)(0),u=(0,d.useRef)(null);(0,d.useEffect)(()=>()=>{u.current&&clearTimeout(u.current)},[]);let f=(0,d.useCallback)(t=>{let i=e[t];i&&(i.kind===`tool`&&n&&r(),s.current=t,l(e=>e+1))},[e,n,r]);return(0,d.useEffect)(()=>{let e=s.current;if(e===null)return;s.current=null;let n=t.current?.querySelector(`[data-item-index="${e}"]`);n&&(i(n),n.scrollIntoView?.({behavior:`smooth`,block:`center`}),o(e),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>o(null),fL))},[c,n,t,i]),{jumpToItem:f,highlightIndex:a}}var mL={tools:`pi-outpost:hide-tools`,reasoning:`pi-outpost:hide-reasoning`},hL=[`tools`,`reasoning`],gL={tools:`Tool calls`,reasoning:`Reasoning`};function _L(e){try{return localStorage.getItem(mL[e])===`1`}catch{return!1}}function vL(){return{tools:!_L(`tools`),reasoning:!_L(`reasoning`)}}function yL(e,t){try{localStorage.setItem(mL[e],t?`0`:`1`)}catch{}}function bL(e){return hL.filter(t=>!e[t]).length}function xL(e,t){let n=null;for(let r of e)(r.repo===``||t===r.repo||t.startsWith(`${r.repo}/`))&&(n===null||r.repo.length>n.repo.length)&&(n=r);return n}var SL=/(?:^|\s)@([^\s@]+)/g,CL=new Set([`,`,`.`,`;`,`:`,`!`,`?`,`)`,`]`]);function wL(e){let t=e.length;for(;t>0&&CL.has(e[t-1]);)t--;return e.slice(0,t)}function TL(e){return[...e.matchAll(SL)].map(([,e])=>wL(e??``)).filter(e=>e.length>0)}var EL=`uploads`,DL=class extends Error{reason;constructor(e,t){super(e),this.name=`UploadError`,this.reason=t}};function OL(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result.split(`,`,2)[1]??``),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function kL(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function AL(e){return e.type.startsWith(`image/`)?`image`:e.type===`application/pdf`||O(e.name)||k(e.name)?`extraction-tool`:e.size<=524288?`inline-text`:NL(e)&&e.size<=26214400?`extraction-tool`:`unsupported`}function jL(e){let t=AL(e);return t===`extraction-tool`||t===`image`&&e.size>7340032}var ML=new Set([`application/json`,`application/xml`,`application/javascript`,`application/x-yaml`,`application/yaml`,`application/sql`]);function NL(e){return e.type.startsWith(`text/`)||ML.has(e.type)}function PL(e){return NL(e)?`${e.name}: file too large to upload (max 25 MB)`:`${e.name}: unsupported file type${e.type?` (${e.type})`:``}`}function FL(e,t){return t instanceof DL?t.reason===`denied`?`${e.name}: cannot upload — the workspace is read-only`:t.reason===`too-large`?`${e.name}: file too large to upload (max 25 MB)`:t.reason===`invalid`?`${e.name}: ${t.message}`:`${e.name}: upload failed — ${t.message}`:`${e.name}: upload failed`}async function IL(e){let t;try{t=await e.text()}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}return t.includes(`\0`)?{attachments:[],errors:[`${e.name}: unsupported binary file`]}:{attachments:[{name:e.name,kind:`text`,data:t,mimeType:e.type||`text/plain`,source:`manual`}],errors:[]}}async function LL(e){try{let t=await OL(e);return{attachments:[{name:e.name,kind:`image`,data:t,mimeType:e.type,source:`manual`}],errors:[]}}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}}async function RL(e,t){if(e.size>26214400)return{attachments:[],errors:[`${e.name}: file too large to upload (max 25 MB)`]};let n;try{n=await OL(e)}catch{return{attachments:[],errors:[`${e.name}: could not be read`]}}try{return{attachments:[KL(await t(e.name,n))],errors:[]}}catch(t){return{attachments:[],errors:[FL(e,t)]}}}async function zL(e,t){let n=await Promise.all([...e].map(e=>{let n=AL(e);return n===`unsupported`?Promise.resolve({attachments:[],errors:[PL(e)]}):n===`inline-text`?IL(e):n===`image`&&e.size<=7340032?LL(e):RL(e,t)}));return{attachments:n.flatMap(e=>e.attachments),errors:n.flatMap(e=>e.errors)}}function BL(e){return{...KL(e),source:`preview`,previewPath:e}}function VL(e){return BL(e)}function HL(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|\\s)@${n}[,.;:!?)\\]]*(\\s|$)`).test(e)}var UL=TL;function WL(e,t){let n=e.trim(),r=e=>{n+=`${n?`
329
329
 
330
- `:``}${e}`};for(let e of t)e.kind===`path`?RL(n,e.data)||r(`@${e.data}`):e.kind===`text`&&r(`\`\`\`${e.name}\n${e.data}\n\`\`\``);return n}async function VL(e,t){try{let n=await fetch(t);if(!n.ok)return`${e}: unable to read preview image for attachment`;let r=n.headers.get(`Content-Type`)?.split(`;`,1)[0]??``;if(!r.startsWith(`image/`))return`${e}: preview is not a supported image attachment`;let i=new Uint8Array(await n.arrayBuffer());return i.byteLength>7340032?`${e}: image too large (max 7 MB)`:{name:e,kind:`image`,data:TL(i),mimeType:r,source:`preview`,previewPath:e}}catch{return`${e}: unable to read preview image for attachment`}}function HL(e){return{name:e,kind:`path`,data:e,mimeType:`text/plain`,source:`manual`}}function UL(e,t){return e.some(e=>e.kind===`path`&&e.data===t)?e:[...e,HL(t)]}function WL(e,t){return[...e.filter(e=>e.source!==`preview`),t]}function GL(e,t){return e.filter((e,n)=>n!==t)}function KL(e,t){if(!t)return!1;let n=e.composedPath();if(n.length>0)return n.includes(t);let r=e.target;return r!==null&&t.contains(r)}function qL(e){let t=(0,d.useRef)(null);return(0,d.useEffect)(()=>{function n(n){t.current&&!KL(n,t.current)&&e()}return document.addEventListener(`mousedown`,n),()=>document.removeEventListener(`mousedown`,n)},[e]),t}var JL=100,YL=new Intl.Collator(void 0,{sensitivity:`base`,numeric:!0}),XL={extension:`ext`,prompt:`prompt`,skill:`skill`};function ZL(e){return e===`directory`||e===`symlink-directory`}function QL(e,t){let n=e.slice(0,t),r=/(?:^|\s)@([^\s@]*)$/.exec(n);return r?{start:t-r[1].length-1,query:r[1]}:null}function $L({isStreaming:e,connected:t,commands:n,fileSearch:r,prefill:i,attachments:a,pendingUploads:o=[],onAttach:s,onMentionPaths:c,onRemoveAttachment:l,onSend:u,onAbort:f,onSearchFiles:p,onClearFileSearch:m,initialDraft:h,onDraftChange:g}){let[_,v]=(0,d.useState)(h??``);(0,d.useEffect)(()=>{g?.(_)},[_,g]);let[y,b]=(0,d.useState)(0),[x,S]=(0,d.useState)(0),[C,w]=(0,d.useState)(!1),T=(0,d.useRef)(null),ee=(0,d.useRef)(null),E=(0,d.useRef)(null),te=(0,d.useRef)(null),D=(0,d.useRef)(null);(0,d.useEffect)(()=>{i&&v(i.text)},[i?.nonce]),(0,d.useEffect)(()=>{D.current!==null&&(E.current?.focus(),E.current?.setSelectionRange(D.current,D.current),D.current=null)},[_]),(0,d.useLayoutEffect)(()=>{let e=E.current;if(!e)return;let t=-1,n=()=>{t=e.offsetWidth,e.style.overflowY=`hidden`,e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`,e.scrollHeight>e.clientHeight&&(e.style.overflowY=`auto`)};n();let r=typeof ResizeObserver>`u`?void 0:new ResizeObserver(()=>{e.offsetWidth!==t&&n()});return r?.observe(e,{box:`border-box`}),()=>r?.disconnect()},[_]);let ne=(0,d.useMemo)(()=>zL(_),[_]);(0,d.useEffect)(()=>{c(ne)},[ne.join(`
331
- `)]);let re=(0,d.useMemo)(()=>{let e=/^\/(\S*)$/.exec(_);return e?e[1].toLowerCase():null},[_]),ie=(0,d.useMemo)(()=>re===null?[]:n.filter(e=>e.name.toLowerCase().includes(re)).sort((e,t)=>{let n=e.name.toLowerCase().startsWith(re);return n===t.name.toLowerCase().startsWith(re)?YL.compare(e.name,t.name):n?-1:1}).slice(0,JL),[re,n]),O=re===null?QL(_,y):null;(0,d.useEffect)(()=>{if(!O||O.query.length===0){m();return}let e=window.setTimeout(()=>p(O.query),150);return()=>clearTimeout(e)},[O?.query]);let k=(0,d.useMemo)(()=>{if(ie.length>0)return{kind:`command`,items:ie};let e=O&&r?.query===O.query?r.results:[];return e.length>0?{kind:`file`,items:e}:null},[ie,O,r]),ae=k!==null&&!C,oe=re===null?O?`file:${O.query}`:null:`cmd:${re}`;(0,d.useEffect)(()=>{S(0)},[oe]),(0,d.useEffect)(()=>{w(!1)},[re===null?O?`file`:null:`command`]),(0,d.useEffect)(()=>{if(!ae)return;let e=e=>{KL(e,T.current)||w(!0)};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e)}},[ae]),(0,d.useEffect)(()=>{ee.current?.querySelector(`[data-selected="true"]`)?.scrollIntoView({block:`nearest`})},[x]);let se=o.length>0,[ce,le]=(0,d.useState)(!1);(0,d.useEffect)(()=>{se||le(!1)},[se]);function ue(){if(se){le(!0);return}let e=BL(_,a),t=a.filter(e=>e.kind===`image`).map(e=>({data:e.data,mimeType:e.mimeType})),n=a.every(e=>e.kind===`path`);(_.trim()||!n&&e||t.length!==0)&&(u(e,t.length>0?t:void 0),v(``),m())}function de(e){let t=`/${e.name} `;v(t),D.current=t.length,b(t.length)}function j(e){if(!O)return;let t=_.slice(0,O.start),n=_.slice(y),r=`@${e.path}${ZL(e.type)?`/`:` `}`,i=`${t}${r}${n}`;v(i),m();let a=t.length+r.length;D.current=a,b(a)}function fe(){if(k){if(k.kind===`command`){let e=k.items[x];e&&de(e)}else{let e=k.items[x];e&&j(e)}}}function pe(e){if(ae&&k){if(e.key===`ArrowDown`){e.preventDefault(),S(e=>(e+1)%k.items.length);return}if(e.key===`ArrowUp`){e.preventDefault(),S(e=>(e-1+k.items.length)%k.items.length);return}if(e.key===`Tab`||e.key===`Enter`){e.preventDefault(),fe();return}if(e.key===`Escape`){e.preventDefault(),w(!0);return}}e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),ue())}function me(e){b(e.currentTarget.selectionStart??0)}function he(e){let t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),s(t))}return(0,A.jsxs)(`div`,{ref:T,className:`relative`,children:[(a.length>0||se)&&(0,A.jsxs)(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[o.map(e=>(0,A.jsxs)(`span`,{"data-pending-upload":e.name,title:`${e.name} — copying into the workspace`,className:`flex items-center gap-1.5 rounded-md border border-dashed border-zinc-300 bg-zinc-50 py-1 pl-1.5 pr-2 text-xs text-zinc-500 dark:border-zinc-600 dark:bg-zinc-800/40 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`animate-pulse`,children:`⏳`}),(0,A.jsx)(`span`,{className:`max-w-40 truncate`,children:e.name}),(0,A.jsx)(`span`,{className:`sr-only`,children:`uploading`})]},e.id)),ce&&(0,A.jsx)(`span`,{role:`status`,className:`flex items-center py-1 text-xs text-amber-600 dark:text-amber-400`,children:`waiting for the attachment to finish uploading…`}),a.map((e,t)=>(0,A.jsxs)(`span`,{title:e.kind===`path`?`${e.name} — sent as a reference; the agent reads the file itself`:e.name,className:`flex items-center gap-1.5 rounded-md border border-zinc-200 bg-zinc-50 py-1 pl-1.5 pr-1 text-xs text-zinc-600 dark:border-zinc-700 dark:bg-zinc-800/60 dark:text-zinc-300`,children:[e.kind===`image`?(0,A.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name,className:`h-8 w-8 rounded object-cover`}):(0,A.jsx)(`span`,{"aria-hidden":!0,className:e.kind===`path`?`font-mono font-bold text-blue-600 dark:text-blue-400`:``,children:e.kind===`path`?`@`:`📄`}),(0,A.jsx)(`span`,{className:`max-w-40 truncate`,children:e.name}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>l(t),title:`remove attachment`,className:`rounded px-1 text-zinc-400 hover:bg-zinc-200 hover:text-zinc-700 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✕`})]},`${e.name}:${t}`))]}),ae&&k&&(0,A.jsx)(`div`,{ref:ee,className:`absolute bottom-full left-0 z-20 mb-2 max-h-72 w-full max-w-xl overflow-y-auto rounded-lg border border-zinc-200 bg-white py-1 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:k.kind===`command`?k.items.map((e,t)=>(0,A.jsxs)(`button`,{type:`button`,"data-selected":t===x,onMouseEnter:()=>S(t),onClick:()=>de(e),className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm ${t===x?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:[`/`,e.name]}),e.argumentHint&&(0,A.jsx)(`span`,{className:`font-mono text-xs text-zinc-500`,children:e.argumentHint}),e.description&&(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-xs text-zinc-500`,children:e.description}),(0,A.jsx)(`span`,{className:`ml-auto shrink-0 rounded bg-zinc-200 px-1 text-[10px] uppercase text-zinc-500 dark:bg-zinc-800`,children:XL[e.source]})]},e.name)):k.items.map((e,t)=>(0,A.jsx)(`button`,{type:`button`,"data-selected":t===x,onMouseEnter:()=>S(t),onClick:()=>j(e),className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm ${t===x?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:(0,A.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-zinc-800 dark:text-zinc-200`,children:[e.path,ZL(e.type)?`/`:``]})},e.path))}),(0,A.jsxs)(`div`,{className:`flex items-end gap-2 rounded-xl border border-zinc-200 bg-zinc-50 p-2 focus-within:border-zinc-400 dark:border-zinc-800 dark:bg-zinc-900 dark:focus-within:border-zinc-600`,children:[(0,A.jsx)(`textarea`,{ref:E,value:_,onChange:e=>{v(e.target.value),b(e.target.selectionStart??e.target.value.length)},onKeyDown:pe,onClick:me,onKeyUp:me,onPaste:he,placeholder:t?e?`steer the agent… (Enter to send)`:`message pi… (/ for commands, @ for files, Enter to send, Shift+Enter for newline)`:`connecting…`,disabled:!t,rows:1,className:`max-h-[min(40vh,20rem)] flex-1 resize-none overflow-y-hidden bg-transparent px-2 py-1.5 text-[15px] outline-none placeholder:text-zinc-400 disabled:opacity-50 dark:placeholder:text-zinc-600`}),e&&(0,A.jsx)(`button`,{type:`button`,onClick:f,title:`stop`,"aria-label":`Stop the agent`,className:`rounded-lg bg-red-100 p-2 text-red-700 hover:bg-red-200 dark:bg-red-900/60 dark:text-red-200 dark:hover:bg-red-900`,children:(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})})}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>te.current?.click(),disabled:!t,title:`attach files`,"aria-label":`Attach files`,className:`rounded-lg p-2 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-700 disabled:opacity-30 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`})})}),(0,A.jsx)(`input`,{ref:te,type:`file`,multiple:!0,hidden:!0,onChange:e=>{e.target.files?.length&&s(Array.from(e.target.files)),e.target.value=``}}),(0,A.jsx)(`button`,{type:`button`,onClick:ue,disabled:!t||se||!_.trim()&&a.length===0,title:se?`waiting for an attachment to finish uploading`:e?`steer`:`send`,"aria-label":e?`Steer the agent`:`Send message`,className:`rounded-lg bg-zinc-900 p-2 text-zinc-100 hover:bg-zinc-800 disabled:opacity-30 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,children:e?(0,A.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:[(0,A.jsx)(`circle`,{cx:`6`,cy:`19`,r:`3`}),(0,A.jsx)(`path`,{strokeLinecap:`round`,d:`M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15`}),(0,A.jsx)(`circle`,{cx:`18`,cy:`5`,r:`3`})]}):(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M6 12 3.27 3.13c6.6 1.9 12.83 4.9 18.43 8.87-5.6 3.97-11.83 6.97-18.43 8.87L6 12Zm0 0h7.5`})})})]})]})}var eR=`rounded-md border px-3 py-1.5 text-sm border-zinc-200 hover:bg-zinc-100 dark:border-zinc-800 dark:hover:bg-zinc-800`,tR=`rounded-md bg-zinc-900 px-3 py-1.5 text-sm text-zinc-100 hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,nR=`w-full rounded-md border border-zinc-300 bg-white px-2 py-1.5 text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:focus:border-zinc-500`,rR=`mb-4 ${nR}`,iR=`1,3`,aR=` — `;function oR(e){let t=e.indexOf(`
332
- `);return t===-1?{heading:e,body:``}:{heading:e.slice(0,t),body:e.slice(t+1).trim()}}function sR(e){let t=/^(\d+)\.\s+(\S[\s\S]*)$/.exec(e.trim());if(!t)return null;let n=t[2],r=n.indexOf(aR);return{index:Number(t[1]),label:r===-1?n:n.slice(0,r),description:r===-1?``:n.slice(r+3)}}function cR(e){if(e.method!==`input`||e.placeholder!==iR)return null;let{heading:t,body:n}=oR(e.title),r=[];for(let e of n.split(`
333
- `)){let t=sR(e);t&&r.push(t)}return r.length<2||r.some((e,t)=>e.index!==t+1)?null:{heading:t,options:r}}function lR({request:e,onRespond:t}){let[n,r]=(0,d.useState)(e.method===`editor`?e.prefill??``:``),[i,a]=(0,d.useState)([]),[o,s]=(0,d.useState)(!1),c=(e.method===`select`||e.method===`confirm`||e.method===`input`)&&e.timeout,[l,u]=(0,d.useState)(c?Math.ceil(c/1e3):null),f=cR(e),{heading:p,body:m}=oR(e.title);function h(){t({id:e.id,cancelled:!0})}function g(e){a(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e].sort((e,t)=>e-t))}function _(){let r=n.trim();t({id:e.id,value:r.length>0?r:i.join(`,`)})}return(0,d.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>s(!1),400);return()=>clearTimeout(e)},[o]),(0,d.useEffect)(()=>{if(l===null)return;if(l<=0){t({id:e.id,cancelled:!0});return}let n=setTimeout(()=>u(e=>e===null?null:e-1),1e3);return()=>clearTimeout(n)},[l,e.id,t]),(0,A.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4`,onClick:()=>s(!0),children:(0,A.jsxs)(`div`,{className:`w-full ${m?`max-w-2xl`:`max-w-md`} rounded-xl border bg-white p-4 shadow-2xl transition-shadow dark:bg-zinc-900 ${o?`border-zinc-400 ring-2 ring-zinc-400/60 dark:border-zinc-500 dark:ring-zinc-500/60`:`border-zinc-200 dark:border-zinc-700`}`,onClick:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`mb-3 flex items-start gap-3`,children:[(0,A.jsx)(`h2`,{className:`flex-1 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:p}),(0,A.jsx)(`button`,{type:`button`,onClick:h,"aria-label":`Refuse to answer`,title:`Refuse to answer`,className:`-mr-1 -mt-1 rounded-md px-1.5 py-0.5 text-sm leading-none text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`✕`})]}),m&&!f&&(0,A.jsx)(`pre`,{className:`mb-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-zinc-50 p-2 font-mono text-xs text-zinc-600 dark:bg-zinc-950 dark:text-zinc-400`,children:m}),e.method===`select`&&(0,A.jsx)(`div`,{className:`mb-1 flex flex-col gap-1`,children:e.options.map(n=>{let r=sR(n);return(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:`text-left ${eR}`,children:r?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-900 dark:text-zinc-100`,children:r.label}),r.description&&(0,A.jsx)(`span`,{className:`mt-0.5 block text-xs text-zinc-500 dark:text-zinc-400`,children:r.description})]}):n},n)})}),e.method===`confirm`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`p`,{className:`mb-4 text-sm text-zinc-600 dark:text-zinc-400`,children:e.message}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,confirmed:!1}),className:eR,children:`No`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,confirmed:!0}),className:tR,children:`Yes`})]})]}),f&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`mb-3 flex flex-col gap-1`,children:f.options.map(e=>(0,A.jsxs)(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:i.includes(e.index),onChange:()=>g(e.index),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-900 dark:text-zinc-100`,children:e.label}),e.description&&(0,A.jsx)(`span`,{className:`mt-0.5 block text-xs text-zinc-500 dark:text-zinc-400`,children:e.description})]})]},e.index))}),(0,A.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`…or type your own answer`,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&h()},className:`mb-1 ${nR}`}),(0,A.jsx)(`p`,{className:`mb-4 text-xs text-zinc-400 dark:text-zinc-600`,children:`A typed answer replaces the selection above.`}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:eR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:_,className:tR,children:`OK`})]})]}),e.method===`input`&&!f&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`input`,{autoFocus:!0,value:n,onChange:e=>r(e.target.value),placeholder:e.placeholder,onKeyDown:r=>{r.key===`Enter`&&t({id:e.id,value:n}),r.key===`Escape`&&h()},className:rR}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:eR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:tR,children:`OK`})]})]}),e.method===`editor`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`textarea`,{autoFocus:!0,value:n,onChange:e=>r(e.target.value),rows:8,onKeyDown:e=>{e.key===`Escape`&&h()},className:`resize-none font-mono ${rR}`}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:eR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:tR,children:`OK`})]})]}),l!==null&&(0,A.jsxs)(`p`,{className:`mt-3 text-right text-xs text-zinc-400 dark:text-zinc-600`,children:[`auto-dismiss in `,l,`s`]})]})})}var uR={info:`border-blue-300 bg-blue-50 text-blue-800 dark:border-blue-900 dark:bg-blue-950/60 dark:text-blue-200`,warning:`border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950/60 dark:text-amber-200`,error:`border-red-300 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950/60 dark:text-red-200`},dR=6e3;function fR({notification:e,onDismiss:t}){let n=(0,d.useRef)(t);return(0,d.useEffect)(()=>{n.current=t}),(0,d.useEffect)(()=>{let e=setTimeout(()=>n.current(),dR);return()=>clearTimeout(e)},[e.id]),(0,A.jsxs)(`div`,{role:`status`,className:`flex items-start gap-2 rounded-lg border px-3 py-2 text-sm shadow-lg ${uR[e.notifyType??`info`]}`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 break-words`,children:e.message}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Dismiss notification`,onClick:()=>n.current(),className:`-mr-1 shrink-0 rounded px-1 leading-5 opacity-60 transition-opacity hover:opacity-100 focus-visible:opacity-100`,children:`×`})]})}function pR({notifications:e,onDismiss:t}){return e.length===0?null:(0,A.jsx)(`div`,{className:`fixed right-4 top-16 z-40 flex w-80 flex-col gap-2`,children:e.map(e=>(0,A.jsx)(fR,{notification:e,onDismiss:()=>t(e.id)},e.id))})}var mR={30:`#3f3f46`,31:`#dc2626`,32:`#16a34a`,33:`#ca8a04`,34:`#2563eb`,35:`#9333ea`,36:`#0891b2`,37:`#71717a`,90:`#a1a1aa`,91:`#ef4444`,92:`#22c55e`,93:`#eab308`,94:`#3b82f6`,95:`#a855f7`,96:`#06b6d4`,97:`#d4d4d8`},hR=/\u001B\[[0-9;:]*[A-Za-z]|\u001B[()][A-Za-z0-9]|\u001B[A-Za-z]/g;function gR(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(r===0)for(let e of Object.keys(n))delete n[e];else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===22)delete n.bold,delete n.dim;else if(r===23)delete n.italic;else if(r===24)delete n.underline;else if(r===39)delete n.color;else if(mR[r]!==void 0)n.color=mR[r];else if(r===38){if(t[e+1]===2){let[r,i,a]=[t[e+2],t[e+3],t[e+4]];[r,i,a].every(e=>Number.isFinite(e))&&(n.color=`rgb(${r} ${i} ${a})`),e+=4}else t[e+1]===5&&(e+=2)}}return n}function _R(e){let t=[],n={},r=0;hR.lastIndex=0;for(let i=hR.exec(e);i!==null;i=hR.exec(e)){i.index>r&&t.push({text:e.slice(r,i.index),...n}),r=i.index+i[0].length;let a=i[0];if(a.endsWith(`m`)){let e=a.slice(2,-1),t=e===``?[0]:e.split(/[;:]/).map(e=>e===``?0:Number(e));n=gR(n,t)}}return r<e.length&&t.push({text:e.slice(r),...n}),t}function vR(e){return e.replace(hR,``)}function yR({line:e}){let t=_R(e);return(0,A.jsx)(A.Fragment,{children:t.map((e,t)=>(0,A.jsx)(`span`,{style:{...e.color?{color:e.color}:{},...e.bold?{fontWeight:600}:{},...e.dim?{opacity:.7}:{},...e.italic?{fontStyle:`italic`}:{},...e.underline?{textDecoration:`underline`}:{}},children:e.text},t))})}function bR({widgets:e,placement:t}){let n=Object.entries(e).filter(([,e])=>e.placement===t);return n.length===0?null:(0,A.jsx)(`div`,{className:`mb-2 flex flex-col gap-1`,children:n.map(([e,t])=>(0,A.jsx)(`div`,{className:`whitespace-pre-wrap rounded-md border border-zinc-200 bg-zinc-50 px-3 py-1.5 font-mono text-xs text-zinc-600 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400`,children:t.lines.map((e,t)=>(0,A.jsx)(`div`,{children:(0,A.jsx)(yR,{line:e})},t))},e))})}var xR=null,SR=null;function CR(){return SR??=me(()=>import(`./CodeEditor-B123NBEk.js`).then(e=>e.t).then(e=>xR=e,e=>{throw SR=null,e}),__vite__mapDeps([22,1,23])),SR}var wR=(0,d.lazy)(()=>{if(xR!==null){let e=xR;return{then:t=>t({default:e.CodeEditor})}}return CR().then(e=>({default:e.CodeEditor}))});function TR({text:e,path:t,serverUrl:n,token:r,workspace:i,template:a}){let[o,s]=(0,d.useState)(`idle`),[c,l]=(0,d.useState)(`plain`),[u,f]=(0,d.useState)(null),p=(0,d.useRef)(!1),m=(0,d.useRef)({plain:0,template:0});async function h(a){if(!(p.current||Date.now()-m.current[a]<750)){p.current=!0,m.current[a]=Date.now(),l(a),s(`working`),f(null);try{let{downloadDocx:o,downloadDocxInTemplate:c}=await me(async()=>{let{downloadDocx:e,downloadDocxInTemplate:t}=await import(`./docxExport-DTdmyOrq.js`);return{downloadDocx:e,downloadDocxInTemplate:t}},__vite__mapDeps([24,21,1,25])),l=typeof e==`function`?e():e;await(a===`template`?c:o)(l,t,{serverUrl:n,token:r,workspace:i}),s(`idle`)}catch(e){s(`failed`),f(e instanceof Error?e.message:String(e))}finally{p.current=!1}}}let g=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 disabled:opacity-50 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`,_=(e,t)=>o===`working`&&c===e?`… exporting`:o===`failed`&&c===e?`⚠ export failed`:t,v=(e,t)=>o===`failed`&&c===e?`Could not export: ${u??`unknown reason`}`:t;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>void h(`plain`),disabled:o===`working`,title:v(`plain`,`Download as a Word document`),"aria-label":`Download as a Word document`,className:g,children:_(`plain`,`⤓ word`)}),a!==void 0&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>void h(`template`),disabled:o===`working`,title:v(`template`,`Download as a Word document in the template ${a}`),"aria-label":`Download as a Word document in the template ${a}`,className:g,children:_(`template`,`⤓ word · template`)})]})}var ER=`pi-outpost:open`,DR=4,OR={css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,svg:`image/svg+xml`,ico:`image/x-icon`,bmp:`image/bmp`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`},kR=`(function () {
330
+ `:``}${e}`};for(let e of t)e.kind===`path`?HL(n,e.data)||r(`@${e.data}`):e.kind===`text`&&r(`\`\`\`${e.name}\n${e.data}\n\`\`\``);return n}async function GL(e,t){try{let n=await fetch(t);if(!n.ok)return`${e}: unable to read preview image for attachment`;let r=n.headers.get(`Content-Type`)?.split(`;`,1)[0]??``;if(!r.startsWith(`image/`))return`${e}: preview is not a supported image attachment`;let i=new Uint8Array(await n.arrayBuffer());return i.byteLength>7340032?`${e}: image too large (max 7 MB)`:{name:e,kind:`image`,data:kL(i),mimeType:r,source:`preview`,previewPath:e}}catch{return`${e}: unable to read preview image for attachment`}}function KL(e){return{name:e,kind:`path`,data:e,mimeType:`text/plain`,source:`manual`}}function qL(e,t){return e.some(e=>e.kind===`path`&&e.data===t)?e:[...e,KL(t)]}function JL(e,t){return[...e.filter(e=>e.source!==`preview`),t]}function YL(e,t){return e.filter((e,n)=>n!==t)}function XL(e,t){if(!t)return!1;let n=e.composedPath();if(n.length>0)return n.includes(t);let r=e.target;return r!==null&&t.contains(r)}function ZL(e){let t=(0,d.useRef)(null);return(0,d.useEffect)(()=>{function n(n){t.current&&!XL(n,t.current)&&e()}return document.addEventListener(`mousedown`,n),()=>document.removeEventListener(`mousedown`,n)},[e]),t}var QL=100,$L=new Intl.Collator(void 0,{sensitivity:`base`,numeric:!0}),eR={extension:`ext`,prompt:`prompt`,skill:`skill`};function tR(e){return e===`directory`||e===`symlink-directory`}function nR(e,t){let n=e.slice(0,t),r=/(?:^|\s)@([^\s@]*)$/.exec(n);return r?{start:t-r[1].length-1,query:r[1]}:null}function rR({isStreaming:e,connected:t,commands:n,fileSearch:r,prefill:i,attachments:a,pendingUploads:o=[],onAttach:s,onMentionPaths:c,onRemoveAttachment:l,onSend:u,onAbort:f,onSearchFiles:p,onClearFileSearch:m,initialDraft:h,onDraftChange:g}){let[_,v]=(0,d.useState)(h??``);(0,d.useEffect)(()=>{g?.(_)},[_,g]);let[y,b]=(0,d.useState)(0),[x,S]=(0,d.useState)(0),[C,w]=(0,d.useState)(!1),T=(0,d.useRef)(null),ee=(0,d.useRef)(null),E=(0,d.useRef)(null),te=(0,d.useRef)(null),D=(0,d.useRef)(null);(0,d.useEffect)(()=>{i&&v(i.text)},[i?.nonce]),(0,d.useEffect)(()=>{D.current!==null&&(E.current?.focus(),E.current?.setSelectionRange(D.current,D.current),D.current=null)},[_]),(0,d.useLayoutEffect)(()=>{let e=E.current;if(!e)return;let t=-1,n=()=>{t=e.offsetWidth,e.style.overflowY=`hidden`,e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`,e.scrollHeight>e.clientHeight&&(e.style.overflowY=`auto`)};n();let r=typeof ResizeObserver>`u`?void 0:new ResizeObserver(()=>{e.offsetWidth!==t&&n()});return r?.observe(e,{box:`border-box`}),()=>r?.disconnect()},[_]);let ne=(0,d.useMemo)(()=>UL(_),[_]);(0,d.useEffect)(()=>{c(ne)},[ne.join(`
331
+ `)]);let re=(0,d.useMemo)(()=>{let e=/^\/(\S*)$/.exec(_);return e?e[1].toLowerCase():null},[_]),ie=(0,d.useMemo)(()=>re===null?[]:n.filter(e=>e.name.toLowerCase().includes(re)).sort((e,t)=>{let n=e.name.toLowerCase().startsWith(re);return n===t.name.toLowerCase().startsWith(re)?$L.compare(e.name,t.name):n?-1:1}).slice(0,QL),[re,n]),O=re===null?nR(_,y):null;(0,d.useEffect)(()=>{if(!O||O.query.length===0){m();return}let e=window.setTimeout(()=>p(O.query),150);return()=>clearTimeout(e)},[O?.query]);let k=(0,d.useMemo)(()=>{if(ie.length>0)return{kind:`command`,items:ie};let e=O&&r?.query===O.query?r.results:[];return e.length>0?{kind:`file`,items:e}:null},[ie,O,r]),ae=k!==null&&!C,oe=re===null?O?`file:${O.query}`:null:`cmd:${re}`;(0,d.useEffect)(()=>{S(0)},[oe]),(0,d.useEffect)(()=>{w(!1)},[re===null?O?`file`:null:`command`]),(0,d.useEffect)(()=>{if(!ae)return;let e=e=>{XL(e,T.current)||w(!0)};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e)}},[ae]),(0,d.useEffect)(()=>{ee.current?.querySelector(`[data-selected="true"]`)?.scrollIntoView({block:`nearest`})},[x]);let se=o.length>0,[ce,le]=(0,d.useState)(!1);(0,d.useEffect)(()=>{se||le(!1)},[se]);function ue(){if(se){le(!0);return}let e=WL(_,a),t=a.filter(e=>e.kind===`image`).map(e=>({data:e.data,mimeType:e.mimeType})),n=a.every(e=>e.kind===`path`);(_.trim()||!n&&e||t.length!==0)&&(u(e,t.length>0?t:void 0),v(``),m())}function de(e){let t=`/${e.name} `;v(t),D.current=t.length,b(t.length)}function j(e){if(!O)return;let t=_.slice(0,O.start),n=_.slice(y),r=`@${e.path}${tR(e.type)?`/`:` `}`,i=`${t}${r}${n}`;v(i),m();let a=t.length+r.length;D.current=a,b(a)}function fe(){if(k){if(k.kind===`command`){let e=k.items[x];e&&de(e)}else{let e=k.items[x];e&&j(e)}}}function pe(e){if(ae&&k){if(e.key===`ArrowDown`){e.preventDefault(),S(e=>(e+1)%k.items.length);return}if(e.key===`ArrowUp`){e.preventDefault(),S(e=>(e-1+k.items.length)%k.items.length);return}if(e.key===`Tab`||e.key===`Enter`){e.preventDefault(),fe();return}if(e.key===`Escape`){e.preventDefault(),w(!0);return}}e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),ue())}function me(e){b(e.currentTarget.selectionStart??0)}function he(e){let t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),s(t))}return(0,A.jsxs)(`div`,{ref:T,className:`relative`,children:[(a.length>0||se)&&(0,A.jsxs)(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[o.map(e=>(0,A.jsxs)(`span`,{"data-pending-upload":e.name,title:`${e.name} — copying into the workspace`,className:`flex items-center gap-1.5 rounded-md border border-dashed border-zinc-300 bg-zinc-50 py-1 pl-1.5 pr-2 text-xs text-zinc-500 dark:border-zinc-600 dark:bg-zinc-800/40 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`animate-pulse`,children:`⏳`}),(0,A.jsx)(`span`,{className:`max-w-40 truncate`,children:e.name}),(0,A.jsx)(`span`,{className:`sr-only`,children:`uploading`})]},e.id)),ce&&(0,A.jsx)(`span`,{role:`status`,className:`flex items-center py-1 text-xs text-amber-600 dark:text-amber-400`,children:`waiting for the attachment to finish uploading…`}),a.map((e,t)=>(0,A.jsxs)(`span`,{title:e.kind===`path`?`${e.name} — sent as a reference; the agent reads the file itself`:e.name,className:`flex items-center gap-1.5 rounded-md border border-zinc-200 bg-zinc-50 py-1 pl-1.5 pr-1 text-xs text-zinc-600 dark:border-zinc-700 dark:bg-zinc-800/60 dark:text-zinc-300`,children:[e.kind===`image`?(0,A.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name,className:`h-8 w-8 rounded object-cover`}):(0,A.jsx)(`span`,{"aria-hidden":!0,className:e.kind===`path`?`font-mono font-bold text-blue-600 dark:text-blue-400`:``,children:e.kind===`path`?`@`:`📄`}),(0,A.jsx)(`span`,{className:`max-w-40 truncate`,children:e.name}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>l(t),title:`remove attachment`,className:`rounded px-1 text-zinc-400 hover:bg-zinc-200 hover:text-zinc-700 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✕`})]},`${e.name}:${t}`))]}),ae&&k&&(0,A.jsx)(`div`,{ref:ee,className:`absolute bottom-full left-0 z-20 mb-2 max-h-72 w-full max-w-xl overflow-y-auto rounded-lg border border-zinc-200 bg-white py-1 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:k.kind===`command`?k.items.map((e,t)=>(0,A.jsxs)(`button`,{type:`button`,"data-selected":t===x,onMouseEnter:()=>S(t),onClick:()=>de(e),className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm ${t===x?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:[`/`,e.name]}),e.argumentHint&&(0,A.jsx)(`span`,{className:`font-mono text-xs text-zinc-500`,children:e.argumentHint}),e.description&&(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-xs text-zinc-500`,children:e.description}),(0,A.jsx)(`span`,{className:`ml-auto shrink-0 rounded bg-zinc-200 px-1 text-[10px] uppercase text-zinc-500 dark:bg-zinc-800`,children:eR[e.source]})]},e.name)):k.items.map((e,t)=>(0,A.jsx)(`button`,{type:`button`,"data-selected":t===x,onMouseEnter:()=>S(t),onClick:()=>j(e),className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm ${t===x?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:(0,A.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-zinc-800 dark:text-zinc-200`,children:[e.path,tR(e.type)?`/`:``]})},e.path))}),(0,A.jsxs)(`div`,{className:`flex items-end gap-2 rounded-xl border border-zinc-200 bg-zinc-50 p-2 focus-within:border-zinc-400 dark:border-zinc-800 dark:bg-zinc-900 dark:focus-within:border-zinc-600`,children:[(0,A.jsx)(`textarea`,{ref:E,value:_,onChange:e=>{v(e.target.value),b(e.target.selectionStart??e.target.value.length)},onKeyDown:pe,onClick:me,onKeyUp:me,onPaste:he,placeholder:t?e?`steer the agent… (Enter to send)`:`message pi… (/ for commands, @ for files, Enter to send, Shift+Enter for newline)`:`connecting…`,disabled:!t,rows:1,className:`max-h-[min(40vh,20rem)] flex-1 resize-none overflow-y-hidden bg-transparent px-2 py-1.5 text-[15px] outline-none placeholder:text-zinc-400 disabled:opacity-50 dark:placeholder:text-zinc-600`}),e&&(0,A.jsx)(`button`,{type:`button`,onClick:f,title:`stop`,"aria-label":`Stop the agent`,className:`rounded-lg bg-red-100 p-2 text-red-700 hover:bg-red-200 dark:bg-red-900/60 dark:text-red-200 dark:hover:bg-red-900`,children:(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})})}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>te.current?.click(),disabled:!t,title:`attach files`,"aria-label":`Attach files`,className:`rounded-lg p-2 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-700 disabled:opacity-30 dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`})})}),(0,A.jsx)(`input`,{ref:te,type:`file`,multiple:!0,hidden:!0,onChange:e=>{e.target.files?.length&&s(Array.from(e.target.files)),e.target.value=``}}),(0,A.jsx)(`button`,{type:`button`,onClick:ue,disabled:!t||se||!_.trim()&&a.length===0,title:se?`waiting for an attachment to finish uploading`:e?`steer`:`send`,"aria-label":e?`Steer the agent`:`Send message`,className:`rounded-lg bg-zinc-900 p-2 text-zinc-100 hover:bg-zinc-800 disabled:opacity-30 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,children:e?(0,A.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:[(0,A.jsx)(`circle`,{cx:`6`,cy:`19`,r:`3`}),(0,A.jsx)(`path`,{strokeLinecap:`round`,d:`M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15`}),(0,A.jsx)(`circle`,{cx:`18`,cy:`5`,r:`3`})]}):(0,A.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":!0,className:`h-4 w-4`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M6 12 3.27 3.13c6.6 1.9 12.83 4.9 18.43 8.87-5.6 3.97-11.83 6.97-18.43 8.87L6 12Zm0 0h7.5`})})})]})]})}var iR=`rounded-md border px-3 py-1.5 text-sm border-zinc-200 hover:bg-zinc-100 dark:border-zinc-800 dark:hover:bg-zinc-800`,aR=`rounded-md bg-zinc-900 px-3 py-1.5 text-sm text-zinc-100 hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,oR=`w-full rounded-md border border-zinc-300 bg-white px-2 py-1.5 text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:focus:border-zinc-500`,sR=`mb-4 ${oR}`,cR=`1,3`,lR=` — `;function uR(e){let t=e.indexOf(`
332
+ `);return t===-1?{heading:e,body:``}:{heading:e.slice(0,t),body:e.slice(t+1).trim()}}function dR(e){let t=/^(\d+)\.\s+(\S[\s\S]*)$/.exec(e.trim());if(!t)return null;let n=t[2],r=n.indexOf(lR);return{index:Number(t[1]),label:r===-1?n:n.slice(0,r),description:r===-1?``:n.slice(r+3)}}function fR(e){if(e.method!==`input`||e.placeholder!==cR)return null;let{heading:t,body:n}=uR(e.title),r=[];for(let e of n.split(`
333
+ `)){let t=dR(e);t&&r.push(t)}return r.length<2||r.some((e,t)=>e.index!==t+1)?null:{heading:t,options:r}}function pR({request:e,onRespond:t}){let[n,r]=(0,d.useState)(e.method===`editor`?e.prefill??``:``),[i,a]=(0,d.useState)([]),[o,s]=(0,d.useState)(!1),c=(e.method===`select`||e.method===`confirm`||e.method===`input`)&&e.timeout,[l,u]=(0,d.useState)(c?Math.ceil(c/1e3):null),f=fR(e),{heading:p,body:m}=uR(e.title);function h(){t({id:e.id,cancelled:!0})}function g(e){a(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e].sort((e,t)=>e-t))}function _(){let r=n.trim();t({id:e.id,value:r.length>0?r:i.join(`,`)})}return(0,d.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>s(!1),400);return()=>clearTimeout(e)},[o]),(0,d.useEffect)(()=>{if(l===null)return;if(l<=0){t({id:e.id,cancelled:!0});return}let n=setTimeout(()=>u(e=>e===null?null:e-1),1e3);return()=>clearTimeout(n)},[l,e.id,t]),(0,A.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4`,onClick:()=>s(!0),children:(0,A.jsxs)(`div`,{className:`w-full ${m?`max-w-2xl`:`max-w-md`} rounded-xl border bg-white p-4 shadow-2xl transition-shadow dark:bg-zinc-900 ${o?`border-zinc-400 ring-2 ring-zinc-400/60 dark:border-zinc-500 dark:ring-zinc-500/60`:`border-zinc-200 dark:border-zinc-700`}`,onClick:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`mb-3 flex items-start gap-3`,children:[(0,A.jsx)(`h2`,{className:`flex-1 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:p}),(0,A.jsx)(`button`,{type:`button`,onClick:h,"aria-label":`Refuse to answer`,title:`Refuse to answer`,className:`-mr-1 -mt-1 rounded-md px-1.5 py-0.5 text-sm leading-none text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`✕`})]}),m&&!f&&(0,A.jsx)(`pre`,{className:`mb-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-zinc-50 p-2 font-mono text-xs text-zinc-600 dark:bg-zinc-950 dark:text-zinc-400`,children:m}),e.method===`select`&&(0,A.jsx)(`div`,{className:`mb-1 flex flex-col gap-1`,children:e.options.map(n=>{let r=dR(n);return(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:`text-left ${iR}`,children:r?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-900 dark:text-zinc-100`,children:r.label}),r.description&&(0,A.jsx)(`span`,{className:`mt-0.5 block text-xs text-zinc-500 dark:text-zinc-400`,children:r.description})]}):n},n)})}),e.method===`confirm`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`p`,{className:`mb-4 text-sm text-zinc-600 dark:text-zinc-400`,children:e.message}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,confirmed:!1}),className:iR,children:`No`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,confirmed:!0}),className:aR,children:`Yes`})]})]}),f&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`mb-3 flex flex-col gap-1`,children:f.options.map(e=>(0,A.jsxs)(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:i.includes(e.index),onChange:()=>g(e.index),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-900 dark:text-zinc-100`,children:e.label}),e.description&&(0,A.jsx)(`span`,{className:`mt-0.5 block text-xs text-zinc-500 dark:text-zinc-400`,children:e.description})]})]},e.index))}),(0,A.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`…or type your own answer`,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&h()},className:`mb-1 ${oR}`}),(0,A.jsx)(`p`,{className:`mb-4 text-xs text-zinc-400 dark:text-zinc-600`,children:`A typed answer replaces the selection above.`}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:iR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:_,className:aR,children:`OK`})]})]}),e.method===`input`&&!f&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`input`,{autoFocus:!0,value:n,onChange:e=>r(e.target.value),placeholder:e.placeholder,onKeyDown:r=>{r.key===`Enter`&&t({id:e.id,value:n}),r.key===`Escape`&&h()},className:sR}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:iR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:aR,children:`OK`})]})]}),e.method===`editor`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`textarea`,{autoFocus:!0,value:n,onChange:e=>r(e.target.value),rows:8,onKeyDown:e=>{e.key===`Escape`&&h()},className:`resize-none font-mono ${sR}`}),(0,A.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:h,className:iR,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>t({id:e.id,value:n}),className:aR,children:`OK`})]})]}),l!==null&&(0,A.jsxs)(`p`,{className:`mt-3 text-right text-xs text-zinc-400 dark:text-zinc-600`,children:[`auto-dismiss in `,l,`s`]})]})})}var mR={info:`border-blue-300 bg-blue-50 text-blue-800 dark:border-blue-900 dark:bg-blue-950/60 dark:text-blue-200`,warning:`border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950/60 dark:text-amber-200`,error:`border-red-300 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950/60 dark:text-red-200`},hR=6e3;function gR({notification:e,onDismiss:t}){let n=(0,d.useRef)(t);return(0,d.useEffect)(()=>{n.current=t}),(0,d.useEffect)(()=>{let e=setTimeout(()=>n.current(),hR);return()=>clearTimeout(e)},[e.id]),(0,A.jsxs)(`div`,{role:`status`,className:`flex items-start gap-2 rounded-lg border px-3 py-2 text-sm shadow-lg ${mR[e.notifyType??`info`]}`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 break-words`,children:e.message}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Dismiss notification`,onClick:()=>n.current(),className:`-mr-1 shrink-0 rounded px-1 leading-5 opacity-60 transition-opacity hover:opacity-100 focus-visible:opacity-100`,children:`×`})]})}function _R({notifications:e,onDismiss:t}){return e.length===0?null:(0,A.jsx)(`div`,{className:`fixed right-4 top-16 z-40 flex w-80 flex-col gap-2`,children:e.map(e=>(0,A.jsx)(gR,{notification:e,onDismiss:()=>t(e.id)},e.id))})}var vR={30:`#3f3f46`,31:`#dc2626`,32:`#16a34a`,33:`#ca8a04`,34:`#2563eb`,35:`#9333ea`,36:`#0891b2`,37:`#71717a`,90:`#a1a1aa`,91:`#ef4444`,92:`#22c55e`,93:`#eab308`,94:`#3b82f6`,95:`#a855f7`,96:`#06b6d4`,97:`#d4d4d8`},yR=/\u001B\[[0-9;:]*[A-Za-z]|\u001B[()][A-Za-z0-9]|\u001B[A-Za-z]/g;function bR(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(r===0)for(let e of Object.keys(n))delete n[e];else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===22)delete n.bold,delete n.dim;else if(r===23)delete n.italic;else if(r===24)delete n.underline;else if(r===39)delete n.color;else if(vR[r]!==void 0)n.color=vR[r];else if(r===38){if(t[e+1]===2){let[r,i,a]=[t[e+2],t[e+3],t[e+4]];[r,i,a].every(e=>Number.isFinite(e))&&(n.color=`rgb(${r} ${i} ${a})`),e+=4}else t[e+1]===5&&(e+=2)}}return n}function xR(e){let t=[],n={},r=0;yR.lastIndex=0;for(let i=yR.exec(e);i!==null;i=yR.exec(e)){i.index>r&&t.push({text:e.slice(r,i.index),...n}),r=i.index+i[0].length;let a=i[0];if(a.endsWith(`m`)){let e=a.slice(2,-1),t=e===``?[0]:e.split(/[;:]/).map(e=>e===``?0:Number(e));n=bR(n,t)}}return r<e.length&&t.push({text:e.slice(r),...n}),t}function SR(e){return e.replace(yR,``)}function CR({line:e}){let t=xR(e);return(0,A.jsx)(A.Fragment,{children:t.map((e,t)=>(0,A.jsx)(`span`,{style:{...e.color?{color:e.color}:{},...e.bold?{fontWeight:600}:{},...e.dim?{opacity:.7}:{},...e.italic?{fontStyle:`italic`}:{},...e.underline?{textDecoration:`underline`}:{}},children:e.text},t))})}function wR({widgets:e,placement:t}){let n=Object.entries(e).filter(([,e])=>e.placement===t);return n.length===0?null:(0,A.jsx)(`div`,{className:`mb-2 flex flex-col gap-1`,children:n.map(([e,t])=>(0,A.jsx)(`div`,{className:`whitespace-pre-wrap rounded-md border border-zinc-200 bg-zinc-50 px-3 py-1.5 font-mono text-xs text-zinc-600 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400`,children:t.lines.map((e,t)=>(0,A.jsx)(`div`,{children:(0,A.jsx)(CR,{line:e})},t))},e))})}var TR=null,ER=null;function DR(){return ER??=me(()=>import(`./CodeEditor-DrXTrob5.js`).then(e=>e.t).then(e=>TR=e,e=>{throw ER=null,e}),__vite__mapDeps([22,1,23])),ER}var OR=(0,d.lazy)(()=>{if(TR!==null){let e=TR;return{then:t=>t({default:e.CodeEditor})}}return DR().then(e=>({default:e.CodeEditor}))});function kR({text:e,path:t,serverUrl:n,token:r,workspace:i,template:a}){let[o,s]=(0,d.useState)(`idle`),[c,l]=(0,d.useState)(`plain`),[u,f]=(0,d.useState)(null),p=(0,d.useRef)(!1),m=(0,d.useRef)({plain:0,template:0});async function h(a){if(!(p.current||Date.now()-m.current[a]<750)){p.current=!0,m.current[a]=Date.now(),l(a),s(`working`),f(null);try{let{downloadDocx:o,downloadDocxInTemplate:c}=await me(async()=>{let{downloadDocx:e,downloadDocxInTemplate:t}=await import(`./docxExport-ButYIRWK.js`);return{downloadDocx:e,downloadDocxInTemplate:t}},__vite__mapDeps([24,21,1,25])),l=typeof e==`function`?e():e;await(a===`template`?c:o)(l,t,{serverUrl:n,token:r,workspace:i}),s(`idle`)}catch(e){s(`failed`),f(e instanceof Error?e.message:String(e))}finally{p.current=!1}}}let g=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 disabled:opacity-50 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`,_=(e,t)=>o===`working`&&c===e?`… exporting`:o===`failed`&&c===e?`⚠ export failed`:t,v=(e,t)=>o===`failed`&&c===e?`Could not export: ${u??`unknown reason`}`:t;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>void h(`plain`),disabled:o===`working`,title:v(`plain`,`Download as a Word document`),"aria-label":`Download as a Word document`,className:g,children:_(`plain`,`⤓ word`)}),a!==void 0&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>void h(`template`),disabled:o===`working`,title:v(`template`,`Download as a Word document in the template ${a}`),"aria-label":`Download as a Word document in the template ${a}`,className:g,children:_(`template`,`⤓ word · template`)})]})}var AR=`pi-outpost:open`,jR=4,MR={css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,svg:`image/svg+xml`,ico:`image/x-icon`,bmp:`image/bmp`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`},NR=`(function () {
334
334
  document.addEventListener("click", function (event) {
335
335
  var link = event.target && event.target.closest ? event.target.closest("a[href]") : null;
336
336
  if (!link || event.defaultPrevented) return;
@@ -355,27 +355,27 @@ l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
355
355
  }
356
356
  if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return;
357
357
  event.preventDefault();
358
- parent.postMessage({ type: "${ER}", href: href }, "*");
358
+ parent.postMessage({ type: "${AR}", href: href }, "*");
359
359
  }, true);
360
- })();`;function AR(e){if(e==null)return!1;let t=e.trim();return t!==``&&!t.startsWith(`#`)&&!ne(t)}function jR(e,t){return OR[e.split(`.`).pop()?.toLowerCase()??``]??t}function MR(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result).replace(/^data:[^;,]*/,`data:${t}`)),i.onerror=()=>r(i.error),i.readAsDataURL(e)})}async function NR(e,t,n){let r=new DOMParser().parseFromString(e,`text/html`),i=new Map,a=e=>{let t=i.get(e);return t===void 0&&(t=n(e).catch(()=>void 0),i.set(e,t)),t},o=async e=>(await a(e))?.text(),s=async e=>{let t=await a(e);return t===void 0?void 0:MR(t,jR(e,t.type||`application/octet-stream`))},c=async(e,t,n=0)=>{let r=[...e.matchAll(/@import\s+(?:url\(\s*(['"]?)([^'")]+)\1\s*\)|(['"])([^'"]+)\3)[^;]*;/gi)];for(let i of r){let r=i[2]??i[4];if(!AR(r)||n>=DR)continue;let a=re(t,r),s=await o(a);s!==void 0&&(e=e.replace(i[0],await c(s,a,n+1)))}let i=/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,a=new Map;for(let n of new Set([...e.matchAll(i)].map(e=>e[2]))){if(!AR(n))continue;let e=await s(re(t,n));e!==void 0&&a.set(n,e)}return e.replace(i,(e,t,n)=>a.has(n)?`url("${a.get(n)}")`:e)},l=Array.from(r.querySelectorAll(`style`));for(let e of Array.from(r.querySelectorAll(`link[href]`))){let n=(e.getAttribute(`rel`)??``).toLowerCase().split(/\s+/),i=e.getAttribute(`href`);if(!AR(i))continue;let a=re(t,i);if(n.includes(`stylesheet`)){let t=await o(a);if(t===void 0)continue;let n=r.createElement(`style`),i=e.getAttribute(`media`);i!==null&&n.setAttribute(`media`,i),n.textContent=await c(t,a),e.replaceWith(n)}else if(n.includes(`icon`)){let t=await s(a);t!==void 0&&e.setAttribute(`href`,t)}}for(let e of l)e.textContent=await c(e.textContent??``,t);for(let e of Array.from(r.querySelectorAll(`[style]`)))e.setAttribute(`style`,await c(e.getAttribute(`style`)??``,t));for(let e of Array.from(r.querySelectorAll(`script[src]`))){let n=e.getAttribute(`src`);if(!AR(n))continue;let r=await o(re(t,n));r!==void 0&&(e.removeAttribute(`src`),e.textContent=r.replace(/<\/script/gi,`<\\/script`))}for(let[e,n]of[[`img`,`src`],[`source`,`src`],[`video`,`src`],[`video`,`poster`],[`audio`,`src`],[`track`,`src`],[`input`,`src`],[`image`,`href`],[`image`,`xlink:href`],[`use`,`href`]])for(let i of Array.from(r.getElementsByTagName(e))){let e=i.getAttribute(n);if(!AR(e))continue;let r=await s(re(t,e));r!==void 0&&i.setAttribute(n,r)}for(let e of Array.from(r.querySelectorAll(`img[srcset], source[srcset]`))){let n=(e.getAttribute(`srcset`)??``).split(`,`).map(e=>e.trim()).filter(Boolean),r=[];for(let e of n){let[n,...i]=e.split(/\s+/),a=AR(n)?await s(re(t,n)):void 0;r.push([a??n,...i].join(` `))}e.setAttribute(`srcset`,r.join(`, `))}let u=r.createElement(`script`);return u.textContent=kR,r.head.prepend(u),`<!doctype html>\n${r.documentElement.outerHTML}`}var PR=`allow-scripts allow-popups allow-popups-to-escape-sandbox`;function FR({source:e,path:t,load:n,onOpen:r}){let i=(0,d.useRef)(null),[a,o]=(0,d.useState)(null);return(0,d.useEffect)(()=>{let r=!0;return NR(e,t,n).then(e=>{r&&o(e)},()=>{r&&o(e)}),()=>{r=!1}},[e,t,n]),(0,d.useEffect)(()=>{function e(e){if(i.current===null||e.source!==i.current.contentWindow)return;let n=e.data;typeof n==`object`&&n&&n.type===`pi-outpost:open`&&typeof n.href==`string`&&r(re(t,n.href))}return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[t,r]),a===null?(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-500`,"data-testid":`html-page-loading`,children:`Loading…`}):(0,A.jsx)(`iframe`,{ref:i,title:t,"data-testid":`html-page`,sandbox:PR,srcDoc:a,className:`h-full min-h-[24rem] w-full border-0 bg-white`})}function IR({query:e,onQueryChange:t,matchCount:n,truncated:r=!1,currentIndex:i,searching:a=!1,onNext:o,onPrev:s,onClose:c,inputRef:l}){let u=(0,d.useRef)(null),f=l??u;(0,d.useEffect)(()=>{f.current?.focus(),f.current?.select()},[]);let p=n===0?a?`searching…`:`0/0`:`${i+1}/${n}${r?`+`:``}`;return(0,A.jsxs)(`div`,{role:`search`,"aria-label":`Find in file`,className:`flex items-center gap-2 border-b border-zinc-200 bg-zinc-50 px-3 py-1.5 text-xs dark:border-zinc-800 dark:bg-zinc-900`,children:[(0,A.jsx)(`input`,{ref:f,type:`text`,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.shiftKey?s():o()):e.key===`Escape`&&(e.stopPropagation(),c())},placeholder:`Find in file`,"aria-label":`Find`,className:`min-w-0 flex-1 rounded border border-zinc-300 bg-white px-2 py-1 text-xs text-zinc-700 outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-200`}),(0,A.jsx)(`span`,{className:`shrink-0 tabular-nums text-zinc-500 dark:text-zinc-400`,children:p}),(0,A.jsx)(`button`,{type:`button`,onClick:s,disabled:n===0,"aria-label":`Previous match`,title:`Previous match (Shift+Enter)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 disabled:opacity-40 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`‹`}),(0,A.jsx)(`button`,{type:`button`,onClick:o,disabled:n===0,"aria-label":`Next match`,title:`Next match (Enter)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 disabled:opacity-40 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`›`}),(0,A.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close find bar`,title:`Close (Esc)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`✕`})]})}var LR=3e3;function RR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function zR(e,t,n=1/0){if(t===``)return[];let r=new RegExp(RR(t),`gi`),i=[],a;for(;(a=r.exec(e))!==null&&(i.push({start:a.index,end:a.index+a[0].length}),!(i.length>=n)););return i}function BR(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[],r=``;for(let e=t.nextNode();e!==null;e=t.nextNode()){let t=e.data.length;t!==0&&(n.push({node:e,start:r.length,end:r.length+t}),r+=e.data)}return{nodes:n,text:r}}function VR(e,t,n=LR){let r={matches:[],truncated:!1,clear:()=>{}};if(t===``)return r;let{nodes:i,text:a}=BR(e);if(a===``)return r;let o=zR(a,t,n+1),s=o.length>n,c=s?o.slice(0,n):o;if(c.length===0)return{matches:[],truncated:s,clear:()=>{}};let l=Array(c.length);for(let e=c.length-1;e>=0;e--){let{start:t,end:n}=c[e],r=[];for(let e of i){if(e.end<=t||e.start>=n)continue;let i=Math.max(0,t-e.start),a=Math.min(e.node.data.length,n-e.start);if(i>=a)continue;let o=e.node;a<o.data.length&&o.splitText(a);let s=i>0?o.splitText(i):o,c=document.createElement(`mark`);c.className=`find-match`,s.replaceWith(c),c.appendChild(s),r.push(c)}l[e]={marks:r}}return{matches:l,truncated:s,clear:()=>{for(let{marks:e}of l)for(let t of e)t.replaceWith(document.createTextNode(t.textContent??``));e.normalize()}}}var HR=(0,d.lazy)(()=>me(()=>import(`./PdfViewer-CvlaA88J.js`),[])),UR=250,WR=`(min-width: 768px)`;function GR(){let[e,t]=(0,d.useState)(()=>window.matchMedia?.(WR).matches??!0);return(0,d.useEffect)(()=>{let e=window.matchMedia?.(WR);if(e===void 0)return;let n=()=>t(e.matches);return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[]),e}function KR(e,t){let[n,r]=(0,d.useState)(e);return(0,d.useEffect)(()=>{let n=window.setTimeout(()=>r(e),t);return()=>window.clearTimeout(n)},[e,t]),n}function qR(e){let t=_u(e);return t.status===`valid`?t.envelope:void 0}var JR=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`;function YR(e){return/\.(md|markdown)$/i.test(e)}function XR(e){return/\.html?$/i.test(e)}function ZR(e,t){return t===void 0?!0:t===null?!1:t===``||e===t||e.startsWith(`${t}/`)}function QR({file:e,writableRoot:t,isStreaming:n,onDirtyChange:r,gitState:i,initialShowGitDiff:a=!1,gitDiff:o,gitBaseline:s=null,onFetchGitDiff:c,onClearGitDiff:l,inRepository:u,onOpenGitHistory:f,onClose:p,onReload:m,onSave:h,serverUrl:g=``,token:_=null,workspace:v,docxTemplate:y,onImageLoad:b,onPdfLoad:x,rawRevision:C=0}){let[w,T]=(0,d.useState)(`rendered`),[ee,te]=(0,d.useState)(null),[D,ne]=(0,d.useState)(a),[k,oe]=(0,d.useState)(e.status===`loaded`&&e.justCreated?{draft:e.content,baseContent:e.content,baseMtimeMs:e.mtimeMs}:null),[se,ce]=(0,d.useState)(`idle`),ue=(0,d.useRef)(null),de=(0,d.useRef)(null),j=e.status===`loaded`?e:null,fe=j!==null&&YR(e.path),pe=j!==null&&XR(e.path),me=ie(e.path),he=O(e.path),ge=(0,d.useMemo)(()=>j===null?void 0:_u(j.content),[j?.content]),_e=ge?.status===`valid`,ve=ge?.status===`valid`||ge?.status===`invalid`,ye=ve||fe||pe,xe=w===`source`,Se=GR(),Ce=ZR(e.path,t)&&!he,we=j!==null&&!me&&!he;(0,d.useEffect)(()=>{we&&CR().catch(()=>{})},[we]);let Te=k!==null&&k.draft!==k.baseContent,Ee=j?.pendingSave!==void 0,De=k!==null&&j!==null&&j.mtimeMs!==k.baseMtimeMs,Oe=j?.saveError?.conflict===!0||De,ke=k?.draft??j?.content??``,Ae=KR(ke,UR),je=(0,d.useMemo)(()=>j===null?void 0:_u(Ae),[Ae,j===null]),[Me,Ne]=(0,d.useState)(()=>e.status===`loaded`?qR(e.content):void 0);(0,d.useEffect)(()=>{je?.status===`valid`&&Ne(je.envelope)},[je]);let Pe=je!==void 0&&je.status!==`valid`&&Me!==void 0,Fe=je?.status===`invalid`?Ae===j?.content&&j.documentIssues!==void 0?j.documentIssues:je.issues:void 0,Ie=je?.status===`not-a-document`?je.why===`unparseable`?`This is not parseable JSON yet.`:"This no longer declares a structured-exchange `schema`.":je?.status===`unsupported-version`?`This declares ${je.schema}, which this version does not render.`:void 0,Le=w===`split`&&ye&&!D&&j!==null&&Se,Re=D?void 0:Le?ve?Me:void 0:k===null&&!xe&&ge?.status===`valid`?ge.envelope:void 0,ze=(0,d.useRef)(null),Be=k!==null,Ve=j!==null&&k===null&&!Le&&!D&&(!fe||xe)&&(!_e||xe)&&(!pe||xe),He=D||Le?`none`:he?`pdf`:k!==null||Ve?`text`:j!==null&&!me?`dom`:`none`,[We,Ge]=(0,d.useState)(!1),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(0),Ze=(0,d.useRef)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(null),[et,tt]=(0,d.useState)({matchCount:0,currentIndex:-1,searching:!1}),[nt,rt]=(0,d.useState)([]),[it,at]=(0,d.useState)(!1),ot=(0,d.useRef)(null),st=(0,d.useRef)([]),ct=(0,d.useRef)(0),lt=(0,d.useRef)(``);function ut(e){ct.current=e;for(let[t,n]of st.current.entries())for(let r of n.marks)r.isConnected&&r.classList.toggle(`find-match-current`,t===e);let t=st.current[e]?.marks;t?.[0]?.isConnected&&t[0].scrollIntoView({block:`center`})}let dt=We?qe:``,ft=(0,d.useMemo)(()=>He===`text`?zR(ke,dt):[],[He,ke,dt]);(0,d.useEffect)(()=>{We&&He===`none`&&Ge(!1)},[We,He]),(0,d.useEffect)(()=>{function e(){ot.current?.clear(),ot.current=null,st.current=[],rt([]),at(!1)}let t=Qe.current;if(He!==`dom`||dt===``||t===null){e();return}ot.current?.clear();let n=VR(t,dt);ot.current=n,st.current=n.matches,rt(n.matches),at(n.truncated);let r=dt!==lt.current;lt.current=dt;let i=r?0:Math.min(ct.current,Math.max(n.matches.length-1,0));return Xe(i),ut(i),e},[He,dt,w,xe]);function pt(e,t){let n=e[t];n!==void 0&&ue.current?.select(n.start,n.end)}(0,d.useEffect)(()=>{if(He!==`text`||!We)return;let e=zR(ke,dt),t=dt!==lt.current;lt.current=dt;let n=t?0:Math.min(Ye,Math.max(e.length-1,0));Xe(n),e.length>0&&pt(e,n)},[dt,He,We,Be]),(0,d.useEffect)(()=>{ue.current?.markMatches(He===`text`?ft:[],Ye)},[He,ft,Ye,Be]);function mt(){Ge(!0)}function ht(){Ge(!1)}function gt(){if(He===`pdf`)$e.current?.findNext();else if(He===`text`){if(ft.length===0)return;let e=(Ye+1)%ft.length;Xe(e),pt(ft,e)}else{let e=st.current.length;if(e===0)return;let t=(ct.current+1)%e;Xe(t),ut(t)}}function _t(){if(He===`pdf`)$e.current?.findPrevious();else if(He===`text`){if(ft.length===0)return;let e=(Ye-1+ft.length)%ft.length;Xe(e),pt(ft,e)}else{let e=st.current.length;if(e===0)return;let t=(ct.current-1+e)%e;Xe(t),ut(t)}}let vt=He===`pdf`?{matchCount:et.matchCount,currentIndex:et.currentIndex,truncated:!1,searching:et.searching}:He===`text`?{matchCount:ft.length,currentIndex:ft.length>0?Math.min(Ye,ft.length-1):-1,truncated:!1,searching:!1}:{matchCount:nt.length,currentIndex:nt.length>0?Math.min(Ye,nt.length-1):-1,truncated:it,searching:!1},yt=k===null?null:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading editor…`}),children:(0,A.jsx)(wR,{handle:ue,path:e.path,value:k.draft,baseline:s,onChange:e=>oe(t=>t===null?t:{...t,draft:e}),onSave:()=>{Te&&!Ee&&!Oe&&Dt()}})},`editor`);function bt(t){return j===null?null:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4`,children:(0,A.jsx)(be,{code:j.content,path:e.path})}),children:(0,A.jsx)(wR,{readOnly:!0,handle:t?ue:void 0,path:e.path,value:j.content,baseline:s})},`source`)}let xt=(0,d.useCallback)(e=>fetch(ae(g,e,_,void 0,v)).then(e=>e.ok?e.blob():void 0,()=>void 0),[g,_,v]);function St(t){return(0,A.jsx)(`div`,{className:`prose-chat mx-auto max-w-3xl p-4 text-zinc-700 dark:text-zinc-300`,children:(0,A.jsx)(Py,{remarkPlugins:[xF,NF],rehypePlugins:[eD],components:{pre:Ue,a:({href:t,children:n,...r})=>!t||/^[a-z][a-z0-9+.-]*:/i.test(t)?(0,A.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,...r,children:n}):t.startsWith(`#`)?(0,A.jsx)(`a`,{href:t,...r,children:n}):(0,A.jsx)(`a`,{href:t,onClick:n=>{n.preventDefault(),m(re(e.path,t))},...r,children:n}),img:({src:t,alt:n,...r})=>{let i=typeof t==`string`&&t!==``&&!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!t.startsWith(`//`)?ae(g,re(e.path,t),_,void 0,v):t;return(0,A.jsx)(`img`,{...r,src:i,alt:n??``,loading:`lazy`,className:`max-w-full rounded-lg`})}},children:E(t)})})}function Ct(e){(w!==`split`||e===`split`||!Te||window.confirm(`Discard unsaved changes?`))&&(w===`split`&&e!==`split`&&oe(null),te(null),T(e))}function wt(){(!Te||window.confirm(`Discard unsaved changes?`))&&p()}function Tt(){j&&(ye&&w===`rendered`&&(te(`rendered`),T(Se?`split`:`source`)),oe({draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs}))}function Et(){ee===null?oe(Le&&j!==null?{draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs}:null):(oe(null),T(ee),te(null))}function Dt(t=!1){j&&k!==null&&!Ee&&(de.current=k.draft,h(e.path,k.draft,k.baseMtimeMs,t))}function Ot(){oe(null),m(e.path)}function kt(){let t=!D;ne(t),t?c(e.path):l()}return(0,d.useEffect)(()=>{k!==null&&j!==null&&de.current!==null&&j.content===de.current&&j.mtimeMs!==k.baseMtimeMs&&(de.current=null,oe({...k,baseContent:j.content,baseMtimeMs:j.mtimeMs}))},[j?.mtimeMs]),(0,d.useEffect)(()=>{function e(e){if(e.key===`Escape`)We?ht():wt();else if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`f`){if(He===`none`)return;e.preventDefault(),mt()}}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)}),(0,d.useEffect)(()=>{Le&&Ce&&k===null&&j!==null&&oe({draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs})},[Le,Ce,j?.mtimeMs]),(0,d.useEffect)(()=>{ce(n?`streaming`:e=>e===`streaming`?`done`:e)},[n]),(0,d.useEffect)(()=>(r(Te),()=>r(!1)),[Te]),(0,d.useEffect)(()=>(a&&c(e.path),()=>l()),[]),(0,A.jsxs)(`div`,{className:`absolute inset-0 z-20 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[ye&&!D&&(0,A.jsx)(`div`,{className:`flex shrink-0 items-center gap-0.5`,role:`group`,"aria-label":`How to show this document`,children:[[`rendered`,`⚏ rendered`,`Show the rendering`],[`split`,`⇹ split`,`Edit the file beside its rendering`],[`source`,`⌗ source`,`Show the file as written`]].map(([e,t,n])=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>Ct(e),"aria-pressed":w===e,title:n,className:`rounded px-1.5 py-0.5 text-xs ${w===e?`bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-200`:`text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`}`,children:t},e))}),i!==void 0&&k===null&&(0,A.jsx)(`button`,{type:`button`,onClick:kt,"aria-pressed":D,title:D?`Show file content`:`Show uncommitted changes (vs HEAD)`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs ${D?`bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300`:`text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`}`,children:`± diff`}),u&&k===null&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>f(e.path),title:`Show this file's history`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`,children:`⎇ history`}),(0,A.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-zinc-500 dark:text-zinc-400`,title:e.path,children:[e.path,Te&&(0,A.jsx)(`span`,{className:`ml-1 text-amber-500`,children:`●`})]}),j&&!me&&!he&&!D&&!ve&&(0,A.jsx)(TR,{text:ke,path:e.path,serverUrl:g,token:_,workspace:v,template:y}),Re?.kind===`table`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(TR,{text:()=>ze.current?.markdown?.()??``,path:`${e.path.replace(/\.[^./]*$/,``)}.md`,serverUrl:g,token:_,workspace:v,template:y}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>ze.current?.xlsx?.(),title:`Download as an Excel workbook`,"aria-label":`Download as an Excel workbook`,className:JR,children:`⤓ excel`})]}),(Re?.kind===`graph`||Re?.kind===`sequence`||Re?.kind===`timeline`)&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>ze.current?.svg?.(),title:`Download the figure as SVG`,"aria-label":`Download the figure as SVG`,className:JR,children:`⤓ svg`}),j&&k===null&&(0,A.jsx)(le,{text:j.content}),j&&k===null&&!D&&Ce&&(0,A.jsx)(`button`,{type:`button`,onClick:Tt,className:`shrink-0 rounded border border-zinc-300 px-2 py-0.5 text-xs text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-700 dark:text-zinc-400 dark:hover:border-zinc-500 dark:hover:text-zinc-200`,children:`✎ edit`}),j&&k===null&&!Ce&&(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,title:`Outside the writable zone`,children:`🔒 read-only`}),k!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>Dt(),disabled:!Te||Ee||Oe,className:`shrink-0 rounded border border-emerald-300 px-2 py-0.5 text-xs text-emerald-700 hover:border-emerald-500 disabled:opacity-50 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600`,children:Ee?`saving…`:`save`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{(!Te||window.confirm(`Discard unsaved changes?`))&&Et()},className:`shrink-0 rounded border border-zinc-300 px-2 py-0.5 text-xs text-zinc-500 hover:border-zinc-400 dark:border-zinc-700 dark:text-zinc-400 dark:hover:border-zinc-500`,children:Te?`cancel`:`done`})]}),(0,A.jsx)(`button`,{type:`button`,onClick:wt,title:`Close (Esc)`,"aria-label":`Close file viewer`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),We&&He!==`none`&&(0,A.jsx)(IR,{inputRef:Ze,query:qe,onQueryChange:Je,matchCount:vt.matchCount,currentIndex:vt.currentIndex,truncated:vt.truncated,searching:vt.searching,onNext:gt,onPrev:_t,onClose:ht}),Oe&&k!==null&&(0,A.jsxs)(`div`,{className:`flex items-center gap-3 border-b border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1`,children:`File changed on disk since you started editing.`}),(0,A.jsx)(`button`,{type:`button`,onClick:Ot,className:`shrink-0 rounded border border-amber-400 px-2 py-0.5 text-xs hover:bg-amber-100 dark:border-amber-800 dark:hover:bg-amber-950/60`,children:`reload (discard my edits)`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>Dt(!0),disabled:Ee,className:`shrink-0 rounded border border-amber-400 px-2 py-0.5 text-xs hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:hover:bg-amber-950/60`,children:`overwrite with my version`})]}),k!==null&&j?.saveError&&!j.saveError.conflict&&(0,A.jsx)(`div`,{className:`border-b border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:j.saveError.message}),(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[D&&k===null&&(0,A.jsxs)(`div`,{className:`p-4`,children:[o?.path===e.path&&`error`in o&&(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:o.error}),o?.path===e.path&&`before`in o&&(0,A.jsx)(Ke,{fill:!0,lines:S(o.before,o.after)}),o?.path!==e.path&&(0,A.jsx)(`div`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`loading diff…`})]}),he&&k===null&&!D&&(0,A.jsx)(Vf,{label:`This PDF`,children:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading…`}),children:(0,A.jsx)(HR,{ref:$e,path:e.path,serverUrl:g,token:_,workspace:v,revision:C,findQuery:He===`pdf`?dt:``,onFindStateChange:tt,...x?{onLoaded:x}:{}})})}),me&&k===null&&!D&&(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center p-4`,children:(0,A.jsx)(`img`,{src:ae(g,e.path,_,C,v),alt:e.path,onLoad:()=>b(e.path),className:`max-h-full max-w-full rounded object-contain`})}),e.status===`loading`&&k===null&&!D&&!me&&!he&&(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading…`}),e.status===`error`&&!me&&!he&&(0,A.jsx)(`div`,{className:`p-4 text-sm text-red-600 dark:text-red-400`,children:e.message}),k!==null&&!Le&&yt,j&&k===null&&!Le&&!D&&fe&&!xe&&(0,A.jsx)(`div`,{ref:Qe,children:St(j.content)}),j&&k===null&&!Le&&!D&&pe&&!xe&&(0,A.jsx)(`div`,{className:`h-full`,"data-testid":`file-html`,children:(0,A.jsx)(FR,{source:j.content,path:e.path,load:xt,onOpen:m})}),Le&&(0,A.jsxs)(`div`,{className:`flex h-full min-h-0`,"data-testid":`file-split`,children:[(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto border-r border-zinc-200 dark:border-zinc-800`,children:yt??bt(!1)}),(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto`,"data-testid":`file-split-rendering`,children:fe&&!ve?(0,A.jsx)(`div`,{className:`prose-chat p-4 text-zinc-700 dark:text-zinc-300`,children:St(Ae)}):pe&&!ve?(0,A.jsx)(FR,{source:Ae,path:e.path,load:xt,onOpen:m}):(0,A.jsxs)(A.Fragment,{children:[Pe&&(0,A.jsx)(`p`,{"data-testid":`file-split-stale`,className:`flex flex-wrap items-center gap-2 border-b border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200`,children:(0,A.jsxs)(`span`,{children:[`Showing the document as it last stood.`,` `,Ie??`The text beside it does not satisfy the schema it declares.`]})}),Fe!==void 0&&(0,A.jsxs)(`ul`,{"data-testid":`file-split-issues`,className:`space-y-0.5 border-b border-zinc-200 px-3 py-1.5 text-xs text-zinc-500 dark:border-zinc-800 dark:text-zinc-400`,children:[Fe.slice(0,6).map((e,t)=>(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`font-mono opacity-70`,children:e.path===``?`(document)`:e.path}),` `,e.message]},t)),Fe.length>6&&(0,A.jsxs)(`li`,{className:`opacity-70`,children:[`…and `,Fe.length-6,` more`]})]}),Me===void 0?(0,A.jsxs)(`p`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,"data-testid":`file-split-nothing`,children:[`Nothing to draw yet. `,Ie??`This document does not satisfy the schema it declares.`]}):(0,A.jsx)(Vf,{label:`This diagram`,children:(0,A.jsx)(`div`,{className:`p-4`,"data-testid":`file-structured-exchange`,children:(0,A.jsx)(Rf,{envelope:Me,source:ke,exportRef:ze})})})]})})]}),j&&k===null&&!Le&&!D&&_e&&!xe&&ge?.status===`valid`&&(0,A.jsx)(Vf,{label:`This diagram`,children:(0,A.jsx)(`div`,{className:`mx-auto max-w-5xl p-4`,"data-testid":`file-structured-exchange`,children:(0,A.jsx)(Rf,{envelope:ge.envelope,source:j.content,exportRef:ze})})}),j&&k===null&&!Le&&!D&&ge?.status===`invalid`&&(0,A.jsxs)(`div`,{"data-testid":`file-structured-exchange-invalid`,className:`mx-4 mt-4 rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200`,children:[(0,A.jsx)(`p`,{className:`font-medium`,children:`This declares a structured-exchange document and does not satisfy the schema.`}),(0,A.jsxs)(`ul`,{className:`mt-1 space-y-0.5 text-xs`,children:[(j.documentIssues??ge.issues).slice(0,8).map((e,t)=>(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`font-mono opacity-70`,children:e.path===``?`(document)`:e.path}),` `,e.message]},t)),(j.documentIssues??ge.issues).length>8&&(0,A.jsxs)(`li`,{className:`opacity-70`,children:[`…and `,(j.documentIssues??ge.issues).length-8,` more`]})]})]}),j&&k===null&&!Le&&!D&&ge?.status===`unsupported-version`&&(0,A.jsxs)(`div`,{"data-testid":`file-structured-exchange-unsupported`,className:`mx-4 mt-4 rounded-lg border border-zinc-300 bg-zinc-50 px-3 py-2 text-sm text-zinc-600 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-400`,children:[`This document declares `,(0,A.jsx)(`span`,{className:`font-mono`,children:ge.schema}),`, which this version does not render. Shown as text.`]}),Ve&&bt(!0)]}),se!==`idle`&&(0,A.jsxs)(`button`,{type:`button`,onClick:wt,"aria-live":`polite`,className:`flex items-center gap-2 border-t border-zinc-200 px-3 py-2 text-left text-sm hover:bg-zinc-50 dark:border-zinc-800 dark:hover:bg-zinc-900`,children:[se===`streaming`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`h-2 w-2 animate-pulse motion-reduce:animate-none rounded-full bg-amber-500`}),(0,A.jsx)(`span`,{className:`text-amber-700 dark:text-amber-400`,children:`π is replying…`})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`h-2 w-2 rounded-full bg-emerald-500`}),(0,A.jsx)(`span`,{className:`text-emerald-700 dark:text-emerald-400`,children:`π replied`})]}),(0,A.jsx)(`span`,{className:`ml-auto text-xs text-zinc-400 dark:text-zinc-500`,children:`show conversation →`})]})]})}function $R(e){return e.split(`
361
- `).map(e=>e.startsWith(`diff --git `)?{kind:`file`,text:e.slice(11)}:e.startsWith(`@@`)||e.startsWith(`+++`)||e.startsWith(`---`)||e.startsWith(`index `)?{kind:`hunk`,text:e}:e.startsWith(`+`)?{kind:`add`,text:e.slice(1)}:e.startsWith(`-`)?{kind:`del`,text:e.slice(1)}:{kind:`context`,text:e.startsWith(` `)?e.slice(1):e})}function ez({show:e,onClose:t}){return(0,d.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopImmediatePropagation(),t())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[t]),(0,A.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`span`,{className:`font-mono text-xs text-amber-600 dark:text-amber-500`,children:e.sha.slice(0,12)}),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-500 dark:text-zinc-400`,children:`commit diff`}),(0,A.jsx)(`button`,{type:`button`,onClick:t,title:`Close (Esc)`,"aria-label":`Close commit diff`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),e.truncated&&(0,A.jsx)(`div`,{className:`border-b border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:`Patch truncated — showing the first 256 KiB.`}),(0,A.jsx)(`pre`,{className:`min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed`,children:$R(e.patch).map((e,t)=>(0,A.jsxs)(`div`,{className:e.kind===`file`?`mt-3 border-t border-zinc-200 pt-2 font-bold text-zinc-700 first:mt-0 first:border-t-0 first:pt-0 dark:border-zinc-800 dark:text-zinc-200`:e.kind===`hunk`?`text-sky-600 dark:text-sky-400`:e.kind===`add`?`bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:e.kind===`del`?`bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`text-zinc-500 dark:text-zinc-500`,children:[e.kind===`add`?`+ `:e.kind===`del`?`− `:``,e.text||` `]},t))})]})}var tz=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`],nz=`worktree`,rz={defaultWidth:288,minWidth:224,maxWidth:640,keyboardStep:16,storageKey:`pi-outpost.files-sidebar-width.v1`},iz={defaultWidth:416,minWidth:224,maxWidth:640,keyboardStep:16,storageKey:`pi-outpost.history-list-width.v1`};function az(e,t){return Number.isFinite(e)?Math.min(t.maxWidth,Math.max(t.minWidth,Math.round(e))):t.defaultWidth}function oz(e,t){return e===null||e.trim()===``?t.defaultWidth:az(Number(e),t)}function sz(e,t){try{return oz((t??window.localStorage).getItem(e.storageKey),e)}catch{return e.defaultWidth}}function cz(e,t,n){try{(n??window.localStorage).setItem(t.storageKey,String(az(e,t)))}catch{}}function lz(e){let[t,n]=(0,d.useState)(()=>sz(e)),r=(0,d.useRef)(t),i=(0,d.useRef)(null),a=(0,d.useCallback)(t=>{let i=az(t,e);return r.current=i,n(i),i},[e]),o=(0,d.useCallback)(()=>{i.current!==null&&(i.current=null,cz(r.current,e))},[e]);return{width:t,separatorProps:{onPointerDown:e=>{e.isPrimary!==!1&&(e.button??0)===0&&(e.preventDefault(),e.currentTarget.setPointerCapture?.(e.pointerId),i.current={pointerId:e.pointerId,startX:e.clientX,startWidth:r.current})},onPointerMove:e=>{let t=i.current;t!==null&&t.pointerId===e.pointerId&&a(t.startWidth+e.clientX-t.startX)},onPointerUp:e=>{i.current?.pointerId===e.pointerId&&o()},onPointerCancel:e=>{let t=i.current;t!==null&&t.pointerId===e.pointerId&&(i.current=null,a(t.startWidth))},onLostPointerCapture:o,onKeyDown:t=>{let n=null;t.key===`ArrowLeft`?n=r.current-e.keyboardStep:t.key===`ArrowRight`?n=r.current+e.keyboardStep:t.key===`Home`&&(n=e.defaultWidth),n!==null&&(t.preventDefault(),cz(a(n),e))}}}}function uz({label:e,width:t,config:n,separatorProps:r,className:i=``}){return(0,A.jsx)(`div`,{...r,role:`separator`,"aria-label":e,"aria-orientation":`vertical`,"aria-valuemin":n.minWidth,"aria-valuemax":n.maxWidth,"aria-valuenow":t,tabIndex:0,title:e,className:`group absolute inset-y-0 -right-1 z-20 w-2 cursor-col-resize touch-none outline-none ${i}`,children:(0,A.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 left-1/2 w-px bg-transparent transition-colors group-hover:bg-blue-400 group-focus-visible:bg-blue-500 group-active:bg-blue-500 dark:group-hover:bg-blue-500`})})}var dz=`#10b981`,fz=[`#8b5cf6`,`#f59e0b`,`#0ea5e9`,`#f43f5e`,`#14b8a6`,`#d946ef`];function pz(e){return e===0?dz:fz[(e-1)%fz.length]}function mz(e){return fz[e%fz.length]}function hz(e){return e*14+7+1}function gz(e){return e*14+2}function _z({row:e,laneCount:t,colorOf:n=pz}){let r=gz(t),i=hz(e.lane),a=e.highlight?dz:n(e.lane),o=e.dashed?`3 3`:void 0;return(0,A.jsxs)(`svg`,{width:r,height:36,viewBox:`0 0 ${r} 36`,"aria-hidden":!0,className:`shrink-0`,children:[e.through.map(e=>(0,A.jsx)(`line`,{x1:hz(e),y1:0,x2:hz(e),y2:36,stroke:n(e),strokeWidth:2,opacity:.55},e)),e.lineAbove&&(0,A.jsx)(`line`,{x1:i,y1:0,x2:i,y2:18,stroke:a,strokeWidth:2,strokeDasharray:o}),e.lineBelow&&(0,A.jsx)(`line`,{x1:i,y1:18,x2:i,y2:36,stroke:a,strokeWidth:2,strokeDasharray:o}),e.forkTo.map(e=>(0,A.jsx)(`path`,{d:`M ${i} 18 C ${i} 36, ${hz(e)} 18, ${hz(e)} 36`,fill:`none`,stroke:n(e),strokeWidth:2,opacity:.75},`fork-${e}`)),(e.mergeFrom??[]).map(e=>(0,A.jsx)(`path`,{d:`M ${i} 18 C ${i} 0, ${hz(e)} 18, ${hz(e)} 0`,fill:`none`,stroke:n(e),strokeWidth:2,opacity:.75},`merge-${e}`)),e.emphasis===`current`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`circle`,{cx:i,cy:18,r:6,fill:`none`,stroke:a,strokeWidth:2}),(0,A.jsx)(`circle`,{cx:i,cy:18,r:2.5,fill:a})]}):(0,A.jsx)(`circle`,{cx:i,cy:18,r:4,fill:e.emphasis===`filled`?a:`var(--tree-off, #d4d4d8)`,stroke:a,strokeWidth:e.emphasis===`filled`?0:1.5})]})}function vz(e,t={}){let n=[],r=[],i=0,a=()=>{let e=r.indexOf(null);return e===-1?(r.push(null),i=Math.max(i,r.length),r.length-1):e};for(let t of e){let e=r.reduce((e,n,r)=>n===t.sha?[...e,r]:e,[]),o=e[0]??a(),s=e.slice(1);for(let e of s)r[e]=null;i=Math.max(i,o+1);let[c,...l]=t.parents;r[o]=c??null;let u=l.map(e=>{let t=a();return r[t]=e,t});n.push({rev:t.sha,path:t.path,entry:t,lane:o,through:r.reduce((e,t,n)=>t!==null&&n!==o&&!u.includes(n)?[...e,n]:e,[]),forkTo:u,mergeFrom:s,lineAbove:!0,lineBelow:t.parents.length>0,emphasis:`filled`})}let o=n[0];return n.unshift({rev:nz,path:o?.path??``,lane:o?.lane??0,through:o?.through??[],forkTo:[],mergeFrom:[],lineAbove:!1,lineBelow:n.length>0,emphasis:`current`,dashed:!t.dirty}),n[1]&&(n[1].lineAbove=!0),{rows:n,laneCount:Math.max(i,1)}}var yz=20;function bz(e){let t=(Date.now()-new Date(e).getTime())/1e3;return t<90?`now`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function xz(e){return e.rev===`worktree`?`working tree`:e.rev.slice(0,7)}function Sz(e,t){return e!==null&&t!==null&&e.rev===t.rev&&e.path===t.path}function Cz(e){return{rev:e.rev,path:e.path}}function wz({history:e,diff:t,dirty:n,onFetchDiff:r,onClearDiff:i,onClose:a}){let[o,s]=(0,d.useState)({base:null,target:null}),{base:c,target:l}=o,[u,f]=(0,d.useState)(0),p=(0,d.useRef)([]),m=lz(iz),{rows:h,laneCount:g}=(0,d.useMemo)(()=>vz(e.entries,{dirty:n}),[e.entries,n]),_=(0,d.useRef)({onFetchDiff:r,onClose:a});_.current={onFetchDiff:r,onClose:a},(0,d.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopImmediatePropagation(),_.current.onClose())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,d.useEffect)(()=>{c===null||l===null||Sz(c,l)||_.current.onFetchDiff(c,l)},[c,l]);let v=(0,d.useCallback)((e,t)=>{let n=Cz(e);s(r=>{if(t===`base`)return{base:n,target:Sz(n,r.target)?r.base:r.target};if(t===`target`)return{base:Sz(n,r.base)?r.target:r.base,target:n};if(r.base===null&&r.target===null){let t=e.entry?.parents[0],r=t===void 0?void 0:h.find(e=>e.rev===t);return{base:r?Cz(r):null,target:n}}return{base:Sz(n,r.base)?r.target:r.base,target:n}})},[h]),y=(0,d.useCallback)(()=>{s({base:null,target:null}),i()},[i]),b=(0,d.useCallback)(()=>s(e=>({base:e.target,target:e.base})),[]),x=(0,d.useCallback)(e=>{f(t=>{let n=Math.max(0,Math.min(h.length-1,t+e));return p.current[n]?.focus(),n})},[h.length]),S=e=>{let t=Cz(e);return Sz(t,c)?`base`:Sz(t,l)?`target`:null},C=h.findIndex(e=>Sz(Cz(e),c)),w=h.findIndex(e=>Sz(Cz(e),l)),T=C>=0&&w>=0?{top:Math.min(C,w)*36+18,height:Math.abs(w-C)*36}:null;return(0,A.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-zinc-500 dark:text-zinc-400`,title:e.path,children:e.path}),c!==null&&l!==null&&(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-zinc-500 dark:text-zinc-400`,"aria-label":`Comparing ${xz(c)} to ${xz(l)}`,children:[(0,A.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:xz(c)}),` → `,(0,A.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:xz(l)})]}),c!==null&&l!==null&&(0,A.jsx)(`button`,{type:`button`,onClick:b,title:`Compare the other way round`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`⇄ swap`}),(c!==null||l!==null)&&(0,A.jsx)(`button`,{type:`button`,onClick:y,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`clear`}),(0,A.jsx)(`button`,{type:`button`,onClick:a,title:`Close (Esc)`,"aria-label":`Close file history`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col md:flex-row`,children:[(0,A.jsxs)(`div`,{role:`region`,"aria-label":`Commit history`,style:{"--history-list-width":`${m.width}px`},className:`relative flex max-h-[40%] w-full shrink-0 flex-col border-b border-zinc-200 md:max-h-none md:w-[var(--history-list-width)] md:border-b-0 md:border-r dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),x(1)):e.key===`ArrowUp`&&(e.preventDefault(),x(-1))},children:[e.status===`loading`&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`Reading history…`}),e.status===`error`&&(0,A.jsx)(`div`,{className:`m-3 rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e.error}),e.status===`loaded`&&e.entries.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`No commits touch this file yet.`}),e.status===`loaded`&&e.entries.length>0&&(0,A.jsxs)(`div`,{className:`relative`,role:`group`,"aria-label":`Commits`,children:[T&&(0,A.jsx)(Tz,{top:T.top,height:T.height,baseFirst:C<w}),h.map((e,t)=>(0,A.jsx)(Oz,{ref:e=>{p.current[t]=e},row:e,laneCount:g,role:S(e),isFocused:t===u,onSelect:t=>v(e,t),onFocus:()=>f(t)},e.rev))]})]}),(0,A.jsx)(uz,{label:`Resize History commit list`,width:m.width,config:iz,separatorProps:m.separatorProps,className:`hidden md:block`})]}),(0,A.jsx)(`div`,{role:`region`,"aria-label":`History diff`,className:`min-h-0 min-w-0 flex-1 overflow-auto p-3`,children:(0,A.jsx)(kz,{diff:t,base:c,target:l})})]})]})}function Tz({top:e,height:t,baseFirst:n}){return(0,A.jsxs)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute left-0 z-10 motion-safe:transition-all motion-safe:duration-150 motion-safe:ease-out`,style:{top:e,height:t,width:yz},children:[(0,A.jsx)(`div`,{className:`absolute inset-y-0 left-2 w-px bg-zinc-400 dark:bg-zinc-500`}),(0,A.jsx)(Ez,{label:n?`base`:`target`,className:`top-0`}),(0,A.jsx)(Ez,{label:n?`target`:`base`,className:`bottom-0`})]})}function Ez({label:e,className:t}){return(0,A.jsx)(`div`,{className:`absolute left-2 flex h-px w-2.5 items-center bg-zinc-400 dark:bg-zinc-500 ${t}`,children:(0,A.jsx)(`span`,{className:`absolute -left-1 -top-1.5 rotate-180 text-[9px] leading-none text-zinc-500 [writing-mode:vertical-rl] dark:text-zinc-400`,children:e})})}var Dz=`shrink-0 rounded px-1 py-0.5 text-[10px] text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 aria-disabled:cursor-default aria-disabled:opacity-30 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`;function Oz({row:e,laneCount:t,role:n,isFocused:r,onSelect:i,onFocus:a,ref:o}){let s=e.entry,c=s?`${s.sha.slice(0,7)} ${s.subject}`:`Working tree`;return(0,A.jsxs)(`div`,{ref:o,role:`button`,tabIndex:r?0:-1,"aria-label":c,"aria-current":n===null?void 0:`true`,onFocus:a,onClick:()=>i(),onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `?(e.preventDefault(),i()):e.key===`b`?i(`base`):e.key===`t`&&i(`target`))},style:{height:36,paddingLeft:yz},className:`group flex cursor-pointer items-center gap-2 pr-2 focus:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800/70 ${n===null?``:`bg-zinc-100 dark:bg-zinc-800/60`}`,children:[(0,A.jsx)(_z,{row:e,laneCount:t}),s?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-amber-600 dark:text-amber-500`,children:s.sha.slice(0,7)}),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-700 dark:text-zinc-300`,title:s.subject,children:s.subject}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[10px] text-zinc-400 dark:text-zinc-600`,children:[s.author,` · `,bz(s.date)]}),(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums`,"aria-label":`${s.added} lines added, ${s.deleted} removed`,children:[(0,A.jsxs)(`span`,{className:`text-emerald-600 dark:text-emerald-500`,children:[`+`,s.added]}),` `,(0,A.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,s.deleted]})]})]}):(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-500 dark:text-zinc-400`,children:`working tree`}),(0,A.jsxs)(`span`,{className:`flex shrink-0 gap-0.5`,children:[(0,A.jsx)(`button`,{type:`button`,title:n===`target`?`Make this the base (swaps the two)`:`Compare from this version`,onClick:e=>{e.stopPropagation(),i(`base`)},className:Dz,children:`base`}),(0,A.jsx)(`button`,{type:`button`,title:n===`base`?`Make this the target (swaps the two)`:`Compare to this version`,onClick:e=>{e.stopPropagation(),i(`target`)},className:Dz,children:`target`})]})]})}function kz({diff:e,base:t,target:n}){return t===null&&n===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Pick a commit to see what changed.`}):t===null||n===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Now pick the version to compare it against.`}):e?.status===`error`?(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e.error}):e===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Loading…`}):e.status===`loaded`&&e.beforeText===e.afterText?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`These two versions are identical.`}):e.status===`loaded`&&x(e.beforeText,e.afterText)?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`These two versions differ only in their line endings.`}):(0,A.jsx)(`div`,{className:e.status===`loading`?`opacity-40`:void 0,children:(0,A.jsx)(Ke,{fill:!0,lines:S(e.beforeText,e.afterText)})})}var Az=`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none`,jz=`inline-flex h-7 min-w-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none`;function Mz(e){let t=e.filter(e=>!e.sideOf).flatMap(t=>[t,...e.filter(e=>e.sideOf===t.root)]);return[...t,...e.filter(e=>!t.includes(e))]}var Nz={stopped:`stopped`,starting:`starting…`,idle:`idle`,working:`working`,waiting:`waiting for you`,"ready-for-review":`ready for review`};function Pz({activity:e}){switch(e){case`stopped`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full border border-dashed border-zinc-400 dark:border-zinc-600`});case`starting`:return(0,A.jsx)(`svg`,{className:`h-2.5 w-2.5 shrink-0 animate-spin text-zinc-500 dark:text-zinc-400`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`3.5`,strokeLinecap:`round`,children:(0,A.jsx)(`path`,{d:`M12 3a9 9 0 0 1 9 9`})});case`working`:return(0,A.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0 items-center justify-center`,children:[(0,A.jsx)(`span`,{className:`absolute h-2 w-2 animate-ping rounded-full bg-blue-700 opacity-60 dark:bg-blue-400`}),(0,A.jsx)(`span`,{className:`relative h-2 w-2 rounded-full bg-blue-700 dark:bg-blue-400`})]});case`waiting`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full bg-amber-500`});case`ready-for-review`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rotate-45 rounded-[1px] border-2 border-violet-600 bg-violet-100 dark:border-violet-400 dark:bg-violet-950`});default:return(0,A.jsx)(`span`,{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-zinc-400 dark:bg-zinc-600`})}}function Fz({className:e}){return(0,A.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,"aria-hidden":`true`,children:[(0,A.jsx)(`path`,{d:`M12 6v7`}),(0,A.jsx)(`path`,{d:`M12 18h.01`})]})}function Iz({className:e}){return(0,A.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,A.jsx)(`path`,{d:`M7 3h10v18H7z`}),(0,A.jsx)(`path`,{d:`m9.5 12 1.7 1.7 3.5-3.7`})]})}function Lz(e){let{workspace:t,workspaces:n,locked:r}=e,[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null);if((0,d.useEffect)(()=>{if(!i)return;let e=e=>{KL(e,o.current)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]),r||!t)return null;let s=n.filter(e=>kI(e)!==kI(t)),c=n.filter(e=>!e.sideOf).length,l=n.filter(e=>e.needsAttention);return(0,A.jsxs)(`div`,{ref:o,className:`relative min-w-[4rem] max-w-[16rem]`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-haspopup":`menu`,title:`Project: ${t.name} (${Nz[t.activity]})`,className:`${jz} max-w-full gap-1.5 ${l.length>0?`border-amber-500 bg-amber-50 text-zinc-700 dark:bg-amber-950/40 dark:text-zinc-200`:`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`}`,children:[(0,A.jsx)(Pz,{activity:t.activity}),(0,A.jsx)(`span`,{className:`truncate font-medium`,children:t.name}),l.length>0?(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-amber-600 dark:text-amber-500`,children:[(0,A.jsx)(Fz,{className:`h-3 w-3`}),(0,A.jsx)(`span`,{className:`font-semibold`,children:l.length})]}):s.some(e=>e.activity===`working`)&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`h-3 w-px bg-zinc-300 dark:bg-zinc-600`}),(0,A.jsx)(`span`,{className:`flex items-center gap-1`,children:s.map(e=>e.activity===`working`?(0,A.jsxs)(`span`,{className:`relative flex h-1.5 w-1.5 items-center justify-center`,children:[(0,A.jsx)(`span`,{className:`absolute h-1.5 w-1.5 animate-ping rounded-full bg-blue-700 opacity-60 dark:bg-blue-400`}),(0,A.jsx)(`span`,{className:`relative h-1.5 w-1.5 rounded-full bg-blue-700 dark:bg-blue-400`})]},kI(e)):(0,A.jsx)(`span`,{className:`h-1 w-1 rounded-full bg-zinc-300 dark:bg-zinc-600`},kI(e)))})]}),(0,A.jsx)(`svg`,{className:`h-3 w-3 text-zinc-500`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`m6 9 6 6 6-6`})})]}),i&&(0,A.jsxs)(`div`,{role:`menu`,className:`absolute left-0 top-full z-40 mt-1 w-87 rounded-md border border-zinc-300 bg-white p-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:[Mz(n).map(n=>{let r=kI(n),i=r===kI(t),o=n.sideOf!==void 0;return(0,A.jsxs)(`div`,{"data-testid":o?`side-session-row`:`project-row`,className:`group flex items-center gap-2.5 rounded-md py-2 pr-2.5 ${o?`pl-7`:`pl-2.5`} ${i?`bg-zinc-100 dark:bg-zinc-800`:`hover:bg-zinc-50 dark:hover:bg-zinc-800/50`}`,children:[(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),o?e.onSwitch(n.root,n.id):e.onSwitch(n.root)},className:`flex min-w-0 flex-1 items-center gap-2.5 text-left`,children:[(0,A.jsx)(Pz,{activity:n.activity}),(0,A.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,A.jsx)(`span`,{className:`truncate text-[13px] ${i?`font-semibold text-zinc-900 dark:text-zinc-100`:`font-medium text-zinc-900 dark:text-zinc-100`}`,children:o?n.label??n.name:n.name}),!o&&(0,A.jsx)(`span`,{className:`truncate font-mono text-[11px] text-zinc-400 dark:text-zinc-500`,children:n.root})]})]}),(0,A.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5`,children:[n.needsAttention?(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-[11px] font-medium ${n.activity===`ready-for-review`?`text-violet-700 dark:text-violet-400`:`text-amber-600 dark:text-amber-500`}`,children:[n.activity===`ready-for-review`?(0,A.jsx)(Iz,{className:`h-3 w-3`}):(0,A.jsx)(Fz,{className:`h-3 w-3`}),Nz[n.activity]]}):(0,A.jsx)(`span`,{className:`text-[11px] ${n.activity===`working`?`text-blue-700 dark:text-blue-400`:`text-zinc-400 dark:text-zinc-500`}`,children:Nz[n.activity]}),!o&&e.onOpenSide&&(0,A.jsx)(`button`,{type:`button`,title:`New side session on ${n.name}`,"aria-label":`New side session on ${n.name}`,onClick:t=>{t.stopPropagation(),a(!1),e.onOpenSide?.(n.root)},className:`flex h-5 w-5 items-center justify-center rounded border border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-800 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500 dark:hover:text-zinc-100`,children:(0,A.jsxs)(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5v14`}),(0,A.jsx)(`path`,{d:`M5 12h14`})]})}),(o||c>1)&&(0,A.jsx)(`button`,{type:`button`,title:`Close ${o?n.label??n.name:n.name}`,"aria-label":`Close ${o?n.label??n.name:n.name}`,onClick:t=>{t.stopPropagation(),o?e.onClose(n.root,n.id):e.onClose(n.root)},className:`flex h-5 w-5 items-center justify-center rounded border border-transparent text-zinc-400 opacity-0 group-hover:border-zinc-300 group-hover:opacity-100 hover:text-zinc-700 dark:group-hover:border-zinc-600 dark:hover:text-zinc-200`,children:(0,A.jsxs)(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,A.jsx)(`path`,{d:`M18 6 6 18`}),(0,A.jsx)(`path`,{d:`m6 6 12 12`})]})})]})]},r)}),(0,A.jsx)(`div`,{className:`my-1 h-px bg-zinc-200 dark:bg-zinc-700`}),(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),e.onOpen()},className:`flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] text-zinc-700 hover:bg-zinc-50 dark:text-zinc-300 dark:hover:bg-zinc-800/50`,children:[(0,A.jsxs)(`svg`,{className:`h-3.5 w-3.5 text-zinc-500`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5v14`}),(0,A.jsx)(`path`,{d:`M5 12h14`})]}),`Open a project…`]})]})]})}function Rz({label:e,browse:t,onBrowse:n,onSelect:r,onCancel:i}){let a=t?.path??`/`,o=t?.entries??[],s=t?.status===`loading`,[c,l]=(0,d.useState)(a);return(0,d.useEffect)(()=>{l(a)},[a]),(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-300 p-2 dark:border-zinc-700`,"data-testid":`server-path-picker`,children:[(0,A.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`text-xs font-semibold text-zinc-600 dark:text-zinc-300`,children:e}),(0,A.jsx)(`button`,{type:`button`,onClick:i,className:`text-xs text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200`,children:`Cancel`})]}),(0,A.jsxs)(`form`,{className:`mb-2 flex gap-1`,onSubmit:e=>{e.preventDefault();let t=c.trim();t&&n(t)},children:[(0,A.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),l(a))},spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":`Current directory`,"data-testid":`picker-path`,className:`min-w-0 flex-1 rounded border border-zinc-300 px-2 py-1 font-mono text-xs text-zinc-700 focus:border-zinc-500 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),(0,A.jsx)(`button`,{type:`submit`,disabled:c.trim()===``||c===a,className:`rounded border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 dark:border-zinc-700 dark:text-zinc-300`,children:`Go`})]}),t?.status===`error`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-2 text-xs text-red-600 dark:text-red-400`,children:t.error}),(0,A.jsxs)(`div`,{className:`mb-2 flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:!t?.parent,onClick:()=>t?.parent&&n(t.parent),className:`rounded border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 dark:border-zinc-700 dark:text-zinc-300`,children:`Up`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>r(a),className:`rounded bg-zinc-800 px-2 py-1 text-xs font-medium text-white hover:bg-zinc-700 dark:bg-zinc-200 dark:text-zinc-900`,children:`Use this directory`})]}),(0,A.jsxs)(`ul`,{className:`max-h-40 overflow-y-auto`,children:[s&&o.length===0&&(0,A.jsx)(`li`,{className:`px-2 py-1 text-xs text-zinc-400`,children:`Loading…`}),!s&&o.length===0&&t?.status!==`error`&&(0,A.jsx)(`li`,{className:`px-2 py-1 text-xs text-zinc-400 dark:text-zinc-500`,children:`No subdirectories`}),o.map(e=>(0,A.jsx)(`li`,{children:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>n(e.path),className:`w-full truncate rounded px-2 py-1 text-left font-mono text-xs text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800`,title:e.path,children:[e.name,e.name.endsWith(`:`)?`\\`:`/`]})},e.path))]})]})}function zz(e){return e.split(/[\\/]/).filter(Boolean).at(-1)??e}function Bz(e){let{sandbox:t,applyState:n,blocked:r=!1,onCloseBrowser:i}=e,[a,o]=(0,d.useState)(!1),s=(0,d.useRef)(!1);if((0,d.useEffect)(()=>{r&&a&&(s.current=!1,o(!1))},[r,a]),(0,d.useEffect)(()=>{s.current&&n?.status!==`applying`&&(n?.status===`error`?s.current=!1:(s.current=!1,o(!1),i()))},[n,i]),!t)return(0,A.jsx)(`span`,{className:`${Az} border-dashed border-zinc-300 text-zinc-400 dark:border-zinc-700 dark:text-zinc-500`,title:`This server runs without a sandbox, so there is no root to move`,children:`No sandbox`});let c=t.locks?.root===!0,l=zz(t.root);return(0,A.jsxs)(`div`,{className:`relative min-w-[4rem] max-w-[14rem]`,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:c,"aria-label":c?`Sandbox root: ${t.root} (locked)`:`Sandbox root: ${t.root}`,title:c?`${t.root} — locked by the server's configuration`:t.root,onClick:()=>{e.onOpened(),o(!0),e.onBrowse(t.root)},className:`${jz} max-w-full gap-1.5 ${c?`cursor-not-allowed border-zinc-200 text-zinc-400 dark:border-zinc-800 dark:text-zinc-500`:`border-zinc-300 text-zinc-600 hover:border-zinc-400 hover:text-zinc-800 dark:border-zinc-700 dark:text-zinc-300 dark:hover:border-zinc-500 dark:hover:text-zinc-100`}`,children:[(0,A.jsx)(`span`,{className:`truncate font-mono`,children:l}),c?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):(0,A.jsx)(`span`,{"aria-hidden":`true`,children:`▾`})]}),a&&!r&&(0,A.jsxs)(`div`,{className:`absolute left-0 top-full z-20 mt-1 w-[380px] rounded-lg border border-zinc-200 bg-white p-2 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[n?.status===`error`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-2 text-xs text-red-600 dark:text-red-400`,children:n.message}),(0,A.jsx)(Rz,{label:`Choose the sandbox root`,browse:e.browse,onBrowse:e.onBrowse,onSelect:t=>{s.current=!0,e.onSelect(t)},onCancel:()=>{s.current=!1,o(!1),i()}})]})]})}function Vz(e){let t=(Date.now()-new Date(e).getTime())/1e3;return t<90?`now`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Hz(e){return e.slice(e.lastIndexOf(`/`)+1)}function Uz({status:e,selected:t,log:n,onFetchLog:r,onShowCommit:i}){let[a,o]=(0,d.useState)(!1),s=qL(()=>o(!1)),c=e?.repos??[],l=(t===null?null:_L(c,t))??(t===null&&c.length===1?c[0]:null),u=l&&(l.ahead>0||l.behind>0)?` ${l.ahead>0?`↑${l.ahead}`:``}${l.behind>0?`↓${l.behind}`:``}`:``,f=c.length>1&&l!==null&&l.repo!==``?`${Hz(l.repo)} `:``,p=e===null?`…`:l?.branch??`—`,m=l!==null&&n?.repo===l.repo?n.entries:null;return(0,d.useEffect)(()=>{a&&l!==null&&n?.repo!==l.repo&&r(l.repo)},[a,l?.repo,r]),(0,A.jsxs)(`div`,{className:`relative min-w-[4rem] max-w-[14rem] shrink-[2]`,ref:s,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:l===null,onClick:()=>{l!==null&&(o(!a),a||r(l.repo))},title:l===null?`no repository selected`:`git history — ${l.repo===``?`this project`:l.repo}`,className:`${jz} max-w-full border-zinc-300 font-mono text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 disabled:cursor-default disabled:hover:border-zinc-300 disabled:hover:text-zinc-500 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200 dark:disabled:hover:border-zinc-800 dark:disabled:hover:text-zinc-400`,children:[(0,A.jsxs)(`span`,{className:`truncate`,children:[f,`⎇ `,p]}),u]}),a&&l!==null&&(0,A.jsxs)(`div`,{className:`absolute left-0 top-full z-20 mt-1 max-h-96 w-[26rem] max-w-[80vw] overflow-y-auto rounded-lg border border-zinc-200 bg-white py-1 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[m===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),m?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no commits`}),m?.map(e=>(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{i(l.repo,e.sha),o(!1)},className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-amber-600 dark:text-amber-500`,children:e.sha.slice(0,7)}),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-zinc-700 dark:text-zinc-300`,title:e.subject,children:e.subject}),(0,A.jsxs)(`span`,{className:`shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,children:[e.author,` · `,Vz(e.date)]})]},e.sha))]})]})}function Wz(e){if(e.installed===void 0)return`not installed`;if(e.restartNeeded)return`${e.installed} installed — restart to use it`;if(e.pinned!==void 0)return`${e.installed}, pinned`;let t=e.check;if(!t)return e.installed;switch(t.state){case`checking`:return`${e.installed}, checking…`;case`newer`:return`${e.installed} — ${t.latest} available`;case`current`:return`${e.installed}, up to date`;case`failed`:return`${e.installed}, not checked: ${t.reason}`;case`off`:return`${e.installed}, not checked: ${t.reason}`}}function Gz({packages:e,update:t,locked:n,onCheck:r,onUpdate:i}){let[a,o]=(0,d.useState)(null);if(e===null||e.length===0)return null;let s=t?.status===`pending`?t.source:null;return(0,A.jsxs)(`div`,{className:`mt-3`,"data-testid":`pi-packages`,children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium text-zinc-600 dark:text-zinc-400`,children:`Packages`}),(0,A.jsx)(`button`,{type:`button`,onClick:r,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200`,children:`check for updates`})]}),(0,A.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>{let r=e.check?.state===`newer`&&!e.restartNeeded?e.check.latest:void 0;return(0,A.jsxs)(`li`,{"data-testid":`pi-package`,className:`rounded bg-zinc-50 px-2 py-1 text-xs dark:bg-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`min-w-0 truncate font-mono text-zinc-700 dark:text-zinc-300`,title:e.source,children:e.name}),r&&!n&&a!==e.source&&(0,A.jsx)(`button`,{type:`button`,disabled:s!==null,onClick:()=>o(e.source),className:`shrink-0 rounded border border-zinc-300 px-1.5 py-0.5 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50 dark:border-zinc-600 dark:text-zinc-200 dark:hover:bg-zinc-700`,children:s===e.source?`updating…`:`Update`})]}),(0,A.jsx)(`div`,{className:`line-clamp-2 text-zinc-500 dark:text-zinc-400`,"data-testid":`pi-package-status`,title:Wz(e),children:Wz(e)}),r&&a===e.source&&(0,A.jsxs)(`div`,{className:`mt-1 rounded border border-amber-300 bg-amber-50 p-2 text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200`,"data-testid":`pi-package-confirm`,children:[(0,A.jsxs)(`p`,{children:[`This replaces code that runs with the agent's privileges: `,e.name,` `,e.installed,` → `,r,`. It takes effect when pi-outpost restarts.`]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{o(null),i(e.source)},className:`rounded bg-amber-600 px-2 py-0.5 text-white hover:bg-amber-700`,children:[`Install `,r]}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(null),className:`rounded px-2 py-0.5 hover:bg-amber-100 dark:hover:bg-amber-900/40`,children:`Cancel`})]})]}),t&&t.status!==`pending`&&t.source===e.source&&(0,A.jsx)(`p`,{"data-testid":`pi-package-result`,className:`mt-1 ${t.status===`installed`?`text-emerald-700 dark:text-emerald-400`:`text-amber-700 dark:text-amber-400`}`,children:t.message})]},e.source)})})]})}function Kz({reasons:e,canRestart:t,restarting:n,onRestart:r}){let[i,a]=(0,d.useState)(!1);return e.length===0?null:(0,A.jsxs)(`div`,{className:`mt-3 rounded border border-sky-200 bg-sky-50 p-2 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,"data-testid":`restart-needed`,children:[(0,A.jsxs)(`p`,{children:[`Installed and waiting on a restart to run: `,e.join(`, `),`.`]}),t?n?(0,A.jsx)(`p`,{className:`mt-1`,children:`Restarting pi-outpost…`}):i?(0,A.jsxs)(`div`,{className:`mt-1`,children:[(0,A.jsx)(`p`,{children:`pi-outpost stops and starts again in the same terminal. Every open window reconnects by itself, and conversations are kept.`}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{a(!1),r()},className:`rounded bg-sky-700 px-2 py-0.5 text-white hover:bg-sky-800`,children:`Restart now`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(!1),className:`rounded px-2 py-0.5 hover:bg-sky-100 dark:hover:bg-sky-900/50`,children:`Cancel`})]})]}):(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(!0),className:`mt-1 rounded border border-sky-300 px-2 py-0.5 hover:bg-sky-100 dark:border-sky-700 dark:hover:bg-sky-900/50`,children:`Restart pi-outpost`}):null]})}var qz=30,Jz={display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`};function Yz({skills:e,groups:t,enabled:n,onChange:r,disabled:i=!1,bound:a}){let[o,s]=(0,d.useState)(()=>e.length>40?new Set(e.filter(e=>n.has(e.relativePath)).map(e=>e.group)):new Set(t.map(e=>e.path))),[c,l]=(0,d.useState)(``),[u,f]=(0,d.useState)(!1),p=c.trim().toLocaleLowerCase(),m=p!==``||u,h=e=>(!u||n.has(e.relativePath))&&(!p||`${e.name} ${e.relativePath} ${e.description??``}`.toLocaleLowerCase().includes(p)),g=new Map;for(let t of e)g.set(t.group,[...g.get(t.group)??[],t]);let _=e.filter(e=>n.has(e.relativePath)).length,v=m?e.filter(h).length:e.length,y=(e,t)=>{let i=new Set(n);for(let n of e)t?i.add(n.relativePath):i.delete(n.relativePath);r(i)},b=e=>{let t=new Set(n);t.has(e)?t.delete(e):t.add(e),r(t)},x=e=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,A.jsxs)(`section`,{className:`rounded-xl border border-zinc-200 p-4 dark:border-zinc-800`,"aria-label":`Collection skills`,children:[(0,A.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,A.jsxs)(`h3`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:[`Skills `,(0,A.jsxs)(`span`,{className:`font-normal text-zinc-500`,children:[`· `,_,` of `,e.length,` on`]})]}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:i||_===e.length,onClick:()=>y(e,!0),className:`rounded-md border px-2.5 py-1 text-xs disabled:opacity-50`,children:`All on`}),(0,A.jsx)(`button`,{type:`button`,disabled:i||_===0,onClick:()=>y(e,!1),className:`rounded-md border px-2.5 py-1 text-xs disabled:opacity-50`,children:`All off`})]})]}),a?(0,A.jsx)(`p`,{className:`mt-2 rounded border border-amber-200 bg-amber-50 p-2 text-xs text-amber-800`,children:a.kind===`count`?`This repository holds more skills than the ${a.limit} listed here.`:`Folders deeper than ${a.limit} levels were not searched for skills.`}):null,e.length>0?(0,A.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`search`,"aria-label":`Search skills`,placeholder:`Search skills by name or folder`,value:c,onChange:e=>l(e.target.value),className:`min-w-0 flex-1 rounded-md border bg-transparent px-2.5 py-1 text-xs`}),(0,A.jsxs)(`button`,{type:`button`,"aria-pressed":u,onClick:()=>f(e=>!e),className:`rounded-md px-2.5 py-1 text-xs ${u?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:[`Only on (`,_,`)`]})]}):null,!m&&_>0&&_<=qz?(0,A.jsxs)(`div`,{role:`region`,"aria-label":`Skills that are on`,className:`mt-3 rounded-lg border border-emerald-200 bg-emerald-50/60 p-2 dark:border-emerald-900 dark:bg-emerald-950/30`,children:[(0,A.jsx)(`p`,{className:`px-1 text-[11px] font-medium text-emerald-800 dark:text-emerald-300`,children:`Turned on`}),(0,A.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.filter(e=>n.has(e.relativePath)).map(e=>(0,A.jsxs)(`li`,{className:`flex items-start justify-between gap-2 px-1`,children:[(0,A.jsxs)(`span`,{className:`min-w-0 text-xs`,children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-800 dark:text-zinc-100`,children:e.name}),` `,(0,A.jsx)(`span`,{className:`font-mono text-[11px] text-zinc-500`,children:e.group||`(repository root)`}),(0,A.jsx)(Xz,{skill:e,checked:!0})]}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Turn off ${e.name} (${e.relativePath})`,disabled:i,onClick:()=>b(e.relativePath),className:`shrink-0 rounded border bg-white px-2 py-0.5 text-[11px] disabled:opacity-50 dark:bg-zinc-900`,children:`Turn off`})]},e.relativePath))})]}):null,e.length===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:`This repository holds no skills.`}):null,m&&v===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:u&&!p?`No skill is on.`:`No skill matches.`}):null,(0,A.jsx)(`ul`,{className:`mt-3 space-y-2`,children:t.map(e=>{let t=g.get(e.path)??[],r=m?t.filter(h):t;if(m&&r.length===0)return null;let a=r.filter(e=>n.has(e.relativePath)).length,s=m||o.has(e.path);return(0,A.jsxs)(`li`,{className:`rounded-lg border border-zinc-100 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-2`,children:[(0,A.jsxs)(`button`,{type:`button`,"aria-expanded":s,onClick:()=>x(e.path),className:`flex min-w-0 flex-1 items-center gap-2 text-left`,children:[(0,A.jsx)(`span`,{"aria-hidden":`true`,className:`text-xs text-zinc-400`,children:s?`▾`:`▸`}),(0,A.jsx)(`span`,{className:`truncate font-mono text-xs font-medium text-zinc-700 dark:text-zinc-200`,children:e.label}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[11px] text-zinc-500`,children:[a,`/`,r.length,` on`]})]}),(0,A.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`All on in ${e.label}`,disabled:i||a===r.length,onClick:()=>y(r,!0),className:`rounded border px-2 py-0.5 text-[11px] disabled:opacity-50`,children:`All on`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`All off in ${e.label}`,disabled:i||a===0,onClick:()=>y(r,!1),className:`rounded border px-2 py-0.5 text-[11px] disabled:opacity-50`,children:`All off`})]})]}),s?(0,A.jsx)(`ul`,{className:`space-y-1 border-t border-zinc-100 px-3 py-2 dark:border-zinc-800`,children:r.map(e=>{let t=n.has(e.relativePath);return(0,A.jsx)(`li`,{children:(0,A.jsxs)(`label`,{className:`flex items-start gap-2 rounded px-1 py-1 ${i?`opacity-60`:`cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-800/60`}`,children:[(0,A.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":t,"aria-label":`${e.name} (${e.relativePath})`,checked:t,disabled:i,onChange:()=>b(e.relativePath),className:`mt-0.5`}),(0,A.jsxs)(`span`,{className:`min-w-0`,children:[(0,A.jsx)(`span`,{className:`block truncate text-sm text-zinc-800 dark:text-zinc-100`,children:e.name}),e.description?(0,A.jsx)(`span`,{title:e.description,style:Jz,className:`text-[11px] text-zinc-500`,children:e.description}):null,(0,A.jsx)(Xz,{skill:e,checked:t})]})]})},e.relativePath)})}):null]},e.path)})})]})}function Xz({skill:e,checked:t}){return t===(e.state!==`off`)?e.state===`on-loaded`?(0,A.jsx)(`span`,{className:`block text-[11px] text-emerald-700 dark:text-emerald-400`,children:`Loaded`}):e.state===`on-not-loaded`?(0,A.jsxs)(`span`,{className:`block text-[11px] text-amber-700 dark:text-amber-400`,children:[`Not loaded — `,e.reason]}):e.state===`on-missing`?(0,A.jsxs)(`span`,{className:`block text-[11px] text-rose-700 dark:text-rose-400`,children:[`Missing — `,e.reason]}):null:(0,A.jsx)(`span`,{className:`block text-[11px] font-medium text-sky-700 dark:text-sky-300`,children:t?`Pending: on`:`Pending: off`})}function Zz(e,t){return[...new Set(e.map(e=>e.group))].sort().map(e=>({path:e,label:e||t}))}function Qz(e){return e.skills.filter(e=>e.state!==`off`).map(e=>e.relativePath)}function $z(e,t){let n=new Set(e),r=new Set(t);return n.size===r.size&&[...n].every(e=>r.has(e))}function eB(e,t){if(t.status===`loading`)return`Removing ${e}…`;if(t.status===`error`)return t.message??`Could not remove ${e}`;let n=t.result;return n?n.status===`removed`?`Removed ${e} and deleted ${n.path}.`:n.status===`removed-files-kept`?`Removed ${e}. ${n.reason??`Its files were kept`} (${n.path}).`:`Removed ${e}, but not every file could be deleted${n.reason?` — ${n.reason}`:``}. What remains is at ${n.path}.`:`Removed ${e}.`}var tB={unchecked:`Not checked`,checking:`Checking…`,current:`Up to date`,updateable:`Update available`,dirty:`Local changes`,detached:`Detached HEAD`,ahead:`Local branch ahead`,diverged:`Histories diverged`,"no-upstream":`No upstream`,locked:`Locked`,busy:`Workspace busy`,unavailable:`Unavailable`,failed:`Check failed`};function nB(e){if(!e)return[];let t=new Map(e.resources.map(e=>[e.id,e])),n=new Set(e.repositories.flatMap(e=>e.resourceIds)),r=e.repositories.map(e=>({id:e.id,name:e.name,path:e.path,repository:e,resources:e.resourceIds.flatMap(e=>t.get(e)?[t.get(e)]:[])})),i=e.resources.filter(e=>!n.has(e.id)),a=i.filter(e=>e.unavailableReason),o=i.filter(e=>!e.unavailableReason);return o.length&&r.push({id:`local`,name:`Local and built in`,reason:`Not backed by an updateable Git repository`,resources:o}),a.length&&r.push({id:`unavailable`,name:`Provenance unavailable`,reason:`The active runtime did not report enough filesystem provenance`,resources:a}),r}function rB(e){let t=e.length;for(;t>0&&(e[t-1]===`/`||e[t-1]===`\\`);)--t;return t===e.length?e:e.slice(0,t)}function iB(e){let t=rB(e),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return n<=0?`/`:t.slice(0,n)}function aB(e,t){let n=rB(t),r=Math.max(n.lastIndexOf(`/`),n.lastIndexOf(`\\`)),i=r>=0?n.slice(r+1):n;return`${rB(e)}/${i||`agent-resources`}`}function oB({kind:e,resources:t,removalLocked:n=!1,onRemove:r}){return(0,A.jsxs)(`section`,{className:`rounded-xl border border-zinc-200 p-4 dark:border-zinc-800`,children:[(0,A.jsxs)(`h3`,{className:`flex items-center justify-between text-sm font-semibold capitalize text-zinc-800 dark:text-zinc-200`,children:[(0,A.jsxs)(`span`,{children:[e,`s`]}),(0,A.jsx)(`span`,{className:`text-xs font-normal text-zinc-400`,children:t.length})]}),t.length===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:`None in this group`}):(0,A.jsx)(`ul`,{className:`mt-3 space-y-2`,children:t.map(e=>(0,A.jsxs)(`li`,{className:`rounded-lg bg-zinc-50 px-3 py-2 dark:bg-zinc-800/70`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`p`,{className:`truncate text-sm font-medium text-zinc-700 dark:text-zinc-200`,children:e.name}),e.userRoot&&!n?(0,A.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.userRoot}`,onClick:()=>r(e),className:`text-xs text-zinc-500 hover:text-red-600`,children:`Remove`}):null]}),(0,A.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-[11px] text-zinc-400`,title:e.path,children:e.path??e.unavailableReason??`Path unavailable`})]},e.id))})]})}function sB({preview:e,busy:t,error:n,onApply:r,onCancel:i}){let[a,o]=(0,d.useState)(()=>new Set(e.roots.filter(e=>!e.locked).map(e=>`${e.kind}:${e.path}`))),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(()=>new Set),f=e.mode===`collection`,p=(0,d.useMemo)(()=>e.skills.map(e=>({...e,state:`off`})),[e.skills]),m=(0,d.useMemo)(()=>Zz(e.skills,e.repositoryName),[e.skills,e.repositoryName]),h=e.roots.filter(e=>e.kind===`extension`&&a.has(`extension:${e.path}`)),g=h.length>0&&!s,_=t||!f&&a.size===0||g,v=()=>{let t=h.map(e=>e.path);f?r([],t,[...l]):r(e.roots.filter(e=>e.kind===`skill`&&a.has(`skill:${e.path}`)).map(e=>e.path),t)},y=e=>{c(!1),o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return(0,A.jsxs)(`div`,{className:`space-y-3`,"data-testid":`resource-preview`,children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsx)(`h3`,{className:`truncate text-xl font-semibold text-zinc-900 dark:text-zinc-100`,children:e.repositoryName}),(0,A.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-[11px] text-zinc-500`,title:e.repositoryPath,children:e.repositoryPath})]}),(0,A.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:i,className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:_,onClick:v,className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900`,children:t?`Saving…`:`Save`})]})]}),g?(0,A.jsx)(`p`,{className:`text-xs text-amber-700`,children:`Confirm the extension warning below to save.`}):null,n?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:n}):null,f?(0,A.jsx)(Yz,{skills:p,groups:m,enabled:l,onChange:u,disabled:t,...e.bound?{bound:e.bound}:{}}):null,e.roots.map(e=>{let t=`${e.kind}:${e.path}`;return(0,A.jsxs)(`label`,{className:`flex items-start gap-2 rounded border p-2 ${e.locked?`opacity-50`:`cursor-pointer`}`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:a.has(t),disabled:e.locked,onChange:()=>y(t)}),(0,A.jsxs)(`span`,{children:[(0,A.jsxs)(`span`,{className:`block text-sm`,children:[e.name,` · `,e.kind]}),(0,A.jsx)(`span`,{className:`font-mono text-[11px] text-zinc-500`,children:e.path}),e.locked?(0,A.jsx)(`span`,{className:`block text-xs text-amber-700`,children:`Extension paths are locked`}):null]})]},t)}),h.length>0?(0,A.jsxs)(`label`,{className:`flex gap-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked)}),(0,A.jsx)(`span`,{children:`Extensions execute code with the agent's privileges. I trust the selected extension roots in this repository.`})]}):null]})}function cB(e){let t=(0,d.useRef)(null),n=(0,d.useRef)(e.onClose),r=(0,d.useRef)(!1),[i,a]=(0,d.useState)(null),[o,s]=(0,d.useState)(``),[c,l]=(0,d.useState)(`all`),[u,f]=(0,d.useState)(!1),[p,m]=(0,d.useState)(null),[h,g]=(0,d.useState)(null),[_,v]=(0,d.useState)(`skill`),[y,b]=(0,d.useState)(``),[x,S]=(0,d.useState)(!1),[C,w]=(0,d.useState)(``),[T,ee]=(0,d.useState)(``),[E,te]=(0,d.useState)(!1),[D,ne]=(0,d.useState)(``),[re,ie]=(0,d.useState)(null),[O,k]=(0,d.useState)({}),[ae,oe]=(0,d.useState)(null),[se,ce]=(0,d.useState)(null),le=(0,d.useMemo)(()=>nB(e.inventory),[e.inventory]),ue=(0,d.useMemo)(()=>{let e=o.trim().toLocaleLowerCase();return le.flatMap(t=>{let n=`repository`in t?t.repository.collection:void 0,r=n?t.resources.filter(e=>e.kind!==`skill`):t.resources,i=c===`all`?r:r.filter(e=>e.kind===c),a=n&&c!==`extension`?n.skills:[],o=i.length+a.length;if(o===0&&!(n&&c===`all`)||u&&(!(`repository`in t)||![`updateable`,`dirty`,`failed`,`unavailable`,`busy`].includes(t.repository.assessment.status)))return[];let s=`${t.name} ${`path`in t?t.path??``:``} ${i.map(e=>`${e.name} ${e.path??``}`).join(` `)} ${a.map(e=>`${e.name} ${e.relativePath}`).join(` `)}`.toLocaleLowerCase(),l=n?n.skills.filter(e=>e.state!==`off`).length:void 0;return!e||s.includes(e)?[{...t,resources:i,count:o,...l===void 0?{}:{onCount:l}}]:[]})},[le,u,c,o]),de=ue.find(e=>e.id===i)??ue[0]??null;if((0,d.useEffect)(()=>{n.current=e.onClose},[e.onClose]),(0,d.useEffect)(()=>{k(t=>{let n={},r=!1;for(let[i,a]of Object.entries(t)){let t=e.inventory?.repositories.find(e=>e.id===i)?.collection;!t||$z(a,Qz(t))?r=!0:n[i]=a}return r?n:t})},[e.inventory]),(0,d.useEffect)(()=>{e.open&&t.current?.focus()},[e.open]),(0,d.useEffect)(()=>{if(!e.open)return;let t=e=>{e.key===`Escape`&&n.current()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e.open]),(0,d.useEffect)(()=>{let t=e.operations.clonePath;t?.status===`ready`&&t.path&&!E&&ee(t.path)},[E,e.operations.clonePath]),(0,d.useEffect)(()=>{e.operations.enrollment?.status===`ready`&&m(null)},[e.operations.enrollment]),(0,d.useEffect)(()=>{e.applyState?.status===`applying`?r.current=!0:r.current&&e.applyState===null&&(r.current=!1,m(null),g(null),S(!1))},[e.applyState]),!e.open)return null;let j=de&&`repository`in de?de.repository:null,fe=j?e.operations.updates[j.id]:void 0,pe=j?.assessment,me=pe?.status===`updateable`&&pe.token&&pe.localRevision&&pe.upstreamRevision,he=()=>{let t=y.trim();t&&(_===`skill`?e.onUpdateConfig({userSkillPaths:[...new Set([...e.userSkillPaths,t])]}):e.onUpdateConfig({userExtensionPaths:[...new Set([...e.userExtensionPaths,t])]}))},ge=t=>{t.userRoot&&(t.kind===`skill`?e.onUpdateConfig({userSkillPaths:e.userSkillPaths.filter(e=>e!==t.userRoot)}):e.onUpdateConfig({userExtensionPaths:e.userExtensionPaths.filter(e=>e!==t.userRoot)}))},_e=(t,n=!1)=>{let r=t.assessment;r.token&&r.localRevision&&r.upstreamRevision&&e.onUpdate(t.id,r.token,r.localRevision,r.upstreamRevision,n)},ve=j?.collection,ye=ve?Qz(ve):[],be=new Set(j&&O[j.id]?O[j.id]:ye),xe=ve?[...new Set([...be,...ye])].filter(e=>be.has(e)!==ye.includes(e)).length:0,Se=j?e.operations.skills?.[j.id]:void 0,Ce=e=>{if(!j)return;let t=j.id;k(n=>{let r={...n};return $z(e,ye)?delete r[t]:r[t]=[...e],r})},we=()=>{if(!j)return;let e=j.id;k(t=>{let n={...t};return delete n[e],n})},Te=()=>{if(!j||!ve)return;let t=new Set(ve.skills.filter(e=>e.state!==`on-missing`).map(e=>e.relativePath));e.onSetSkills(j.id,[...be].filter(e=>t.has(e)))},Ee=se?e.operations.removals?.[se.id]:void 0,De=Ee?.status===`error`||Ee?.result?.status===`removed-delete-failed`;return(0,A.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/45 p-4`,role:`presentation`,onMouseDown:t=>{t.currentTarget===t.target&&e.onClose()},children:[(0,A.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`agent-resources-title`,className:`flex h-[min(760px,92vh)] w-[min(1120px,96vw)] flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`header`,{className:`flex items-center justify-between border-b border-zinc-200 px-5 py-4 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h2`,{id:`agent-resources-title`,className:`text-lg font-semibold text-zinc-900 dark:text-zinc-100`,children:`Agent resources`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Skills and extensions, grouped by repository`})]}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.refresh?.status===`loading`,onClick:()=>e.onRefresh(),className:`rounded-md border px-3 py-1.5 text-xs disabled:opacity-50`,children:`Refresh all`}),(0,A.jsx)(`button`,{ref:t,type:`button`,"aria-label":`Close agent resources`,onClick:e.onClose,className:`rounded-md border px-2 py-1 text-sm`,children:`✕`})]})]}),(0,A.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-[300px_1fr]`,children:[(0,A.jsxs)(`aside`,{className:`flex min-h-0 flex-col border-r border-zinc-200 bg-zinc-50/80 p-3 dark:border-zinc-800 dark:bg-zinc-950/40`,children:[(0,A.jsx)(`input`,{"aria-label":`Search resources`,value:o,onChange:e=>s(e.target.value),placeholder:`Search repositories or resources`,className:`rounded-md border bg-white px-3 py-2 text-xs dark:bg-zinc-900`}),(0,A.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1`,children:[[`all`,`skill`,`extension`].map(e=>(0,A.jsx)(`button`,{type:`button`,"aria-pressed":c===e,onClick:()=>l(e),className:`rounded px-2 py-1 text-[11px] ${c===e?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:e===`all`?`All`:`${e}s`},e)),(0,A.jsx)(`button`,{type:`button`,"aria-pressed":u,onClick:()=>f(e=>!e),className:`rounded px-2 py-1 text-[11px] ${u?`bg-amber-600 text-white`:`border`}`,children:`Needs attention`})]}),(0,A.jsxs)(`div`,{className:`mt-3 min-h-0 flex-1 space-y-1 overflow-y-auto`,children:[ue.map(e=>(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(e.id),className:`w-full rounded-lg px-3 py-2.5 text-left ${de?.id===e.id?`bg-white shadow-sm ring-1 ring-zinc-200 dark:bg-zinc-800 dark:ring-zinc-700`:`hover:bg-white/70 dark:hover:bg-zinc-900`}`,children:[(0,A.jsxs)(`span`,{className:`flex items-center justify-between gap-2 text-sm font-medium`,children:[(0,A.jsx)(`span`,{className:`truncate`,children:e.name}),(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-zinc-400`,children:e.onCount===void 0?e.count??e.resources.length:`${e.onCount} on · ${e.count}`})]}),(0,A.jsx)(`span`,{className:`mt-1 block text-xs text-zinc-500`,children:`repository`in e?tB[e.repository.assessment.status]:e.reason})]},e.id)),ue.length===0?(0,A.jsx)(`p`,{className:`px-2 py-4 text-xs text-zinc-500`,children:`No matching resources`}):null]}),(0,A.jsxs)(`div`,{className:`mt-3 grid gap-2 border-t pt-3`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{S(!1),m(`local`),g(`local`),e.onBrowseServerPath(y||`/`)},className:`rounded-md border bg-white px-3 py-2 text-xs font-medium dark:bg-zinc-900`,children:`Add local folder…`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>m(`git`),className:`rounded-md bg-zinc-900 px-3 py-2 text-xs font-medium text-white dark:bg-zinc-100 dark:text-zinc-900`,children:`Add Git repository…`})]})]}),(0,A.jsxs)(`main`,{className:`min-w-0 overflow-y-auto p-6`,children:[se&&Ee?(0,A.jsxs)(`div`,{role:De?`alert`:`status`,className:`mb-4 flex items-start justify-between gap-3 rounded-lg border p-3 text-sm ${De?`border-rose-200 bg-rose-50 text-rose-800`:`border-zinc-200 bg-zinc-50 text-zinc-700`}`,children:[(0,A.jsx)(`p`,{className:`min-w-0 break-words`,children:eB(se.name,Ee)}),Ee.status===`loading`?null:(0,A.jsx)(`button`,{type:`button`,onClick:()=>ce(null),className:`shrink-0 text-xs underline`,children:`Dismiss`})]}):null,p===`local`?(0,A.jsxs)(`div`,{className:`max-w-xl space-y-4`,"data-testid":`add-local-folder`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Add local folder`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Choose an existing folder on the server and how the agent should load it.`})]}),(0,A.jsx)(`div`,{className:`flex gap-2`,children:[`skill`,`extension`].map(t=>(0,A.jsx)(`button`,{type:`button`,"aria-pressed":_===t,disabled:t===`extension`&&e.extensionLock,onClick:()=>{v(t),S(!1)},className:`rounded-md px-3 py-1.5 text-xs ${_===t?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:t===`skill`?`Skill folder`:`Extension folder`},t))}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`input`,{"aria-label":`Local resource folder`,value:y,onChange:e=>{S(!1),b(e.target.value)},className:`min-w-0 flex-1 rounded-md border bg-transparent px-3 py-2 text-sm`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{g(`local`),e.onBrowseServerPath(y||`/`)},className:`rounded-md border px-3 text-xs`,children:`Browse…`})]}),h===`local`?(0,A.jsx)(Rz,{label:`Choose a local resource folder`,browse:e.serverBrowse,onBrowse:e.onBrowseServerPath,onSelect:t=>{S(!1),b(t),g(null),e.onCloseServerBrowser()},onCancel:()=>{g(null),e.onCloseServerBrowser()}}):null,_===`extension`?(0,A.jsxs)(`label`,{className:`flex gap-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,A.jsx)(`span`,{children:`Extensions execute code with the agent's privileges. I trust every extension in this folder.`})]}):null,e.extensionLock?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Extension paths are locked by this deployment.`}):null,e.applyState?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.applyState.message}):null,(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{S(!1),m(null),g(null),e.onCloseServerBrowser()},className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:!y.trim()||e.applyState?.status===`applying`||_===`extension`&&(!x||e.extensionLock),onClick:he,className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:e.applyState?.status===`applying`?`Applying…`:`Add folder`})]})]}):p===`git`?(0,A.jsx)(`div`,{className:`max-w-2xl space-y-4`,"data-testid":`add-git-repository`,children:e.operations.preview?.status===`ready`&&e.operations.preview.preview?(0,A.jsx)(sB,{onCancel:()=>{m(null),g(null),e.onCloseServerBrowser()},preview:e.operations.preview.preview,busy:e.operations.enrollment?.status===`loading`,error:e.operations.enrollment?.status===`error`?e.operations.enrollment.message:void 0,onApply:(t,n,r)=>r?e.onEnrollRepository(e.operations.preview.preview.token,t,n,r):e.onEnrollRepository(e.operations.preview.preview.token,t,n)}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Add Git repository`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Clone it to a local folder, then choose what to turn on.`})]}),(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium`,children:`Repository address`}),(0,A.jsx)(`input`,{"aria-label":`Repository address`,value:C,onChange:e=>w(e.target.value),onBlur:()=>{let t=C.trim();t&&(te(!1),ne(t),e.onSuggestClonePath(C))},placeholder:`https://github.com/team/resources.git`,className:`mt-1 w-full rounded-md border bg-transparent px-3 py-2 text-sm`})]}),(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium`,children:`Local folder`}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{"aria-label":`Local clone folder`,value:T,onChange:e=>{te(!0),ee(e.target.value)},placeholder:`/path/to/resource-repositories/team-resources-ab12cd`,className:`min-w-0 flex-1 rounded-md border bg-transparent px-3 py-2 text-sm`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{g(`clone-parent`),e.onBrowseServerPath(iB(T))},className:`rounded-md border px-3 text-xs`,children:`Choose parent…`})]})]}),e.operations.clonePath?.status===`loading`?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Suggesting a managed folder…`}):null,e.operations.clonePath?.status===`error`&&C.trim()===D?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.operations.clonePath.message}):null,h===`clone-parent`?(0,A.jsx)(Rz,{label:`Choose the clone's parent folder`,browse:e.serverBrowse,onBrowse:e.onBrowseServerPath,onSelect:t=>{ee(aB(t,T)),g(null),e.onCloseServerBrowser()},onCancel:()=>{g(null),e.onCloseServerBrowser()}}):null,e.operations.preview?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.operations.preview.message}):null,(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{m(null),g(null),e.onCloseServerBrowser()},className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:!C.trim()||!T.trim()||e.operations.preview?.status===`loading`,onClick:()=>e.onCloneRepository(C,T),className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:e.operations.preview?.status===`loading`?`Cloning…`:`Clone and inspect`})]})]})}):de?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`h3`,{className:`text-xl font-semibold`,children:de.name}),j?(0,A.jsx)(`span`,{className:`rounded-full border px-2 py-0.5 text-[11px]`,children:tB[j.assessment.status]}):null]}),(0,A.jsx)(`p`,{className:`mt-1 truncate font-mono text-xs text-zinc-500`,children:`repository`in de?de.path:de.reason}),pe?.branch?(0,A.jsxs)(`p`,{className:`mt-1 text-xs text-zinc-400`,children:[pe.branch,pe.upstream?` → ${pe.upstream}`:``]}):null,j?.removal&&!j.removal.allowed?(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-500`,children:j.removal.reason}):null]}),j?(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[j.removal?.allowed?(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.removals?.[j.id]?.status===`loading`,onClick:()=>oe(j),className:`rounded-md border border-red-200 px-3 py-1.5 text-xs text-red-700 disabled:opacity-50 dark:border-red-900 dark:text-red-400`,children:`Remove repository`}):null,(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.refresh?.status===`loading`,onClick:()=>e.onRefresh(j.id),className:`rounded-md border px-3 py-1.5 text-xs`,children:`Check`}),me||fe?.status===`loading`?(0,A.jsx)(`button`,{type:`button`,disabled:fe?.status===`loading`,onClick:()=>j.containsExtensions?ie(j):_e(j),className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:fe?.status===`loading`?`Updating…`:`Update repository`}):null]}):null]}),pe?.reason?(0,A.jsxs)(`div`,{className:`mt-5 rounded-lg border p-3 text-sm ${pe.status===`dirty`?`border-rose-200 bg-rose-50 text-rose-800`:`border-zinc-200 bg-zinc-50 text-zinc-700`}`,children:[pe.reason,pe.status===`dirty`?(0,A.jsx)(`p`,{className:`mt-1 text-xs`,children:`Review and resolve these local changes in an external terminal, then check again. This updater never commits, stashes, discards, rebases, or merges them.`}):null]}):null,pe?.hasSubmodules?(0,A.jsx)(`p`,{className:`mt-3 rounded border border-amber-200 bg-amber-50 p-2 text-xs text-amber-800`,children:`This repository declares submodules. Their working trees will not be initialized or updated.`}):null,fe?.status===`ready`?(0,A.jsx)(`p`,{role:`status`,className:`mt-3 text-xs text-zinc-600`,children:fe.result?.status===`updated`&&fe.result.reloads.some(e=>e.status===`restart-required`)?`Repository updated. Its skills are reloaded; its extension code runs after pi-outpost restarts — restart it from Settings.`:fe.result?.status===`updated`?`Repository updated and runtimes reloaded.`:fe.result?.status===`updated-reload-failed`?`Repository updated on disk, but at least one runtime failed to reload.`:fe.result?.reason}):null,fe?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`mt-3 text-xs text-red-600`,children:fe.message}):null,ve&&j&&c!==`extension`?(0,A.jsxs)(`div`,{className:`mt-6 space-y-4`,children:[xe>0||Se?.status===`loading`?(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50 px-3 py-2 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,children:[(0,A.jsx)(`span`,{children:Se?.status===`loading`?`Applying…`:`${xe} pending change${xe===1?``:`s`} — applying replaces the session`}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:Se?.status===`loading`,onClick:we,className:`rounded border bg-white px-2.5 py-1 disabled:opacity-50 dark:bg-zinc-900`,children:`Discard`}),(0,A.jsx)(`button`,{type:`button`,disabled:Se?.status===`loading`||xe===0,onClick:Te,className:`rounded bg-zinc-900 px-2.5 py-1 font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900`,children:`Apply`})]})]}):null,Se?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:Se.message}):null,(0,A.jsx)(Yz,{skills:ve.skills,groups:ve.groups,enabled:be,onChange:Ce,disabled:Se?.status===`loading`,...ve.bound?{bound:ve.bound}:{}},j.id),de.resources.some(e=>e.kind===`extension`)?(0,A.jsx)(oB,{kind:`extension`,resources:de.resources.filter(e=>e.kind===`extension`),removalLocked:e.extensionLock,onRemove:ge}):null]}):(0,A.jsxs)(`div`,{className:`mt-6 grid grid-cols-2 gap-4`,children:[(0,A.jsx)(oB,{kind:`skill`,resources:de.resources.filter(e=>e.kind===`skill`),onRemove:ge}),(0,A.jsx)(oB,{kind:`extension`,resources:de.resources.filter(e=>e.kind===`extension`),removalLocked:e.extensionLock,onRemove:ge})]})]}):(0,A.jsx)(`p`,{className:`text-sm text-zinc-500`,children:`No resources are reported by this runtime.`})]})]})]}),re?(0,A.jsx)(`div`,{className:`fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4`,children:(0,A.jsxs)(`div`,{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`extension-update-title`,className:`w-full max-w-md rounded-xl bg-white p-5 shadow-2xl dark:bg-zinc-900`,children:[(0,A.jsx)(`h3`,{id:`extension-update-title`,className:`font-semibold`,children:`Update executable extensions?`}),(0,A.jsxs)(`p`,{className:`mt-2 text-sm text-zinc-600 dark:text-zinc-300`,children:[re.name,` contains extensions that run with the agent's privileges. Confirm updating `,re.assessment.localRevision?.slice(0,8),` to `,re.assessment.upstreamRevision?.slice(0,8),`.`]}),(0,A.jsxs)(`div`,{className:`mt-4 flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>ie(null),className:`rounded border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{_e(re,!0),ie(null)},className:`rounded bg-amber-600 px-3 py-1.5 text-xs font-medium text-white`,children:`Confirm executable update`})]})]})}):null,ae?(0,A.jsx)(`div`,{className:`fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4`,children:(0,A.jsxs)(`div`,{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`remove-repository-title`,"aria-describedby":`remove-repository-detail`,className:`w-full max-w-md rounded-xl bg-white p-5 shadow-2xl dark:bg-zinc-900`,children:[(0,A.jsxs)(`h3`,{id:`remove-repository-title`,className:`font-semibold`,children:[`Remove `,ae.name,`?`]}),(0,A.jsx)(`p`,{id:`remove-repository-detail`,className:`mt-2 break-words text-sm text-zinc-600 dark:text-zinc-300`,children:ae.removal?.deletesFiles?(0,A.jsxs)(A.Fragment,{children:[`This stops loading everything from `,ae.name,` and deletes `,(0,A.jsx)(`span`,{className:`font-mono`,children:ae.removal.path}),` from disk, with any local changes in it. This cannot be undone.`]}):(0,A.jsxs)(A.Fragment,{children:[`This stops loading everything from `,ae.name,`. pi-outpost does not manage `,(0,A.jsx)(`span`,{className:`font-mono`,children:ae.removal?.path??ae.path}),`, so its files will be kept.`]})}),(0,A.jsxs)(`div`,{className:`mt-4 flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>oe(null),className:`rounded border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemoveRepository(ae.id),ce({id:ae.id,name:ae.name}),oe(null)},className:`rounded bg-red-600 px-3 py-1.5 text-xs font-medium text-white`,children:ae.removal?.deletesFiles?`Delete and remove`:`Remove repository`})]})]})}):null]})}var lB=`w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 placeholder:text-zinc-400 focus:border-zinc-400 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-600`,uB=`rounded-md border border-zinc-300 px-3 py-1.5 text-xs font-medium text-zinc-700 hover:bg-zinc-50 disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`;function dB({event:e}){switch(e.type){case`auth_url`:return(0,A.jsxs)(`div`,{"data-testid":`login-auth-url`,className:`space-y-1`,children:[(0,A.jsx)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:e.instructions??`Open this page to sign in:`}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`truncate text-sm text-sky-700 underline dark:text-sky-400`,children:e.url}),(0,A.jsx)(`button`,{type:`button`,className:uB,onClick:()=>void navigator.clipboard?.writeText(e.url),children:`Copy`})]})]});case`device_code`:return(0,A.jsxs)(`div`,{"data-testid":`login-device-code`,className:`space-y-1`,children:[(0,A.jsxs)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:[`Enter this code at`,` `,(0,A.jsx)(`a`,{href:e.verificationUri,target:`_blank`,rel:`noopener noreferrer`,className:`text-sky-700 underline dark:text-sky-400`,children:e.verificationUri}),`:`]}),(0,A.jsx)(`p`,{className:`select-all font-mono text-2xl tracking-widest text-zinc-900 dark:text-zinc-50`,children:e.userCode})]});case`info`:return(0,A.jsxs)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:[e.message,e.links?.map(e=>(0,A.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`ml-2 text-sky-700 underline dark:text-sky-400`,children:e.label??e.url},e.url))]});case`progress`:return(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:e.message})}}function fB({prompt:e,onAnswer:t}){let[n,r]=(0,d.useState)(``),i=e.type===`manual_code`&&/^http:\/\/(?:localhost|127\.0\.0\.1):1455\/auth\/callback\/?$/.test(e.placeholder??``);return e.type===`select`?(0,A.jsxs)(`div`,{"data-testid":`login-prompt`,className:`space-y-2`,children:[(0,A.jsx)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:e.message}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.options.map(e=>(0,A.jsx)(`button`,{type:`button`,className:uB,title:e.description,onClick:()=>t(e.id),children:e.label},e.id))})]}):(0,A.jsxs)(`div`,{"data-testid":`login-prompt`,className:`space-y-2`,children:[(0,A.jsxs)(`label`,{className:`block text-sm text-zinc-700 dark:text-zinc-200`,children:[e.type===`manual_code`?`${e.message} — or the whole address the browser was sent to`:e.message,(0,A.jsx)(`input`,{className:`${lB} mt-1`,type:e.type===`secret`?`password`:`text`,name:`provider-auth-response`,placeholder:e.placeholder,autoComplete:`off`,spellCheck:e.type!==`manual_code`,autoFocus:!0,value:n,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),n.trim()&&t(n.trim()))}})]}),i&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-600 dark:text-zinc-300`,children:`If Pi Outpost runs on another computer, your browser may say it cannot connect to localhost. Copy the full address from that browser page and paste it above to finish signing in.`}),(0,A.jsx)(`button`,{type:`button`,className:uB,disabled:!n.trim(),onClick:()=>t(n.trim()),children:`Continue`})]})}function pB({login:e,providerName:t,onAnswer:n,onCancel:r,onDismiss:i}){return(0,A.jsxs)(`div`,{"data-testid":`login-flow`,className:`space-y-3 rounded-md border border-zinc-200 p-3 dark:border-zinc-700`,children:[(0,A.jsxs)(`p`,{className:`text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:[`Signing in to `,t]}),(0,A.jsxs)(`div`,{"aria-live":`polite`,"aria-atomic":`false`,children:[e.events.map((e,t)=>(0,A.jsx)(dB,{event:e},t)),e.prompt&&(0,A.jsx)(fB,{prompt:e.prompt.prompt,onAnswer:n},e.prompt.promptId),!e.done&&!e.prompt&&e.events.length===0&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:`Starting…`}),e.done?(0,A.jsxs)(`div`,{"data-testid":`login-done`,"data-ok":e.done.ok?`true`:`false`,className:`space-y-2`,children:[(0,A.jsx)(`p`,{className:`text-sm ${e.done.ok?`text-emerald-700 dark:text-emerald-400`:`text-red-700 dark:text-red-400`}`,children:e.done.ok?`Signed in to ${t}.`:e.done.cancelled?`Sign-in cancelled.`:`Sign-in failed: ${e.done.message??`unknown error`}`}),(0,A.jsx)(`button`,{type:`button`,className:uB,onClick:i,children:`Close`})]}):(0,A.jsx)(`button`,{type:`button`,className:uB,onClick:r,children:`Cancel`})]})]})}function mB(e){return[...e].sort((e,t)=>e.localeCompare(t))}function hB(e,t){return e===`models_json_key`?`This key is managed in models.json. Remove it from that provider configuration.`:e===`environment`?`This key comes from ${t??`the server environment`}. Remove it from there.`:`This key is managed by ${t??e??`the provider runtime`}. Remove it from that source.`}function gB(e,t){return e===`models_json_key`?`models.json`:t??e}function _B({credentials:e,login:t,onStartLogin:n,onAnswerLogin:r,onCancelLogin:i,onDismissLogin:a,onLogoutProvider:o,extensionPaths:s,configuredExtensionPaths:c,userExtensionPaths:l,extensionLock:u,piPackages:f=null,piPackageUpdate:p=null,canRestartServer:m=!1,serverRestarting:h=!1,onCheckPiPackages:g,onUpdatePiPackage:_,onRestartServer:v,restartNeeded:y=[],tools:b,commands:x,sandbox:S,showRoots:C=!0,gitUnavailable:w,userSkillPaths:T,serverBrowse:ee,pickerBlocked:E=!1,onPickerOpened:te,applyState:D,agentResources:ne=null,agentResourceOperations:re={clonePath:null,preview:null,enrollment:null,refresh:null,updates:{},skills:{},removals:{}},versions:ie,onBrowseServerPath:O,onCloseServerBrowser:k,onUpdateConfig:ae,onSuggestAgentResourceClonePath:oe=()=>{},onCloneAgentResourceRepository:se=()=>{},onEnrollAgentResourceRepository:ce=()=>{},onSetAgentResourceSkills:le=()=>{},onRemoveAgentResourceRepository:ue=()=>{},onRefreshAgentResourceRepositories:de=()=>{},onUpdateAgentResourceRepository:j=()=>{}}){let[fe,pe]=(0,d.useState)(!1),me=(0,d.useRef)(new Map),[he,ge]=(0,d.useState)(!1),_e=(0,d.useRef)(null),[ve,ye]=(0,d.useState)(``),[be,xe]=(0,d.useState)(``),[Se,Ce]=(0,d.useState)(!1),[we,Te]=(0,d.useState)(!1),[Ee,De]=(0,d.useState)(null),Oe=(e,r)=>{if(t&&!t.done){i?.(),a?.();let e=me.current.get(t.provider);e&&(e.open=!1)}else n?.(e,r)};(0,d.useEffect)(()=>{E&&Ee!==null&&De(null)},[E,Ee]);let ke=qL(()=>{(fe||Ee!==null)&&Le()}),Ae=b.filter(e=>e.active),je=b.filter(e=>!e.active),Me=x.filter(e=>e.source===`skill`),Ne=[...b].sort((e,t)=>e.name.localeCompare(t.name)||Number(t.active)-Number(e.active)),Pe=D?.status===`applying`,Fe=D?.status===`error`?D.message:null;(0,d.useEffect)(()=>{S&&(ye(S.root),xe(S.writableRoot??``),Ce(S.allowWrite),Te(S.allowBash))},[S]);let Ie=(0,d.useRef)(!1);(0,d.useEffect)(()=>{Ie.current&&D===null&&Le(),Ie.current=Pe},[D,Pe]);function Le(){pe(!1),De(null),k()}function Re(e,t){te?.(),De(e),O(t.trim()||`/`)}function ze(e){Ee===`root`?ye(e):Ee===`writableRoot`&&xe(e),De(null),k()}let Be=S!==null&&(ve!==S.root||(be.trim()||void 0)!==(S.writableRoot||void 0)||Se!==S.allowWrite||we!==S.allowBash);function Ve(){S&&Be&&ae({sandbox:{root:ve,allowWrite:Se,allowBash:we,writableRoot:be.trim()||void 0}})}let He=C&&S?.rootEditable!==!1,Ue=Ee!==null&&!E&&(0,A.jsx)(Rz,{label:Ee===`root`?`Choose the sandbox root`:`Choose the writable root`,browse:ee,onBrowse:O,onSelect:ze,onCancel:()=>{De(null),k()}});return(0,A.jsxs)(`div`,{className:`relative`,ref:ke,children:[(0,A.jsx)(`button`,{ref:_e,type:`button`,onClick:()=>pe(!fe),title:`Settings`,"aria-label":`Settings`,className:`${Az} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`⚙`}),fe&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-[80vh] w-[380px] flex-col rounded-lg border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsx)(`div`,{className:`border-b border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:(0,A.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:`Settings`})}),(0,A.jsxs)(`div`,{className:`min-h-0 overflow-y-auto p-4`,children:[w&&(0,A.jsxs)(`section`,{className:`mb-4`,"data-testid":`git-unavailable`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Version control`}),w.reason===`no-repository`?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:`This project is not in a git repository.`}):(0,A.jsxs)(`div`,{className:`rounded border border-amber-300 bg-amber-50 px-2 py-1.5 dark:border-amber-900 dark:bg-amber-950/40`,children:[(0,A.jsx)(`p`,{className:`text-xs text-amber-800 dark:text-amber-300`,children:w.reason===`no-executable`?`Git is unavailable: its executable could not be run.`:`Git is unavailable: it refused this repository.`}),(0,A.jsx)(`p`,{className:`mt-1 break-all font-mono text-[11px] text-amber-700 dark:text-amber-400`,children:w.message}),w.reason===`no-executable`&&(0,A.jsxs)(`p`,{className:`mt-1 text-xs text-amber-700 dark:text-amber-400`,children:[`Install git, add it to PATH, or name it with `,(0,A.jsx)(`span`,{className:`font-mono`,children:`gitPath`}),` in the configuration.`]})]})]}),e&&(0,A.jsxs)(`details`,{className:`mb-4`,"data-testid":`accounts-panel`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:[`Accounts · `,(0,A.jsxs)(`span`,{className:`text-emerald-700 dark:text-emerald-400`,children:[e.providers.filter(e=>e.configured).length,` providers configured`]})]}),(0,A.jsxs)(`div`,{className:`mt-2`,children:[(0,A.jsx)(`ul`,{className:`space-y-2`,children:e.providers.map(n=>(0,A.jsx)(`li`,{className:`rounded border border-zinc-200 p-2 dark:border-zinc-700`,children:(0,A.jsxs)(`details`,{ref:e=>{e?me.current.set(n.id,e):me.current.delete(n.id)},"data-testid":`account-${n.id}`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium text-zinc-800 dark:text-zinc-200`,children:n.name}),(0,A.jsx)(`span`,{className:`ml-2 text-[11px] ${n.configured?`text-emerald-700 dark:text-emerald-400`:`text-zinc-500 dark:text-zinc-400`}`,children:n.configured?`${n.auth??`Authenticated`}${n.source?` · ${gB(n.source,n.label)}`:``}`:`Not signed in`})]}),(0,A.jsxs)(`div`,{className:`mt-2`,children:[n.configured&&n.auth===`api_key`&&n.source!==`stored`&&(0,A.jsx)(`p`,{className:`mb-2 text-[11px] text-zinc-500 dark:text-zinc-400`,children:hB(n.source,n.label)}),!e.locked&&(0,A.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[n.methods?.includes(`oauth`)&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>Oe(n.id,`oauth`),children:`Sign in`}),n.methods?.includes(`api_key`)&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>Oe(n.id,`api_key`),children:`API key`}),n.configured&&n.source===`stored`&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>o?.(n.id),children:n.auth===`api_key`?`Remove API key`:`Sign out`})]}),t?.provider===n.id&&(0,A.jsx)(`div`,{className:`mt-2`,children:(0,A.jsx)(pB,{login:t,providerName:n.name,onAnswer:e=>r?.(e),onCancel:()=>i?.(),onDismiss:()=>a?.()})})]})]})},n.id))}),e.locked&&(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-500 dark:text-zinc-400`,children:`Credentials are locked by this server.`})]})]}),(0,A.jsxs)(`section`,{className:`mb-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Agent resources`}),b.length===0?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`Tool inventory unavailable for this runtime`}):(0,A.jsxs)(`details`,{"data-testid":`tools-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[Ae.length,` tools active`,je.length?` · ${je.length} inactive`:``]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:Ne.map(e=>(0,A.jsxs)(`li`,{className:`flex justify-between rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{children:e.name}),(0,A.jsx)(`span`,{children:e.active?`active`:`inactive`})]},e.name))})]}),Me.length===0?(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-400 dark:text-zinc-500`,children:`No skills loaded`}):(0,A.jsxs)(`details`,{className:`mt-2`,"data-testid":`skills-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[Me.length,` skills loaded`]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:mB(Me.map(e=>e.name)).map(e=>(0,A.jsx)(`li`,{className:`rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:e},e))})]}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Manage agent resources`,onClick:()=>{pe(!1),ge(!0)},className:`mt-3 w-full rounded-md border border-zinc-300 px-3 py-2 text-xs font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`,children:`Manage resources…`})]}),(0,A.jsxs)(`section`,{className:`mb-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Extensions`}),s===null?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,"data-testid":`extensions-unknown`,children:`Not reported by this runtime`}):s.length===0?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`No extensions loaded`}):(0,A.jsxs)(`details`,{"data-testid":`extensions-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[s.length,` `,s.length===1?`extension`:`extensions`,` loaded`]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:mB(s).map(e=>(0,A.jsx)(`li`,{className:`truncate rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,title:e,children:e},e))})]}),c.length>0&&(0,A.jsxs)(`details`,{className:`mt-2`,"data-testid":`extensions-configured`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[c.length,` configured by this deployment`]}),(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-400 dark:text-zinc-500`,children:`Declared in the configuration file. They load either way, and nothing here can remove them.`}),(0,A.jsx)(`ul`,{className:`mt-1 space-y-1`,children:mB(c).map(e=>(0,A.jsx)(`li`,{className:`truncate rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,title:e,children:e},e))})]}),u?(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-400 dark:text-zinc-500`,"data-testid":`extensions-locked`,children:`Extension paths and repository updates that contain extensions are locked by this deployment.`}):null,(0,A.jsx)(Gz,{packages:f,update:p,locked:u,onCheck:()=>g?.(),onUpdate:e=>_?.(e)}),(0,A.jsx)(Kz,{reasons:y,canRestart:m,restarting:h,onRestart:()=>v?.()})]}),S&&(0,A.jsxs)(`section`,{children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:He?`Sandbox`:`Agent permissions`}),(0,A.jsxs)(`div`,{className:`space-y-3`,children:[!He&&(0,A.jsxs)(`p`,{"data-testid":`sandbox-project-root`,className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`This project is confined to its own folder,`,` `,(0,A.jsx)(`span`,{className:`break-all font-mono text-zinc-800 dark:text-zinc-200`,children:S.projectRoot??S.root}),`. Each open project is confined to its own. A change here applies to this project now, and to projects opened after.`]}),He&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Root `,S.locks?.root?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{type:`text`,value:ve,onChange:e=>ye(e.target.value),disabled:S.locks?.root,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none focus:border-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Browse for sandbox root`,disabled:S.locks?.root,onClick:()=>Re(`root`,ve),className:`shrink-0 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300`,children:`Browse…`})]})]}),Ee===`root`&&Ue,(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Writable root (optional) `,S.locks?.writableRoot?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{type:`text`,value:be,onChange:e=>xe(e.target.value),disabled:S.locks?.writableRoot,placeholder:`Same as root`,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Browse for writable root`,disabled:S.locks?.writableRoot,onClick:()=>Re(`writableRoot`,be||ve),className:`shrink-0 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300`,children:`Browse…`})]})]}),Ee===`writableRoot`&&Ue]}),(0,A.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:Se,onChange:e=>Ce(e.target.checked),disabled:S.locks?.allowWrite,className:`rounded border-zinc-300 text-zinc-700 focus:ring-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Allow write `,S.locks?.allowWrite?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]})]}),(0,A.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:we,onChange:e=>Te(e.target.checked),disabled:S.locks?.allowBash,className:`rounded border-zinc-300 text-zinc-700 focus:ring-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Allow bash `,S.locks?.allowBash?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]})]})]})]}),!S&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`No sandbox configured`}),S&&(0,A.jsxs)(`div`,{className:`mt-4 space-y-2`,children:[Fe&&(0,A.jsx)(`p`,{role:`alert`,className:`rounded-md border border-red-300 bg-red-50 px-2 py-1 text-xs text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:Fe}),(0,A.jsx)(`button`,{type:`button`,disabled:Pe||!Be||S!==null&&!ve.trim(),onClick:Ve,className:`w-full rounded-md bg-zinc-800 px-3 py-1.5 text-xs font-medium text-white hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-zinc-200 dark:text-zinc-900 dark:hover:bg-zinc-300`,children:Pe?`Applying…`:`Apply & restart session`}),(0,A.jsx)(`p`,{className:`text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Saved to the server's configuration file, then the session is rebuilt — the change survives a restart.`})]}),ie&&(0,A.jsxs)(`section`,{className:`mt-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Versions`}),(0,A.jsxs)(`div`,{className:`space-y-1 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsxs)(`p`,{children:[`pi-outpost: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.piOutpost})]}),ie.piSdk&&(0,A.jsxs)(`p`,{children:[`pi SDK: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.piSdk})]}),ie.agent&&(0,A.jsxs)(`p`,{children:[`agent: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.agent})]})]})]})]})]}),(0,A.jsx)(cB,{open:he,inventory:ne,operations:re,extensionLock:u,userSkillPaths:T,userExtensionPaths:l,serverBrowse:ee,applyState:D,onClose:()=>{ge(!1),k(),_e.current?.focus()},onBrowseServerPath:e=>{te?.(),O(e)},onCloseServerBrowser:k,onUpdateConfig:ae,onSuggestClonePath:oe,onCloneRepository:se,onEnrollRepository:ce,onSetSkills:le,onRemoveRepository:ue,onRefresh:de,onUpdate:j})]})}function vB(e){let t=[],n=new Set,r=0,i=0;function a(e,o,s,c){let l=e.children,u=l.slice(1).map(e=>[e,r++]);u.length>0&&i++;let d=e.onPath&&!l.some(e=>e.onPath);if(t.push({node:e,lane:o,through:[...n].filter(e=>e!==o),forkTo:u.map(([,e])=>e),lineAbove:s,lineBelow:l.length>0,branchIndex:c,isCurrent:d,emphasis:d?`current`:e.onPath?`filled`:`hollow`,highlight:e.onPath}),l.length===0)n.delete(o);else{for(let[,e]of u)n.add(e);a(l[0],o,!0,u.length>0?1:void 0),u.forEach(([e,t],n)=>a(e,t,!0,n+2))}}return e.length>1&&i++,e.forEach((t,i)=>{let o=r++;n.add(o),a(t,o,!1,e.length>1?i+1:void 0)}),{rows:t,laneCount:r,branchPoints:i}}function yB(e){return e.flatMap(e=>[e,...yB(e.children)])}function bB({children:e,tone:t}){let n={current:`border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300`,branch:`border-zinc-300 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400`,label:`border-violet-300 bg-violet-50 text-violet-700 dark:border-violet-900 dark:bg-violet-950/50 dark:text-violet-300`}[t];return(0,A.jsx)(`span`,{className:`shrink-0 rounded-full border px-1.5 py-px text-[10px] leading-4 ${n}`,children:e})}var xB=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`;function SB({row:e,laneCount:t,isStreaming:n,onNavigate:r,onFork:i,onClose:a}){let{node:o}=e,s=o.tipId??o.entryId;return(0,A.jsxs)(`div`,{className:`group flex items-center gap-1 pr-2 hover:bg-zinc-100 dark:hover:bg-zinc-800/70 ${e.isCurrent?`bg-emerald-50/60 dark:bg-emerald-950/20`:``}`,style:{height:36},children:[(0,A.jsxs)(`button`,{type:`button`,disabled:n,onClick:()=>{r(s),a()},title:n?`unavailable while the agent is running`:o.tipId?`restore the conversation at this point (reply included)`:`go back to this point`,className:`flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left text-sm disabled:opacity-50`,children:[(0,A.jsx)(_z,{row:e,laneCount:t,colorOf:mz}),(0,A.jsx)(`span`,{className:`min-w-0 truncate ${o.onPath?`text-zinc-800 dark:text-zinc-200`:`text-zinc-600 dark:text-zinc-400`}`,children:o.text||`(empty)`}),e.forkTo.length>0&&(0,A.jsxs)(bB,{tone:`branch`,children:[e.forkTo.length+1,` branches`]}),e.branchIndex!==void 0&&(0,A.jsxs)(bB,{tone:`branch`,children:[`branch `,e.branchIndex,o.onPath&&!e.isCurrent?` · current`:``]}),e.isCurrent&&(0,A.jsx)(bB,{tone:`current`,children:`current`}),o.label&&(0,A.jsx)(bB,{tone:`label`,children:o.label})]}),(0,A.jsx)(`button`,{type:`button`,disabled:n,onClick:()=>{r(o.entryId),a()},title:`rewind to just before this message (its text comes back in the composer)`,"aria-label":`Rewind to before this message`,className:xB,children:`↺ redo`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{i(o.entryId),a()},title:`fork a new session from this point`,className:xB,children:`⑂ fork`})]})}function CB({tree:e,isStreaming:t,onListTree:n,onNavigate:r,onFork:i}){let[a,o]=(0,d.useState)(!1),[s,c]=(0,d.useState)(``),l=qL(()=>o(!1));(0,d.useEffect)(()=>{a&&e===null&&n()},[a,e]);let u=(0,d.useMemo)(()=>e&&e.length>0?vB(e):null,[e]),f=(0,d.useMemo)(()=>{if(!e||!s.trim())return null;let t=s.trim().toLowerCase();return yB(e).filter(e=>e.text.toLowerCase().includes(t)||e.label?.toLowerCase().includes(t))},[e,s]);return(0,A.jsxs)(`div`,{className:`relative`,ref:l,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{o(!a),a||(c(``),n())},title:`conversation tree: go back to an earlier point or fork`,className:`${Az} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`tree`}),a&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-[70vh] w-[32rem] max-w-[90vw] flex-col rounded-lg border border-zinc-200 bg-white shadow-xl [--tree-off:#e4e4e7] dark:border-zinc-700 dark:bg-zinc-900 dark:[--tree-off:#3f3f46]`,children:[e===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),e?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no messages yet`}),e&&e.length>0&&u&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,A.jsx)(`span`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:`Conversation tree`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:[u.rows.length,` turn`,u.rows.length===1?``:`s`,` · `,u.branchPoints,` branch point`,u.branchPoints===1?``:`s`]})]}),(0,A.jsx)(`input`,{type:`search`,value:s,onChange:e=>c(e.target.value),placeholder:`Search tree`,"aria-label":`Search conversation tree`,className:`mt-2 w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`p`,{className:`mt-1.5 text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Follow the colored lines — the current branch is highlighted. Click a turn to restore the conversation there · ↺ to send it again · ⑂ to fork a session`})]}),(0,A.jsx)(`div`,{className:`min-h-0 overflow-y-auto py-1`,children:f===null?u.rows.map(e=>(0,A.jsx)(SB,{row:e,laneCount:u.laneCount,isStreaming:t,onNavigate:r,onFork:i,onClose:()=>o(!1)},e.node.entryId)):f.length===0?(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no matches`}):f.map(e=>(0,A.jsxs)(`div`,{className:`group flex items-center gap-1 pr-2 hover:bg-zinc-100 dark:hover:bg-zinc-800/70`,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:t,onClick:()=>{r(e.tipId??e.entryId),o(!1)},title:e.tipId?`restore the conversation at this point (reply included)`:`go back to this point`,className:`flex min-w-0 flex-1 items-center gap-2 px-3 py-1.5 text-left text-sm disabled:opacity-50`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:e.onPath?`text-emerald-500`:`text-zinc-300 dark:text-zinc-600`,children:`●`}),(0,A.jsx)(`span`,{className:`min-w-0 truncate text-zinc-700 dark:text-zinc-300`,children:e.text||`(empty)`}),e.onPath&&(0,A.jsx)(bB,{tone:`current`,children:`on current branch`}),e.label&&(0,A.jsx)(bB,{tone:`label`,children:e.label})]}),(0,A.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>{r(e.entryId),o(!1)},title:`rewind to just before this message (its text comes back in the composer)`,"aria-label":`Rewind to before this message`,className:xB,children:`↺ redo`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{i(e.entryId),o(!1)},title:`fork a new session from this point`,className:xB,children:`⑂ fork`})]},e.entryId))})]})]})]})}var wB=200;function TB({initial:e,onCommit:t,onCancel:n}){let[r,i]=(0,d.useState)(e);return(0,A.jsx)(`input`,{autoFocus:!0,value:r,onChange:e=>i(e.target.value),onBlur:n,onKeyDown:e=>{e.key===`Enter`?t(r):e.key===`Escape`&&n()},placeholder:`Session name (empty to clear)`,"aria-label":`Session name`,className:`w-full rounded-md border border-zinc-400 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 dark:border-zinc-600 dark:placeholder:text-zinc-600`})}function EB({session:e,isCurrent:t,renaming:n,onSwitch:r,onDelete:i,onStartRename:a,onRename:o,onCancelRename:s}){return n?(0,A.jsx)(`div`,{className:`px-3 py-2`,children:(0,A.jsx)(TB,{initial:e.name??``,onCommit:o,onCancel:s})}):(0,A.jsxs)(`div`,{className:`group flex items-start gap-1 hover:bg-zinc-100 dark:hover:bg-zinc-800 ${t?`bg-zinc-100 dark:bg-zinc-800/60`:``}`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:r,className:`min-w-0 flex-1 px-3 py-2 text-left text-sm`,children:[(0,A.jsx)(`div`,{className:`truncate text-zinc-700 dark:text-zinc-300`,children:e.name||e.firstMessage||`(empty)`}),e.snippet&&(0,A.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-zinc-500 dark:text-zinc-500`,children:e.snippet}),(0,A.jsxs)(`div`,{className:`mt-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:[new Date(e.modified).toLocaleString(),` · `,e.messageCount,` messages`,t?` · current`:``,!t&&e.liveIn?(0,A.jsxs)(`span`,{"data-testid":`session-live-in`,children:[` · open in `,e.liveIn]}):null]})]}),(0,A.jsx)(`button`,{type:`button`,onClick:a,title:`rename session`,"aria-label":`Rename session`,className:`mt-2 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✎`}),!t&&!e.liveIn&&(0,A.jsx)(`button`,{type:`button`,onClick:i,title:`delete session`,"aria-label":`Delete session`,className:`mr-2 mt-2 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-red-100 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-600 dark:hover:bg-red-950/60 dark:hover:text-red-400`,children:`✕`})]})}function DB({sessions:e,sessionSearch:t,sessionId:n,onSwitchSession:r,onDeleteSession:i,onListSessions:a,onRenameSession:o,onSearchSessions:s,onClearSessionSearch:c}){let[l,u]=(0,d.useState)(!1),[f,p]=(0,d.useState)(``),[m,h]=(0,d.useState)(null),g=qL(()=>u(!1)),_=f.trim(),v=_.length>=2;(0,d.useEffect)(()=>{if(!l)return;if(!v){c();return}let e=setTimeout(()=>s(_),wB);return()=>clearTimeout(e)},[l,_,v]);function y(){u(!1),h(null)}let b=v&&(t?.status!==`loaded`||t.query!==_),x=v?b?null:t?.results??null:e;return(0,A.jsxs)(`div`,{className:`relative`,ref:g,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{l?y():(u(!0),p(``),h(null),c(),a())},className:`${Az} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`sessions`}),l&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-96 w-96 flex-col rounded-lg border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`input`,{type:`search`,value:f,onChange:e=>p(e.target.value),placeholder:`Search sessions`,"aria-label":`Search sessions`,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`p`,{className:`mt-1.5 text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Searches names and everything said in a session · ✎ to rename`})]}),(0,A.jsxs)(`div`,{className:`min-h-0 overflow-y-auto`,children:[x===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),x?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:v?`no matches`:`no saved sessions`}),x?.map(e=>(0,A.jsx)(EB,{session:e,isCurrent:e.id===n,renaming:m===e.path,onSwitch:()=>{r(e.path),y()},onDelete:()=>{window.confirm(`Delete this session?`)&&i(e.path)},onStartRename:()=>h(e.path),onRename:t=>{o(e.path,t),h(null),v&&s(f.trim())},onCancelRename:()=>h(null)},e.path))]})]})]})}function OB({filters:e,onFilterChange:t}){let[n,r]=(0,d.useState)(!1),i=qL(()=>r(!1)),a=gL(e),o=a>0?`Filter · ${a} hidden`:`Filter`;return(0,A.jsxs)(`div`,{className:`relative`,ref:i,onKeyDown:e=>{e.key===`Escape`&&n&&(e.stopPropagation(),r(!1))},children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>r(!n),"aria-haspopup":`menu`,"aria-expanded":n,title:`Choose what the conversation shows`,className:`${Az} ${a>0?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:o}),n&&(0,A.jsx)(`div`,{role:`menu`,className:`absolute right-0 z-30 mt-1 w-48 rounded-md border border-zinc-200 bg-white py-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:dL.map(n=>(0,A.jsxs)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":e[n],onClick:()=>t(n,!e[n]),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`w-3`,children:e[n]?`✓`:``}),(0,A.jsx)(`span`,{children:fL[n]})]},n))})]})}function kB({statuses:e,bar:t}){let n=Object.entries(e).map(([e,t])=>[e,vR(t)]).filter(([,e])=>e.trim()!==``),r=n.map(([e,t])=>`${e}\u0000${t}`).join(``),[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null),s=(0,d.useRef)(null),[c,l]=(0,d.useState)(!1),u=qL(()=>l(!1));if((0,d.useLayoutEffect)(()=>{o.current=null,a(!1),l(!1)},[r]),(0,d.useLayoutEffect)(()=>{let e=t;if(e===null)return;let n=()=>{o.current===null?(Array.from(s.current?.querySelectorAll(`[data-status-text]`)??[]).some(e=>e.scrollWidth>e.clientWidth+1)||e.scrollWidth>e.clientWidth+1)&&(o.current=e.clientWidth,a(!0)):e.clientWidth>o.current+64&&(o.current=null,a(!1),l(!1))};if(n(),typeof ResizeObserver>`u`)return;let r=new ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[t,i,r]),n.length===0)return null;if(!i)return(0,A.jsx)(`div`,{ref:s,className:`flex shrink-0 items-center gap-1.5`,children:n.map(([e,t])=>(0,A.jsx)(`span`,{title:t,className:`${Az} max-w-[16rem] border-zinc-200 text-zinc-500 dark:border-zinc-800 dark:text-zinc-400`,children:(0,A.jsx)(`span`,{"data-status-text":!0,className:`truncate`,children:t})},e))});let f=`${n.length} ${n.length===1?`status`:`statuses`}`;return(0,A.jsxs)(`div`,{ref:u,className:`relative shrink-0`,onKeyDown:e=>{e.key===`Escape`&&c&&(e.stopPropagation(),l(!1))},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>l(!c),"aria-expanded":c,title:n.map(([,e])=>e).join(`
362
- `),className:`${Az} border-zinc-200 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:[f,` ▾`]}),c&&(0,A.jsx)(`ul`,{"aria-label":`Extension statuses`,className:`absolute left-0 top-full z-20 mt-1 w-max max-w-[24rem] rounded-md border border-zinc-200 bg-white py-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:n.map(([e,t])=>(0,A.jsx)(`li`,{className:`break-words px-3 py-1.5 text-xs text-zinc-600 dark:text-zinc-300`,children:t},e))})]})}function AB({theme:e,onToggle:t}){return(0,A.jsx)(`button`,{type:`button`,onClick:t,title:e===`dark`?`Switch to light theme`:`Switch to dark theme`,"aria-label":e===`dark`?`Switch to light theme`:`Switch to dark theme`,className:`${Az} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:e===`dark`?`☀`:`☾`})}function jB(e){let{isStreaming:t,connected:n}=e,[r,i]=(0,d.useState)(null);return(0,A.jsxs)(`header`,{ref:i,className:`relative z-30 flex min-w-0 items-center gap-1.5 border-b border-zinc-200 px-4 py-2 dark:border-zinc-800`,children:[e.workspaceControl===`projects`&&(0,A.jsx)(Lz,{workspace:e.workspace,workspaces:e.workspaces,locked:e.workspaceLocked,onSwitch:e.onSwitchWorkspace,onOpen:e.onOpenProject,onClose:e.onCloseProject,onOpenSide:e.onOpenSideSession}),e.workspaceControl===`root`&&e.rootControl&&(0,A.jsx)(Bz,{sandbox:e.rootControl.sandbox,browse:e.rootControl.browse,applyState:e.rootControl.applyState,blocked:e.rootControl.blocked,onBrowse:e.rootControl.onBrowse,onCloseBrowser:e.rootControl.onCloseBrowser,onOpened:e.rootControl.onOpened,onSelect:e.rootControl.onSelect}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onToggleSidebar,title:e.sidebarOpen?`Hide files (panel opens on the left)`:`Show files`,"aria-pressed":e.sidebarOpen,className:`${Az} ${e.sidebarOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:[e.sidebarOpen?`◧`:`◨`,` files`]}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onToggleOutcome,"aria-pressed":e.outcomeOpen,title:`Review structured workspace Outcome`,className:`${Az} ${e.outcomeOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:e.workspace?.activity===`ready-for-review`?`border-amber-400 text-amber-700 dark:text-amber-300`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 dark:border-zinc-800 dark:text-zinc-400`}`,children:[`Outcome`,e.workspace?.activity===`ready-for-review`?` •`:``]}),e.gitAvailable&&(0,A.jsx)(Uz,{status:e.gitStatus,selected:e.gitSelectedPath,log:e.gitLog,onFetchLog:e.onFetchGitLog,onShowCommit:e.onShowCommit}),(0,A.jsx)(`span`,{title:e.title??void 0,className:`min-w-[2.25rem] shrink-[4] truncate whitespace-nowrap text-lg font-semibold leading-tight tracking-tight`,style:{color:`var(--accent, inherit)`},children:e.title??`π`}),(0,A.jsx)(kB,{statuses:e.statuses,bar:r}),(0,A.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1.5`,children:[(0,A.jsx)(OB,{filters:e.filters,onFilterChange:e.onFilterChange}),e.onExportConversation&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onExportConversation,disabled:!!e.exportProgress,"aria-busy":!!e.exportProgress,title:`Save the whole conversation as one HTML file`,"aria-label":`Export the conversation as HTML`,className:`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 disabled:cursor-progress disabled:opacity-60 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:e.exportProgress??`↓ html`}),e.onToggleTerminal&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onToggleTerminal,title:e.terminalOpen?"Close Terminal (Ctrl+`)":"Open Terminal (Ctrl+`)","aria-pressed":e.terminalOpen,className:`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none ${e.terminalOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:`>_ terminal`}),e.showThemeToggle&&(0,A.jsx)(AB,{theme:e.theme,onToggle:e.onToggleTheme}),(0,A.jsx)(`button`,{type:`button`,onClick:e.onNewSession,title:`new session`,className:`${Az} border-emerald-300 text-emerald-700 hover:border-emerald-500 hover:text-emerald-600 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600 dark:hover:text-emerald-300`,children:`+ new`}),(0,A.jsx)(CB,{tree:e.tree,isStreaming:t,onListTree:e.onListTree,onNavigate:e.onNavigateTree,onFork:e.onForkSession}),(0,A.jsx)(DB,{sessions:e.sessions,sessionSearch:e.sessionSearch,sessionId:e.sessionId,onSwitchSession:e.onSwitchSession,onDeleteSession:e.onDeleteSession,onListSessions:e.onListSessions,onRenameSession:e.onRenameSession,onSearchSessions:e.onSearchSessions,onClearSessionSearch:e.onClearSessionSearch}),(0,A.jsx)(_B,{credentials:e.credentials,login:e.login,onStartLogin:e.onStartLogin,onAnswerLogin:e.onAnswerLogin,onCancelLogin:e.onCancelLogin,onDismissLogin:e.onDismissLogin,onLogoutProvider:e.onLogoutProvider,extensionPaths:e.extensionPaths,configuredExtensionPaths:e.configuredExtensionPaths,userExtensionPaths:e.userExtensionPaths,extensionLock:e.extensionLock,piPackages:e.piPackages??null,piPackageUpdate:e.piPackageUpdate??null,canRestartServer:e.canRestartServer??!1,serverRestarting:e.serverRestarting??!1,...e.onCheckPiPackages?{onCheckPiPackages:e.onCheckPiPackages}:{},...e.onUpdatePiPackage?{onUpdatePiPackage:e.onUpdatePiPackage}:{},...e.onRestartServer?{onRestartServer:e.onRestartServer}:{},restartNeeded:e.restartNeeded??[],tools:e.tools??[],commands:e.commands??[],sandbox:e.sandbox,showRoots:!(e.workspaceControl===`projects`&&e.workspaces.filter(e=>!e.sideOf).length>1),gitUnavailable:e.gitUnavailable,userSkillPaths:e.userSkillPaths,serverBrowse:e.serverBrowse,applyState:e.settingsApply,agentResources:e.agentResources,agentResourceOperations:e.agentResourceOperations,versions:e.versions,onBrowseServerPath:e.onBrowseServerPath,onCloseServerBrowser:e.onCloseServerBrowser,pickerBlocked:e.settingsPickerBlocked,onPickerOpened:e.onSettingsPickerOpened,onUpdateConfig:e.onUpdateConfig,onSuggestAgentResourceClonePath:e.onSuggestAgentResourceClonePath,onCloneAgentResourceRepository:e.onCloneAgentResourceRepository,onEnrollAgentResourceRepository:e.onEnrollAgentResourceRepository,onSetAgentResourceSkills:e.onSetAgentResourceSkills,onRemoveAgentResourceRepository:e.onRemoveAgentResourceRepository,onRefreshAgentResourceRepositories:e.onRefreshAgentResourceRepositories,onUpdateAgentResourceRepository:e.onUpdateAgentResourceRepository}),(0,A.jsx)(`span`,{className:`h-2 w-2 rounded-full ${n?`bg-emerald-500`:`bg-red-500`}`,title:n?`connected`:`disconnected`})]})]})}function MB(e,t){let n=(0,d.useRef)(new Map);(0,d.useEffect)(()=>{if(typeof Notification>`u`)return;let r=e.filter(e=>e.needsAttention),i=r.filter(e=>kI(e)!==t);for(let e of[...n.current.keys()])r.some(t=>kI(t)===e)||n.current.delete(e);if(Notification.permission===`granted`&&(typeof document>`u`||document.visibilityState!==`visible`)){for(let e of i)if(n.current.get(kI(e))!==e.activity){n.current.set(kI(e),e.activity);try{let t=e.activity===`ready-for-review`;new Notification(t?`${e.name} is ready for review`:`${e.name} needs you`,{body:t?`Background work is ready for review.`:`The agent needs an answer to continue.`,tag:`pi-outpost:${kI(e)}`})}catch{}}}},[e,t])}var NB={"agent-directory":`read the agent directory (the provider keys)`,"beside-root":`read a file beside the root`,"write-beside-root":`write beside the root`,"signal-process":`signal another process of the server's user`,"server-environment":`inherit the server's environment`,"server-process-environment":`read the server's process environment (/proc)`,"unlisted-host":`reach a host not in sandbox.allowedHosts`,"direct-connection":`connect around the proxy`},PB=e=>e.map(e=>NB[e]??e),FB=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()};function IB(e,t){let n=t===`shell`?`The agent's shell`:`This terminal`;switch(e.state){case`checking`:return`${n} runs under ${e.runner||`a sandbox runner`}; its confinement is being checked.`;case`verified`:return[`${n} is confined by ${e.runner}, checked at ${FB(e.checkedAt)}. A command could not:`,...PB(e.refused).map(e=>`• ${e}`),...e.environmentReadable?[`The server's process environment is readable, and holds no secret.`]:[],...e.notChecked.length?[`Not checked:`,...e.notChecked.map(e=>`• ${NB[e.attempt]??e.attempt} — ${e.why}`)]:[]].join(`
363
- `);case`partial`:return[`${n} is confined by ${e.runner}, checked at ${FB(e.checkedAt)}, except one thing: a command can read the server's process environment, which holds ${e.exposed.join(`, `)}.`,`Move these out of the server's environment — provider keys belong in the agent directory.`,`A command could not:`,...PB(e.refused).map(e=>`• ${e}`)].join(`
364
- `);case`leaking`:return[`${n} is NOT confined as configured: under ${e.runner}, checked at ${FB(e.checkedAt)}, a command could:`,...PB(e.reached).map(e=>`• ${e}`),`The configuration is unchanged: fix the runner or its host, or stop using it.`].join(`
365
- `);case`failed`:return`${n}'s confinement could not be checked (${e.runner}, ${FB(e.checkedAt)}): ${e.reason}`}}function LB({verdict:e,surface:t,root:n}){let r=n?` to ${n}`:``,i=e.state===`verified`?{icon:`🔒`,text:`confined${r}`,tone:`bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200`}:e.state===`partial`?{icon:`🔐`,text:`partly confined`,tone:`bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200`}:e.state===`leaking`?{icon:`🔓`,text:`not confined`,tone:`bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-200`}:e.state===`failed`?{icon:`⚠`,text:`confinement unchecked`,tone:`bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200`}:{icon:`…`,text:`checking confinement`,tone:`bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-300`};return(0,A.jsxs)(`span`,{"data-testid":t===`shell`?`shell-confinement`:`terminal-confined`,"data-state":e.state,title:IB(e,t),className:`shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 font-sans text-[11px] ${i.tone}`,children:[i.icon,` `,t===`shell`?`shell ${i.text}`:i.text]})}function RB(e){return!e||e.percent===null?`text-zinc-400 dark:text-zinc-600`:e.percent>=85?`text-red-500`:e.percent>=60?`text-amber-500 dark:text-amber-400`:`text-emerald-500`}function zB({usage:e,analysisOpen:t,onToggleAnalysis:n}){if(e.turns===0)return null;let r=e.turns-e.unpriced,i=[`${e.turns} turn${e.turns===1?``:`s`}`,`input ${e.input.toLocaleString()}`,`output ${e.output.toLocaleString()}`,`cache read ${e.cacheRead.toLocaleString()}`,`cache write ${e.cacheWrite.toLocaleString()}`,...e.unpriced>0&&r>0?[`${e.unpriced} unpriced`]:[]].join(` · `),a=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{children:[II(e.totalTokens),` tok`]}),r>0&&(0,A.jsxs)(`span`,{className:`text-zinc-400 dark:text-zinc-500`,children:[FI(e.cost),e.unpriced>0&&`*`]})]}),o=`flex items-center gap-1.5 rounded-md border px-2 py-1 font-mono text-xs text-zinc-500 dark:text-zinc-400`;return n?(0,A.jsx)(`button`,{type:`button`,onClick:n,title:`${i} — click for the session analysis`,"aria-haspopup":`dialog`,"aria-expanded":t??!1,className:`${o} ${t?`border-zinc-400 dark:border-zinc-600`:`border-zinc-300 hover:border-zinc-400 dark:border-zinc-800 dark:hover:border-zinc-600`}`,children:a}):(0,A.jsx)(`span`,{title:i,className:`${o} border-zinc-300 dark:border-zinc-800`,children:a})}function BB({usage:e}){let t=15.9155,n=2*Math.PI*t,r=e?.percent??0,i=Math.min(100,Math.max(0,r))/100*n;return(0,A.jsxs)(`svg`,{width:18,height:18,viewBox:`0 0 36 36`,className:`-rotate-90 shrink-0`,children:[(0,A.jsx)(`circle`,{cx:`18`,cy:`18`,r:t,fill:`none`,stroke:`currentColor`,strokeWidth:`4`,className:`text-zinc-200 dark:text-zinc-800`}),e&&e.percent!==null&&(0,A.jsx)(`circle`,{cx:`18`,cy:`18`,r:t,fill:`none`,stroke:`currentColor`,strokeWidth:`4`,strokeLinecap:`round`,strokeDasharray:`${i} ${n-i}`,className:RB(e)})]})}function VB({thinkingLevel:e,thinkingLevels:t,isStreaming:n,onSetThinking:r}){let[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null),s=e!==`off`,c=t&&t.length>0?t:tz,l=c.indexOf(e),u=c.length>1;return(0,d.useEffect)(()=>{if(!i)return;function e(e){o.current&&!KL(e,o.current)&&a(!1)}function t(e){e.key===`Escape`&&a(!1)}return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]),(0,A.jsxs)(`div`,{className:`relative`,ref:o,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(!i),disabled:n,title:`thinking level`,"aria-haspopup":`true`,"aria-expanded":i,className:`flex items-center gap-1.5 rounded-md border px-2 py-1 font-mono text-xs disabled:opacity-50 ${s?`border-amber-300 text-amber-700 hover:border-amber-400 dark:border-amber-900 dark:text-amber-400 dark:hover:border-amber-700`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600`}`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`text-sm leading-none ${s?``:`opacity-40 grayscale`}`,children:`🧠`}),e]}),i&&(0,A.jsxs)(`div`,{className:`absolute bottom-full left-0 z-20 mb-1 w-48 rounded-lg border border-zinc-200 bg-white p-3 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between text-xs`,children:[(0,A.jsx)(`span`,{className:`text-zinc-500 dark:text-zinc-400`,children:`thinking`}),(0,A.jsx)(`span`,{className:`font-mono text-zinc-700 dark:text-zinc-200`,children:e})]}),u?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`input`,{type:`range`,min:0,max:c.length-1,step:1,value:l===-1?0:l,onChange:e=>r(c[Number(e.target.value)]),"aria-label":`Thinking level`,"aria-valuetext":e,className:`w-full accent-amber-500`}),(0,A.jsxs)(`div`,{className:`mt-0.5 flex justify-between font-mono text-[9px] text-zinc-400 dark:text-zinc-600`,children:[(0,A.jsx)(`span`,{children:c[0]}),(0,A.jsx)(`span`,{children:c[c.length-1]})]})]}):(0,A.jsxs)(`p`,{className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:[`this model accepts `,(0,A.jsx)(`span`,{className:`font-mono`,children:c[0]}),` only`]})]})]})}function HB(e){let{model:t,models:n,thinkingLevel:r,modelSupportsReasoning:i,isStreaming:a,contextUsage:o,sessionUsage:s,isCompacting:c}=e;return(0,A.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,A.jsxs)(`select`,{value:t,onChange:t=>{let r=n.find(e=>`${e.provider}/${e.id}`===t.target.value);r&&e.onSetModel(r.provider,r.id)},disabled:a,className:`max-w-64 rounded-md border border-zinc-300 bg-white px-2 py-1 font-mono text-xs text-zinc-700 outline-none hover:border-zinc-400 disabled:opacity-50 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:border-zinc-600`,children:[!n.some(e=>`${e.provider}/${e.id}`===t)&&(0,A.jsx)(`option`,{value:t,children:t}),n.map(e=>(0,A.jsxs)(`option`,{value:`${e.provider}/${e.id}`,children:[e.provider,`/`,e.id]},`${e.provider}/${e.id}`))]}),i&&(0,A.jsx)(VB,{thinkingLevel:r,thinkingLevels:e.thinkingLevels,isStreaming:a,onSetThinking:e.onSetThinking}),e.shellConfinement&&(0,A.jsx)(`span`,{className:`ml-auto`,children:(0,A.jsx)(LB,{verdict:e.shellConfinement,surface:`shell`})}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onCompact,disabled:a||c,title:o?.tokens==null?`Click to compact the conversation context`:`${o.tokens.toLocaleString()} / ${o.contextWindow.toLocaleString()} tokens — click to compact`,className:`${e.shellConfinement?``:`ml-auto `}flex items-center gap-1.5 rounded-md border border-zinc-300 px-2 py-1 font-mono text-xs text-zinc-500 hover:border-zinc-400 disabled:opacity-50 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600`,children:[(0,A.jsx)(BB,{usage:o}),c?`compacting…`:o?.percent==null?`context`:`${Math.round(o.percent)}%`]}),(0,A.jsx)(zB,{usage:s,analysisOpen:e.analysisOpen,onToggleAnalysis:e.onToggleAnalysis})]})}var UB=`w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 placeholder:text-zinc-400 focus:border-zinc-400 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-600`,WB=`mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400`;function GB({title:e,credentials:t,onSetCredential:n,onStartLogin:r,login:i,onAnswerLogin:a,onCancelLogin:o,onDismissLogin:s,onDeclareProvider:c,errors:l}){let u=t.providers,[f,p]=(0,d.useState)(u.length>0?`known`:`custom`),[m,h]=(0,d.useState)(u[0]?.id??``),[g,_]=(0,d.useState)(``),[v,y]=(0,d.useState)(``),[b,x]=(0,d.useState)(``),[S,C]=(0,d.useState)(``),[w,T]=(0,d.useState)(!0),[ee,E]=(0,d.useState)(!0);function te(e){i?.provider===e?(i.done||o(),s()):(i&&(i.done||o(),s()),r(e,`oauth`))}let D=u.some(e=>e.configured)&&!t.usableModel;function ne(e){e.preventDefault(),!D&&(f===`known`?m&&g.trim()&&n(m,g.trim()):v.trim()&&b.trim()&&g.trim()&&S.trim()&&c({provider:v.trim(),baseUrl:b.trim(),apiKey:g.trim(),models:[S.trim()],compat:{supportsDeveloperRole:w,supportsReasoningEffort:ee}}))}return(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center overflow-auto p-6`,children:(0,A.jsxs)(`form`,{onSubmit:ne,className:`w-full max-w-md rounded-xl border border-zinc-200 p-6 shadow-sm dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`mb-1 text-center text-3xl`,children:e??`π`}),D?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`h1`,{className:`mb-3 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`No model is available.`}),(0,A.jsxs)(`p`,{className:`text-sm text-zinc-600 dark:text-zinc-400`,children:[`Credentials are configured, so this is not a missing key: `,(0,A.jsx)(`code`,{children:`allowedModels`}),` in your configuration leaves nothing to choose from. Widen it, or remove it, then restart.`]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`h1`,{className:`mb-4 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`No model provider is set up yet. Add one to start chatting.`}),(0,A.jsx)(`div`,{className:`mb-4 flex gap-1 rounded-lg bg-zinc-100 p-1 text-xs dark:bg-zinc-800`,children:[`known`,`custom`].map(e=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>p(e),className:`flex-1 rounded-md px-2 py-1.5 ${f===e?`bg-white font-medium text-zinc-800 shadow-sm dark:bg-zinc-900 dark:text-zinc-100`:`text-zinc-500 dark:text-zinc-400`}`,children:e===`known`?`Provider API key`:`OpenAI-compatible endpoint`},e))}),t.signIn&&u.some(e=>e.methods?.includes(`oauth`))&&(0,A.jsxs)(`section`,{className:`mb-4 rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,"data-testid":`onboarding-account-signin`,children:[(0,A.jsx)(`h2`,{className:`mb-2 text-xs font-medium text-zinc-700 dark:text-zinc-300`,children:`Sign in with an account`}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:u.filter(e=>e.methods?.includes(`oauth`)).map(e=>{let t=i?.provider===e.id;return(0,A.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-controls":`onboarding-login-flow-${e.id}`,className:`rounded border px-3 py-2 text-xs ${t?`border-sky-500 bg-sky-50 text-sky-800 dark:bg-sky-950/40 dark:text-sky-200`:``}`,onClick:()=>te(e.id),children:e.name},e.id)})}),i&&(0,A.jsx)(`div`,{id:`onboarding-login-flow-${i.provider}`,className:`mt-3`,children:(0,A.jsx)(pB,{login:i,providerName:u.find(e=>e.id===i.provider)?.name??i.provider,onAnswer:a,onCancel:o,onDismiss:s})})]}),f===`known`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{htmlFor:`onboarding-provider`,className:WB,children:`Provider`}),(0,A.jsx)(`select`,{id:`onboarding-provider`,value:m,onChange:e=>h(e.target.value),className:`${UB} mb-3`,children:u.map(e=>(0,A.jsxs)(`option`,{value:e.id,children:[e.name,e.configured?` (already configured)`:``]},e.id))})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{htmlFor:`onboarding-name`,className:WB,children:`Name`}),(0,A.jsx)(`input`,{id:`onboarding-name`,value:v,onChange:e=>y(e.target.value),placeholder:`corp`,className:`${UB} mb-3`}),(0,A.jsx)(`label`,{htmlFor:`onboarding-url`,className:WB,children:`Base URL`}),(0,A.jsx)(`input`,{id:`onboarding-url`,value:b,onChange:e=>x(e.target.value),placeholder:`https://llm.corp.example/v1`,className:`${UB} mb-3`}),(0,A.jsx)(`label`,{htmlFor:`onboarding-model`,className:WB,children:`Model id`}),(0,A.jsx)(`input`,{id:`onboarding-model`,value:S,onChange:e=>C(e.target.value),placeholder:`gpt-oss-120b`,className:`${UB} mb-3`})]}),(0,A.jsx)(`label`,{htmlFor:`onboarding-key`,className:WB,children:`API key`}),(0,A.jsx)(`input`,{id:`onboarding-key`,type:`password`,autoComplete:`off`,value:g,onChange:e=>_(e.target.value),placeholder:`sk-…`,className:UB}),f===`custom`&&(0,A.jsxs)(`fieldset`,{className:`mt-4 rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,children:[(0,A.jsx)(`legend`,{className:`px-1 text-xs text-zinc-500 dark:text-zinc-400`,children:`Compatibility`}),(0,A.jsxs)(`label`,{className:`flex items-start gap-2 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[`Server understands the `,(0,A.jsx)(`code`,{children:`developer`}),` role. Uncheck for vLLM, SGLang and most corporate gateways — the system prompt is then sent as a `,(0,A.jsx)(`code`,{children:`system`}),` message.`]})]}),(0,A.jsxs)(`label`,{className:`mt-2 flex items-start gap-2 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:ee,onChange:e=>E(e.target.checked),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[`Server accepts `,(0,A.jsx)(`code`,{children:`reasoning_effort`}),`. Uncheck if it rejects unknown fields.`]})]})]}),(0,A.jsx)(`button`,{type:`submit`,className:`mt-4 w-full rounded-md bg-zinc-800 px-3 py-2 text-sm font-medium text-white hover:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,children:`Save and start`})]}),l.map((e,t)=>(0,A.jsx)(`p`,{className:`mt-3 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:e},t)),(0,A.jsxs)(`p`,{className:`mt-4 text-center text-xs text-zinc-400 dark:text-zinc-600`,children:[t.agentDir?`Stored in ${t.agentDir}. `:``,`Provider environment variables work too, as does `,(0,A.jsx)(`code`,{children:`pi-outpost login`}),`.`]})]})})}var KB=`application/x-pi-outpost-file`,qB=`application/x-pi-outpost-read-only-file`,JB=`mr-1 shrink-0 rounded px-1 text-xs text-zinc-400 hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 [@media(hover:hover)]:opacity-0`,YB={modified:{label:`M`,className:`text-amber-600 dark:text-amber-400`},added:{label:`A`,className:`text-emerald-600 dark:text-emerald-400`},untracked:{label:`U`,className:`text-emerald-600 dark:text-emerald-400`},deleted:{label:`D`,className:`text-red-600 dark:text-red-400`},conflicted:{label:`C`,className:`text-purple-600 dark:text-purple-400`}};function XB(e,t){return t?Object.keys(t).filter(t=>t.startsWith(`${e}/`)).length:0}function ZB(e){return e===`directory`||e===`symlink-directory`}function QB(e,t){return t===void 0?!1:t===null||t!==``&&e!==t&&!e.startsWith(`${t}/`)}function $B({dir:e,depth:t,creation:n}){let[r,i]=(0,d.useState)(``),a=(0,d.useRef)(null),o=n.localError??n.serverError;return(0,d.useEffect)(()=>{a.current?.focus()},[]),(0,A.jsxs)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5`,children:[(0,A.jsx)(`input`,{ref:a,value:r,onChange:e=>i(e.target.value),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),n.submit(e,r)):t.key===`Escape`&&(t.preventDefault(),n.cancel())},onBlur:()=>{o===null&&n.cancel()},placeholder:`name, or name/ for a folder`,"aria-label":`New file or folder in ${e===``?`the workspace root`:e}`,spellCheck:!1,className:`w-full rounded border border-zinc-300 bg-white px-1 py-0.5 text-xs text-zinc-800 outline-none focus:border-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),o!==null&&(0,A.jsx)(`p`,{className:`px-1 pt-0.5 text-xs text-red-600 dark:text-red-400`,children:o})]})}function eV({path:e,name:t,depth:n,rename:r}){let[i,a]=(0,d.useState)(t),o=(0,d.useRef)(null),s=r.localError??r.serverError;return(0,d.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]),(0,A.jsxs)(`div`,{style:{paddingLeft:n*12+16},className:`py-0.5`,children:[(0,A.jsx)(`input`,{ref:o,value:i,disabled:r.pending,onChange:e=>a(e.target.value),onKeyDown:t=>{t.key===`Enter`&&!r.pending?(t.preventDefault(),r.submit(e,i)):t.key===`Escape`&&(t.preventDefault(),r.cancel())},onBlur:()=>{s===null&&r.cancel()},"aria-label":`Rename ${t}`,spellCheck:!1,className:`w-full rounded border border-zinc-300 bg-white px-1 py-0.5 text-xs text-zinc-800 outline-none focus:border-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),s!==null&&(0,A.jsx)(`p`,{className:`px-1 pt-0.5 text-xs text-red-600 dark:text-red-400`,children:s})]})}function tV({path:e,depth:t,...n}){let r=n.tree[e],i=n.creation?.openIn===e?(0,A.jsx)($B,{dir:e,depth:t,creation:n.creation}):null;return r===void 0?i:r===`loading`?(0,A.jsxs)(A.Fragment,{children:[i,(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:`loading…`})]}):`error`in r?(0,A.jsxs)(A.Fragment,{children:[i,(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-red-600 dark:text-red-400`,children:r.error})]}):r.length===0?(0,A.jsxs)(A.Fragment,{children:[i,i===null&&(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:`empty`})]}):(0,A.jsxs)(A.Fragment,{children:[i,r.map(r=>(0,A.jsx)(nV,{parentPath:e,entry:r,depth:t,...n},r.name))]})}function nV({parentPath:e,entry:t,depth:n,...r}){let[i,a]=(0,d.useState)(!1),[o,s]=(0,d.useState)(!1),c=e?`${e}/${t.name}`:t.name,l=QB(c,r.writableRoot),u=r.fileOperation?.status===`pending`;if(ZB(t.type)){let e=!l&&!u,d=e=>e.includes(qB)?r.onCopyFile===void 0?null:`copy`:r.onMoveFile===void 0?null:`move`;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`group flex w-full items-center rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 ${o?`bg-blue-50 ring-1 ring-blue-400 dark:bg-blue-950/40`:``}`,onDragOver:t=>{if(!e||!Array.from(t.dataTransfer.types).includes(KB))return;let n=d(Array.from(t.dataTransfer.types));n!==null&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=n,s(!0))},onDragLeave:()=>s(!1),onDrop:t=>{if(!e)return;let n=t.dataTransfer.getData(KB),i=n?d(Array.from(t.dataTransfer.types)):null;i!==null&&(t.preventDefault(),t.stopPropagation(),s(!1),i===`copy`?r.onCopyFile?.(n,c):r.onMoveFile?.(n,c))},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{let e=!i;a(e),e&&r.tree[c]===void 0&&r.onExpand(c),r.onSelectDirectory?.(c)},style:{paddingLeft:n*12},className:`flex min-w-0 flex-1 items-center gap-1 rounded py-0.5 text-left`,children:[(0,A.jsx)(`span`,{className:`w-3 shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,children:i?`▾`:`▸`}),(0,A.jsx)(`span`,{title:t.name,className:`truncate ${l?`text-zinc-400 dark:text-zinc-600`:`text-zinc-700 dark:text-zinc-300`}`,children:t.name}),!i&&XB(c,r.gitFiles)>0&&(0,A.jsx)(`span`,{className:`ml-1 shrink-0 rounded bg-amber-100 px-1 font-mono text-[10px] font-bold text-amber-700 dark:bg-amber-950/60 dark:text-amber-400`,title:`${XB(c,r.gitFiles)} changed file(s) inside`,children:XB(c,r.gitFiles)})]}),r.onRevealNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onRevealNative?.(c),title:`Show in the file manager`,"aria-label":`Show ${t.name} in the file manager`,className:JB,children:`⌂`}),r.creation&&!l&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{a(!0),r.tree[c]===void 0&&r.onExpand(c),r.creation?.start(c)},title:`New file or folder here`,"aria-label":`New file or folder in ${t.name}`,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs text-zinc-400 hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 [@media(hover:hover)]:opacity-0`,children:`+`})]}),i&&(0,A.jsx)(tV,{path:c,depth:n+1,...r})]})}let f=c===r.openFilePath,p=r.gitFiles?.[c],m=r.attachedPaths?.includes(c)??!1,h=t.type===`file`,g=h||t.type===`symlink-file`,_=h&&!l,v=h&&(l?r.onCopyFile!==void 0:r.onMoveFile!==void 0);return r.rename?.path===c?(0,A.jsx)(eV,{path:c,name:t.name,depth:n,rename:r.rename}):(0,A.jsxs)(`div`,{className:`group flex w-full items-center rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 ${f?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:[(0,A.jsx)(`button`,{type:`button`,draggable:v&&!u,onDragStart:e=>{v&&!u&&(e.dataTransfer.effectAllowed=l?`copy`:`move`,e.dataTransfer.setData(KB,c),l&&e.dataTransfer.setData(qB,`copy`))},onClick:()=>r.onSelectFile(c),style:{paddingLeft:n*12+16},className:`flex min-w-0 flex-1 items-center py-0.5 text-left`,children:(0,A.jsx)(`span`,{title:t.name,className:`truncate ${l?`text-zinc-400 dark:text-zinc-600`:`text-zinc-600 dark:text-zinc-400`}`,children:t.name})}),g&&r.onOpenNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onOpenNative?.(c),title:`Open with the associated application`,"aria-label":`Open ${t.name} with the associated application`,className:JB,children:`↗`}),r.onRevealNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onRevealNative?.(c),title:`Show in the file manager`,"aria-label":`Show ${t.name} in the file manager`,className:JB,children:`⌂`}),_&&r.onRenameFile&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.rename?.start(c),title:`Rename file`,"aria-label":`Rename ${t.name}`,className:JB,children:`✎`}),_&&r.onDeleteFile&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>{window.confirm(`Delete "${t.name}" permanently?`)&&r.onDeleteFile?.(c)},title:`Delete file`,"aria-label":`Delete ${t.name}`,className:`${JB} hover:text-red-600 dark:hover:text-red-400`,children:`×`}),r.onToggleAttachPath&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>r.onToggleAttachPath?.(c),title:m?`Remove this file from the prompt`:`Reference this file in the prompt`,"aria-label":`${m?`Remove`:`Reference`} ${t.name} in the prompt`,"aria-pressed":m,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:hover:bg-zinc-700 ${m?`font-bold text-blue-600 dark:text-blue-400`:`text-zinc-400 dark:text-zinc-600 [@media(hover:hover)]:opacity-0`}`,children:`@`}),p&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>(r.onSelectDiff??r.onSelectFile)(c),title:`Show uncommitted diff`,"aria-label":`Show diff of ${t.name}`,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs font-bold hover:bg-zinc-200 dark:hover:bg-zinc-700 ${YB[p].className}`,children:YB[p].label})]})}function rV(e){let t=e.trim();if(t===``)return{error:`A name is required`};let n=t.endsWith(`/`),r=n?t.slice(0,-1).trim():t;return r===``?{error:`A name is required`}:r.includes(`/`)||r.includes(`\\`)?{error:`That is a path, not a name`}:r===`.`||r===`..`?{error:`"${r}" is not a name`}:{kind:n?`directory`:`file`,name:r}}function iV(e){let t=rV(e);return`error`in t?t:t.kind===`directory`?{error:`That is a folder name`}:{name:t.name}}function aV(e){let[t,n]=(0,d.useState)(null),[r,i]=(0,d.useState)(null),[a,o]=(0,d.useState)(null),[s,c]=(0,d.useState)(null),[l,u]=(0,d.useState)(null),[f,p]=(0,d.useState)(null),m=e.onCreateFile!==void 0||e.onCreateDirectory!==void 0,h=e.createError&&a&&e.createError.path===oV(a.dir,a.name)?e.createError.message:null,g=e.created??null;(0,d.useEffect)(()=>{a!==null&&g!==null&&g===oV(a.dir,a.name)&&(n(null),o(null),i(null))},[a,g]);let _=e.fileOperation?.status===`error`&&e.fileOperation.operation===`rename_file`&&f===e.fileOperation.path?e.fileOperation.message:null;(0,d.useEffect)(()=>{let t=e.fileOperation;t?.status===`succeeded`&&t.operation===`rename_file`&&f===t.path&&(c(null),p(null),u(null))},[f,e.fileOperation]);let v=m?{openIn:t,localError:r,serverError:h,start:e=>{n(e),i(null),o(null)},cancel:()=>{n(null),i(null),o(null)},submit:(t,n)=>{let r=rV(n);if(`error`in r){i(r.error);return}i(null),o({dir:t,name:r.name});let a=oV(t,r.name);r.kind===`directory`?e.onCreateDirectory?.(a):e.onCreateFile?.(a)}}:void 0,y=e.onRenameFile?{path:s,pending:f!==null&&e.fileOperation?.status===`pending`&&e.fileOperation.operation===`rename_file`&&e.fileOperation.path===f,localError:l,serverError:_,start:e=>{c(e),p(null),u(null)},cancel:()=>{c(null),p(null),u(null)},submit:(t,n)=>{if(n.trim()===``){c(null),p(null),u(null);return}let r=iV(n);`error`in r?u(r.error):(u(null),p(t),e.onRenameFile?.(t,r.name))}}:void 0,b=!QB(``,e.writableRoot);return(0,A.jsxs)(`div`,{className:`text-sm`,children:[e.fileOperation?.status===`error`&&e.fileOperation.operation!==`rename_file`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-1 rounded bg-red-50 px-2 py-1 text-xs text-red-700 dark:bg-red-950/40 dark:text-red-300`,children:e.fileOperation.message}),(v&&b||e.onRefresh)&&(0,A.jsxs)(`div`,{className:`mb-1 flex items-center`,children:[v&&b&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>v.start(``),"aria-label":`New file or folder in the workspace root`,className:`rounded px-1 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-400`,children:`+ new`}),e.onRefresh&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onRefresh,title:`Refresh the file tree`,"aria-label":`Refresh the file tree`,className:`ml-auto rounded px-1 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-400`,children:`↻`})]}),(0,A.jsx)(tV,{path:``,depth:0,...e,...v?{creation:v}:{},...y?{rename:y}:{}})]})}function oV(e,t){return e===``?t:`${e}/${t}`}function sV({tree:e,openFile:t,writableRoot:n,gitFiles:r,attachedPaths:i,onExpand:a,onSelectDirectory:o,onRefresh:s,onSelectFile:c,onSelectDiff:l,onToggleAttachPath:u,onCreateFile:f,onCreateDirectory:p,onOpenNative:m,onRevealNative:h,onRenameFile:g,onDeleteFile:_,onMoveFile:v,onCopyFile:y,fileOperation:b,createError:x,created:S}){let C=lz(rz);return(0,d.useEffect)(()=>{e[``]===void 0&&a(``)},[]),(0,A.jsxs)(`aside`,{"aria-label":`Files`,style:{width:C.width},className:`relative flex shrink-0 flex-col border-r border-zinc-200 dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`border-b border-zinc-200 px-3 py-2 text-xs font-semibold uppercase text-zinc-400 dark:border-zinc-800 dark:text-zinc-600`,children:`Files`}),(0,A.jsx)(`div`,{className:`flex-1 overflow-auto p-2`,children:(0,A.jsx)(aV,{tree:e,openFilePath:t?.path,writableRoot:n,gitFiles:r,attachedPaths:i,onExpand:a,onSelectDirectory:o,onRefresh:s,onSelectFile:c,onSelectDiff:l,onToggleAttachPath:u,onCreateFile:f,onCreateDirectory:p,onOpenNative:m,onRevealNative:h,onRenameFile:g,onDeleteFile:_,onMoveFile:v,onCopyFile:y,fileOperation:b,createError:x,created:S})}),(0,A.jsx)(uz,{label:`Resize Files sidebar`,width:C.width,config:rz,separatorProps:C.separatorProps})]})}function cV({title:e,onSubmit:t}){let[n,r]=(0,d.useState)(``);return(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center p-6`,children:(0,A.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),n.trim()&&t(n.trim())},className:`w-full max-w-sm rounded-xl border border-zinc-200 p-6 shadow-sm dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`mb-1 text-center text-3xl`,children:e??`π`}),(0,A.jsx)(`h1`,{className:`mb-4 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`This server requires an access token.`}),(0,A.jsx)(`label`,{htmlFor:`pi-outpost-token`,className:`mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400`,children:`Access token`}),(0,A.jsx)(`input`,{id:`pi-outpost-token`,name:`token`,type:`password`,autoComplete:`off`,spellCheck:!1,value:n,onChange:e=>r(e.target.value),placeholder:`paste the token…`,className:`mb-3 w-full rounded-md border border-zinc-300 bg-white px-2 py-1.5 font-mono text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`submit`,disabled:!n.trim(),className:`w-full rounded-md border border-emerald-300 px-2 py-1.5 text-sm text-emerald-700 hover:border-emerald-500 disabled:opacity-50 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600`,children:`Connect`}),(0,A.jsxs)(`p`,{className:`mt-3 text-center text-xs text-zinc-400 dark:text-zinc-600`,children:[`Ask the operator for the token, or open the link containing `,(0,A.jsx)(`code`,{children:`?token=…`})]})]})})}var lV={todo:{icon:`○`,label:`To do`,className:`text-zinc-500`},in_progress:{icon:`●`,label:`In progress`,className:`text-blue-600 dark:text-blue-400`},done:{icon:`✓`,label:`Done`,className:`text-emerald-600 dark:text-emerald-400`},blocked:{icon:`!`,label:`Blocked`,className:`text-red-600 dark:text-red-400`},needs_review:{icon:`?`,label:`Needs review`,className:`text-amber-600 dark:text-amber-400`}},uV=8;function dV(e){let t=e.uri.startsWith(`workspace:`)?e.uri.slice(10):/^[a-z][a-z0-9+.-]*:/i.test(e.uri)?null:e.uri;return t===null||t===``||/^(?:[\\/]|[a-z]:[\\/])/i.test(t)||t.replaceAll(`\\`,`/`).split(`/`).includes(`..`)?null:t}function fV({plan:e,open:t,onToggle:n,onOpenWorkspace:r,requestedTaskId:i,onTaskRequestHandled:a}){let o=(0,d.useId)(),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(null),[f,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{i&&(e.tasks.some(e=>e.id===i)?(u(i),p(null)):(u(null),p(i)),a?.())},[e.tasks,i,a]),(0,d.useEffect)(()=>{l!==null&&!e.tasks.some(e=>e.id===l)&&u(null)},[e,l]),(0,d.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&c(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let m=(0,d.useMemo)(()=>{let t=new Map;for(let n of e.tasks)t.set(n.parentId,[...t.get(n.parentId)??[],n]);return t},[e.tasks]),h=(0,d.useMemo)(()=>new Map(e.tasks.map(e=>[e.id,e])),[e.tasks]),g=(0,d.useMemo)(()=>{let e=[],t=(n,r)=>{for(let i of m.get(n)??[])e.push({task:i,depth:r}),t(i.id,r+1)};return t(void 0,0),e.slice(0,uV)},[m]),_=l?h.get(l):void 0,v=e.tasks.filter(e=>e.status===`done`).length,y=(e,t=0)=>(m.get(e)??[]).flatMap(e=>{let n=lV[e.status];return[(0,A.jsxs)(`button`,{type:`button`,role:`treeitem`,"aria-level":t+1,"aria-selected":l===e.id,onClick:()=>u(e.id),"aria-current":e.status===`in_progress`?`step`:void 0,className:`flex w-full items-start gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800 ${l===e.id?`bg-zinc-100 dark:bg-zinc-800`:``}`,style:{paddingLeft:`${.5+t*.85}rem`},children:[(0,A.jsx)(`span`,{className:`mt-px w-4 shrink-0 text-center font-semibold ${n.className}`,"aria-label":n.label,children:n.icon}),(0,A.jsx)(`span`,{className:e.status===`done`?`text-zinc-500 line-through`:`text-zinc-800 dark:text-zinc-200`,children:e.title})]},e.id),...y(e.id,t+1)]});return t?(0,A.jsxs)(`aside`,{"aria-label":`Work Plan`,className:`absolute inset-y-0 right-0 z-10 flex w-full flex-col border-l border-zinc-200 bg-white/95 shadow-lg backdrop-blur md:w-[23rem] dark:border-zinc-800 dark:bg-zinc-950/95`,children:[(0,A.jsxs)(`header`,{className:`border-b border-zinc-200 px-3 py-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-zinc-500`,children:`Work Plan`}),(0,A.jsx)(`h2`,{className:`truncate text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.title})]}),(0,A.jsx)(`button`,{type:`button`,onClick:n,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,"aria-label":`Close Work Plan`,children:`×`})]}),(0,A.jsxs)(`div`,{className:`mt-2 text-xs text-zinc-500`,children:[`Progress: `,v,` / `,e.tasks.length]}),(0,A.jsx)(`div`,{className:`mt-1 h-1.5 overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800`,"aria-hidden":!0,children:(0,A.jsx)(`div`,{className:`h-full bg-emerald-500`,style:{width:`${e.tasks.length===0?0:v/e.tasks.length*100}%`}})})]}),(0,A.jsx)(`div`,{role:`tree`,"aria-label":`Work Plan tasks`,className:`min-h-0 flex-1 overflow-y-auto p-2`,children:y(void 0)}),f&&(0,A.jsx)(`div`,{role:`status`,className:`border-t border-amber-200 bg-amber-50 p-3 text-xs text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300`,children:`That Outcome task no longer exists in the current Work Plan.`}),_&&(0,A.jsxs)(`section`,{"aria-label":`Task details`,className:`max-h-[45%] overflow-y-auto border-t border-zinc-200 p-3 text-xs dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`font-semibold ${lV[_.status].className}`,children:lV[_.status].label}),(0,A.jsx)(`h3`,{className:`mt-1 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:_.title}),_.description&&(0,A.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-zinc-600 dark:text-zinc-300`,children:_.description}),_.statusReason&&(0,A.jsx)(`p`,{className:`mt-2 rounded bg-zinc-100 p-2 text-zinc-700 dark:bg-zinc-900 dark:text-zinc-300`,children:_.statusReason}),_.dependsOn.length>0&&(0,A.jsxs)(`div`,{className:`mt-3`,children:[(0,A.jsx)(`span`,{className:`font-semibold`,children:`Depends on:`}),` `,_.dependsOn.map(e=>h.get(e)?.title??e).join(`, `)]}),_.resources.length>0&&(0,A.jsxs)(`div`,{className:`mt-3 space-y-1`,children:[(0,A.jsx)(`div`,{className:`font-semibold`,children:`Resources`}),_.resources.map(e=>{let t=dV(e),n=e.label??e.uri;return t===null?/^https?:/i.test(e.uri)?(0,A.jsx)(`a`,{href:e.uri,target:`_blank`,rel:`noreferrer`,className:`block truncate text-blue-600 hover:underline dark:text-blue-400`,children:n},e.uri):(0,A.jsx)(`span`,{className:`block truncate text-zinc-500`,title:`No navigator is available for this resource`,children:n},e.uri):(0,A.jsx)(`button`,{type:`button`,className:`block max-w-full truncate text-left text-blue-600 hover:underline dark:text-blue-400`,onClick:()=>r(t),children:n},e.uri)})]})]})]}):(0,A.jsxs)(`div`,{className:`absolute right-3 top-3 z-20`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocusCapture:()=>c(!0),onBlurCapture:()=>c(!1),children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{c(!1),n()},className:`rounded-md border border-zinc-300 bg-white px-2 py-1 text-xs shadow-sm dark:border-zinc-700 dark:bg-zinc-900`,"aria-label":`Open Work Plan`,"aria-describedby":o,children:[`Plan `,v,`/`,e.tasks.length]}),(0,A.jsx)(`div`,{id:o,role:`tooltip`,className:`absolute right-0 top-full w-72 pt-2 ${s?`block`:`hidden`}`,children:(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-200 bg-white p-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsx)(`ul`,{className:`space-y-1`,children:g.map(({task:e,depth:t})=>(0,A.jsxs)(`li`,{className:`flex min-w-0 items-start gap-1.5 text-xs`,style:{paddingLeft:`${t*.75}rem`},children:[(0,A.jsx)(`span`,{"aria-label":lV[e.status].label,className:`shrink-0 font-semibold ${lV[e.status].className}`,children:e.status===`done`?`☑`:`☐`}),(0,A.jsx)(`span`,{className:`truncate ${e.status===`done`?`text-zinc-500 line-through`:`text-zinc-800 dark:text-zinc-200`}`,children:e.title})]},e.id))}),e.tasks.length>g.length&&(0,A.jsxs)(`div`,{className:`mt-1 text-[11px] text-zinc-500`,children:[`+`,e.tasks.length-g.length,` more`]})]})})]})}var pV=Object.defineProperty,mV=Object.getOwnPropertyDescriptor,hV=(e,t)=>{for(var n in t)pV(e,n,{get:t[n],enumerable:!0})},gV=(e,t,n,r)=>{for(var i=r>1?void 0:r?mV(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&pV(t,n,i),i},_V=(e,t)=>(n,r)=>t(n,r,e),vV=`Terminal input`,yV={get:()=>vV,set:e=>vV=e},bV=`Too much output to announce, navigate to rows manually to read`,xV={get:()=>bV,set:e=>bV=e};function SV(e){return e.replace(/\r?\n/g,`\r`)}function CV(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function wV(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function TV(e,t,n,r){e.stopPropagation(),e.clipboardData&&EV(e.clipboardData.getData(`text/plain`),t,n,r)}function EV(e,t,n,r){e=SV(e),e=CV(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function DV(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function OV(e,t,n,r,i){DV(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function kV(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function AV(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var jV=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},MV=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},NV=``,PV=` `,FV=class e{constructor(){this.fg=0,this.bg=0,this.extended=new IV}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},IV=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},LV=class e extends FV{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new IV,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?kV(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},RV=`di$target`,zV=`di$dependencies`,BV=new Map;function VV(e){return e[zV]||[]}function HV(e){if(BV.has(e))return BV.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);UV(t,e,r)};return t._id=e,BV.set(e,t),t}function UV(e,t,n){t[RV]===t?t[zV].push({id:e,index:n}):(t[zV]=[{id:e,index:n}],t[RV]=t)}var WV=HV(`BufferService`),GV=HV(`CoreMouseService`),KV=HV(`CoreService`),qV=HV(`CharsetService`),JV=HV(`InstantiationService`),YV=HV(`LogService`),XV=HV(`OptionsService`),ZV=HV(`OscLinkService`),QV=HV(`UnicodeService`),$V=HV(`DecorationService`),eH=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new LV,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):tH(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};eH=gV([_V(0,WV),_V(1,XV),_V(2,ZV)],eH);function tH(e,t){if(confirm(`Do you want to navigate to ${t}?
360
+ })();`;function PR(e){if(e==null)return!1;let t=e.trim();return t!==``&&!t.startsWith(`#`)&&!ne(t)}function FR(e,t){return MR[e.split(`.`).pop()?.toLowerCase()??``]??t}function IR(e,t){return new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result).replace(/^data:[^;,]*/,`data:${t}`)),i.onerror=()=>r(i.error),i.readAsDataURL(e)})}async function LR(e,t,n){let r=new DOMParser().parseFromString(e,`text/html`),i=new Map,a=e=>{let t=i.get(e);return t===void 0&&(t=n(e).catch(()=>void 0),i.set(e,t)),t},o=async e=>(await a(e))?.text(),s=async e=>{let t=await a(e);return t===void 0?void 0:IR(t,FR(e,t.type||`application/octet-stream`))},c=async(e,t,n=0)=>{let r=[...e.matchAll(/@import\s+(?:url\(\s*(['"]?)([^'")]+)\1\s*\)|(['"])([^'"]+)\3)[^;]*;/gi)];for(let i of r){let r=i[2]??i[4];if(!PR(r)||n>=jR)continue;let a=re(t,r),s=await o(a);s!==void 0&&(e=e.replace(i[0],await c(s,a,n+1)))}let i=/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,a=new Map;for(let n of new Set([...e.matchAll(i)].map(e=>e[2]))){if(!PR(n))continue;let e=await s(re(t,n));e!==void 0&&a.set(n,e)}return e.replace(i,(e,t,n)=>a.has(n)?`url("${a.get(n)}")`:e)},l=Array.from(r.querySelectorAll(`style`));for(let e of Array.from(r.querySelectorAll(`link[href]`))){let n=(e.getAttribute(`rel`)??``).toLowerCase().split(/\s+/),i=e.getAttribute(`href`);if(!PR(i))continue;let a=re(t,i);if(n.includes(`stylesheet`)){let t=await o(a);if(t===void 0)continue;let n=r.createElement(`style`),i=e.getAttribute(`media`);i!==null&&n.setAttribute(`media`,i),n.textContent=await c(t,a),e.replaceWith(n)}else if(n.includes(`icon`)){let t=await s(a);t!==void 0&&e.setAttribute(`href`,t)}}for(let e of l)e.textContent=await c(e.textContent??``,t);for(let e of Array.from(r.querySelectorAll(`[style]`)))e.setAttribute(`style`,await c(e.getAttribute(`style`)??``,t));for(let e of Array.from(r.querySelectorAll(`script[src]`))){let n=e.getAttribute(`src`);if(!PR(n))continue;let r=await o(re(t,n));r!==void 0&&(e.removeAttribute(`src`),e.textContent=r.replace(/<\/script/gi,`<\\/script`))}for(let[e,n]of[[`img`,`src`],[`source`,`src`],[`video`,`src`],[`video`,`poster`],[`audio`,`src`],[`track`,`src`],[`input`,`src`],[`image`,`href`],[`image`,`xlink:href`],[`use`,`href`]])for(let i of Array.from(r.getElementsByTagName(e))){let e=i.getAttribute(n);if(!PR(e))continue;let r=await s(re(t,e));r!==void 0&&i.setAttribute(n,r)}for(let e of Array.from(r.querySelectorAll(`img[srcset], source[srcset]`))){let n=(e.getAttribute(`srcset`)??``).split(`,`).map(e=>e.trim()).filter(Boolean),r=[];for(let e of n){let[n,...i]=e.split(/\s+/),a=PR(n)?await s(re(t,n)):void 0;r.push([a??n,...i].join(` `))}e.setAttribute(`srcset`,r.join(`, `))}let u=r.createElement(`script`);return u.textContent=NR,r.head.prepend(u),`<!doctype html>\n${r.documentElement.outerHTML}`}var RR=`allow-scripts allow-popups allow-popups-to-escape-sandbox`;function zR({source:e,path:t,load:n,onOpen:r}){let i=(0,d.useRef)(null),[a,o]=(0,d.useState)(null);return(0,d.useEffect)(()=>{let r=!0;return LR(e,t,n).then(e=>{r&&o(e)},()=>{r&&o(e)}),()=>{r=!1}},[e,t,n]),(0,d.useEffect)(()=>{function e(e){if(i.current===null||e.source!==i.current.contentWindow)return;let n=e.data;typeof n==`object`&&n&&n.type===`pi-outpost:open`&&typeof n.href==`string`&&r(re(t,n.href))}return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[t,r]),a===null?(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-500`,"data-testid":`html-page-loading`,children:`Loading…`}):(0,A.jsx)(`iframe`,{ref:i,title:t,"data-testid":`html-page`,sandbox:RR,srcDoc:a,className:`h-full min-h-[24rem] w-full border-0 bg-white`})}function BR({query:e,onQueryChange:t,matchCount:n,truncated:r=!1,currentIndex:i,searching:a=!1,onNext:o,onPrev:s,onClose:c,inputRef:l}){let u=(0,d.useRef)(null),f=l??u;(0,d.useEffect)(()=>{f.current?.focus(),f.current?.select()},[]);let p=n===0?a?`searching…`:`0/0`:`${i+1}/${n}${r?`+`:``}`;return(0,A.jsxs)(`div`,{role:`search`,"aria-label":`Find in file`,className:`flex items-center gap-2 border-b border-zinc-200 bg-zinc-50 px-3 py-1.5 text-xs dark:border-zinc-800 dark:bg-zinc-900`,children:[(0,A.jsx)(`input`,{ref:f,type:`text`,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.shiftKey?s():o()):e.key===`Escape`&&(e.stopPropagation(),c())},placeholder:`Find in file`,"aria-label":`Find`,className:`min-w-0 flex-1 rounded border border-zinc-300 bg-white px-2 py-1 text-xs text-zinc-700 outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-200`}),(0,A.jsx)(`span`,{className:`shrink-0 tabular-nums text-zinc-500 dark:text-zinc-400`,children:p}),(0,A.jsx)(`button`,{type:`button`,onClick:s,disabled:n===0,"aria-label":`Previous match`,title:`Previous match (Shift+Enter)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 disabled:opacity-40 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`‹`}),(0,A.jsx)(`button`,{type:`button`,onClick:o,disabled:n===0,"aria-label":`Next match`,title:`Next match (Enter)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 disabled:opacity-40 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`›`}),(0,A.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close find bar`,title:`Close (Esc)`,className:`shrink-0 rounded px-1.5 py-0.5 text-zinc-500 hover:bg-zinc-200 dark:text-zinc-400 dark:hover:bg-zinc-800`,children:`✕`})]})}var VR=3e3;function HR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function UR(e,t,n=1/0){if(t===``)return[];let r=new RegExp(HR(t),`gi`),i=[],a;for(;(a=r.exec(e))!==null&&(i.push({start:a.index,end:a.index+a[0].length}),!(i.length>=n)););return i}function WR(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[],r=``;for(let e=t.nextNode();e!==null;e=t.nextNode()){let t=e.data.length;t!==0&&(n.push({node:e,start:r.length,end:r.length+t}),r+=e.data)}return{nodes:n,text:r}}function GR(e,t,n=VR){let r={matches:[],truncated:!1,clear:()=>{}};if(t===``)return r;let{nodes:i,text:a}=WR(e);if(a===``)return r;let o=UR(a,t,n+1),s=o.length>n,c=s?o.slice(0,n):o;if(c.length===0)return{matches:[],truncated:s,clear:()=>{}};let l=Array(c.length);for(let e=c.length-1;e>=0;e--){let{start:t,end:n}=c[e],r=[];for(let e of i){if(e.end<=t||e.start>=n)continue;let i=Math.max(0,t-e.start),a=Math.min(e.node.data.length,n-e.start);if(i>=a)continue;let o=e.node;a<o.data.length&&o.splitText(a);let s=i>0?o.splitText(i):o,c=document.createElement(`mark`);c.className=`find-match`,s.replaceWith(c),c.appendChild(s),r.push(c)}l[e]={marks:r}}return{matches:l,truncated:s,clear:()=>{for(let{marks:e}of l)for(let t of e)t.replaceWith(document.createTextNode(t.textContent??``));e.normalize()}}}var KR=(0,d.lazy)(()=>me(()=>import(`./PdfViewer-CKkstSlI.js`),[])),qR=250,JR=`(min-width: 768px)`;function YR(){let[e,t]=(0,d.useState)(()=>window.matchMedia?.(JR).matches??!0);return(0,d.useEffect)(()=>{let e=window.matchMedia?.(JR);if(e===void 0)return;let n=()=>t(e.matches);return n(),e.addEventListener?.(`change`,n),()=>e.removeEventListener?.(`change`,n)},[]),e}function XR(e,t){let[n,r]=(0,d.useState)(e);return(0,d.useEffect)(()=>{let n=window.setTimeout(()=>r(e),t);return()=>window.clearTimeout(n)},[e,t]),n}function ZR(e){let t=_u(e);return t.status===`valid`?t.envelope:void 0}var QR=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`;function $R(e){return/\.(md|markdown)$/i.test(e)}function ez(e){return/\.html?$/i.test(e)}function tz(e,t){return t===void 0?!0:t===null?!1:t===``||e===t||e.startsWith(`${t}/`)}function nz({file:e,writableRoot:t,isStreaming:n,onDirtyChange:r,gitState:i,initialShowGitDiff:a=!1,gitDiff:o,gitBaseline:s=null,onFetchGitDiff:c,onClearGitDiff:l,inRepository:u,onOpenGitHistory:f,onClose:p,onReload:m,onSave:h,serverUrl:g=``,token:_=null,workspace:v,docxTemplate:y,onImageLoad:b,onPdfLoad:x,rawRevision:C=0}){let[w,T]=(0,d.useState)(`rendered`),[ee,te]=(0,d.useState)(null),[D,ne]=(0,d.useState)(a),[k,oe]=(0,d.useState)(e.status===`loaded`&&e.justCreated?{draft:e.content,baseContent:e.content,baseMtimeMs:e.mtimeMs}:null),[se,ce]=(0,d.useState)(`idle`),ue=(0,d.useRef)(null),de=(0,d.useRef)(null),j=e.status===`loaded`?e:null,fe=j!==null&&$R(e.path),pe=j!==null&&ez(e.path),me=ie(e.path),he=O(e.path),ge=(0,d.useMemo)(()=>j===null?void 0:_u(j.content),[j?.content]),_e=ge?.status===`valid`,ve=ge?.status===`valid`||ge?.status===`invalid`,ye=ve||fe||pe,xe=w===`source`,Se=YR(),Ce=tz(e.path,t)&&!he,we=j!==null&&!me&&!he;(0,d.useEffect)(()=>{we&&DR().catch(()=>{})},[we]);let Te=k!==null&&k.draft!==k.baseContent,Ee=j?.pendingSave!==void 0,De=k!==null&&j!==null&&j.mtimeMs!==k.baseMtimeMs,Oe=j?.saveError?.conflict===!0||De,ke=k?.draft??j?.content??``,Ae=XR(ke,qR),je=(0,d.useMemo)(()=>j===null?void 0:_u(Ae),[Ae,j===null]),[Me,Ne]=(0,d.useState)(()=>e.status===`loaded`?ZR(e.content):void 0);(0,d.useEffect)(()=>{je?.status===`valid`&&Ne(je.envelope)},[je]);let Pe=je!==void 0&&je.status!==`valid`&&Me!==void 0,Fe=je?.status===`invalid`?Ae===j?.content&&j.documentIssues!==void 0?j.documentIssues:je.issues:void 0,Ie=je?.status===`not-a-document`?je.why===`unparseable`?`This is not parseable JSON yet.`:"This no longer declares a structured-exchange `schema`.":je?.status===`unsupported-version`?`This declares ${je.schema}, which this version does not render.`:void 0,Le=w===`split`&&ye&&!D&&j!==null&&Se,Re=D?void 0:Le?ve?Me:void 0:k===null&&!xe&&ge?.status===`valid`?ge.envelope:void 0,ze=(0,d.useRef)(null),Be=k!==null,Ve=j!==null&&k===null&&!Le&&!D&&(!fe||xe)&&(!_e||xe)&&(!pe||xe),He=D||Le?`none`:he?`pdf`:k!==null||Ve?`text`:j!==null&&!me?`dom`:`none`,[We,Ge]=(0,d.useState)(!1),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(0),Ze=(0,d.useRef)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(null),[et,tt]=(0,d.useState)({matchCount:0,currentIndex:-1,searching:!1}),[nt,rt]=(0,d.useState)([]),[it,at]=(0,d.useState)(!1),ot=(0,d.useRef)(null),st=(0,d.useRef)([]),ct=(0,d.useRef)(0),lt=(0,d.useRef)(``);function ut(e){ct.current=e;for(let[t,n]of st.current.entries())for(let r of n.marks)r.isConnected&&r.classList.toggle(`find-match-current`,t===e);let t=st.current[e]?.marks;t?.[0]?.isConnected&&t[0].scrollIntoView({block:`center`})}let dt=We?qe:``,ft=(0,d.useMemo)(()=>He===`text`?UR(ke,dt):[],[He,ke,dt]);(0,d.useEffect)(()=>{We&&He===`none`&&Ge(!1)},[We,He]),(0,d.useEffect)(()=>{function e(){ot.current?.clear(),ot.current=null,st.current=[],rt([]),at(!1)}let t=Qe.current;if(He!==`dom`||dt===``||t===null){e();return}ot.current?.clear();let n=GR(t,dt);ot.current=n,st.current=n.matches,rt(n.matches),at(n.truncated);let r=dt!==lt.current;lt.current=dt;let i=r?0:Math.min(ct.current,Math.max(n.matches.length-1,0));return Xe(i),ut(i),e},[He,dt,w,xe]);function pt(e,t){let n=e[t];n!==void 0&&ue.current?.select(n.start,n.end)}(0,d.useEffect)(()=>{if(He!==`text`||!We)return;let e=UR(ke,dt),t=dt!==lt.current;lt.current=dt;let n=t?0:Math.min(Ye,Math.max(e.length-1,0));Xe(n),e.length>0&&pt(e,n)},[dt,He,We,Be]),(0,d.useEffect)(()=>{ue.current?.markMatches(He===`text`?ft:[],Ye)},[He,ft,Ye,Be]);function mt(){Ge(!0)}function ht(){Ge(!1)}function gt(){if(He===`pdf`)$e.current?.findNext();else if(He===`text`){if(ft.length===0)return;let e=(Ye+1)%ft.length;Xe(e),pt(ft,e)}else{let e=st.current.length;if(e===0)return;let t=(ct.current+1)%e;Xe(t),ut(t)}}function _t(){if(He===`pdf`)$e.current?.findPrevious();else if(He===`text`){if(ft.length===0)return;let e=(Ye-1+ft.length)%ft.length;Xe(e),pt(ft,e)}else{let e=st.current.length;if(e===0)return;let t=(ct.current-1+e)%e;Xe(t),ut(t)}}let vt=He===`pdf`?{matchCount:et.matchCount,currentIndex:et.currentIndex,truncated:!1,searching:et.searching}:He===`text`?{matchCount:ft.length,currentIndex:ft.length>0?Math.min(Ye,ft.length-1):-1,truncated:!1,searching:!1}:{matchCount:nt.length,currentIndex:nt.length>0?Math.min(Ye,nt.length-1):-1,truncated:it,searching:!1},yt=k===null?null:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading editor…`}),children:(0,A.jsx)(OR,{handle:ue,path:e.path,value:k.draft,baseline:s,onChange:e=>oe(t=>t===null?t:{...t,draft:e}),onSave:()=>{Te&&!Ee&&!Oe&&Dt()}})},`editor`);function bt(t){return j===null?null:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4`,children:(0,A.jsx)(be,{code:j.content,path:e.path})}),children:(0,A.jsx)(OR,{readOnly:!0,handle:t?ue:void 0,path:e.path,value:j.content,baseline:s})},`source`)}let xt=(0,d.useCallback)(e=>fetch(ae(g,e,_,void 0,v)).then(e=>e.ok?e.blob():void 0,()=>void 0),[g,_,v]);function St(t){return(0,A.jsx)(`div`,{className:`prose-chat mx-auto max-w-3xl p-4 text-zinc-700 dark:text-zinc-300`,children:(0,A.jsx)(Py,{remarkPlugins:[xF,NF],rehypePlugins:[eD],components:{pre:Ue,a:({href:t,children:n,...r})=>!t||/^[a-z][a-z0-9+.-]*:/i.test(t)?(0,A.jsx)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,...r,children:n}):t.startsWith(`#`)?(0,A.jsx)(`a`,{href:t,...r,children:n}):(0,A.jsx)(`a`,{href:t,onClick:n=>{n.preventDefault(),m(re(e.path,t))},...r,children:n}),img:({src:t,alt:n,...r})=>{let i=typeof t==`string`&&t!==``&&!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!t.startsWith(`//`)?ae(g,re(e.path,t),_,void 0,v):t;return(0,A.jsx)(`img`,{...r,src:i,alt:n??``,loading:`lazy`,className:`max-w-full rounded-lg`})}},children:E(t)})})}function Ct(e){(w!==`split`||e===`split`||!Te||window.confirm(`Discard unsaved changes?`))&&(w===`split`&&e!==`split`&&oe(null),te(null),T(e))}function wt(){(!Te||window.confirm(`Discard unsaved changes?`))&&p()}function Tt(){j&&(ye&&w===`rendered`&&(te(`rendered`),T(Se?`split`:`source`)),oe({draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs}))}function Et(){ee===null?oe(Le&&j!==null?{draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs}:null):(oe(null),T(ee),te(null))}function Dt(t=!1){j&&k!==null&&!Ee&&(de.current=k.draft,h(e.path,k.draft,k.baseMtimeMs,t))}function Ot(){oe(null),m(e.path)}function kt(){let t=!D;ne(t),t?c(e.path):l()}return(0,d.useEffect)(()=>{k!==null&&j!==null&&de.current!==null&&j.content===de.current&&j.mtimeMs!==k.baseMtimeMs&&(de.current=null,oe({...k,baseContent:j.content,baseMtimeMs:j.mtimeMs}))},[j?.mtimeMs]),(0,d.useEffect)(()=>{function e(e){if(e.key===`Escape`)We?ht():wt();else if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`f`){if(He===`none`)return;e.preventDefault(),mt()}}return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)}),(0,d.useEffect)(()=>{Le&&Ce&&k===null&&j!==null&&oe({draft:j.content,baseContent:j.content,baseMtimeMs:j.mtimeMs})},[Le,Ce,j?.mtimeMs]),(0,d.useEffect)(()=>{ce(n?`streaming`:e=>e===`streaming`?`done`:e)},[n]),(0,d.useEffect)(()=>(r(Te),()=>r(!1)),[Te]),(0,d.useEffect)(()=>(a&&c(e.path),()=>l()),[]),(0,A.jsxs)(`div`,{className:`absolute inset-0 z-20 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[ye&&!D&&(0,A.jsx)(`div`,{className:`flex shrink-0 items-center gap-0.5`,role:`group`,"aria-label":`How to show this document`,children:[[`rendered`,`⚏ rendered`,`Show the rendering`],[`split`,`⇹ split`,`Edit the file beside its rendering`],[`source`,`⌗ source`,`Show the file as written`]].map(([e,t,n])=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>Ct(e),"aria-pressed":w===e,title:n,className:`rounded px-1.5 py-0.5 text-xs ${w===e?`bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-200`:`text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`}`,children:t},e))}),i!==void 0&&k===null&&(0,A.jsx)(`button`,{type:`button`,onClick:kt,"aria-pressed":D,title:D?`Show file content`:`Show uncommitted changes (vs HEAD)`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs ${D?`bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300`:`text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`}`,children:`± diff`}),u&&k===null&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>f(e.path),title:`Show this file's history`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300`,children:`⎇ history`}),(0,A.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-zinc-500 dark:text-zinc-400`,title:e.path,children:[e.path,Te&&(0,A.jsx)(`span`,{className:`ml-1 text-amber-500`,children:`●`})]}),j&&!me&&!he&&!D&&!ve&&(0,A.jsx)(kR,{text:ke,path:e.path,serverUrl:g,token:_,workspace:v,template:y}),Re?.kind===`table`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(kR,{text:()=>ze.current?.markdown?.()??``,path:`${e.path.replace(/\.[^./]*$/,``)}.md`,serverUrl:g,token:_,workspace:v,template:y}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>ze.current?.xlsx?.(),title:`Download as an Excel workbook`,"aria-label":`Download as an Excel workbook`,className:QR,children:`⤓ excel`})]}),(Re?.kind===`graph`||Re?.kind===`sequence`||Re?.kind===`timeline`)&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>ze.current?.svg?.(),title:`Download the figure as SVG`,"aria-label":`Download the figure as SVG`,className:QR,children:`⤓ svg`}),j&&k===null&&(0,A.jsx)(le,{text:j.content}),j&&k===null&&!D&&Ce&&(0,A.jsx)(`button`,{type:`button`,onClick:Tt,className:`shrink-0 rounded border border-zinc-300 px-2 py-0.5 text-xs text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-700 dark:text-zinc-400 dark:hover:border-zinc-500 dark:hover:text-zinc-200`,children:`✎ edit`}),j&&k===null&&!Ce&&(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,title:`Outside the writable zone`,children:`🔒 read-only`}),k!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>Dt(),disabled:!Te||Ee||Oe,className:`shrink-0 rounded border border-emerald-300 px-2 py-0.5 text-xs text-emerald-700 hover:border-emerald-500 disabled:opacity-50 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600`,children:Ee?`saving…`:`save`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{(!Te||window.confirm(`Discard unsaved changes?`))&&Et()},className:`shrink-0 rounded border border-zinc-300 px-2 py-0.5 text-xs text-zinc-500 hover:border-zinc-400 dark:border-zinc-700 dark:text-zinc-400 dark:hover:border-zinc-500`,children:Te?`cancel`:`done`})]}),(0,A.jsx)(`button`,{type:`button`,onClick:wt,title:`Close (Esc)`,"aria-label":`Close file viewer`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),We&&He!==`none`&&(0,A.jsx)(BR,{inputRef:Ze,query:qe,onQueryChange:Je,matchCount:vt.matchCount,currentIndex:vt.currentIndex,truncated:vt.truncated,searching:vt.searching,onNext:gt,onPrev:_t,onClose:ht}),Oe&&k!==null&&(0,A.jsxs)(`div`,{className:`flex items-center gap-3 border-b border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1`,children:`File changed on disk since you started editing.`}),(0,A.jsx)(`button`,{type:`button`,onClick:Ot,className:`shrink-0 rounded border border-amber-400 px-2 py-0.5 text-xs hover:bg-amber-100 dark:border-amber-800 dark:hover:bg-amber-950/60`,children:`reload (discard my edits)`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>Dt(!0),disabled:Ee,className:`shrink-0 rounded border border-amber-400 px-2 py-0.5 text-xs hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:hover:bg-amber-950/60`,children:`overwrite with my version`})]}),k!==null&&j?.saveError&&!j.saveError.conflict&&(0,A.jsx)(`div`,{className:`border-b border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:j.saveError.message}),(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[D&&k===null&&(0,A.jsxs)(`div`,{className:`p-4`,children:[o?.path===e.path&&`error`in o&&(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:o.error}),o?.path===e.path&&`before`in o&&(0,A.jsx)(Ke,{fill:!0,lines:S(o.before,o.after)}),o?.path!==e.path&&(0,A.jsx)(`div`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`loading diff…`})]}),he&&k===null&&!D&&(0,A.jsx)(Vf,{label:`This PDF`,children:(0,A.jsx)(d.Suspense,{fallback:(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading…`}),children:(0,A.jsx)(KR,{ref:$e,path:e.path,serverUrl:g,token:_,workspace:v,revision:C,findQuery:He===`pdf`?dt:``,onFindStateChange:tt,...x?{onLoaded:x}:{}})})}),me&&k===null&&!D&&(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center p-4`,children:(0,A.jsx)(`img`,{src:ae(g,e.path,_,C,v),alt:e.path,onLoad:()=>b(e.path),className:`max-h-full max-w-full rounded object-contain`})}),e.status===`loading`&&k===null&&!D&&!me&&!he&&(0,A.jsx)(`div`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,children:`loading…`}),e.status===`error`&&!me&&!he&&(0,A.jsx)(`div`,{className:`p-4 text-sm text-red-600 dark:text-red-400`,children:e.message}),k!==null&&!Le&&yt,j&&k===null&&!Le&&!D&&fe&&!xe&&(0,A.jsx)(`div`,{ref:Qe,children:St(j.content)}),j&&k===null&&!Le&&!D&&pe&&!xe&&(0,A.jsx)(`div`,{className:`h-full`,"data-testid":`file-html`,children:(0,A.jsx)(zR,{source:j.content,path:e.path,load:xt,onOpen:m})}),Le&&(0,A.jsxs)(`div`,{className:`flex h-full min-h-0`,"data-testid":`file-split`,children:[(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto border-r border-zinc-200 dark:border-zinc-800`,children:yt??bt(!1)}),(0,A.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto`,"data-testid":`file-split-rendering`,children:fe&&!ve?(0,A.jsx)(`div`,{className:`prose-chat p-4 text-zinc-700 dark:text-zinc-300`,children:St(Ae)}):pe&&!ve?(0,A.jsx)(zR,{source:Ae,path:e.path,load:xt,onOpen:m}):(0,A.jsxs)(A.Fragment,{children:[Pe&&(0,A.jsx)(`p`,{"data-testid":`file-split-stale`,className:`flex flex-wrap items-center gap-2 border-b border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200`,children:(0,A.jsxs)(`span`,{children:[`Showing the document as it last stood.`,` `,Ie??`The text beside it does not satisfy the schema it declares.`]})}),Fe!==void 0&&(0,A.jsxs)(`ul`,{"data-testid":`file-split-issues`,className:`space-y-0.5 border-b border-zinc-200 px-3 py-1.5 text-xs text-zinc-500 dark:border-zinc-800 dark:text-zinc-400`,children:[Fe.slice(0,6).map((e,t)=>(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`font-mono opacity-70`,children:e.path===``?`(document)`:e.path}),` `,e.message]},t)),Fe.length>6&&(0,A.jsxs)(`li`,{className:`opacity-70`,children:[`…and `,Fe.length-6,` more`]})]}),Me===void 0?(0,A.jsxs)(`p`,{className:`p-4 text-sm text-zinc-400 dark:text-zinc-600`,"data-testid":`file-split-nothing`,children:[`Nothing to draw yet. `,Ie??`This document does not satisfy the schema it declares.`]}):(0,A.jsx)(Vf,{label:`This diagram`,children:(0,A.jsx)(`div`,{className:`p-4`,"data-testid":`file-structured-exchange`,children:(0,A.jsx)(Rf,{envelope:Me,source:ke,exportRef:ze})})})]})})]}),j&&k===null&&!Le&&!D&&_e&&!xe&&ge?.status===`valid`&&(0,A.jsx)(Vf,{label:`This diagram`,children:(0,A.jsx)(`div`,{className:`mx-auto max-w-5xl p-4`,"data-testid":`file-structured-exchange`,children:(0,A.jsx)(Rf,{envelope:ge.envelope,source:j.content,exportRef:ze})})}),j&&k===null&&!Le&&!D&&ge?.status===`invalid`&&(0,A.jsxs)(`div`,{"data-testid":`file-structured-exchange-invalid`,className:`mx-4 mt-4 rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200`,children:[(0,A.jsx)(`p`,{className:`font-medium`,children:`This declares a structured-exchange document and does not satisfy the schema.`}),(0,A.jsxs)(`ul`,{className:`mt-1 space-y-0.5 text-xs`,children:[(j.documentIssues??ge.issues).slice(0,8).map((e,t)=>(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`font-mono opacity-70`,children:e.path===``?`(document)`:e.path}),` `,e.message]},t)),(j.documentIssues??ge.issues).length>8&&(0,A.jsxs)(`li`,{className:`opacity-70`,children:[`…and `,(j.documentIssues??ge.issues).length-8,` more`]})]})]}),j&&k===null&&!Le&&!D&&ge?.status===`unsupported-version`&&(0,A.jsxs)(`div`,{"data-testid":`file-structured-exchange-unsupported`,className:`mx-4 mt-4 rounded-lg border border-zinc-300 bg-zinc-50 px-3 py-2 text-sm text-zinc-600 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-400`,children:[`This document declares `,(0,A.jsx)(`span`,{className:`font-mono`,children:ge.schema}),`, which this version does not render. Shown as text.`]}),Ve&&bt(!0)]}),se!==`idle`&&(0,A.jsxs)(`button`,{type:`button`,onClick:wt,"aria-live":`polite`,className:`flex items-center gap-2 border-t border-zinc-200 px-3 py-2 text-left text-sm hover:bg-zinc-50 dark:border-zinc-800 dark:hover:bg-zinc-900`,children:[se===`streaming`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`h-2 w-2 animate-pulse motion-reduce:animate-none rounded-full bg-amber-500`}),(0,A.jsx)(`span`,{className:`text-amber-700 dark:text-amber-400`,children:`π is replying…`})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`h-2 w-2 rounded-full bg-emerald-500`}),(0,A.jsx)(`span`,{className:`text-emerald-700 dark:text-emerald-400`,children:`π replied`})]}),(0,A.jsx)(`span`,{className:`ml-auto text-xs text-zinc-400 dark:text-zinc-500`,children:`show conversation →`})]})]})}function rz(e){return e.split(`
361
+ `).map(e=>e.startsWith(`diff --git `)?{kind:`file`,text:e.slice(11)}:e.startsWith(`@@`)||e.startsWith(`+++`)||e.startsWith(`---`)||e.startsWith(`index `)?{kind:`hunk`,text:e}:e.startsWith(`+`)?{kind:`add`,text:e.slice(1)}:e.startsWith(`-`)?{kind:`del`,text:e.slice(1)}:{kind:`context`,text:e.startsWith(` `)?e.slice(1):e})}function iz({show:e,onClose:t}){return(0,d.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopImmediatePropagation(),t())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[t]),(0,A.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`span`,{className:`font-mono text-xs text-amber-600 dark:text-amber-500`,children:e.sha.slice(0,12)}),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-500 dark:text-zinc-400`,children:`commit diff`}),(0,A.jsx)(`button`,{type:`button`,onClick:t,title:`Close (Esc)`,"aria-label":`Close commit diff`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),e.truncated&&(0,A.jsx)(`div`,{className:`border-b border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:`Patch truncated — showing the first 256 KiB.`}),(0,A.jsx)(`pre`,{className:`min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed`,children:rz(e.patch).map((e,t)=>(0,A.jsxs)(`div`,{className:e.kind===`file`?`mt-3 border-t border-zinc-200 pt-2 font-bold text-zinc-700 first:mt-0 first:border-t-0 first:pt-0 dark:border-zinc-800 dark:text-zinc-200`:e.kind===`hunk`?`text-sky-600 dark:text-sky-400`:e.kind===`add`?`bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300`:e.kind===`del`?`bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300`:`text-zinc-500 dark:text-zinc-500`,children:[e.kind===`add`?`+ `:e.kind===`del`?`− `:``,e.text||` `]},t))})]})}var az=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`],oz=`worktree`,sz={defaultWidth:288,minWidth:224,maxWidth:640,keyboardStep:16,storageKey:`pi-outpost.files-sidebar-width.v1`},cz={defaultWidth:416,minWidth:224,maxWidth:640,keyboardStep:16,storageKey:`pi-outpost.history-list-width.v1`};function lz(e,t){return Number.isFinite(e)?Math.min(t.maxWidth,Math.max(t.minWidth,Math.round(e))):t.defaultWidth}function uz(e,t){return e===null||e.trim()===``?t.defaultWidth:lz(Number(e),t)}function dz(e,t){try{return uz((t??window.localStorage).getItem(e.storageKey),e)}catch{return e.defaultWidth}}function fz(e,t,n){try{(n??window.localStorage).setItem(t.storageKey,String(lz(e,t)))}catch{}}function pz(e){let[t,n]=(0,d.useState)(()=>dz(e)),r=(0,d.useRef)(t),i=(0,d.useRef)(null),a=(0,d.useCallback)(t=>{let i=lz(t,e);return r.current=i,n(i),i},[e]),o=(0,d.useCallback)(()=>{i.current!==null&&(i.current=null,fz(r.current,e))},[e]);return{width:t,separatorProps:{onPointerDown:e=>{e.isPrimary!==!1&&(e.button??0)===0&&(e.preventDefault(),e.currentTarget.setPointerCapture?.(e.pointerId),i.current={pointerId:e.pointerId,startX:e.clientX,startWidth:r.current})},onPointerMove:e=>{let t=i.current;t!==null&&t.pointerId===e.pointerId&&a(t.startWidth+e.clientX-t.startX)},onPointerUp:e=>{i.current?.pointerId===e.pointerId&&o()},onPointerCancel:e=>{let t=i.current;t!==null&&t.pointerId===e.pointerId&&(i.current=null,a(t.startWidth))},onLostPointerCapture:o,onKeyDown:t=>{let n=null;t.key===`ArrowLeft`?n=r.current-e.keyboardStep:t.key===`ArrowRight`?n=r.current+e.keyboardStep:t.key===`Home`&&(n=e.defaultWidth),n!==null&&(t.preventDefault(),fz(a(n),e))}}}}function mz({label:e,width:t,config:n,separatorProps:r,className:i=``}){return(0,A.jsx)(`div`,{...r,role:`separator`,"aria-label":e,"aria-orientation":`vertical`,"aria-valuemin":n.minWidth,"aria-valuemax":n.maxWidth,"aria-valuenow":t,tabIndex:0,title:e,className:`group absolute inset-y-0 -right-1 z-20 w-2 cursor-col-resize touch-none outline-none ${i}`,children:(0,A.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 left-1/2 w-px bg-transparent transition-colors group-hover:bg-blue-400 group-focus-visible:bg-blue-500 group-active:bg-blue-500 dark:group-hover:bg-blue-500`})})}var hz=`#10b981`,gz=[`#8b5cf6`,`#f59e0b`,`#0ea5e9`,`#f43f5e`,`#14b8a6`,`#d946ef`];function _z(e){return e===0?hz:gz[(e-1)%gz.length]}function vz(e){return gz[e%gz.length]}function yz(e){return e*14+7+1}function bz(e){return e*14+2}function xz({row:e,laneCount:t,colorOf:n=_z}){let r=bz(t),i=yz(e.lane),a=e.highlight?hz:n(e.lane),o=e.dashed?`3 3`:void 0;return(0,A.jsxs)(`svg`,{width:r,height:36,viewBox:`0 0 ${r} 36`,"aria-hidden":!0,className:`shrink-0`,children:[e.through.map(e=>(0,A.jsx)(`line`,{x1:yz(e),y1:0,x2:yz(e),y2:36,stroke:n(e),strokeWidth:2,opacity:.55},e)),e.lineAbove&&(0,A.jsx)(`line`,{x1:i,y1:0,x2:i,y2:18,stroke:a,strokeWidth:2,strokeDasharray:o}),e.lineBelow&&(0,A.jsx)(`line`,{x1:i,y1:18,x2:i,y2:36,stroke:a,strokeWidth:2,strokeDasharray:o}),e.forkTo.map(e=>(0,A.jsx)(`path`,{d:`M ${i} 18 C ${i} 36, ${yz(e)} 18, ${yz(e)} 36`,fill:`none`,stroke:n(e),strokeWidth:2,opacity:.75},`fork-${e}`)),(e.mergeFrom??[]).map(e=>(0,A.jsx)(`path`,{d:`M ${i} 18 C ${i} 0, ${yz(e)} 18, ${yz(e)} 0`,fill:`none`,stroke:n(e),strokeWidth:2,opacity:.75},`merge-${e}`)),e.emphasis===`current`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`circle`,{cx:i,cy:18,r:6,fill:`none`,stroke:a,strokeWidth:2}),(0,A.jsx)(`circle`,{cx:i,cy:18,r:2.5,fill:a})]}):(0,A.jsx)(`circle`,{cx:i,cy:18,r:4,fill:e.emphasis===`filled`?a:`var(--tree-off, #d4d4d8)`,stroke:a,strokeWidth:e.emphasis===`filled`?0:1.5})]})}function Sz(e,t){let n=[],r=t===void 0?[]:[t],i=r.length,a=t!==void 0,o=()=>{let e=r.indexOf(null);return e===-1?(r.push(null),i=Math.max(i,r.length),r.length-1):e};for(let s of e){let e=r.reduce((e,t,n)=>t===s.sha?[...e,n]:e,[]),c=e[0]??o();s.sha===t&&(a=!1);let l=(s.sha===t?e.length-1:e.length)===0,u=e.slice(1);for(let e of u)r[e]=null;i=Math.max(i,c+1);let[d,...f]=s.parents;r[c]=d??null;let p=f.map(e=>{let t=o();return r[t]=e,t});n.push({lane:c,through:r.reduce((e,t,n)=>t!==null&&n!==c&&!p.includes(n)&&!(a&&n===0)?[...e,n]:e,[]),forkTo:p,mergeFrom:u,tip:l})}return{lanes:n,laneCount:Math.max(i,1)}}function Cz(e){let t=e.find(e=>e.head)?.sha,{lanes:n,laneCount:r}=Sz(e,t);return{rows:e.map((e,t)=>{let{lane:r,through:i,forkTo:a,mergeFrom:o,tip:s}=n[t];return{lane:r,through:i,forkTo:a,mergeFrom:o,entry:e,lineAbove:!s,lineBelow:e.parents.length>0,emphasis:e.head?`current`:`filled`}}),laneCount:r}}function wz(e,t={}){let{lanes:n,laneCount:r}=Sz(e),i=e.map((e,t)=>{let{lane:r,through:i,forkTo:a,mergeFrom:o}=n[t];return{lane:r,through:i,forkTo:a,mergeFrom:o,rev:e.sha,path:e.path,entry:e,lineAbove:!0,lineBelow:e.parents.length>0,emphasis:`filled`}}),a=i[0];return i.unshift({rev:oz,path:a?.path??``,lane:a?.lane??0,through:a?.through??[],forkTo:[],mergeFrom:[],lineAbove:!1,lineBelow:i.length>0,emphasis:`current`,dashed:!t.dirty}),i[1]&&(i[1].lineAbove=!0),{rows:i,laneCount:r}}var Tz=20;function Ez(e){let t=(Date.now()-new Date(e).getTime())/1e3;return t<90?`now`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Dz(e){return e.rev===`worktree`?`working tree`:e.rev.slice(0,7)}function Oz(e,t){return e!==null&&t!==null&&e.rev===t.rev&&e.path===t.path}function kz(e){return{rev:e.rev,path:e.path}}function Az({history:e,diff:t,dirty:n,onFetchDiff:r,onClearDiff:i,onClose:a}){let[o,s]=(0,d.useState)({base:null,target:null}),{base:c,target:l}=o,[u,f]=(0,d.useState)(0),p=(0,d.useRef)([]),m=pz(cz),{rows:h,laneCount:g}=(0,d.useMemo)(()=>wz(e.entries,{dirty:n}),[e.entries,n]),_=(0,d.useRef)({onFetchDiff:r,onClose:a});_.current={onFetchDiff:r,onClose:a},(0,d.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopImmediatePropagation(),_.current.onClose())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,d.useEffect)(()=>{c===null||l===null||Oz(c,l)||_.current.onFetchDiff(c,l)},[c,l]);let v=(0,d.useCallback)((e,t)=>{let n=kz(e);s(r=>{if(t===`base`)return{base:n,target:Oz(n,r.target)?r.base:r.target};if(t===`target`)return{base:Oz(n,r.base)?r.target:r.base,target:n};if(r.base===null&&r.target===null){let t=e.entry?.parents[0],r=t===void 0?void 0:h.find(e=>e.rev===t);return{base:r?kz(r):null,target:n}}return{base:Oz(n,r.base)?r.target:r.base,target:n}})},[h]),y=(0,d.useCallback)(()=>{s({base:null,target:null}),i()},[i]),b=(0,d.useCallback)(()=>s(e=>({base:e.target,target:e.base})),[]),x=(0,d.useCallback)(e=>{f(t=>{let n=Math.max(0,Math.min(h.length-1,t+e));return p.current[n]?.focus(),n})},[h.length]),S=e=>{let t=kz(e);return Oz(t,c)?`base`:Oz(t,l)?`target`:null},C=h.findIndex(e=>Oz(kz(e),c)),w=h.findIndex(e=>Oz(kz(e),l)),T=C>=0&&w>=0?{top:Math.min(C,w)*36+18,height:Math.abs(w-C)*36}:null;return(0,A.jsxs)(`div`,{className:`absolute inset-0 z-30 flex flex-col bg-white dark:bg-zinc-950`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-zinc-500 dark:text-zinc-400`,title:e.path,children:e.path}),c!==null&&l!==null&&(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-zinc-500 dark:text-zinc-400`,"aria-label":`Comparing ${Dz(c)} to ${Dz(l)}`,children:[(0,A.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:Dz(c)}),` → `,(0,A.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:Dz(l)})]}),c!==null&&l!==null&&(0,A.jsx)(`button`,{type:`button`,onClick:b,title:`Compare the other way round`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`⇄ swap`}),(c!==null||l!==null)&&(0,A.jsx)(`button`,{type:`button`,onClick:y,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-700 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200`,children:`clear`}),(0,A.jsx)(`button`,{type:`button`,onClick:a,title:`Close (Esc)`,"aria-label":`Close file history`,className:`shrink-0 px-1 text-sm text-zinc-400 hover:text-zinc-600 dark:text-zinc-600 dark:hover:text-zinc-300`,children:`✕`})]}),(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col md:flex-row`,children:[(0,A.jsxs)(`div`,{role:`region`,"aria-label":`Commit history`,style:{"--history-list-width":`${m.width}px`},className:`relative flex max-h-[40%] w-full shrink-0 flex-col border-b border-zinc-200 md:max-h-none md:w-[var(--history-list-width)] md:border-b-0 md:border-r dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),x(1)):e.key===`ArrowUp`&&(e.preventDefault(),x(-1))},children:[e.status===`loading`&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`Reading history…`}),e.status===`error`&&(0,A.jsx)(`div`,{className:`m-3 rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e.error}),e.status===`loaded`&&e.entries.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`No commits touch this file yet.`}),e.status===`loaded`&&e.entries.length>0&&(0,A.jsxs)(`div`,{className:`relative`,role:`group`,"aria-label":`Commits`,children:[T&&(0,A.jsx)(jz,{top:T.top,height:T.height,baseFirst:C<w}),h.map((e,t)=>(0,A.jsx)(Pz,{ref:e=>{p.current[t]=e},row:e,laneCount:g,role:S(e),isFocused:t===u,onSelect:t=>v(e,t),onFocus:()=>f(t)},e.rev))]})]}),(0,A.jsx)(mz,{label:`Resize History commit list`,width:m.width,config:cz,separatorProps:m.separatorProps,className:`hidden md:block`})]}),(0,A.jsx)(`div`,{role:`region`,"aria-label":`History diff`,className:`min-h-0 min-w-0 flex-1 overflow-auto p-3`,children:(0,A.jsx)(Fz,{diff:t,base:c,target:l})})]})]})}function jz({top:e,height:t,baseFirst:n}){return(0,A.jsxs)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute left-0 z-10 motion-safe:transition-all motion-safe:duration-150 motion-safe:ease-out`,style:{top:e,height:t,width:Tz},children:[(0,A.jsx)(`div`,{className:`absolute inset-y-0 left-2 w-px bg-zinc-400 dark:bg-zinc-500`}),(0,A.jsx)(Mz,{label:n?`base`:`target`,className:`top-0`}),(0,A.jsx)(Mz,{label:n?`target`:`base`,className:`bottom-0`})]})}function Mz({label:e,className:t}){return(0,A.jsx)(`div`,{className:`absolute left-2 flex h-px w-2.5 items-center bg-zinc-400 dark:bg-zinc-500 ${t}`,children:(0,A.jsx)(`span`,{className:`absolute -left-1 -top-1.5 rotate-180 text-[9px] leading-none text-zinc-500 [writing-mode:vertical-rl] dark:text-zinc-400`,children:e})})}var Nz=`shrink-0 rounded px-1 py-0.5 text-[10px] text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 aria-disabled:cursor-default aria-disabled:opacity-30 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`;function Pz({row:e,laneCount:t,role:n,isFocused:r,onSelect:i,onFocus:a,ref:o}){let s=e.entry,c=s?`${s.sha.slice(0,7)} ${s.subject}`:`Working tree`;return(0,A.jsxs)(`div`,{ref:o,role:`button`,tabIndex:r?0:-1,"aria-label":c,"aria-current":n===null?void 0:`true`,onFocus:a,onClick:()=>i(),onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `?(e.preventDefault(),i()):e.key===`b`?i(`base`):e.key===`t`&&i(`target`))},style:{height:36,paddingLeft:Tz},className:`group flex cursor-pointer items-center gap-2 pr-2 focus:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800/70 ${n===null?``:`bg-zinc-100 dark:bg-zinc-800/60`}`,children:[(0,A.jsx)(xz,{row:e,laneCount:t}),s?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-amber-600 dark:text-amber-500`,children:s.sha.slice(0,7)}),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-700 dark:text-zinc-300`,title:s.subject,children:s.subject}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[10px] text-zinc-400 dark:text-zinc-600`,children:[s.author,` · `,Ez(s.date)]}),(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums`,"aria-label":`${s.added} lines added, ${s.deleted} removed`,children:[(0,A.jsxs)(`span`,{className:`text-emerald-600 dark:text-emerald-500`,children:[`+`,s.added]}),` `,(0,A.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,s.deleted]})]})]}):(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-zinc-500 dark:text-zinc-400`,children:`working tree`}),(0,A.jsxs)(`span`,{className:`flex shrink-0 gap-0.5`,children:[(0,A.jsx)(`button`,{type:`button`,title:n===`target`?`Make this the base (swaps the two)`:`Compare from this version`,onClick:e=>{e.stopPropagation(),i(`base`)},className:Nz,children:`base`}),(0,A.jsx)(`button`,{type:`button`,title:n===`base`?`Make this the target (swaps the two)`:`Compare to this version`,onClick:e=>{e.stopPropagation(),i(`target`)},className:Nz,children:`target`})]})]})}function Fz({diff:e,base:t,target:n}){return t===null&&n===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Pick a commit to see what changed.`}):t===null||n===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Now pick the version to compare it against.`}):e?.status===`error`?(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e.error}):e===null?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`Loading…`}):e.status===`loaded`&&e.beforeText===e.afterText?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`These two versions are identical.`}):e.status===`loaded`&&x(e.beforeText,e.afterText)?(0,A.jsx)(`p`,{className:`text-sm text-zinc-400 dark:text-zinc-600`,children:`These two versions differ only in their line endings.`}):(0,A.jsx)(`div`,{className:e.status===`loading`?`opacity-40`:void 0,children:(0,A.jsx)(Ke,{fill:!0,lines:S(e.beforeText,e.afterText)})})}var Iz=`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none`,Lz=`inline-flex h-7 min-w-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none`;function Rz(e){let t=e.filter(e=>!e.sideOf).flatMap(t=>[t,...e.filter(e=>e.sideOf===t.root)]);return[...t,...e.filter(e=>!t.includes(e))]}var zz={stopped:`stopped`,starting:`starting…`,idle:`idle`,working:`working`,waiting:`waiting for you`,"ready-for-review":`ready for review`};function Bz({activity:e}){switch(e){case`stopped`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full border border-dashed border-zinc-400 dark:border-zinc-600`});case`starting`:return(0,A.jsx)(`svg`,{className:`h-2.5 w-2.5 shrink-0 animate-spin text-zinc-500 dark:text-zinc-400`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`3.5`,strokeLinecap:`round`,children:(0,A.jsx)(`path`,{d:`M12 3a9 9 0 0 1 9 9`})});case`working`:return(0,A.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0 items-center justify-center`,children:[(0,A.jsx)(`span`,{className:`absolute h-2 w-2 animate-ping rounded-full bg-blue-700 opacity-60 dark:bg-blue-400`}),(0,A.jsx)(`span`,{className:`relative h-2 w-2 rounded-full bg-blue-700 dark:bg-blue-400`})]});case`waiting`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full bg-amber-500`});case`ready-for-review`:return(0,A.jsx)(`span`,{className:`h-2 w-2 shrink-0 rotate-45 rounded-[1px] border-2 border-violet-600 bg-violet-100 dark:border-violet-400 dark:bg-violet-950`});default:return(0,A.jsx)(`span`,{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-zinc-400 dark:bg-zinc-600`})}}function Vz({className:e}){return(0,A.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,"aria-hidden":`true`,children:[(0,A.jsx)(`path`,{d:`M12 6v7`}),(0,A.jsx)(`path`,{d:`M12 18h.01`})]})}function Hz({className:e}){return(0,A.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,A.jsx)(`path`,{d:`M7 3h10v18H7z`}),(0,A.jsx)(`path`,{d:`m9.5 12 1.7 1.7 3.5-3.7`})]})}function Uz(e){let{workspace:t,workspaces:n,locked:r}=e,[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null);if((0,d.useEffect)(()=>{if(!i)return;let e=e=>{XL(e,o.current)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]),r||!t)return null;let s=n.filter(e=>NI(e)!==NI(t)),c=n.filter(e=>!e.sideOf).length,l=n.filter(e=>e.needsAttention);return(0,A.jsxs)(`div`,{ref:o,className:`relative min-w-[4rem] max-w-[16rem]`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-haspopup":`menu`,title:`Project: ${t.name} (${zz[t.activity]})`,className:`${Lz} max-w-full gap-1.5 ${l.length>0?`border-amber-500 bg-amber-50 text-zinc-700 dark:bg-amber-950/40 dark:text-zinc-200`:`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`}`,children:[(0,A.jsx)(Bz,{activity:t.activity}),(0,A.jsx)(`span`,{className:`truncate font-medium`,children:t.name}),l.length>0?(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-amber-600 dark:text-amber-500`,children:[(0,A.jsx)(Vz,{className:`h-3 w-3`}),(0,A.jsx)(`span`,{className:`font-semibold`,children:l.length})]}):s.some(e=>e.activity===`working`)&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`h-3 w-px bg-zinc-300 dark:bg-zinc-600`}),(0,A.jsx)(`span`,{className:`flex items-center gap-1`,children:s.map(e=>e.activity===`working`?(0,A.jsxs)(`span`,{className:`relative flex h-1.5 w-1.5 items-center justify-center`,children:[(0,A.jsx)(`span`,{className:`absolute h-1.5 w-1.5 animate-ping rounded-full bg-blue-700 opacity-60 dark:bg-blue-400`}),(0,A.jsx)(`span`,{className:`relative h-1.5 w-1.5 rounded-full bg-blue-700 dark:bg-blue-400`})]},NI(e)):(0,A.jsx)(`span`,{className:`h-1 w-1 rounded-full bg-zinc-300 dark:bg-zinc-600`},NI(e)))})]}),(0,A.jsx)(`svg`,{className:`h-3 w-3 text-zinc-500`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`m6 9 6 6 6-6`})})]}),i&&(0,A.jsxs)(`div`,{role:`menu`,className:`absolute left-0 top-full z-40 mt-1 w-87 rounded-md border border-zinc-300 bg-white p-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:[Rz(n).map(n=>{let r=NI(n),i=r===NI(t),o=n.sideOf!==void 0;return(0,A.jsxs)(`div`,{"data-testid":o?`side-session-row`:`project-row`,className:`group flex items-center gap-2.5 rounded-md py-2 pr-2.5 ${o?`pl-7`:`pl-2.5`} ${i?`bg-zinc-100 dark:bg-zinc-800`:`hover:bg-zinc-50 dark:hover:bg-zinc-800/50`}`,children:[(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),o?e.onSwitch(n.root,n.id):e.onSwitch(n.root)},className:`flex min-w-0 flex-1 items-center gap-2.5 text-left`,children:[(0,A.jsx)(Bz,{activity:n.activity}),(0,A.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,A.jsx)(`span`,{className:`truncate text-[13px] ${i?`font-semibold text-zinc-900 dark:text-zinc-100`:`font-medium text-zinc-900 dark:text-zinc-100`}`,children:o?n.label??n.name:n.name}),!o&&(0,A.jsx)(`span`,{className:`truncate font-mono text-[11px] text-zinc-400 dark:text-zinc-500`,children:n.root})]})]}),(0,A.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5`,children:[n.needsAttention?(0,A.jsxs)(`span`,{className:`flex items-center gap-1 text-[11px] font-medium ${n.activity===`ready-for-review`?`text-violet-700 dark:text-violet-400`:`text-amber-600 dark:text-amber-500`}`,children:[n.activity===`ready-for-review`?(0,A.jsx)(Hz,{className:`h-3 w-3`}):(0,A.jsx)(Vz,{className:`h-3 w-3`}),zz[n.activity]]}):(0,A.jsx)(`span`,{className:`text-[11px] ${n.activity===`working`?`text-blue-700 dark:text-blue-400`:`text-zinc-400 dark:text-zinc-500`}`,children:zz[n.activity]}),!o&&e.onOpenSide&&(0,A.jsx)(`button`,{type:`button`,title:`New side session on ${n.name}`,"aria-label":`New side session on ${n.name}`,onClick:t=>{t.stopPropagation(),a(!1),e.onOpenSide?.(n.root)},className:`flex h-5 w-5 items-center justify-center rounded border border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-800 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500 dark:hover:text-zinc-100`,children:(0,A.jsxs)(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5v14`}),(0,A.jsx)(`path`,{d:`M5 12h14`})]})}),(o||c>1)&&(0,A.jsx)(`button`,{type:`button`,title:`Close ${o?n.label??n.name:n.name}`,"aria-label":`Close ${o?n.label??n.name:n.name}`,onClick:t=>{t.stopPropagation(),o?e.onClose(n.root,n.id):e.onClose(n.root)},className:`flex h-5 w-5 items-center justify-center rounded border border-transparent text-zinc-400 opacity-0 group-hover:border-zinc-300 group-hover:opacity-100 hover:text-zinc-700 dark:group-hover:border-zinc-600 dark:hover:text-zinc-200`,children:(0,A.jsxs)(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,A.jsx)(`path`,{d:`M18 6 6 18`}),(0,A.jsx)(`path`,{d:`m6 6 12 12`})]})})]})]},r)}),(0,A.jsx)(`div`,{className:`my-1 h-px bg-zinc-200 dark:bg-zinc-700`}),(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),e.onOpen()},className:`flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] text-zinc-700 hover:bg-zinc-50 dark:text-zinc-300 dark:hover:bg-zinc-800/50`,children:[(0,A.jsxs)(`svg`,{className:`h-3.5 w-3.5 text-zinc-500`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5v14`}),(0,A.jsx)(`path`,{d:`M5 12h14`})]}),`Open a project…`]})]})]})}function Wz({label:e,browse:t,onBrowse:n,onSelect:r,onCancel:i}){let a=t?.path??`/`,o=t?.entries??[],s=t?.status===`loading`,[c,l]=(0,d.useState)(a);return(0,d.useEffect)(()=>{l(a)},[a]),(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-300 p-2 dark:border-zinc-700`,"data-testid":`server-path-picker`,children:[(0,A.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`text-xs font-semibold text-zinc-600 dark:text-zinc-300`,children:e}),(0,A.jsx)(`button`,{type:`button`,onClick:i,className:`text-xs text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200`,children:`Cancel`})]}),(0,A.jsxs)(`form`,{className:`mb-2 flex gap-1`,onSubmit:e=>{e.preventDefault();let t=c.trim();t&&n(t)},children:[(0,A.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),l(a))},spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":`Current directory`,"data-testid":`picker-path`,className:`min-w-0 flex-1 rounded border border-zinc-300 px-2 py-1 font-mono text-xs text-zinc-700 focus:border-zinc-500 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),(0,A.jsx)(`button`,{type:`submit`,disabled:c.trim()===``||c===a,className:`rounded border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 dark:border-zinc-700 dark:text-zinc-300`,children:`Go`})]}),t?.status===`error`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-2 text-xs text-red-600 dark:text-red-400`,children:t.error}),(0,A.jsxs)(`div`,{className:`mb-2 flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:!t?.parent,onClick:()=>t?.parent&&n(t.parent),className:`rounded border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-40 dark:border-zinc-700 dark:text-zinc-300`,children:`Up`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>r(a),className:`rounded bg-zinc-800 px-2 py-1 text-xs font-medium text-white hover:bg-zinc-700 dark:bg-zinc-200 dark:text-zinc-900`,children:`Use this directory`})]}),(0,A.jsxs)(`ul`,{className:`max-h-40 overflow-y-auto`,children:[s&&o.length===0&&(0,A.jsx)(`li`,{className:`px-2 py-1 text-xs text-zinc-400`,children:`Loading…`}),!s&&o.length===0&&t?.status!==`error`&&(0,A.jsx)(`li`,{className:`px-2 py-1 text-xs text-zinc-400 dark:text-zinc-500`,children:`No subdirectories`}),o.map(e=>(0,A.jsx)(`li`,{children:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>n(e.path),className:`w-full truncate rounded px-2 py-1 text-left font-mono text-xs text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800`,title:e.path,children:[e.name,e.name.endsWith(`:`)?`\\`:`/`]})},e.path))]})]})}function Gz(e){return e.split(/[\\/]/).filter(Boolean).at(-1)??e}function Kz(e){let{sandbox:t,applyState:n,blocked:r=!1,onCloseBrowser:i}=e,[a,o]=(0,d.useState)(!1),s=(0,d.useRef)(!1);if((0,d.useEffect)(()=>{r&&a&&(s.current=!1,o(!1))},[r,a]),(0,d.useEffect)(()=>{s.current&&n?.status!==`applying`&&(n?.status===`error`?s.current=!1:(s.current=!1,o(!1),i()))},[n,i]),!t)return(0,A.jsx)(`span`,{className:`${Iz} border-dashed border-zinc-300 text-zinc-400 dark:border-zinc-700 dark:text-zinc-500`,title:`This server runs without a sandbox, so there is no root to move`,children:`No sandbox`});let c=t.locks?.root===!0,l=Gz(t.root);return(0,A.jsxs)(`div`,{className:`relative min-w-[4rem] max-w-[14rem]`,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:c,"aria-label":c?`Sandbox root: ${t.root} (locked)`:`Sandbox root: ${t.root}`,title:c?`${t.root} — locked by the server's configuration`:t.root,onClick:()=>{e.onOpened(),o(!0),e.onBrowse(t.root)},className:`${Lz} max-w-full gap-1.5 ${c?`cursor-not-allowed border-zinc-200 text-zinc-400 dark:border-zinc-800 dark:text-zinc-500`:`border-zinc-300 text-zinc-600 hover:border-zinc-400 hover:text-zinc-800 dark:border-zinc-700 dark:text-zinc-300 dark:hover:border-zinc-500 dark:hover:text-zinc-100`}`,children:[(0,A.jsx)(`span`,{className:`truncate font-mono`,children:l}),c?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):(0,A.jsx)(`span`,{"aria-hidden":`true`,children:`▾`})]}),a&&!r&&(0,A.jsxs)(`div`,{className:`absolute left-0 top-full z-20 mt-1 w-[380px] rounded-lg border border-zinc-200 bg-white p-2 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[n?.status===`error`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-2 text-xs text-red-600 dark:text-red-400`,children:n.message}),(0,A.jsx)(Wz,{label:`Choose the sandbox root`,browse:e.browse,onBrowse:e.onBrowse,onSelect:t=>{s.current=!0,e.onSelect(t)},onCancel:()=>{s.current=!1,o(!1),i()}})]})]})}function qz(e){let t=(Date.now()-new Date(e).getTime())/1e3;return t<90?`now`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Jz(e){return e.slice(e.lastIndexOf(`/`)+1)}function Yz({status:e,selected:t,log:n,onFetchLog:r,onShowCommit:i}){let[a,o]=(0,d.useState)(!1),s=ZL(()=>o(!1)),c=e?.repos??[],l=(t===null?null:xL(c,t))??(t===null&&c.length===1?c[0]:null),u=l&&(l.ahead>0||l.behind>0)?` ${l.ahead>0?`↑${l.ahead}`:``}${l.behind>0?`↓${l.behind}`:``}`:``,f=c.length>1&&l!==null&&l.repo!==``?`${Jz(l.repo)} `:``,p=e===null?`…`:l?.branch??`—`,m=l!==null&&n?.repo===l.repo?n.entries:null,h=(0,d.useMemo)(()=>m===null?null:Cz(m),[m]);return(0,d.useEffect)(()=>{a&&l!==null&&n?.repo!==l.repo&&r(l.repo)},[a,l?.repo,r]),(0,A.jsxs)(`div`,{className:`relative min-w-[4rem] max-w-[14rem] shrink-[2]`,ref:s,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:l===null,onClick:()=>{l!==null&&(o(!a),a||r(l.repo))},title:l===null?`no repository selected`:`git history — ${l.repo===``?`this project`:l.repo}`,className:`${Lz} max-w-full border-zinc-300 font-mono text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 disabled:cursor-default disabled:hover:border-zinc-300 disabled:hover:text-zinc-500 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200 dark:disabled:hover:border-zinc-800 dark:disabled:hover:text-zinc-400`,children:[(0,A.jsxs)(`span`,{className:`truncate`,children:[f,`⎇ `,p]}),u]}),a&&l!==null&&(0,A.jsxs)(`div`,{className:`absolute left-0 top-full z-20 mt-1 max-h-96 w-[26rem] max-w-[80vw] overflow-y-auto rounded-lg border border-zinc-200 bg-white py-1 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[m===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),m?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no commits`}),h?.rows.map(e=>{let{entry:t}=e;return(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{i(l.repo,t.sha),o(!1)},style:{height:36},className:`flex w-full items-center gap-2 pl-2 pr-3 text-left text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(xz,{row:e,laneCount:h.laneCount}),(0,A.jsx)(`span`,{className:`shrink-0 font-mono text-xs text-amber-600 dark:text-amber-500`,children:t.sha.slice(0,7)}),t.refs.map(t=>{let n=t===l.branch?`#10b981`:_z(e.lane);return(0,A.jsx)(`span`,{style:{borderColor:n,color:n},className:`max-w-[8rem] shrink-0 truncate rounded-full border px-1.5 font-mono text-[10px] leading-4 ${t===l.branch?`font-semibold`:``}`,children:t},t)}),t.tags.map(e=>(0,A.jsxs)(`span`,{title:`tag ${e}`,className:`max-w-[8rem] shrink-0 truncate rounded border border-zinc-300 px-1 font-mono text-[10px] leading-4 text-zinc-500 dark:border-zinc-600 dark:text-zinc-400`,children:[`◆ `,e]},`tag-${e}`)),(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-zinc-700 dark:text-zinc-300`,title:t.subject,children:t.subject}),(0,A.jsxs)(`span`,{className:`shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,children:[t.author,` · `,qz(t.date)]})]},t.sha)})]})]})}function Xz(e){if(e.installed===void 0)return`not installed`;if(e.restartNeeded)return`${e.installed} installed — restart to use it`;if(e.pinned!==void 0)return`${e.installed}, pinned`;let t=e.check;if(!t)return e.installed;switch(t.state){case`checking`:return`${e.installed}, checking…`;case`newer`:return`${e.installed} — ${t.latest} available`;case`current`:return`${e.installed}, up to date`;case`failed`:return`${e.installed}, not checked: ${t.reason}`;case`off`:return`${e.installed}, not checked: ${t.reason}`}}function Zz({packages:e,update:t,locked:n,onCheck:r,onUpdate:i}){let[a,o]=(0,d.useState)(null);if(e===null||e.length===0)return null;let s=t?.status===`pending`?t.source:null;return(0,A.jsxs)(`div`,{className:`mt-3`,"data-testid":`pi-packages`,children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium text-zinc-600 dark:text-zinc-400`,children:`Packages`}),(0,A.jsx)(`button`,{type:`button`,onClick:r,className:`text-xs text-zinc-500 underline hover:text-zinc-800 dark:hover:text-zinc-200`,children:`check for updates`})]}),(0,A.jsx)(`ul`,{className:`space-y-1`,children:e.map(e=>{let r=e.check?.state===`newer`&&!e.restartNeeded?e.check.latest:void 0;return(0,A.jsxs)(`li`,{"data-testid":`pi-package`,className:`rounded bg-zinc-50 px-2 py-1 text-xs dark:bg-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`min-w-0 truncate font-mono text-zinc-700 dark:text-zinc-300`,title:e.source,children:e.name}),r&&!n&&a!==e.source&&(0,A.jsx)(`button`,{type:`button`,disabled:s!==null,onClick:()=>o(e.source),className:`shrink-0 rounded border border-zinc-300 px-1.5 py-0.5 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50 dark:border-zinc-600 dark:text-zinc-200 dark:hover:bg-zinc-700`,children:s===e.source?`updating…`:`Update`})]}),(0,A.jsx)(`div`,{className:`line-clamp-2 text-zinc-500 dark:text-zinc-400`,"data-testid":`pi-package-status`,title:Xz(e),children:Xz(e)}),r&&a===e.source&&(0,A.jsxs)(`div`,{className:`mt-1 rounded border border-amber-300 bg-amber-50 p-2 text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200`,"data-testid":`pi-package-confirm`,children:[(0,A.jsxs)(`p`,{children:[`This replaces code that runs with the agent's privileges: `,e.name,` `,e.installed,` → `,r,`. It takes effect when pi-outpost restarts.`]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{o(null),i(e.source)},className:`rounded bg-amber-600 px-2 py-0.5 text-white hover:bg-amber-700`,children:[`Install `,r]}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(null),className:`rounded px-2 py-0.5 hover:bg-amber-100 dark:hover:bg-amber-900/40`,children:`Cancel`})]})]}),t&&t.status!==`pending`&&t.source===e.source&&(0,A.jsx)(`p`,{"data-testid":`pi-package-result`,className:`mt-1 ${t.status===`installed`?`text-emerald-700 dark:text-emerald-400`:`text-amber-700 dark:text-amber-400`}`,children:t.message})]},e.source)})})]})}function Qz({reasons:e,canRestart:t,restarting:n,onRestart:r}){let[i,a]=(0,d.useState)(!1);return e.length===0?null:(0,A.jsxs)(`div`,{className:`mt-3 rounded border border-sky-200 bg-sky-50 p-2 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,"data-testid":`restart-needed`,children:[(0,A.jsxs)(`p`,{children:[`Installed and waiting on a restart to run: `,e.join(`, `),`.`]}),t?n?(0,A.jsx)(`p`,{className:`mt-1`,children:`Restarting pi-outpost…`}):i?(0,A.jsxs)(`div`,{className:`mt-1`,children:[(0,A.jsx)(`p`,{children:`pi-outpost stops and starts again in the same terminal. Every open window reconnects by itself, and conversations are kept.`}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{a(!1),r()},className:`rounded bg-sky-700 px-2 py-0.5 text-white hover:bg-sky-800`,children:`Restart now`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(!1),className:`rounded px-2 py-0.5 hover:bg-sky-100 dark:hover:bg-sky-900/50`,children:`Cancel`})]})]}):(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(!0),className:`mt-1 rounded border border-sky-300 px-2 py-0.5 hover:bg-sky-100 dark:border-sky-700 dark:hover:bg-sky-900/50`,children:`Restart pi-outpost`}):null]})}var $z=30,eB={display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`};function tB({skills:e,groups:t,enabled:n,onChange:r,disabled:i=!1,bound:a}){let[o,s]=(0,d.useState)(()=>e.length>40?new Set(e.filter(e=>n.has(e.relativePath)).map(e=>e.group)):new Set(t.map(e=>e.path))),[c,l]=(0,d.useState)(``),[u,f]=(0,d.useState)(!1),p=c.trim().toLocaleLowerCase(),m=p!==``||u,h=e=>(!u||n.has(e.relativePath))&&(!p||`${e.name} ${e.relativePath} ${e.description??``}`.toLocaleLowerCase().includes(p)),g=new Map;for(let t of e)g.set(t.group,[...g.get(t.group)??[],t]);let _=e.filter(e=>n.has(e.relativePath)).length,v=m?e.filter(h).length:e.length,y=(e,t)=>{let i=new Set(n);for(let n of e)t?i.add(n.relativePath):i.delete(n.relativePath);r(i)},b=e=>{let t=new Set(n);t.has(e)?t.delete(e):t.add(e),r(t)},x=e=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,A.jsxs)(`section`,{className:`rounded-xl border border-zinc-200 p-4 dark:border-zinc-800`,"aria-label":`Collection skills`,children:[(0,A.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,A.jsxs)(`h3`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:[`Skills `,(0,A.jsxs)(`span`,{className:`font-normal text-zinc-500`,children:[`· `,_,` of `,e.length,` on`]})]}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:i||_===e.length,onClick:()=>y(e,!0),className:`rounded-md border px-2.5 py-1 text-xs disabled:opacity-50`,children:`All on`}),(0,A.jsx)(`button`,{type:`button`,disabled:i||_===0,onClick:()=>y(e,!1),className:`rounded-md border px-2.5 py-1 text-xs disabled:opacity-50`,children:`All off`})]})]}),a?(0,A.jsx)(`p`,{className:`mt-2 rounded border border-amber-200 bg-amber-50 p-2 text-xs text-amber-800`,children:a.kind===`count`?`This repository holds more skills than the ${a.limit} listed here.`:`Folders deeper than ${a.limit} levels were not searched for skills.`}):null,e.length>0?(0,A.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`search`,"aria-label":`Search skills`,placeholder:`Search skills by name or folder`,value:c,onChange:e=>l(e.target.value),className:`min-w-0 flex-1 rounded-md border bg-transparent px-2.5 py-1 text-xs`}),(0,A.jsxs)(`button`,{type:`button`,"aria-pressed":u,onClick:()=>f(e=>!e),className:`rounded-md px-2.5 py-1 text-xs ${u?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:[`Only on (`,_,`)`]})]}):null,!m&&_>0&&_<=$z?(0,A.jsxs)(`div`,{role:`region`,"aria-label":`Skills that are on`,className:`mt-3 rounded-lg border border-emerald-200 bg-emerald-50/60 p-2 dark:border-emerald-900 dark:bg-emerald-950/30`,children:[(0,A.jsx)(`p`,{className:`px-1 text-[11px] font-medium text-emerald-800 dark:text-emerald-300`,children:`Turned on`}),(0,A.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.filter(e=>n.has(e.relativePath)).map(e=>(0,A.jsxs)(`li`,{className:`flex items-start justify-between gap-2 px-1`,children:[(0,A.jsxs)(`span`,{className:`min-w-0 text-xs`,children:[(0,A.jsx)(`span`,{className:`font-medium text-zinc-800 dark:text-zinc-100`,children:e.name}),` `,(0,A.jsx)(`span`,{className:`font-mono text-[11px] text-zinc-500`,children:e.group||`(repository root)`}),(0,A.jsx)(nB,{skill:e,checked:!0})]}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Turn off ${e.name} (${e.relativePath})`,disabled:i,onClick:()=>b(e.relativePath),className:`shrink-0 rounded border bg-white px-2 py-0.5 text-[11px] disabled:opacity-50 dark:bg-zinc-900`,children:`Turn off`})]},e.relativePath))})]}):null,e.length===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:`This repository holds no skills.`}):null,m&&v===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:u&&!p?`No skill is on.`:`No skill matches.`}):null,(0,A.jsx)(`ul`,{className:`mt-3 space-y-2`,children:t.map(e=>{let t=g.get(e.path)??[],r=m?t.filter(h):t;if(m&&r.length===0)return null;let a=r.filter(e=>n.has(e.relativePath)).length,s=m||o.has(e.path);return(0,A.jsxs)(`li`,{className:`rounded-lg border border-zinc-100 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-2`,children:[(0,A.jsxs)(`button`,{type:`button`,"aria-expanded":s,onClick:()=>x(e.path),className:`flex min-w-0 flex-1 items-center gap-2 text-left`,children:[(0,A.jsx)(`span`,{"aria-hidden":`true`,className:`text-xs text-zinc-400`,children:s?`▾`:`▸`}),(0,A.jsx)(`span`,{className:`truncate font-mono text-xs font-medium text-zinc-700 dark:text-zinc-200`,children:e.label}),(0,A.jsxs)(`span`,{className:`shrink-0 text-[11px] text-zinc-500`,children:[a,`/`,r.length,` on`]})]}),(0,A.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`All on in ${e.label}`,disabled:i||a===r.length,onClick:()=>y(r,!0),className:`rounded border px-2 py-0.5 text-[11px] disabled:opacity-50`,children:`All on`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`All off in ${e.label}`,disabled:i||a===0,onClick:()=>y(r,!1),className:`rounded border px-2 py-0.5 text-[11px] disabled:opacity-50`,children:`All off`})]})]}),s?(0,A.jsx)(`ul`,{className:`space-y-1 border-t border-zinc-100 px-3 py-2 dark:border-zinc-800`,children:r.map(e=>{let t=n.has(e.relativePath);return(0,A.jsx)(`li`,{children:(0,A.jsxs)(`label`,{className:`flex items-start gap-2 rounded px-1 py-1 ${i?`opacity-60`:`cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-800/60`}`,children:[(0,A.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-checked":t,"aria-label":`${e.name} (${e.relativePath})`,checked:t,disabled:i,onChange:()=>b(e.relativePath),className:`mt-0.5`}),(0,A.jsxs)(`span`,{className:`min-w-0`,children:[(0,A.jsx)(`span`,{className:`block truncate text-sm text-zinc-800 dark:text-zinc-100`,children:e.name}),e.description?(0,A.jsx)(`span`,{title:e.description,style:eB,className:`text-[11px] text-zinc-500`,children:e.description}):null,(0,A.jsx)(nB,{skill:e,checked:t})]})]})},e.relativePath)})}):null]},e.path)})})]})}function nB({skill:e,checked:t}){return t===(e.state!==`off`)?e.state===`on-loaded`?(0,A.jsx)(`span`,{className:`block text-[11px] text-emerald-700 dark:text-emerald-400`,children:`Loaded`}):e.state===`on-not-loaded`?(0,A.jsxs)(`span`,{className:`block text-[11px] text-amber-700 dark:text-amber-400`,children:[`Not loaded — `,e.reason]}):e.state===`on-missing`?(0,A.jsxs)(`span`,{className:`block text-[11px] text-rose-700 dark:text-rose-400`,children:[`Missing — `,e.reason]}):null:(0,A.jsx)(`span`,{className:`block text-[11px] font-medium text-sky-700 dark:text-sky-300`,children:t?`Pending: on`:`Pending: off`})}function rB(e,t){return[...new Set(e.map(e=>e.group))].sort().map(e=>({path:e,label:e||t}))}function iB(e){return e.skills.filter(e=>e.state!==`off`).map(e=>e.relativePath)}function aB(e,t){let n=new Set(e),r=new Set(t);return n.size===r.size&&[...n].every(e=>r.has(e))}function oB(e,t){if(t.status===`loading`)return`Removing ${e}…`;if(t.status===`error`)return t.message??`Could not remove ${e}`;let n=t.result;return n?n.status===`removed`?`Removed ${e} and deleted ${n.path}.`:n.status===`removed-files-kept`?`Removed ${e}. ${n.reason??`Its files were kept`} (${n.path}).`:`Removed ${e}, but not every file could be deleted${n.reason?` — ${n.reason}`:``}. What remains is at ${n.path}.`:`Removed ${e}.`}var sB={unchecked:`Not checked`,checking:`Checking…`,current:`Up to date`,updateable:`Update available`,dirty:`Local changes`,detached:`Detached HEAD`,ahead:`Local branch ahead`,diverged:`Histories diverged`,"no-upstream":`No upstream`,locked:`Locked`,busy:`Workspace busy`,unavailable:`Unavailable`,failed:`Check failed`};function cB(e){if(!e)return[];let t=new Map(e.resources.map(e=>[e.id,e])),n=new Set(e.repositories.flatMap(e=>e.resourceIds)),r=e.repositories.map(e=>({id:e.id,name:e.name,path:e.path,repository:e,resources:e.resourceIds.flatMap(e=>t.get(e)?[t.get(e)]:[])})),i=e.resources.filter(e=>!n.has(e.id)),a=i.filter(e=>e.unavailableReason),o=i.filter(e=>!e.unavailableReason);return o.length&&r.push({id:`local`,name:`Local and built in`,reason:`Not backed by an updateable Git repository`,resources:o}),a.length&&r.push({id:`unavailable`,name:`Provenance unavailable`,reason:`The active runtime did not report enough filesystem provenance`,resources:a}),r}function lB(e){let t=e.length;for(;t>0&&(e[t-1]===`/`||e[t-1]===`\\`);)--t;return t===e.length?e:e.slice(0,t)}function uB(e){let t=lB(e),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return n<=0?`/`:t.slice(0,n)}function dB(e,t){let n=lB(t),r=Math.max(n.lastIndexOf(`/`),n.lastIndexOf(`\\`)),i=r>=0?n.slice(r+1):n;return`${lB(e)}/${i||`agent-resources`}`}function fB({kind:e,resources:t,removalLocked:n=!1,onRemove:r}){return(0,A.jsxs)(`section`,{className:`rounded-xl border border-zinc-200 p-4 dark:border-zinc-800`,children:[(0,A.jsxs)(`h3`,{className:`flex items-center justify-between text-sm font-semibold capitalize text-zinc-800 dark:text-zinc-200`,children:[(0,A.jsxs)(`span`,{children:[e,`s`]}),(0,A.jsx)(`span`,{className:`text-xs font-normal text-zinc-400`,children:t.length})]}),t.length===0?(0,A.jsx)(`p`,{className:`mt-4 text-xs text-zinc-400`,children:`None in this group`}):(0,A.jsx)(`ul`,{className:`mt-3 space-y-2`,children:t.map(e=>(0,A.jsxs)(`li`,{className:`rounded-lg bg-zinc-50 px-3 py-2 dark:bg-zinc-800/70`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`p`,{className:`truncate text-sm font-medium text-zinc-700 dark:text-zinc-200`,children:e.name}),e.userRoot&&!n?(0,A.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.userRoot}`,onClick:()=>r(e),className:`text-xs text-zinc-500 hover:text-red-600`,children:`Remove`}):null]}),(0,A.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-[11px] text-zinc-400`,title:e.path,children:e.path??e.unavailableReason??`Path unavailable`})]},e.id))})]})}function pB({preview:e,busy:t,error:n,onApply:r,onCancel:i}){let[a,o]=(0,d.useState)(()=>new Set(e.roots.filter(e=>!e.locked).map(e=>`${e.kind}:${e.path}`))),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(()=>new Set),f=e.mode===`collection`,p=(0,d.useMemo)(()=>e.skills.map(e=>({...e,state:`off`})),[e.skills]),m=(0,d.useMemo)(()=>rB(e.skills,e.repositoryName),[e.skills,e.repositoryName]),h=e.roots.filter(e=>e.kind===`extension`&&a.has(`extension:${e.path}`)),g=h.length>0&&!s,_=t||!f&&a.size===0||g,v=()=>{let t=h.map(e=>e.path);f?r([],t,[...l]):r(e.roots.filter(e=>e.kind===`skill`&&a.has(`skill:${e.path}`)).map(e=>e.path),t)},y=e=>{c(!1),o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return(0,A.jsxs)(`div`,{className:`space-y-3`,"data-testid":`resource-preview`,children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsx)(`h3`,{className:`truncate text-xl font-semibold text-zinc-900 dark:text-zinc-100`,children:e.repositoryName}),(0,A.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-[11px] text-zinc-500`,title:e.repositoryPath,children:e.repositoryPath})]}),(0,A.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:i,className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:_,onClick:v,className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900`,children:t?`Saving…`:`Save`})]})]}),g?(0,A.jsx)(`p`,{className:`text-xs text-amber-700`,children:`Confirm the extension warning below to save.`}):null,n?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:n}):null,f?(0,A.jsx)(tB,{skills:p,groups:m,enabled:l,onChange:u,disabled:t,...e.bound?{bound:e.bound}:{}}):null,e.roots.map(e=>{let t=`${e.kind}:${e.path}`;return(0,A.jsxs)(`label`,{className:`flex items-start gap-2 rounded border p-2 ${e.locked?`opacity-50`:`cursor-pointer`}`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:a.has(t),disabled:e.locked,onChange:()=>y(t)}),(0,A.jsxs)(`span`,{children:[(0,A.jsxs)(`span`,{className:`block text-sm`,children:[e.name,` · `,e.kind]}),(0,A.jsx)(`span`,{className:`font-mono text-[11px] text-zinc-500`,children:e.path}),e.locked?(0,A.jsx)(`span`,{className:`block text-xs text-amber-700`,children:`Extension paths are locked`}):null]})]},t)}),h.length>0?(0,A.jsxs)(`label`,{className:`flex gap-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked)}),(0,A.jsx)(`span`,{children:`Extensions execute code with the agent's privileges. I trust the selected extension roots in this repository.`})]}):null]})}function mB(e){let t=(0,d.useRef)(null),n=(0,d.useRef)(e.onClose),r=(0,d.useRef)(!1),[i,a]=(0,d.useState)(null),[o,s]=(0,d.useState)(``),[c,l]=(0,d.useState)(`all`),[u,f]=(0,d.useState)(!1),[p,m]=(0,d.useState)(null),[h,g]=(0,d.useState)(null),[_,v]=(0,d.useState)(`skill`),[y,b]=(0,d.useState)(``),[x,S]=(0,d.useState)(!1),[C,w]=(0,d.useState)(``),[T,ee]=(0,d.useState)(``),[E,te]=(0,d.useState)(!1),[D,ne]=(0,d.useState)(``),[re,ie]=(0,d.useState)(null),[O,k]=(0,d.useState)({}),[ae,oe]=(0,d.useState)(null),[se,ce]=(0,d.useState)(null),le=(0,d.useMemo)(()=>cB(e.inventory),[e.inventory]),ue=(0,d.useMemo)(()=>{let e=o.trim().toLocaleLowerCase();return le.flatMap(t=>{let n=`repository`in t?t.repository.collection:void 0,r=n?t.resources.filter(e=>e.kind!==`skill`):t.resources,i=c===`all`?r:r.filter(e=>e.kind===c),a=n&&c!==`extension`?n.skills:[],o=i.length+a.length;if(o===0&&!(n&&c===`all`)||u&&(!(`repository`in t)||![`updateable`,`dirty`,`failed`,`unavailable`,`busy`].includes(t.repository.assessment.status)))return[];let s=`${t.name} ${`path`in t?t.path??``:``} ${i.map(e=>`${e.name} ${e.path??``}`).join(` `)} ${a.map(e=>`${e.name} ${e.relativePath}`).join(` `)}`.toLocaleLowerCase(),l=n?n.skills.filter(e=>e.state!==`off`).length:void 0;return!e||s.includes(e)?[{...t,resources:i,count:o,...l===void 0?{}:{onCount:l}}]:[]})},[le,u,c,o]),de=ue.find(e=>e.id===i)??ue[0]??null;if((0,d.useEffect)(()=>{n.current=e.onClose},[e.onClose]),(0,d.useEffect)(()=>{k(t=>{let n={},r=!1;for(let[i,a]of Object.entries(t)){let t=e.inventory?.repositories.find(e=>e.id===i)?.collection;!t||aB(a,iB(t))?r=!0:n[i]=a}return r?n:t})},[e.inventory]),(0,d.useEffect)(()=>{e.open&&t.current?.focus()},[e.open]),(0,d.useEffect)(()=>{if(!e.open)return;let t=e=>{e.key===`Escape`&&n.current()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e.open]),(0,d.useEffect)(()=>{let t=e.operations.clonePath;t?.status===`ready`&&t.path&&!E&&ee(t.path)},[E,e.operations.clonePath]),(0,d.useEffect)(()=>{e.operations.enrollment?.status===`ready`&&m(null)},[e.operations.enrollment]),(0,d.useEffect)(()=>{e.applyState?.status===`applying`?r.current=!0:r.current&&e.applyState===null&&(r.current=!1,m(null),g(null),S(!1))},[e.applyState]),!e.open)return null;let j=de&&`repository`in de?de.repository:null,fe=j?e.operations.updates[j.id]:void 0,pe=j?.assessment,me=pe?.status===`updateable`&&pe.token&&pe.localRevision&&pe.upstreamRevision,he=()=>{let t=y.trim();t&&(_===`skill`?e.onUpdateConfig({userSkillPaths:[...new Set([...e.userSkillPaths,t])]}):e.onUpdateConfig({userExtensionPaths:[...new Set([...e.userExtensionPaths,t])]}))},ge=t=>{t.userRoot&&(t.kind===`skill`?e.onUpdateConfig({userSkillPaths:e.userSkillPaths.filter(e=>e!==t.userRoot)}):e.onUpdateConfig({userExtensionPaths:e.userExtensionPaths.filter(e=>e!==t.userRoot)}))},_e=(t,n=!1)=>{let r=t.assessment;r.token&&r.localRevision&&r.upstreamRevision&&e.onUpdate(t.id,r.token,r.localRevision,r.upstreamRevision,n)},ve=j?.collection,ye=ve?iB(ve):[],be=new Set(j&&O[j.id]?O[j.id]:ye),xe=ve?[...new Set([...be,...ye])].filter(e=>be.has(e)!==ye.includes(e)).length:0,Se=j?e.operations.skills?.[j.id]:void 0,Ce=e=>{if(!j)return;let t=j.id;k(n=>{let r={...n};return aB(e,ye)?delete r[t]:r[t]=[...e],r})},we=()=>{if(!j)return;let e=j.id;k(t=>{let n={...t};return delete n[e],n})},Te=()=>{if(!j||!ve)return;let t=new Set(ve.skills.filter(e=>e.state!==`on-missing`).map(e=>e.relativePath));e.onSetSkills(j.id,[...be].filter(e=>t.has(e)))},Ee=se?e.operations.removals?.[se.id]:void 0,De=Ee?.status===`error`||Ee?.result?.status===`removed-delete-failed`;return(0,A.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/45 p-4`,role:`presentation`,onMouseDown:t=>{t.currentTarget===t.target&&e.onClose()},children:[(0,A.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`agent-resources-title`,className:`flex h-[min(760px,92vh)] w-[min(1120px,96vw)] flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-2xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`header`,{className:`flex items-center justify-between border-b border-zinc-200 px-5 py-4 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h2`,{id:`agent-resources-title`,className:`text-lg font-semibold text-zinc-900 dark:text-zinc-100`,children:`Agent resources`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Skills and extensions, grouped by repository`})]}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.refresh?.status===`loading`,onClick:()=>e.onRefresh(),className:`rounded-md border px-3 py-1.5 text-xs disabled:opacity-50`,children:`Refresh all`}),(0,A.jsx)(`button`,{ref:t,type:`button`,"aria-label":`Close agent resources`,onClick:e.onClose,className:`rounded-md border px-2 py-1 text-sm`,children:`✕`})]})]}),(0,A.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-[300px_1fr]`,children:[(0,A.jsxs)(`aside`,{className:`flex min-h-0 flex-col border-r border-zinc-200 bg-zinc-50/80 p-3 dark:border-zinc-800 dark:bg-zinc-950/40`,children:[(0,A.jsx)(`input`,{"aria-label":`Search resources`,value:o,onChange:e=>s(e.target.value),placeholder:`Search repositories or resources`,className:`rounded-md border bg-white px-3 py-2 text-xs dark:bg-zinc-900`}),(0,A.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1`,children:[[`all`,`skill`,`extension`].map(e=>(0,A.jsx)(`button`,{type:`button`,"aria-pressed":c===e,onClick:()=>l(e),className:`rounded px-2 py-1 text-[11px] ${c===e?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:e===`all`?`All`:`${e}s`},e)),(0,A.jsx)(`button`,{type:`button`,"aria-pressed":u,onClick:()=>f(e=>!e),className:`rounded px-2 py-1 text-[11px] ${u?`bg-amber-600 text-white`:`border`}`,children:`Needs attention`})]}),(0,A.jsxs)(`div`,{className:`mt-3 min-h-0 flex-1 space-y-1 overflow-y-auto`,children:[ue.map(e=>(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(e.id),className:`w-full rounded-lg px-3 py-2.5 text-left ${de?.id===e.id?`bg-white shadow-sm ring-1 ring-zinc-200 dark:bg-zinc-800 dark:ring-zinc-700`:`hover:bg-white/70 dark:hover:bg-zinc-900`}`,children:[(0,A.jsxs)(`span`,{className:`flex items-center justify-between gap-2 text-sm font-medium`,children:[(0,A.jsx)(`span`,{className:`truncate`,children:e.name}),(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-zinc-400`,children:e.onCount===void 0?e.count??e.resources.length:`${e.onCount} on · ${e.count}`})]}),(0,A.jsx)(`span`,{className:`mt-1 block text-xs text-zinc-500`,children:`repository`in e?sB[e.repository.assessment.status]:e.reason})]},e.id)),ue.length===0?(0,A.jsx)(`p`,{className:`px-2 py-4 text-xs text-zinc-500`,children:`No matching resources`}):null]}),(0,A.jsxs)(`div`,{className:`mt-3 grid gap-2 border-t pt-3`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{S(!1),m(`local`),g(`local`),e.onBrowseServerPath(y||`/`)},className:`rounded-md border bg-white px-3 py-2 text-xs font-medium dark:bg-zinc-900`,children:`Add local folder…`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>m(`git`),className:`rounded-md bg-zinc-900 px-3 py-2 text-xs font-medium text-white dark:bg-zinc-100 dark:text-zinc-900`,children:`Add Git repository…`})]})]}),(0,A.jsxs)(`main`,{className:`min-w-0 overflow-y-auto p-6`,children:[se&&Ee?(0,A.jsxs)(`div`,{role:De?`alert`:`status`,className:`mb-4 flex items-start justify-between gap-3 rounded-lg border p-3 text-sm ${De?`border-rose-200 bg-rose-50 text-rose-800`:`border-zinc-200 bg-zinc-50 text-zinc-700`}`,children:[(0,A.jsx)(`p`,{className:`min-w-0 break-words`,children:oB(se.name,Ee)}),Ee.status===`loading`?null:(0,A.jsx)(`button`,{type:`button`,onClick:()=>ce(null),className:`shrink-0 text-xs underline`,children:`Dismiss`})]}):null,p===`local`?(0,A.jsxs)(`div`,{className:`max-w-xl space-y-4`,"data-testid":`add-local-folder`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Add local folder`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Choose an existing folder on the server and how the agent should load it.`})]}),(0,A.jsx)(`div`,{className:`flex gap-2`,children:[`skill`,`extension`].map(t=>(0,A.jsx)(`button`,{type:`button`,"aria-pressed":_===t,disabled:t===`extension`&&e.extensionLock,onClick:()=>{v(t),S(!1)},className:`rounded-md px-3 py-1.5 text-xs ${_===t?`bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900`:`border`}`,children:t===`skill`?`Skill folder`:`Extension folder`},t))}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`input`,{"aria-label":`Local resource folder`,value:y,onChange:e=>{S(!1),b(e.target.value)},className:`min-w-0 flex-1 rounded-md border bg-transparent px-3 py-2 text-sm`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{g(`local`),e.onBrowseServerPath(y||`/`)},className:`rounded-md border px-3 text-xs`,children:`Browse…`})]}),h===`local`?(0,A.jsx)(Wz,{label:`Choose a local resource folder`,browse:e.serverBrowse,onBrowse:e.onBrowseServerPath,onSelect:t=>{S(!1),b(t),g(null),e.onCloseServerBrowser()},onCancel:()=>{g(null),e.onCloseServerBrowser()}}):null,_===`extension`?(0,A.jsxs)(`label`,{className:`flex gap-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-xs text-amber-900`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),(0,A.jsx)(`span`,{children:`Extensions execute code with the agent's privileges. I trust every extension in this folder.`})]}):null,e.extensionLock?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Extension paths are locked by this deployment.`}):null,e.applyState?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.applyState.message}):null,(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{S(!1),m(null),g(null),e.onCloseServerBrowser()},className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:!y.trim()||e.applyState?.status===`applying`||_===`extension`&&(!x||e.extensionLock),onClick:he,className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:e.applyState?.status===`applying`?`Applying…`:`Add folder`})]})]}):p===`git`?(0,A.jsx)(`div`,{className:`max-w-2xl space-y-4`,"data-testid":`add-git-repository`,children:e.operations.preview?.status===`ready`&&e.operations.preview.preview?(0,A.jsx)(pB,{onCancel:()=>{m(null),g(null),e.onCloseServerBrowser()},preview:e.operations.preview.preview,busy:e.operations.enrollment?.status===`loading`,error:e.operations.enrollment?.status===`error`?e.operations.enrollment.message:void 0,onApply:(t,n,r)=>r?e.onEnrollRepository(e.operations.preview.preview.token,t,n,r):e.onEnrollRepository(e.operations.preview.preview.token,t,n)}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Add Git repository`}),(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Clone it to a local folder, then choose what to turn on.`})]}),(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium`,children:`Repository address`}),(0,A.jsx)(`input`,{"aria-label":`Repository address`,value:C,onChange:e=>w(e.target.value),onBlur:()=>{let t=C.trim();t&&(te(!1),ne(t),e.onSuggestClonePath(C))},placeholder:`https://github.com/team/resources.git`,className:`mt-1 w-full rounded-md border bg-transparent px-3 py-2 text-sm`})]}),(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium`,children:`Local folder`}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{"aria-label":`Local clone folder`,value:T,onChange:e=>{te(!0),ee(e.target.value)},placeholder:`/path/to/resource-repositories/team-resources-ab12cd`,className:`min-w-0 flex-1 rounded-md border bg-transparent px-3 py-2 text-sm`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{g(`clone-parent`),e.onBrowseServerPath(uB(T))},className:`rounded-md border px-3 text-xs`,children:`Choose parent…`})]})]}),e.operations.clonePath?.status===`loading`?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500`,children:`Suggesting a managed folder…`}):null,e.operations.clonePath?.status===`error`&&C.trim()===D?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.operations.clonePath.message}):null,h===`clone-parent`?(0,A.jsx)(Wz,{label:`Choose the clone's parent folder`,browse:e.serverBrowse,onBrowse:e.onBrowseServerPath,onSelect:t=>{ee(dB(t,T)),g(null),e.onCloseServerBrowser()},onCancel:()=>{g(null),e.onCloseServerBrowser()}}):null,e.operations.preview?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:e.operations.preview.message}):null,(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{m(null),g(null),e.onCloseServerBrowser()},className:`rounded-md border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,disabled:!C.trim()||!T.trim()||e.operations.preview?.status===`loading`,onClick:()=>e.onCloneRepository(C,T),className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:e.operations.preview?.status===`loading`?`Cloning…`:`Clone and inspect`})]})]})}):de?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`h3`,{className:`text-xl font-semibold`,children:de.name}),j?(0,A.jsx)(`span`,{className:`rounded-full border px-2 py-0.5 text-[11px]`,children:sB[j.assessment.status]}):null]}),(0,A.jsx)(`p`,{className:`mt-1 truncate font-mono text-xs text-zinc-500`,children:`repository`in de?de.path:de.reason}),pe?.branch?(0,A.jsxs)(`p`,{className:`mt-1 text-xs text-zinc-400`,children:[pe.branch,pe.upstream?` → ${pe.upstream}`:``]}):null,j?.removal&&!j.removal.allowed?(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-500`,children:j.removal.reason}):null]}),j?(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[j.removal?.allowed?(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.removals?.[j.id]?.status===`loading`,onClick:()=>oe(j),className:`rounded-md border border-red-200 px-3 py-1.5 text-xs text-red-700 disabled:opacity-50 dark:border-red-900 dark:text-red-400`,children:`Remove repository`}):null,(0,A.jsx)(`button`,{type:`button`,disabled:e.operations.refresh?.status===`loading`,onClick:()=>e.onRefresh(j.id),className:`rounded-md border px-3 py-1.5 text-xs`,children:`Check`}),me||fe?.status===`loading`?(0,A.jsx)(`button`,{type:`button`,disabled:fe?.status===`loading`,onClick:()=>j.containsExtensions?ie(j):_e(j),className:`rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-white disabled:opacity-50`,children:fe?.status===`loading`?`Updating…`:`Update repository`}):null]}):null]}),pe?.reason?(0,A.jsxs)(`div`,{className:`mt-5 rounded-lg border p-3 text-sm ${pe.status===`dirty`?`border-rose-200 bg-rose-50 text-rose-800`:`border-zinc-200 bg-zinc-50 text-zinc-700`}`,children:[pe.reason,pe.status===`dirty`?(0,A.jsx)(`p`,{className:`mt-1 text-xs`,children:`Review and resolve these local changes in an external terminal, then check again. This updater never commits, stashes, discards, rebases, or merges them.`}):null]}):null,pe?.hasSubmodules?(0,A.jsx)(`p`,{className:`mt-3 rounded border border-amber-200 bg-amber-50 p-2 text-xs text-amber-800`,children:`This repository declares submodules. Their working trees will not be initialized or updated.`}):null,fe?.status===`ready`?(0,A.jsx)(`p`,{role:`status`,className:`mt-3 text-xs text-zinc-600`,children:fe.result?.status===`updated`&&fe.result.reloads.some(e=>e.status===`restart-required`)?`Repository updated. Its skills are reloaded; its extension code runs after pi-outpost restarts — restart it from Settings.`:fe.result?.status===`updated`?`Repository updated and runtimes reloaded.`:fe.result?.status===`updated-reload-failed`?`Repository updated on disk, but at least one runtime failed to reload.`:fe.result?.reason}):null,fe?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`mt-3 text-xs text-red-600`,children:fe.message}):null,ve&&j&&c!==`extension`?(0,A.jsxs)(`div`,{className:`mt-6 space-y-4`,children:[xe>0||Se?.status===`loading`?(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50 px-3 py-2 text-xs text-sky-900 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200`,children:[(0,A.jsx)(`span`,{children:Se?.status===`loading`?`Applying…`:`${xe} pending change${xe===1?``:`s`} — applying replaces the session`}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:Se?.status===`loading`,onClick:we,className:`rounded border bg-white px-2.5 py-1 disabled:opacity-50 dark:bg-zinc-900`,children:`Discard`}),(0,A.jsx)(`button`,{type:`button`,disabled:Se?.status===`loading`||xe===0,onClick:Te,className:`rounded bg-zinc-900 px-2.5 py-1 font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900`,children:`Apply`})]})]}):null,Se?.status===`error`?(0,A.jsx)(`p`,{role:`alert`,className:`text-xs text-red-600`,children:Se.message}):null,(0,A.jsx)(tB,{skills:ve.skills,groups:ve.groups,enabled:be,onChange:Ce,disabled:Se?.status===`loading`,...ve.bound?{bound:ve.bound}:{}},j.id),de.resources.some(e=>e.kind===`extension`)?(0,A.jsx)(fB,{kind:`extension`,resources:de.resources.filter(e=>e.kind===`extension`),removalLocked:e.extensionLock,onRemove:ge}):null]}):(0,A.jsxs)(`div`,{className:`mt-6 grid grid-cols-2 gap-4`,children:[(0,A.jsx)(fB,{kind:`skill`,resources:de.resources.filter(e=>e.kind===`skill`),onRemove:ge}),(0,A.jsx)(fB,{kind:`extension`,resources:de.resources.filter(e=>e.kind===`extension`),removalLocked:e.extensionLock,onRemove:ge})]})]}):(0,A.jsx)(`p`,{className:`text-sm text-zinc-500`,children:`No resources are reported by this runtime.`})]})]})]}),re?(0,A.jsx)(`div`,{className:`fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4`,children:(0,A.jsxs)(`div`,{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`extension-update-title`,className:`w-full max-w-md rounded-xl bg-white p-5 shadow-2xl dark:bg-zinc-900`,children:[(0,A.jsx)(`h3`,{id:`extension-update-title`,className:`font-semibold`,children:`Update executable extensions?`}),(0,A.jsxs)(`p`,{className:`mt-2 text-sm text-zinc-600 dark:text-zinc-300`,children:[re.name,` contains extensions that run with the agent's privileges. Confirm updating `,re.assessment.localRevision?.slice(0,8),` to `,re.assessment.upstreamRevision?.slice(0,8),`.`]}),(0,A.jsxs)(`div`,{className:`mt-4 flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>ie(null),className:`rounded border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{_e(re,!0),ie(null)},className:`rounded bg-amber-600 px-3 py-1.5 text-xs font-medium text-white`,children:`Confirm executable update`})]})]})}):null,ae?(0,A.jsx)(`div`,{className:`fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4`,children:(0,A.jsxs)(`div`,{role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`remove-repository-title`,"aria-describedby":`remove-repository-detail`,className:`w-full max-w-md rounded-xl bg-white p-5 shadow-2xl dark:bg-zinc-900`,children:[(0,A.jsxs)(`h3`,{id:`remove-repository-title`,className:`font-semibold`,children:[`Remove `,ae.name,`?`]}),(0,A.jsx)(`p`,{id:`remove-repository-detail`,className:`mt-2 break-words text-sm text-zinc-600 dark:text-zinc-300`,children:ae.removal?.deletesFiles?(0,A.jsxs)(A.Fragment,{children:[`This stops loading everything from `,ae.name,` and deletes `,(0,A.jsx)(`span`,{className:`font-mono`,children:ae.removal.path}),` from disk, with any local changes in it. This cannot be undone.`]}):(0,A.jsxs)(A.Fragment,{children:[`This stops loading everything from `,ae.name,`. pi-outpost does not manage `,(0,A.jsx)(`span`,{className:`font-mono`,children:ae.removal?.path??ae.path}),`, so its files will be kept.`]})}),(0,A.jsxs)(`div`,{className:`mt-4 flex justify-end gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>oe(null),className:`rounded border px-3 py-1.5 text-xs`,children:`Cancel`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemoveRepository(ae.id),ce({id:ae.id,name:ae.name}),oe(null)},className:`rounded bg-red-600 px-3 py-1.5 text-xs font-medium text-white`,children:ae.removal?.deletesFiles?`Delete and remove`:`Remove repository`})]})]})}):null]})}var hB=`w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 placeholder:text-zinc-400 focus:border-zinc-400 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-600`,gB=`rounded-md border border-zinc-300 px-3 py-1.5 text-xs font-medium text-zinc-700 hover:bg-zinc-50 disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`;function _B({event:e}){switch(e.type){case`auth_url`:return(0,A.jsxs)(`div`,{"data-testid":`login-auth-url`,className:`space-y-1`,children:[(0,A.jsx)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:e.instructions??`Open this page to sign in:`}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`truncate text-sm text-sky-700 underline dark:text-sky-400`,children:e.url}),(0,A.jsx)(`button`,{type:`button`,className:gB,onClick:()=>void navigator.clipboard?.writeText(e.url),children:`Copy`})]})]});case`device_code`:return(0,A.jsxs)(`div`,{"data-testid":`login-device-code`,className:`space-y-1`,children:[(0,A.jsxs)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:[`Enter this code at`,` `,(0,A.jsx)(`a`,{href:e.verificationUri,target:`_blank`,rel:`noopener noreferrer`,className:`text-sky-700 underline dark:text-sky-400`,children:e.verificationUri}),`:`]}),(0,A.jsx)(`p`,{className:`select-all font-mono text-2xl tracking-widest text-zinc-900 dark:text-zinc-50`,children:e.userCode})]});case`info`:return(0,A.jsxs)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:[e.message,e.links?.map(e=>(0,A.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`ml-2 text-sky-700 underline dark:text-sky-400`,children:e.label??e.url},e.url))]});case`progress`:return(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:e.message})}}function vB({prompt:e,onAnswer:t}){let[n,r]=(0,d.useState)(``),i=e.type===`manual_code`&&/^http:\/\/(?:localhost|127\.0\.0\.1):1455\/auth\/callback\/?$/.test(e.placeholder??``);return e.type===`select`?(0,A.jsxs)(`div`,{"data-testid":`login-prompt`,className:`space-y-2`,children:[(0,A.jsx)(`p`,{className:`text-sm text-zinc-700 dark:text-zinc-200`,children:e.message}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:e.options.map(e=>(0,A.jsx)(`button`,{type:`button`,className:gB,title:e.description,onClick:()=>t(e.id),children:e.label},e.id))})]}):(0,A.jsxs)(`div`,{"data-testid":`login-prompt`,className:`space-y-2`,children:[(0,A.jsxs)(`label`,{className:`block text-sm text-zinc-700 dark:text-zinc-200`,children:[e.type===`manual_code`?`${e.message} — or the whole address the browser was sent to`:e.message,(0,A.jsx)(`input`,{className:`${hB} mt-1`,type:e.type===`secret`?`password`:`text`,name:`provider-auth-response`,placeholder:e.placeholder,autoComplete:`off`,spellCheck:e.type!==`manual_code`,autoFocus:!0,value:n,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),n.trim()&&t(n.trim()))}})]}),i&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-600 dark:text-zinc-300`,children:`If Pi Outpost runs on another computer, your browser may say it cannot connect to localhost. Copy the full address from that browser page and paste it above to finish signing in.`}),(0,A.jsx)(`button`,{type:`button`,className:gB,disabled:!n.trim(),onClick:()=>t(n.trim()),children:`Continue`})]})}function yB({login:e,providerName:t,onAnswer:n,onCancel:r,onDismiss:i}){return(0,A.jsxs)(`div`,{"data-testid":`login-flow`,className:`space-y-3 rounded-md border border-zinc-200 p-3 dark:border-zinc-700`,children:[(0,A.jsxs)(`p`,{className:`text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:[`Signing in to `,t]}),(0,A.jsxs)(`div`,{"aria-live":`polite`,"aria-atomic":`false`,children:[e.events.map((e,t)=>(0,A.jsx)(_B,{event:e},t)),e.prompt&&(0,A.jsx)(vB,{prompt:e.prompt.prompt,onAnswer:n},e.prompt.promptId),!e.done&&!e.prompt&&e.events.length===0&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:`Starting…`}),e.done?(0,A.jsxs)(`div`,{"data-testid":`login-done`,"data-ok":e.done.ok?`true`:`false`,className:`space-y-2`,children:[(0,A.jsx)(`p`,{className:`text-sm ${e.done.ok?`text-emerald-700 dark:text-emerald-400`:`text-red-700 dark:text-red-400`}`,children:e.done.ok?`Signed in to ${t}.`:e.done.cancelled?`Sign-in cancelled.`:`Sign-in failed: ${e.done.message??`unknown error`}`}),(0,A.jsx)(`button`,{type:`button`,className:gB,onClick:i,children:`Close`})]}):(0,A.jsx)(`button`,{type:`button`,className:gB,onClick:r,children:`Cancel`})]})]})}function bB(e){return[...e].sort((e,t)=>e.localeCompare(t))}function xB(e,t){return e===`models_json_key`?`This key is managed in models.json. Remove it from that provider configuration.`:e===`environment`?`This key comes from ${t??`the server environment`}. Remove it from there.`:`This key is managed by ${t??e??`the provider runtime`}. Remove it from that source.`}function SB(e,t){return e===`models_json_key`?`models.json`:t??e}function CB({credentials:e,login:t,onStartLogin:n,onAnswerLogin:r,onCancelLogin:i,onDismissLogin:a,onLogoutProvider:o,extensionPaths:s,configuredExtensionPaths:c,userExtensionPaths:l,extensionLock:u,piPackages:f=null,piPackageUpdate:p=null,canRestartServer:m=!1,serverRestarting:h=!1,onCheckPiPackages:g,onUpdatePiPackage:_,onRestartServer:v,restartNeeded:y=[],tools:b,commands:x,sandbox:S,showRoots:C=!0,gitUnavailable:w,userSkillPaths:T,serverBrowse:ee,pickerBlocked:E=!1,onPickerOpened:te,applyState:D,agentResources:ne=null,agentResourceOperations:re={clonePath:null,preview:null,enrollment:null,refresh:null,updates:{},skills:{},removals:{}},versions:ie,onBrowseServerPath:O,onCloseServerBrowser:k,onUpdateConfig:ae,onSuggestAgentResourceClonePath:oe=()=>{},onCloneAgentResourceRepository:se=()=>{},onEnrollAgentResourceRepository:ce=()=>{},onSetAgentResourceSkills:le=()=>{},onRemoveAgentResourceRepository:ue=()=>{},onRefreshAgentResourceRepositories:de=()=>{},onUpdateAgentResourceRepository:j=()=>{}}){let[fe,pe]=(0,d.useState)(!1),me=(0,d.useRef)(new Map),[he,ge]=(0,d.useState)(!1),_e=(0,d.useRef)(null),[ve,ye]=(0,d.useState)(``),[be,xe]=(0,d.useState)(``),[Se,Ce]=(0,d.useState)(!1),[we,Te]=(0,d.useState)(!1),[Ee,De]=(0,d.useState)(null),Oe=(e,r)=>{if(t&&!t.done){i?.(),a?.();let e=me.current.get(t.provider);e&&(e.open=!1)}else n?.(e,r)};(0,d.useEffect)(()=>{E&&Ee!==null&&De(null)},[E,Ee]);let ke=ZL(()=>{(fe||Ee!==null)&&Le()}),Ae=b.filter(e=>e.active),je=b.filter(e=>!e.active),Me=x.filter(e=>e.source===`skill`),Ne=[...b].sort((e,t)=>e.name.localeCompare(t.name)||Number(t.active)-Number(e.active)),Pe=D?.status===`applying`,Fe=D?.status===`error`?D.message:null;(0,d.useEffect)(()=>{S&&(ye(S.root),xe(S.writableRoot??``),Ce(S.allowWrite),Te(S.allowBash))},[S]);let Ie=(0,d.useRef)(!1);(0,d.useEffect)(()=>{Ie.current&&D===null&&Le(),Ie.current=Pe},[D,Pe]);function Le(){pe(!1),De(null),k()}function Re(e,t){te?.(),De(e),O(t.trim()||`/`)}function ze(e){Ee===`root`?ye(e):Ee===`writableRoot`&&xe(e),De(null),k()}let Be=S!==null&&(ve!==S.root||(be.trim()||void 0)!==(S.writableRoot||void 0)||Se!==S.allowWrite||we!==S.allowBash);function Ve(){S&&Be&&ae({sandbox:{root:ve,allowWrite:Se,allowBash:we,writableRoot:be.trim()||void 0}})}let He=C&&S?.rootEditable!==!1,Ue=Ee!==null&&!E&&(0,A.jsx)(Wz,{label:Ee===`root`?`Choose the sandbox root`:`Choose the writable root`,browse:ee,onBrowse:O,onSelect:ze,onCancel:()=>{De(null),k()}});return(0,A.jsxs)(`div`,{className:`relative`,ref:ke,children:[(0,A.jsx)(`button`,{ref:_e,type:`button`,onClick:()=>pe(!fe),title:`Settings`,"aria-label":`Settings`,className:`${Iz} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`⚙`}),fe&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-[80vh] w-[380px] flex-col rounded-lg border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsx)(`div`,{className:`border-b border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:(0,A.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:`Settings`})}),(0,A.jsxs)(`div`,{className:`min-h-0 overflow-y-auto p-4`,children:[w&&(0,A.jsxs)(`section`,{className:`mb-4`,"data-testid":`git-unavailable`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Version control`}),w.reason===`no-repository`?(0,A.jsx)(`p`,{className:`text-xs text-zinc-500 dark:text-zinc-400`,children:`This project is not in a git repository.`}):(0,A.jsxs)(`div`,{className:`rounded border border-amber-300 bg-amber-50 px-2 py-1.5 dark:border-amber-900 dark:bg-amber-950/40`,children:[(0,A.jsx)(`p`,{className:`text-xs text-amber-800 dark:text-amber-300`,children:w.reason===`no-executable`?`Git is unavailable: its executable could not be run.`:`Git is unavailable: it refused this repository.`}),(0,A.jsx)(`p`,{className:`mt-1 break-all font-mono text-[11px] text-amber-700 dark:text-amber-400`,children:w.message}),w.reason===`no-executable`&&(0,A.jsxs)(`p`,{className:`mt-1 text-xs text-amber-700 dark:text-amber-400`,children:[`Install git, add it to PATH, or name it with `,(0,A.jsx)(`span`,{className:`font-mono`,children:`gitPath`}),` in the configuration.`]})]})]}),e&&(0,A.jsxs)(`details`,{className:`mb-4`,"data-testid":`accounts-panel`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:[`Accounts · `,(0,A.jsxs)(`span`,{className:`text-emerald-700 dark:text-emerald-400`,children:[e.providers.filter(e=>e.configured).length,` providers configured`]})]}),(0,A.jsxs)(`div`,{className:`mt-2`,children:[(0,A.jsx)(`ul`,{className:`space-y-2`,children:e.providers.map(n=>(0,A.jsx)(`li`,{className:`rounded border border-zinc-200 p-2 dark:border-zinc-700`,children:(0,A.jsxs)(`details`,{ref:e=>{e?me.current.set(n.id,e):me.current.delete(n.id)},"data-testid":`account-${n.id}`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer`,children:[(0,A.jsx)(`span`,{className:`text-xs font-medium text-zinc-800 dark:text-zinc-200`,children:n.name}),(0,A.jsx)(`span`,{className:`ml-2 text-[11px] ${n.configured?`text-emerald-700 dark:text-emerald-400`:`text-zinc-500 dark:text-zinc-400`}`,children:n.configured?`${n.auth??`Authenticated`}${n.source?` · ${SB(n.source,n.label)}`:``}`:`Not signed in`})]}),(0,A.jsxs)(`div`,{className:`mt-2`,children:[n.configured&&n.auth===`api_key`&&n.source!==`stored`&&(0,A.jsx)(`p`,{className:`mb-2 text-[11px] text-zinc-500 dark:text-zinc-400`,children:xB(n.source,n.label)}),!e.locked&&(0,A.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[n.methods?.includes(`oauth`)&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>Oe(n.id,`oauth`),children:`Sign in`}),n.methods?.includes(`api_key`)&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>Oe(n.id,`api_key`),children:`API key`}),n.configured&&n.source===`stored`&&(0,A.jsx)(`button`,{type:`button`,className:`rounded border px-2 py-1 text-[11px]`,onClick:()=>o?.(n.id),children:n.auth===`api_key`?`Remove API key`:`Sign out`})]}),t?.provider===n.id&&(0,A.jsx)(`div`,{className:`mt-2`,children:(0,A.jsx)(yB,{login:t,providerName:n.name,onAnswer:e=>r?.(e),onCancel:()=>i?.(),onDismiss:()=>a?.()})})]})]})},n.id))}),e.locked&&(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-500 dark:text-zinc-400`,children:`Credentials are locked by this server.`})]})]}),(0,A.jsxs)(`section`,{className:`mb-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Agent resources`}),b.length===0?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`Tool inventory unavailable for this runtime`}):(0,A.jsxs)(`details`,{"data-testid":`tools-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[Ae.length,` tools active`,je.length?` · ${je.length} inactive`:``]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:Ne.map(e=>(0,A.jsxs)(`li`,{className:`flex justify-between rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:[(0,A.jsx)(`span`,{children:e.name}),(0,A.jsx)(`span`,{children:e.active?`active`:`inactive`})]},e.name))})]}),Me.length===0?(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-400 dark:text-zinc-500`,children:`No skills loaded`}):(0,A.jsxs)(`details`,{className:`mt-2`,"data-testid":`skills-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[Me.length,` skills loaded`]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:bB(Me.map(e=>e.name)).map(e=>(0,A.jsx)(`li`,{className:`rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,children:e},e))})]}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Manage agent resources`,onClick:()=>{pe(!1),ge(!0)},className:`mt-3 w-full rounded-md border border-zinc-300 px-3 py-2 text-xs font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`,children:`Manage resources…`})]}),(0,A.jsxs)(`section`,{className:`mb-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Extensions`}),s===null?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,"data-testid":`extensions-unknown`,children:`Not reported by this runtime`}):s.length===0?(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`No extensions loaded`}):(0,A.jsxs)(`details`,{"data-testid":`extensions-loaded`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[s.length,` `,s.length===1?`extension`:`extensions`,` loaded`]}),(0,A.jsx)(`ul`,{className:`mt-2 space-y-1`,children:bB(s).map(e=>(0,A.jsx)(`li`,{className:`truncate rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,title:e,children:e},e))})]}),c.length>0&&(0,A.jsxs)(`details`,{className:`mt-2`,"data-testid":`extensions-configured`,children:[(0,A.jsxs)(`summary`,{className:`cursor-pointer text-xs text-zinc-600 dark:text-zinc-400`,children:[c.length,` configured by this deployment`]}),(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-400 dark:text-zinc-500`,children:`Declared in the configuration file. They load either way, and nothing here can remove them.`}),(0,A.jsx)(`ul`,{className:`mt-1 space-y-1`,children:bB(c).map(e=>(0,A.jsx)(`li`,{className:`truncate rounded bg-zinc-50 px-2 py-1 font-mono text-xs text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400`,title:e,children:e},e))})]}),u?(0,A.jsx)(`p`,{className:`mt-2 text-xs text-zinc-400 dark:text-zinc-500`,"data-testid":`extensions-locked`,children:`Extension paths and repository updates that contain extensions are locked by this deployment.`}):null,(0,A.jsx)(Zz,{packages:f,update:p,locked:u,onCheck:()=>g?.(),onUpdate:e=>_?.(e)}),(0,A.jsx)(Qz,{reasons:y,canRestart:m,restarting:h,onRestart:()=>v?.()})]}),S&&(0,A.jsxs)(`section`,{children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:He?`Sandbox`:`Agent permissions`}),(0,A.jsxs)(`div`,{className:`space-y-3`,children:[!He&&(0,A.jsxs)(`p`,{"data-testid":`sandbox-project-root`,className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`This project is confined to its own folder,`,` `,(0,A.jsx)(`span`,{className:`break-all font-mono text-zinc-800 dark:text-zinc-200`,children:S.projectRoot??S.root}),`. Each open project is confined to its own. A change here applies to this project now, and to projects opened after.`]}),He&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Root `,S.locks?.root?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{type:`text`,value:ve,onChange:e=>ye(e.target.value),disabled:S.locks?.root,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none focus:border-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Browse for sandbox root`,disabled:S.locks?.root,onClick:()=>Re(`root`,ve),className:`shrink-0 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300`,children:`Browse…`})]})]}),Ee===`root`&&Ue,(0,A.jsxs)(`label`,{className:`block`,children:[(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Writable root (optional) `,S.locks?.writableRoot?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]}),(0,A.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,A.jsx)(`input`,{type:`text`,value:be,onChange:e=>xe(e.target.value),disabled:S.locks?.writableRoot,placeholder:`Same as root`,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`button`,"aria-label":`Browse for writable root`,disabled:S.locks?.writableRoot,onClick:()=>Re(`writableRoot`,be||ve),className:`shrink-0 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-600 hover:border-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300`,children:`Browse…`})]})]}),Ee===`writableRoot`&&Ue]}),(0,A.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:Se,onChange:e=>Ce(e.target.checked),disabled:S.locks?.allowWrite,className:`rounded border-zinc-300 text-zinc-700 focus:ring-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Allow write `,S.locks?.allowWrite?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]})]}),(0,A.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:we,onChange:e=>Te(e.target.checked),disabled:S.locks?.allowBash,className:`rounded border-zinc-300 text-zinc-700 focus:ring-zinc-500 disabled:cursor-not-allowed disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-600 dark:text-zinc-400`,children:[`Allow bash `,S.locks?.allowBash?(0,A.jsx)(`span`,{className:`text-zinc-400`,children:`(locked)`}):null]})]})]})]}),!S&&(0,A.jsx)(`p`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:`No sandbox configured`}),S&&(0,A.jsxs)(`div`,{className:`mt-4 space-y-2`,children:[Fe&&(0,A.jsx)(`p`,{role:`alert`,className:`rounded-md border border-red-300 bg-red-50 px-2 py-1 text-xs text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:Fe}),(0,A.jsx)(`button`,{type:`button`,disabled:Pe||!Be||S!==null&&!ve.trim(),onClick:Ve,className:`w-full rounded-md bg-zinc-800 px-3 py-1.5 text-xs font-medium text-white hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-zinc-200 dark:text-zinc-900 dark:hover:bg-zinc-300`,children:Pe?`Applying…`:`Apply & restart session`}),(0,A.jsx)(`p`,{className:`text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Saved to the server's configuration file, then the session is rebuilt — the change survives a restart.`})]}),ie&&(0,A.jsxs)(`section`,{className:`mt-4`,children:[(0,A.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500 dark:text-zinc-400`,children:`Versions`}),(0,A.jsxs)(`div`,{className:`space-y-1 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsxs)(`p`,{children:[`pi-outpost: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.piOutpost})]}),ie.piSdk&&(0,A.jsxs)(`p`,{children:[`pi SDK: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.piSdk})]}),ie.agent&&(0,A.jsxs)(`p`,{children:[`agent: `,(0,A.jsx)(`span`,{className:`font-mono text-zinc-800 dark:text-zinc-200`,children:ie.agent})]})]})]})]})]}),(0,A.jsx)(mB,{open:he,inventory:ne,operations:re,extensionLock:u,userSkillPaths:T,userExtensionPaths:l,serverBrowse:ee,applyState:D,onClose:()=>{ge(!1),k(),_e.current?.focus()},onBrowseServerPath:e=>{te?.(),O(e)},onCloseServerBrowser:k,onUpdateConfig:ae,onSuggestClonePath:oe,onCloneRepository:se,onEnrollRepository:ce,onSetSkills:le,onRemoveRepository:ue,onRefresh:de,onUpdate:j})]})}function wB(e){let t=[],n=new Set,r=0,i=0;function a(e,o,s,c){let l=e.children,u=l.slice(1).map(e=>[e,r++]);u.length>0&&i++;let d=e.onPath&&!l.some(e=>e.onPath);if(t.push({node:e,lane:o,through:[...n].filter(e=>e!==o),forkTo:u.map(([,e])=>e),lineAbove:s,lineBelow:l.length>0,branchIndex:c,isCurrent:d,emphasis:d?`current`:e.onPath?`filled`:`hollow`,highlight:e.onPath}),l.length===0)n.delete(o);else{for(let[,e]of u)n.add(e);a(l[0],o,!0,u.length>0?1:void 0),u.forEach(([e,t],n)=>a(e,t,!0,n+2))}}return e.length>1&&i++,e.forEach((t,i)=>{let o=r++;n.add(o),a(t,o,!1,e.length>1?i+1:void 0)}),{rows:t,laneCount:r,branchPoints:i}}function TB(e){return e.flatMap(e=>[e,...TB(e.children)])}function EB({children:e,tone:t}){let n={current:`border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300`,branch:`border-zinc-300 text-zinc-500 dark:border-zinc-700 dark:text-zinc-400`,label:`border-violet-300 bg-violet-50 text-violet-700 dark:border-violet-900 dark:bg-violet-950/50 dark:text-violet-300`}[t];return(0,A.jsx)(`span`,{className:`shrink-0 rounded-full border px-1.5 py-px text-[10px] leading-4 ${n}`,children:e})}var DB=`shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-500 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`;function OB({row:e,laneCount:t,isStreaming:n,onNavigate:r,onFork:i,onClose:a}){let{node:o}=e,s=o.tipId??o.entryId;return(0,A.jsxs)(`div`,{className:`group flex items-center gap-1 pr-2 hover:bg-zinc-100 dark:hover:bg-zinc-800/70 ${e.isCurrent?`bg-emerald-50/60 dark:bg-emerald-950/20`:``}`,style:{height:36},children:[(0,A.jsxs)(`button`,{type:`button`,disabled:n,onClick:()=>{r(s),a()},title:n?`unavailable while the agent is running`:o.tipId?`restore the conversation at this point (reply included)`:`go back to this point`,className:`flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left text-sm disabled:opacity-50`,children:[(0,A.jsx)(xz,{row:e,laneCount:t,colorOf:vz}),(0,A.jsx)(`span`,{className:`min-w-0 truncate ${o.onPath?`text-zinc-800 dark:text-zinc-200`:`text-zinc-600 dark:text-zinc-400`}`,children:o.text||`(empty)`}),e.forkTo.length>0&&(0,A.jsxs)(EB,{tone:`branch`,children:[e.forkTo.length+1,` branches`]}),e.branchIndex!==void 0&&(0,A.jsxs)(EB,{tone:`branch`,children:[`branch `,e.branchIndex,o.onPath&&!e.isCurrent?` · current`:``]}),e.isCurrent&&(0,A.jsx)(EB,{tone:`current`,children:`current`}),o.label&&(0,A.jsx)(EB,{tone:`label`,children:o.label})]}),(0,A.jsx)(`button`,{type:`button`,disabled:n,onClick:()=>{r(o.entryId),a()},title:`rewind to just before this message (its text comes back in the composer)`,"aria-label":`Rewind to before this message`,className:DB,children:`↺ redo`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{i(o.entryId),a()},title:`fork a new session from this point`,className:DB,children:`⑂ fork`})]})}function kB({tree:e,isStreaming:t,onListTree:n,onNavigate:r,onFork:i}){let[a,o]=(0,d.useState)(!1),[s,c]=(0,d.useState)(``),l=ZL(()=>o(!1));(0,d.useEffect)(()=>{a&&e===null&&n()},[a,e]);let u=(0,d.useMemo)(()=>e&&e.length>0?wB(e):null,[e]),f=(0,d.useMemo)(()=>{if(!e||!s.trim())return null;let t=s.trim().toLowerCase();return TB(e).filter(e=>e.text.toLowerCase().includes(t)||e.label?.toLowerCase().includes(t))},[e,s]);return(0,A.jsxs)(`div`,{className:`relative`,ref:l,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{o(!a),a||(c(``),n())},title:`conversation tree: go back to an earlier point or fork`,className:`${Iz} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`tree`}),a&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-[70vh] w-[32rem] max-w-[90vw] flex-col rounded-lg border border-zinc-200 bg-white shadow-xl [--tree-off:#e4e4e7] dark:border-zinc-700 dark:bg-zinc-900 dark:[--tree-off:#3f3f46]`,children:[e===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),e?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no messages yet`}),e&&e.length>0&&u&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,A.jsx)(`span`,{className:`text-sm font-semibold text-zinc-800 dark:text-zinc-200`,children:`Conversation tree`}),(0,A.jsxs)(`span`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:[u.rows.length,` turn`,u.rows.length===1?``:`s`,` · `,u.branchPoints,` branch point`,u.branchPoints===1?``:`s`]})]}),(0,A.jsx)(`input`,{type:`search`,value:s,onChange:e=>c(e.target.value),placeholder:`Search tree`,"aria-label":`Search conversation tree`,className:`mt-2 w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`p`,{className:`mt-1.5 text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Follow the colored lines — the current branch is highlighted. Click a turn to restore the conversation there · ↺ to send it again · ⑂ to fork a session`})]}),(0,A.jsx)(`div`,{className:`min-h-0 overflow-y-auto py-1`,children:f===null?u.rows.map(e=>(0,A.jsx)(OB,{row:e,laneCount:u.laneCount,isStreaming:t,onNavigate:r,onFork:i,onClose:()=>o(!1)},e.node.entryId)):f.length===0?(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`no matches`}):f.map(e=>(0,A.jsxs)(`div`,{className:`group flex items-center gap-1 pr-2 hover:bg-zinc-100 dark:hover:bg-zinc-800/70`,children:[(0,A.jsxs)(`button`,{type:`button`,disabled:t,onClick:()=>{r(e.tipId??e.entryId),o(!1)},title:e.tipId?`restore the conversation at this point (reply included)`:`go back to this point`,className:`flex min-w-0 flex-1 items-center gap-2 px-3 py-1.5 text-left text-sm disabled:opacity-50`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:e.onPath?`text-emerald-500`:`text-zinc-300 dark:text-zinc-600`,children:`●`}),(0,A.jsx)(`span`,{className:`min-w-0 truncate text-zinc-700 dark:text-zinc-300`,children:e.text||`(empty)`}),e.onPath&&(0,A.jsx)(EB,{tone:`current`,children:`on current branch`}),e.label&&(0,A.jsx)(EB,{tone:`label`,children:e.label})]}),(0,A.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>{r(e.entryId),o(!1)},title:`rewind to just before this message (its text comes back in the composer)`,"aria-label":`Rewind to before this message`,className:DB,children:`↺ redo`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>{i(e.entryId),o(!1)},title:`fork a new session from this point`,className:DB,children:`⑂ fork`})]},e.entryId))})]})]})]})}var AB=200;function jB({initial:e,onCommit:t,onCancel:n}){let[r,i]=(0,d.useState)(e);return(0,A.jsx)(`input`,{autoFocus:!0,value:r,onChange:e=>i(e.target.value),onBlur:n,onKeyDown:e=>{e.key===`Enter`?t(r):e.key===`Escape`&&n()},placeholder:`Session name (empty to clear)`,"aria-label":`Session name`,className:`w-full rounded-md border border-zinc-400 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 dark:border-zinc-600 dark:placeholder:text-zinc-600`})}function MB({session:e,isCurrent:t,renaming:n,onSwitch:r,onDelete:i,onStartRename:a,onRename:o,onCancelRename:s}){return n?(0,A.jsx)(`div`,{className:`px-3 py-2`,children:(0,A.jsx)(jB,{initial:e.name??``,onCommit:o,onCancel:s})}):(0,A.jsxs)(`div`,{className:`group flex items-start gap-1 hover:bg-zinc-100 dark:hover:bg-zinc-800 ${t?`bg-zinc-100 dark:bg-zinc-800/60`:``}`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:r,className:`min-w-0 flex-1 px-3 py-2 text-left text-sm`,children:[(0,A.jsx)(`div`,{className:`truncate text-zinc-700 dark:text-zinc-300`,children:e.name||e.firstMessage||`(empty)`}),e.snippet&&(0,A.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-zinc-500 dark:text-zinc-500`,children:e.snippet}),(0,A.jsxs)(`div`,{className:`mt-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:[new Date(e.modified).toLocaleString(),` · `,e.messageCount,` messages`,t?` · current`:``,!t&&e.liveIn?(0,A.jsxs)(`span`,{"data-testid":`session-live-in`,children:[` · open in `,e.liveIn]}):null]})]}),(0,A.jsx)(`button`,{type:`button`,onClick:a,title:`rename session`,"aria-label":`Rename session`,className:`mt-2 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-zinc-200 hover:text-zinc-700 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 dark:hover:text-zinc-200`,children:`✎`}),!t&&!e.liveIn&&(0,A.jsx)(`button`,{type:`button`,onClick:i,title:`delete session`,"aria-label":`Delete session`,className:`mr-2 mt-2 rounded px-1.5 py-0.5 text-xs text-zinc-400 opacity-0 hover:bg-red-100 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:text-zinc-600 dark:hover:bg-red-950/60 dark:hover:text-red-400`,children:`✕`})]})}function NB({sessions:e,sessionSearch:t,sessionId:n,onSwitchSession:r,onDeleteSession:i,onListSessions:a,onRenameSession:o,onSearchSessions:s,onClearSessionSearch:c}){let[l,u]=(0,d.useState)(!1),[f,p]=(0,d.useState)(``),[m,h]=(0,d.useState)(null),g=ZL(()=>u(!1)),_=f.trim(),v=_.length>=2;(0,d.useEffect)(()=>{if(!l)return;if(!v){c();return}let e=setTimeout(()=>s(_),AB);return()=>clearTimeout(e)},[l,_,v]);function y(){u(!1),h(null)}let b=v&&(t?.status!==`loaded`||t.query!==_),x=v?b?null:t?.results??null:e;return(0,A.jsxs)(`div`,{className:`relative`,ref:g,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>{l?y():(u(!0),p(``),h(null),c(),a())},className:`${Iz} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:`sessions`}),l&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full z-20 mt-1 flex max-h-96 w-96 flex-col rounded-lg border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`border-b border-zinc-200 px-3 py-2 dark:border-zinc-800`,children:[(0,A.jsx)(`input`,{type:`search`,value:f,onChange:e=>p(e.target.value),placeholder:`Search sessions`,"aria-label":`Search sessions`,className:`w-full rounded-md border border-zinc-300 bg-transparent px-2 py-1 text-sm outline-none placeholder:text-zinc-400 focus:border-zinc-500 dark:border-zinc-700 dark:placeholder:text-zinc-600 dark:focus:border-zinc-500`}),(0,A.jsx)(`p`,{className:`mt-1.5 text-[11px] text-zinc-400 dark:text-zinc-500`,children:`Searches names and everything said in a session · ✎ to rename`})]}),(0,A.jsxs)(`div`,{className:`min-h-0 overflow-y-auto`,children:[x===null&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:`loading…`}),x?.length===0&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-zinc-500`,children:v?`no matches`:`no saved sessions`}),x?.map(e=>(0,A.jsx)(MB,{session:e,isCurrent:e.id===n,renaming:m===e.path,onSwitch:()=>{r(e.path),y()},onDelete:()=>{window.confirm(`Delete this session?`)&&i(e.path)},onStartRename:()=>h(e.path),onRename:t=>{o(e.path,t),h(null),v&&s(f.trim())},onCancelRename:()=>h(null)},e.path))]})]})]})}function PB({filters:e,onFilterChange:t}){let[n,r]=(0,d.useState)(!1),i=ZL(()=>r(!1)),a=bL(e),o=a>0?`Filter · ${a} hidden`:`Filter`;return(0,A.jsxs)(`div`,{className:`relative`,ref:i,onKeyDown:e=>{e.key===`Escape`&&n&&(e.stopPropagation(),r(!1))},children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>r(!n),"aria-haspopup":`menu`,"aria-expanded":n,title:`Choose what the conversation shows`,className:`${Iz} ${a>0?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:o}),n&&(0,A.jsx)(`div`,{role:`menu`,className:`absolute right-0 z-30 mt-1 w-48 rounded-md border border-zinc-200 bg-white py-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:hL.map(n=>(0,A.jsxs)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":e[n],onClick:()=>t(n,!e[n]),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-zinc-600 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`w-3`,children:e[n]?`✓`:``}),(0,A.jsx)(`span`,{children:gL[n]})]},n))})]})}function FB({statuses:e,bar:t}){let n=Object.entries(e).map(([e,t])=>[e,SR(t)]).filter(([,e])=>e.trim()!==``),r=n.map(([e,t])=>`${e}\u0000${t}`).join(``),[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null),s=(0,d.useRef)(null),[c,l]=(0,d.useState)(!1),u=ZL(()=>l(!1));if((0,d.useLayoutEffect)(()=>{o.current=null,a(!1),l(!1)},[r]),(0,d.useLayoutEffect)(()=>{let e=t;if(e===null)return;let n=()=>{o.current===null?(Array.from(s.current?.querySelectorAll(`[data-status-text]`)??[]).some(e=>e.scrollWidth>e.clientWidth+1)||e.scrollWidth>e.clientWidth+1)&&(o.current=e.clientWidth,a(!0)):e.clientWidth>o.current+64&&(o.current=null,a(!1),l(!1))};if(n(),typeof ResizeObserver>`u`)return;let r=new ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[t,i,r]),n.length===0)return null;if(!i)return(0,A.jsx)(`div`,{ref:s,className:`flex shrink-0 items-center gap-1.5`,children:n.map(([e,t])=>(0,A.jsx)(`span`,{title:t,className:`${Iz} max-w-[16rem] border-zinc-200 text-zinc-500 dark:border-zinc-800 dark:text-zinc-400`,children:(0,A.jsx)(`span`,{"data-status-text":!0,className:`truncate`,children:t})},e))});let f=`${n.length} ${n.length===1?`status`:`statuses`}`;return(0,A.jsxs)(`div`,{ref:u,className:`relative shrink-0`,onKeyDown:e=>{e.key===`Escape`&&c&&(e.stopPropagation(),l(!1))},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>l(!c),"aria-expanded":c,title:n.map(([,e])=>e).join(`
362
+ `),className:`${Iz} border-zinc-200 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:[f,` ▾`]}),c&&(0,A.jsx)(`ul`,{"aria-label":`Extension statuses`,className:`absolute left-0 top-full z-20 mt-1 w-max max-w-[24rem] rounded-md border border-zinc-200 bg-white py-1 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:n.map(([e,t])=>(0,A.jsx)(`li`,{className:`break-words px-3 py-1.5 text-xs text-zinc-600 dark:text-zinc-300`,children:t},e))})]})}function IB({theme:e,onToggle:t}){return(0,A.jsx)(`button`,{type:`button`,onClick:t,title:e===`dark`?`Switch to light theme`:`Switch to dark theme`,"aria-label":e===`dark`?`Switch to light theme`:`Switch to dark theme`,className:`${Iz} border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:e===`dark`?`☀`:`☾`})}function LB(e){let{isStreaming:t,connected:n}=e,[r,i]=(0,d.useState)(null);return(0,A.jsxs)(`header`,{ref:i,className:`relative z-30 flex min-w-0 items-center gap-1.5 border-b border-zinc-200 px-4 py-2 dark:border-zinc-800`,children:[e.workspaceControl===`projects`&&(0,A.jsx)(Uz,{workspace:e.workspace,workspaces:e.workspaces,locked:e.workspaceLocked,onSwitch:e.onSwitchWorkspace,onOpen:e.onOpenProject,onClose:e.onCloseProject,onOpenSide:e.onOpenSideSession}),e.workspaceControl===`root`&&e.rootControl&&(0,A.jsx)(Kz,{sandbox:e.rootControl.sandbox,browse:e.rootControl.browse,applyState:e.rootControl.applyState,blocked:e.rootControl.blocked,onBrowse:e.rootControl.onBrowse,onCloseBrowser:e.rootControl.onCloseBrowser,onOpened:e.rootControl.onOpened,onSelect:e.rootControl.onSelect}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onToggleSidebar,title:e.sidebarOpen?`Hide files (panel opens on the left)`:`Show files`,"aria-pressed":e.sidebarOpen,className:`${Iz} ${e.sidebarOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:[e.sidebarOpen?`◧`:`◨`,` files`]}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onToggleOutcome,"aria-pressed":e.outcomeOpen,title:`Review structured workspace Outcome`,className:`${Iz} ${e.outcomeOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:e.workspace?.activity===`ready-for-review`?`border-amber-400 text-amber-700 dark:text-amber-300`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 dark:border-zinc-800 dark:text-zinc-400`}`,children:[`Outcome`,e.workspace?.activity===`ready-for-review`?` •`:``]}),e.gitAvailable&&(0,A.jsx)(Yz,{status:e.gitStatus,selected:e.gitSelectedPath,log:e.gitLog,onFetchLog:e.onFetchGitLog,onShowCommit:e.onShowCommit}),(0,A.jsx)(`span`,{title:e.title??void 0,className:`min-w-[2.25rem] shrink-[4] truncate whitespace-nowrap text-lg font-semibold leading-tight tracking-tight`,style:{color:`var(--accent, inherit)`},children:e.title??`π`}),(0,A.jsx)(FB,{statuses:e.statuses,bar:r}),(0,A.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1.5`,children:[(0,A.jsx)(PB,{filters:e.filters,onFilterChange:e.onFilterChange}),e.onExportConversation&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onExportConversation,disabled:!!e.exportProgress,"aria-busy":!!e.exportProgress,title:`Save the whole conversation as one HTML file`,"aria-label":`Export the conversation as HTML`,className:`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 disabled:cursor-progress disabled:opacity-60 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`,children:e.exportProgress??`↓ html`}),e.onToggleTerminal&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onToggleTerminal,title:e.terminalOpen?"Close Terminal (Ctrl+`)":"Open Terminal (Ctrl+`)","aria-pressed":e.terminalOpen,className:`inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs leading-none ${e.terminalOpen?`border-zinc-400 bg-zinc-100 text-zinc-700 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600 dark:hover:text-zinc-200`}`,children:`>_ terminal`}),e.showThemeToggle&&(0,A.jsx)(IB,{theme:e.theme,onToggle:e.onToggleTheme}),(0,A.jsx)(`button`,{type:`button`,onClick:e.onNewSession,title:`new session`,className:`${Iz} border-emerald-300 text-emerald-700 hover:border-emerald-500 hover:text-emerald-600 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600 dark:hover:text-emerald-300`,children:`+ new`}),(0,A.jsx)(kB,{tree:e.tree,isStreaming:t,onListTree:e.onListTree,onNavigate:e.onNavigateTree,onFork:e.onForkSession}),(0,A.jsx)(NB,{sessions:e.sessions,sessionSearch:e.sessionSearch,sessionId:e.sessionId,onSwitchSession:e.onSwitchSession,onDeleteSession:e.onDeleteSession,onListSessions:e.onListSessions,onRenameSession:e.onRenameSession,onSearchSessions:e.onSearchSessions,onClearSessionSearch:e.onClearSessionSearch}),(0,A.jsx)(CB,{credentials:e.credentials,login:e.login,onStartLogin:e.onStartLogin,onAnswerLogin:e.onAnswerLogin,onCancelLogin:e.onCancelLogin,onDismissLogin:e.onDismissLogin,onLogoutProvider:e.onLogoutProvider,extensionPaths:e.extensionPaths,configuredExtensionPaths:e.configuredExtensionPaths,userExtensionPaths:e.userExtensionPaths,extensionLock:e.extensionLock,piPackages:e.piPackages??null,piPackageUpdate:e.piPackageUpdate??null,canRestartServer:e.canRestartServer??!1,serverRestarting:e.serverRestarting??!1,...e.onCheckPiPackages?{onCheckPiPackages:e.onCheckPiPackages}:{},...e.onUpdatePiPackage?{onUpdatePiPackage:e.onUpdatePiPackage}:{},...e.onRestartServer?{onRestartServer:e.onRestartServer}:{},restartNeeded:e.restartNeeded??[],tools:e.tools??[],commands:e.commands??[],sandbox:e.sandbox,showRoots:!(e.workspaceControl===`projects`&&e.workspaces.filter(e=>!e.sideOf).length>1),gitUnavailable:e.gitUnavailable,userSkillPaths:e.userSkillPaths,serverBrowse:e.serverBrowse,applyState:e.settingsApply,agentResources:e.agentResources,agentResourceOperations:e.agentResourceOperations,versions:e.versions,onBrowseServerPath:e.onBrowseServerPath,onCloseServerBrowser:e.onCloseServerBrowser,pickerBlocked:e.settingsPickerBlocked,onPickerOpened:e.onSettingsPickerOpened,onUpdateConfig:e.onUpdateConfig,onSuggestAgentResourceClonePath:e.onSuggestAgentResourceClonePath,onCloneAgentResourceRepository:e.onCloneAgentResourceRepository,onEnrollAgentResourceRepository:e.onEnrollAgentResourceRepository,onSetAgentResourceSkills:e.onSetAgentResourceSkills,onRemoveAgentResourceRepository:e.onRemoveAgentResourceRepository,onRefreshAgentResourceRepositories:e.onRefreshAgentResourceRepositories,onUpdateAgentResourceRepository:e.onUpdateAgentResourceRepository}),(0,A.jsx)(`span`,{className:`h-2 w-2 rounded-full ${n?`bg-emerald-500`:`bg-red-500`}`,title:n?`connected`:`disconnected`})]})]})}function RB(e,t){let n=(0,d.useRef)(new Map);(0,d.useEffect)(()=>{if(typeof Notification>`u`)return;let r=e.filter(e=>e.needsAttention),i=r.filter(e=>NI(e)!==t);for(let e of[...n.current.keys()])r.some(t=>NI(t)===e)||n.current.delete(e);if(Notification.permission===`granted`&&(typeof document>`u`||document.visibilityState!==`visible`)){for(let e of i)if(n.current.get(NI(e))!==e.activity){n.current.set(NI(e),e.activity);try{let t=e.activity===`ready-for-review`;new Notification(t?`${e.name} is ready for review`:`${e.name} needs you`,{body:t?`Background work is ready for review.`:`The agent needs an answer to continue.`,tag:`pi-outpost:${NI(e)}`})}catch{}}}},[e,t])}var zB={"agent-directory":`read the agent directory (the provider keys)`,"beside-root":`read a file beside the root`,"write-beside-root":`write beside the root`,"signal-process":`signal another process of the server's user`,"server-environment":`inherit the server's environment`,"server-process-environment":`read the server's process environment (/proc)`,"unlisted-host":`reach a host not in sandbox.allowedHosts`,"direct-connection":`connect around the proxy`},BB=e=>e.map(e=>zB[e]??e),VB=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()};function HB(e,t){let n=t===`shell`?`The agent's shell`:`This terminal`;switch(e.state){case`checking`:return`${n} runs under ${e.runner||`a sandbox runner`}; its confinement is being checked.`;case`verified`:return[`${n} is confined by ${e.runner}, checked at ${VB(e.checkedAt)}. A command could not:`,...BB(e.refused).map(e=>`• ${e}`),...e.environmentReadable?[`The server's process environment is readable, and holds no secret.`]:[],...e.notChecked.length?[`Not checked:`,...e.notChecked.map(e=>`• ${zB[e.attempt]??e.attempt} — ${e.why}`)]:[]].join(`
363
+ `);case`partial`:return[`${n} is confined by ${e.runner}, checked at ${VB(e.checkedAt)}, except one thing: a command can read the server's process environment, which holds ${e.exposed.join(`, `)}.`,`Move these out of the server's environment — provider keys belong in the agent directory.`,`A command could not:`,...BB(e.refused).map(e=>`• ${e}`)].join(`
364
+ `);case`leaking`:return[`${n} is NOT confined as configured: under ${e.runner}, checked at ${VB(e.checkedAt)}, a command could:`,...BB(e.reached).map(e=>`• ${e}`),`The configuration is unchanged: fix the runner or its host, or stop using it.`].join(`
365
+ `);case`failed`:return`${n}'s confinement could not be checked (${e.runner}, ${VB(e.checkedAt)}): ${e.reason}`}}function UB({verdict:e,surface:t,root:n}){let r=n?` to ${n}`:``,i=e.state===`verified`?{icon:`🔒`,text:`confined${r}`,tone:`bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200`}:e.state===`partial`?{icon:`🔐`,text:`partly confined`,tone:`bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200`}:e.state===`leaking`?{icon:`🔓`,text:`not confined`,tone:`bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-200`}:e.state===`failed`?{icon:`⚠`,text:`confinement unchecked`,tone:`bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200`}:{icon:`…`,text:`checking confinement`,tone:`bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-300`};return(0,A.jsxs)(`span`,{"data-testid":t===`shell`?`shell-confinement`:`terminal-confined`,"data-state":e.state,title:HB(e,t),className:`shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 font-sans text-[11px] ${i.tone}`,children:[i.icon,` `,t===`shell`?`shell ${i.text}`:i.text]})}function WB(e){return!e||e.percent===null?`text-zinc-400 dark:text-zinc-600`:e.percent>=85?`text-red-500`:e.percent>=60?`text-amber-500 dark:text-amber-400`:`text-emerald-500`}function GB({usage:e,analysisOpen:t,onToggleAnalysis:n}){if(e.turns===0)return null;let r=e.turns-e.unpriced,i=[`${e.turns} turn${e.turns===1?``:`s`}`,`input ${e.input.toLocaleString()}`,`output ${e.output.toLocaleString()}`,`cache read ${e.cacheRead.toLocaleString()}`,`cache write ${e.cacheWrite.toLocaleString()}`,...e.unpriced>0&&r>0?[`${e.unpriced} unpriced`]:[]].join(` · `),a=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{children:[BI(e.totalTokens),` tok`]}),r>0&&(0,A.jsxs)(`span`,{className:`text-zinc-400 dark:text-zinc-500`,children:[zI(e.cost),e.unpriced>0&&`*`]})]}),o=`flex items-center gap-1.5 rounded-md border px-2 py-1 font-mono text-xs text-zinc-500 dark:text-zinc-400`;return n?(0,A.jsx)(`button`,{type:`button`,onClick:n,title:`${i} — click for the session analysis`,"aria-haspopup":`dialog`,"aria-expanded":t??!1,className:`${o} ${t?`border-zinc-400 dark:border-zinc-600`:`border-zinc-300 hover:border-zinc-400 dark:border-zinc-800 dark:hover:border-zinc-600`}`,children:a}):(0,A.jsx)(`span`,{title:i,className:`${o} border-zinc-300 dark:border-zinc-800`,children:a})}function KB({usage:e}){let t=15.9155,n=2*Math.PI*t,r=e?.percent??0,i=Math.min(100,Math.max(0,r))/100*n;return(0,A.jsxs)(`svg`,{width:18,height:18,viewBox:`0 0 36 36`,className:`-rotate-90 shrink-0`,children:[(0,A.jsx)(`circle`,{cx:`18`,cy:`18`,r:t,fill:`none`,stroke:`currentColor`,strokeWidth:`4`,className:`text-zinc-200 dark:text-zinc-800`}),e&&e.percent!==null&&(0,A.jsx)(`circle`,{cx:`18`,cy:`18`,r:t,fill:`none`,stroke:`currentColor`,strokeWidth:`4`,strokeLinecap:`round`,strokeDasharray:`${i} ${n-i}`,className:WB(e)})]})}function qB({thinkingLevel:e,thinkingLevels:t,isStreaming:n,onSetThinking:r}){let[i,a]=(0,d.useState)(!1),o=(0,d.useRef)(null),s=e!==`off`,c=t&&t.length>0?t:az,l=c.indexOf(e),u=c.length>1;return(0,d.useEffect)(()=>{if(!i)return;function e(e){o.current&&!XL(e,o.current)&&a(!1)}function t(e){e.key===`Escape`&&a(!1)}return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]),(0,A.jsxs)(`div`,{className:`relative`,ref:o,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(!i),disabled:n,title:`thinking level`,"aria-haspopup":`true`,"aria-expanded":i,className:`flex items-center gap-1.5 rounded-md border px-2 py-1 font-mono text-xs disabled:opacity-50 ${s?`border-amber-300 text-amber-700 hover:border-amber-400 dark:border-amber-900 dark:text-amber-400 dark:hover:border-amber-700`:`border-zinc-300 text-zinc-500 hover:border-zinc-400 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600`}`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,className:`text-sm leading-none ${s?``:`opacity-40 grayscale`}`,children:`🧠`}),e]}),i&&(0,A.jsxs)(`div`,{className:`absolute bottom-full left-0 z-20 mb-1 w-48 rounded-lg border border-zinc-200 bg-white p-3 shadow-xl dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between text-xs`,children:[(0,A.jsx)(`span`,{className:`text-zinc-500 dark:text-zinc-400`,children:`thinking`}),(0,A.jsx)(`span`,{className:`font-mono text-zinc-700 dark:text-zinc-200`,children:e})]}),u?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`input`,{type:`range`,min:0,max:c.length-1,step:1,value:l===-1?0:l,onChange:e=>r(c[Number(e.target.value)]),"aria-label":`Thinking level`,"aria-valuetext":e,className:`w-full accent-amber-500`}),(0,A.jsxs)(`div`,{className:`mt-0.5 flex justify-between font-mono text-[9px] text-zinc-400 dark:text-zinc-600`,children:[(0,A.jsx)(`span`,{children:c[0]}),(0,A.jsx)(`span`,{children:c[c.length-1]})]})]}):(0,A.jsxs)(`p`,{className:`text-[11px] text-zinc-500 dark:text-zinc-400`,children:[`this model accepts `,(0,A.jsx)(`span`,{className:`font-mono`,children:c[0]}),` only`]})]})]})}function JB(e){let{model:t,models:n,thinkingLevel:r,modelSupportsReasoning:i,isStreaming:a,contextUsage:o,sessionUsage:s,isCompacting:c}=e;return(0,A.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,A.jsxs)(`select`,{value:t,onChange:t=>{let r=n.find(e=>`${e.provider}/${e.id}`===t.target.value);r&&e.onSetModel(r.provider,r.id)},disabled:a,className:`max-w-64 rounded-md border border-zinc-300 bg-white px-2 py-1 font-mono text-xs text-zinc-700 outline-none hover:border-zinc-400 disabled:opacity-50 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:border-zinc-600`,children:[!n.some(e=>`${e.provider}/${e.id}`===t)&&(0,A.jsx)(`option`,{value:t,children:t}),n.map(e=>(0,A.jsxs)(`option`,{value:`${e.provider}/${e.id}`,children:[e.provider,`/`,e.id]},`${e.provider}/${e.id}`))]}),i&&(0,A.jsx)(qB,{thinkingLevel:r,thinkingLevels:e.thinkingLevels,isStreaming:a,onSetThinking:e.onSetThinking}),e.shellConfinement&&(0,A.jsx)(`span`,{className:`ml-auto`,children:(0,A.jsx)(UB,{verdict:e.shellConfinement,surface:`shell`})}),(0,A.jsxs)(`button`,{type:`button`,onClick:e.onCompact,disabled:a||c,title:o?.tokens==null?`Click to compact the conversation context`:`${o.tokens.toLocaleString()} / ${o.contextWindow.toLocaleString()} tokens — click to compact`,className:`${e.shellConfinement?``:`ml-auto `}flex items-center gap-1.5 rounded-md border border-zinc-300 px-2 py-1 font-mono text-xs text-zinc-500 hover:border-zinc-400 disabled:opacity-50 dark:border-zinc-800 dark:text-zinc-400 dark:hover:border-zinc-600`,children:[(0,A.jsx)(KB,{usage:o}),c?`compacting…`:o?.percent==null?`context`:`${Math.round(o.percent)}%`]}),(0,A.jsx)(GB,{usage:s,analysisOpen:e.analysisOpen,onToggleAnalysis:e.onToggleAnalysis})]})}var YB=`w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 placeholder:text-zinc-400 focus:border-zinc-400 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-600`,XB=`mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400`;function ZB({title:e,credentials:t,onSetCredential:n,onStartLogin:r,login:i,onAnswerLogin:a,onCancelLogin:o,onDismissLogin:s,onDeclareProvider:c,errors:l}){let u=t.providers,[f,p]=(0,d.useState)(u.length>0?`known`:`custom`),[m,h]=(0,d.useState)(u[0]?.id??``),[g,_]=(0,d.useState)(``),[v,y]=(0,d.useState)(``),[b,x]=(0,d.useState)(``),[S,C]=(0,d.useState)(``),[w,T]=(0,d.useState)(!0),[ee,E]=(0,d.useState)(!0);function te(e){i?.provider===e?(i.done||o(),s()):(i&&(i.done||o(),s()),r(e,`oauth`))}let D=u.some(e=>e.configured)&&!t.usableModel;function ne(e){e.preventDefault(),!D&&(f===`known`?m&&g.trim()&&n(m,g.trim()):v.trim()&&b.trim()&&g.trim()&&S.trim()&&c({provider:v.trim(),baseUrl:b.trim(),apiKey:g.trim(),models:[S.trim()],compat:{supportsDeveloperRole:w,supportsReasoningEffort:ee}}))}return(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center overflow-auto p-6`,children:(0,A.jsxs)(`form`,{onSubmit:ne,className:`w-full max-w-md rounded-xl border border-zinc-200 p-6 shadow-sm dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`mb-1 text-center text-3xl`,children:e??`π`}),D?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`h1`,{className:`mb-3 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`No model is available.`}),(0,A.jsxs)(`p`,{className:`text-sm text-zinc-600 dark:text-zinc-400`,children:[`Credentials are configured, so this is not a missing key: `,(0,A.jsx)(`code`,{children:`allowedModels`}),` in your configuration leaves nothing to choose from. Widen it, or remove it, then restart.`]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`h1`,{className:`mb-4 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`No model provider is set up yet. Add one to start chatting.`}),(0,A.jsx)(`div`,{className:`mb-4 flex gap-1 rounded-lg bg-zinc-100 p-1 text-xs dark:bg-zinc-800`,children:[`known`,`custom`].map(e=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>p(e),className:`flex-1 rounded-md px-2 py-1.5 ${f===e?`bg-white font-medium text-zinc-800 shadow-sm dark:bg-zinc-900 dark:text-zinc-100`:`text-zinc-500 dark:text-zinc-400`}`,children:e===`known`?`Provider API key`:`OpenAI-compatible endpoint`},e))}),t.signIn&&u.some(e=>e.methods?.includes(`oauth`))&&(0,A.jsxs)(`section`,{className:`mb-4 rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,"data-testid":`onboarding-account-signin`,children:[(0,A.jsx)(`h2`,{className:`mb-2 text-xs font-medium text-zinc-700 dark:text-zinc-300`,children:`Sign in with an account`}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:u.filter(e=>e.methods?.includes(`oauth`)).map(e=>{let t=i?.provider===e.id;return(0,A.jsx)(`button`,{type:`button`,"aria-expanded":t,"aria-controls":`onboarding-login-flow-${e.id}`,className:`rounded border px-3 py-2 text-xs ${t?`border-sky-500 bg-sky-50 text-sky-800 dark:bg-sky-950/40 dark:text-sky-200`:``}`,onClick:()=>te(e.id),children:e.name},e.id)})}),i&&(0,A.jsx)(`div`,{id:`onboarding-login-flow-${i.provider}`,className:`mt-3`,children:(0,A.jsx)(yB,{login:i,providerName:u.find(e=>e.id===i.provider)?.name??i.provider,onAnswer:a,onCancel:o,onDismiss:s})})]}),f===`known`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{htmlFor:`onboarding-provider`,className:XB,children:`Provider`}),(0,A.jsx)(`select`,{id:`onboarding-provider`,value:m,onChange:e=>h(e.target.value),className:`${YB} mb-3`,children:u.map(e=>(0,A.jsxs)(`option`,{value:e.id,children:[e.name,e.configured?` (already configured)`:``]},e.id))})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{htmlFor:`onboarding-name`,className:XB,children:`Name`}),(0,A.jsx)(`input`,{id:`onboarding-name`,value:v,onChange:e=>y(e.target.value),placeholder:`corp`,className:`${YB} mb-3`}),(0,A.jsx)(`label`,{htmlFor:`onboarding-url`,className:XB,children:`Base URL`}),(0,A.jsx)(`input`,{id:`onboarding-url`,value:b,onChange:e=>x(e.target.value),placeholder:`https://llm.corp.example/v1`,className:`${YB} mb-3`}),(0,A.jsx)(`label`,{htmlFor:`onboarding-model`,className:XB,children:`Model id`}),(0,A.jsx)(`input`,{id:`onboarding-model`,value:S,onChange:e=>C(e.target.value),placeholder:`gpt-oss-120b`,className:`${YB} mb-3`})]}),(0,A.jsx)(`label`,{htmlFor:`onboarding-key`,className:XB,children:`API key`}),(0,A.jsx)(`input`,{id:`onboarding-key`,type:`password`,autoComplete:`off`,value:g,onChange:e=>_(e.target.value),placeholder:`sk-…`,className:YB}),f===`custom`&&(0,A.jsxs)(`fieldset`,{className:`mt-4 rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,children:[(0,A.jsx)(`legend`,{className:`px-1 text-xs text-zinc-500 dark:text-zinc-400`,children:`Compatibility`}),(0,A.jsxs)(`label`,{className:`flex items-start gap-2 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[`Server understands the `,(0,A.jsx)(`code`,{children:`developer`}),` role. Uncheck for vLLM, SGLang and most corporate gateways — the system prompt is then sent as a `,(0,A.jsx)(`code`,{children:`system`}),` message.`]})]}),(0,A.jsxs)(`label`,{className:`mt-2 flex items-start gap-2 text-xs text-zinc-600 dark:text-zinc-400`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:ee,onChange:e=>E(e.target.checked),className:`mt-0.5`}),(0,A.jsxs)(`span`,{children:[`Server accepts `,(0,A.jsx)(`code`,{children:`reasoning_effort`}),`. Uncheck if it rejects unknown fields.`]})]})]}),(0,A.jsx)(`button`,{type:`submit`,className:`mt-4 w-full rounded-md bg-zinc-800 px-3 py-2 text-sm font-medium text-white hover:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white`,children:`Save and start`})]}),l.map((e,t)=>(0,A.jsx)(`p`,{className:`mt-3 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:e},t)),(0,A.jsxs)(`p`,{className:`mt-4 text-center text-xs text-zinc-400 dark:text-zinc-600`,children:[t.agentDir?`Stored in ${t.agentDir}. `:``,`Provider environment variables work too, as does `,(0,A.jsx)(`code`,{children:`pi-outpost login`}),`.`]})]})})}var QB=`application/x-pi-outpost-file`,$B=`application/x-pi-outpost-read-only-file`,eV=`mr-1 shrink-0 rounded px-1 text-xs text-zinc-400 hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 [@media(hover:hover)]:opacity-0`,tV={modified:{label:`M`,className:`text-amber-600 dark:text-amber-400`},added:{label:`A`,className:`text-emerald-600 dark:text-emerald-400`},untracked:{label:`U`,className:`text-emerald-600 dark:text-emerald-400`},deleted:{label:`D`,className:`text-red-600 dark:text-red-400`},conflicted:{label:`C`,className:`text-purple-600 dark:text-purple-400`}};function nV(e,t){return t?Object.keys(t).filter(t=>t.startsWith(`${e}/`)).length:0}function rV(e){return e===`directory`||e===`symlink-directory`}function iV(e,t){return t===void 0?!1:t===null||t!==``&&e!==t&&!e.startsWith(`${t}/`)}function aV({dir:e,depth:t,creation:n}){let[r,i]=(0,d.useState)(``),a=(0,d.useRef)(null),o=n.localError??n.serverError;return(0,d.useEffect)(()=>{a.current?.focus()},[]),(0,A.jsxs)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5`,children:[(0,A.jsx)(`input`,{ref:a,value:r,onChange:e=>i(e.target.value),onKeyDown:t=>{t.key===`Enter`?(t.preventDefault(),n.submit(e,r)):t.key===`Escape`&&(t.preventDefault(),n.cancel())},onBlur:()=>{o===null&&n.cancel()},placeholder:`name, or name/ for a folder`,"aria-label":`New file or folder in ${e===``?`the workspace root`:e}`,spellCheck:!1,className:`w-full rounded border border-zinc-300 bg-white px-1 py-0.5 text-xs text-zinc-800 outline-none focus:border-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),o!==null&&(0,A.jsx)(`p`,{className:`px-1 pt-0.5 text-xs text-red-600 dark:text-red-400`,children:o})]})}function oV({path:e,name:t,depth:n,rename:r}){let[i,a]=(0,d.useState)(t),o=(0,d.useRef)(null),s=r.localError??r.serverError;return(0,d.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]),(0,A.jsxs)(`div`,{style:{paddingLeft:n*12+16},className:`py-0.5`,children:[(0,A.jsx)(`input`,{ref:o,value:i,disabled:r.pending,onChange:e=>a(e.target.value),onKeyDown:t=>{t.key===`Enter`&&!r.pending?(t.preventDefault(),r.submit(e,i)):t.key===`Escape`&&(t.preventDefault(),r.cancel())},onBlur:()=>{s===null&&r.cancel()},"aria-label":`Rename ${t}`,spellCheck:!1,className:`w-full rounded border border-zinc-300 bg-white px-1 py-0.5 text-xs text-zinc-800 outline-none focus:border-zinc-400 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200`}),s!==null&&(0,A.jsx)(`p`,{className:`px-1 pt-0.5 text-xs text-red-600 dark:text-red-400`,children:s})]})}function sV({path:e,depth:t,...n}){let r=n.tree[e],i=n.creation?.openIn===e?(0,A.jsx)(aV,{dir:e,depth:t,creation:n.creation}):null;return r===void 0?i:r===`loading`?(0,A.jsxs)(A.Fragment,{children:[i,(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:`loading…`})]}):`error`in r?(0,A.jsxs)(A.Fragment,{children:[i,(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-red-600 dark:text-red-400`,children:r.error})]}):r.length===0?(0,A.jsxs)(A.Fragment,{children:[i,i===null&&(0,A.jsx)(`div`,{style:{paddingLeft:t*12+4},className:`py-0.5 text-xs text-zinc-400 dark:text-zinc-600`,children:`empty`})]}):(0,A.jsxs)(A.Fragment,{children:[i,r.map(r=>(0,A.jsx)(cV,{parentPath:e,entry:r,depth:t,...n},r.name))]})}function cV({parentPath:e,entry:t,depth:n,...r}){let[i,a]=(0,d.useState)(!1),[o,s]=(0,d.useState)(!1),c=e?`${e}/${t.name}`:t.name,l=iV(c,r.writableRoot),u=r.fileOperation?.status===`pending`;if(rV(t.type)){let e=!l&&!u,d=e=>e.includes($B)?r.onCopyFile===void 0?null:`copy`:r.onMoveFile===void 0?null:`move`;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`group flex w-full items-center rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 ${o?`bg-blue-50 ring-1 ring-blue-400 dark:bg-blue-950/40`:``}`,onDragOver:t=>{if(!e||!Array.from(t.dataTransfer.types).includes(QB))return;let n=d(Array.from(t.dataTransfer.types));n!==null&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=n,s(!0))},onDragLeave:()=>s(!1),onDrop:t=>{if(!e)return;let n=t.dataTransfer.getData(QB),i=n?d(Array.from(t.dataTransfer.types)):null;i!==null&&(t.preventDefault(),t.stopPropagation(),s(!1),i===`copy`?r.onCopyFile?.(n,c):r.onMoveFile?.(n,c))},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{let e=!i;a(e),e&&r.tree[c]===void 0&&r.onExpand(c),r.onSelectDirectory?.(c)},style:{paddingLeft:n*12},className:`flex min-w-0 flex-1 items-center gap-1 rounded py-0.5 text-left`,children:[(0,A.jsx)(`span`,{className:`w-3 shrink-0 text-xs text-zinc-400 dark:text-zinc-600`,children:i?`▾`:`▸`}),(0,A.jsx)(`span`,{title:t.name,className:`truncate ${l?`text-zinc-400 dark:text-zinc-600`:`text-zinc-700 dark:text-zinc-300`}`,children:t.name}),!i&&nV(c,r.gitFiles)>0&&(0,A.jsx)(`span`,{className:`ml-1 shrink-0 rounded bg-amber-100 px-1 font-mono text-[10px] font-bold text-amber-700 dark:bg-amber-950/60 dark:text-amber-400`,title:`${nV(c,r.gitFiles)} changed file(s) inside`,children:nV(c,r.gitFiles)})]}),r.onRevealNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onRevealNative?.(c),title:`Show in the file manager`,"aria-label":`Show ${t.name} in the file manager`,className:eV,children:`⌂`}),r.creation&&!l&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{a(!0),r.tree[c]===void 0&&r.onExpand(c),r.creation?.start(c)},title:`New file or folder here`,"aria-label":`New file or folder in ${t.name}`,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs text-zinc-400 hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:text-zinc-600 dark:hover:bg-zinc-700 [@media(hover:hover)]:opacity-0`,children:`+`})]}),i&&(0,A.jsx)(sV,{path:c,depth:n+1,...r})]})}let f=c===r.openFilePath,p=r.gitFiles?.[c],m=r.attachedPaths?.includes(c)??!1,h=t.type===`file`,g=h||t.type===`symlink-file`,_=h&&!l,v=h&&(l?r.onCopyFile!==void 0:r.onMoveFile!==void 0);return r.rename?.path===c?(0,A.jsx)(oV,{path:c,name:t.name,depth:n,rename:r.rename}):(0,A.jsxs)(`div`,{className:`group flex w-full items-center rounded hover:bg-zinc-100 dark:hover:bg-zinc-800 ${f?`bg-zinc-100 dark:bg-zinc-800`:``}`,children:[(0,A.jsx)(`button`,{type:`button`,draggable:v&&!u,onDragStart:e=>{v&&!u&&(e.dataTransfer.effectAllowed=l?`copy`:`move`,e.dataTransfer.setData(QB,c),l&&e.dataTransfer.setData($B,`copy`))},onClick:()=>r.onSelectFile(c),style:{paddingLeft:n*12+16},className:`flex min-w-0 flex-1 items-center py-0.5 text-left`,children:(0,A.jsx)(`span`,{title:t.name,className:`truncate ${l?`text-zinc-400 dark:text-zinc-600`:`text-zinc-600 dark:text-zinc-400`}`,children:t.name})}),g&&r.onOpenNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onOpenNative?.(c),title:`Open with the associated application`,"aria-label":`Open ${t.name} with the associated application`,className:eV,children:`↗`}),r.onRevealNative&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.onRevealNative?.(c),title:`Show in the file manager`,"aria-label":`Show ${t.name} in the file manager`,className:eV,children:`⌂`}),_&&r.onRenameFile&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>r.rename?.start(c),title:`Rename file`,"aria-label":`Rename ${t.name}`,className:eV,children:`✎`}),_&&r.onDeleteFile&&(0,A.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>{window.confirm(`Delete "${t.name}" permanently?`)&&r.onDeleteFile?.(c)},title:`Delete file`,"aria-label":`Delete ${t.name}`,className:`${eV} hover:text-red-600 dark:hover:text-red-400`,children:`×`}),r.onToggleAttachPath&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>r.onToggleAttachPath?.(c),title:m?`Remove this file from the prompt`:`Reference this file in the prompt`,"aria-label":`${m?`Remove`:`Reference`} ${t.name} in the prompt`,"aria-pressed":m,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs hover:bg-zinc-200 group-hover:opacity-100 focus-visible:opacity-100 dark:hover:bg-zinc-700 ${m?`font-bold text-blue-600 dark:text-blue-400`:`text-zinc-400 dark:text-zinc-600 [@media(hover:hover)]:opacity-0`}`,children:`@`}),p&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>(r.onSelectDiff??r.onSelectFile)(c),title:`Show uncommitted diff`,"aria-label":`Show diff of ${t.name}`,className:`mr-1 shrink-0 rounded px-1 font-mono text-xs font-bold hover:bg-zinc-200 dark:hover:bg-zinc-700 ${tV[p].className}`,children:tV[p].label})]})}function lV(e){let t=e.trim();if(t===``)return{error:`A name is required`};let n=t.endsWith(`/`),r=n?t.slice(0,-1).trim():t;return r===``?{error:`A name is required`}:r.includes(`/`)||r.includes(`\\`)?{error:`That is a path, not a name`}:r===`.`||r===`..`?{error:`"${r}" is not a name`}:{kind:n?`directory`:`file`,name:r}}function uV(e){let t=lV(e);return`error`in t?t:t.kind===`directory`?{error:`That is a folder name`}:{name:t.name}}function dV(e){let[t,n]=(0,d.useState)(null),[r,i]=(0,d.useState)(null),[a,o]=(0,d.useState)(null),[s,c]=(0,d.useState)(null),[l,u]=(0,d.useState)(null),[f,p]=(0,d.useState)(null),m=e.onCreateFile!==void 0||e.onCreateDirectory!==void 0,h=e.createError&&a&&e.createError.path===fV(a.dir,a.name)?e.createError.message:null,g=e.created??null;(0,d.useEffect)(()=>{a!==null&&g!==null&&g===fV(a.dir,a.name)&&(n(null),o(null),i(null))},[a,g]);let _=e.fileOperation?.status===`error`&&e.fileOperation.operation===`rename_file`&&f===e.fileOperation.path?e.fileOperation.message:null;(0,d.useEffect)(()=>{let t=e.fileOperation;t?.status===`succeeded`&&t.operation===`rename_file`&&f===t.path&&(c(null),p(null),u(null))},[f,e.fileOperation]);let v=m?{openIn:t,localError:r,serverError:h,start:e=>{n(e),i(null),o(null)},cancel:()=>{n(null),i(null),o(null)},submit:(t,n)=>{let r=lV(n);if(`error`in r){i(r.error);return}i(null),o({dir:t,name:r.name});let a=fV(t,r.name);r.kind===`directory`?e.onCreateDirectory?.(a):e.onCreateFile?.(a)}}:void 0,y=e.onRenameFile?{path:s,pending:f!==null&&e.fileOperation?.status===`pending`&&e.fileOperation.operation===`rename_file`&&e.fileOperation.path===f,localError:l,serverError:_,start:e=>{c(e),p(null),u(null)},cancel:()=>{c(null),p(null),u(null)},submit:(t,n)=>{if(n.trim()===``){c(null),p(null),u(null);return}let r=uV(n);`error`in r?u(r.error):(u(null),p(t),e.onRenameFile?.(t,r.name))}}:void 0,b=!iV(``,e.writableRoot);return(0,A.jsxs)(`div`,{className:`text-sm`,children:[e.fileOperation?.status===`error`&&e.fileOperation.operation!==`rename_file`&&(0,A.jsx)(`p`,{role:`alert`,className:`mb-1 rounded bg-red-50 px-2 py-1 text-xs text-red-700 dark:bg-red-950/40 dark:text-red-300`,children:e.fileOperation.message}),(v&&b||e.onRefresh)&&(0,A.jsxs)(`div`,{className:`mb-1 flex items-center`,children:[v&&b&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>v.start(``),"aria-label":`New file or folder in the workspace root`,className:`rounded px-1 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-400`,children:`+ new`}),e.onRefresh&&(0,A.jsx)(`button`,{type:`button`,onClick:e.onRefresh,title:`Refresh the file tree`,"aria-label":`Refresh the file tree`,className:`ml-auto rounded px-1 py-0.5 text-xs text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-400`,children:`↻`})]}),(0,A.jsx)(sV,{path:``,depth:0,...e,...v?{creation:v}:{},...y?{rename:y}:{}})]})}function fV(e,t){return e===``?t:`${e}/${t}`}function pV({tree:e,openFile:t,writableRoot:n,gitFiles:r,attachedPaths:i,onExpand:a,onSelectDirectory:o,onRefresh:s,onSelectFile:c,onSelectDiff:l,onToggleAttachPath:u,onCreateFile:f,onCreateDirectory:p,onOpenNative:m,onRevealNative:h,onRenameFile:g,onDeleteFile:_,onMoveFile:v,onCopyFile:y,fileOperation:b,createError:x,created:S}){let C=pz(sz);return(0,d.useEffect)(()=>{e[``]===void 0&&a(``)},[]),(0,A.jsxs)(`aside`,{"aria-label":`Files`,style:{width:C.width},className:`relative flex shrink-0 flex-col border-r border-zinc-200 dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`border-b border-zinc-200 px-3 py-2 text-xs font-semibold uppercase text-zinc-400 dark:border-zinc-800 dark:text-zinc-600`,children:`Files`}),(0,A.jsx)(`div`,{className:`flex-1 overflow-auto p-2`,children:(0,A.jsx)(dV,{tree:e,openFilePath:t?.path,writableRoot:n,gitFiles:r,attachedPaths:i,onExpand:a,onSelectDirectory:o,onRefresh:s,onSelectFile:c,onSelectDiff:l,onToggleAttachPath:u,onCreateFile:f,onCreateDirectory:p,onOpenNative:m,onRevealNative:h,onRenameFile:g,onDeleteFile:_,onMoveFile:v,onCopyFile:y,fileOperation:b,createError:x,created:S})}),(0,A.jsx)(mz,{label:`Resize Files sidebar`,width:C.width,config:sz,separatorProps:C.separatorProps})]})}function mV({title:e,onSubmit:t}){let[n,r]=(0,d.useState)(``);return(0,A.jsx)(`div`,{className:`flex h-full items-center justify-center p-6`,children:(0,A.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),n.trim()&&t(n.trim())},className:`w-full max-w-sm rounded-xl border border-zinc-200 p-6 shadow-sm dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`mb-1 text-center text-3xl`,children:e??`π`}),(0,A.jsx)(`h1`,{className:`mb-4 text-center text-sm text-zinc-500 dark:text-zinc-400`,children:`This server requires an access token.`}),(0,A.jsx)(`label`,{htmlFor:`pi-outpost-token`,className:`mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400`,children:`Access token`}),(0,A.jsx)(`input`,{id:`pi-outpost-token`,name:`token`,type:`password`,autoComplete:`off`,spellCheck:!1,value:n,onChange:e=>r(e.target.value),placeholder:`paste the token…`,className:`mb-3 w-full rounded-md border border-zinc-300 bg-white px-2 py-1.5 font-mono text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:focus:border-zinc-500`}),(0,A.jsx)(`button`,{type:`submit`,disabled:!n.trim(),className:`w-full rounded-md border border-emerald-300 px-2 py-1.5 text-sm text-emerald-700 hover:border-emerald-500 disabled:opacity-50 dark:border-emerald-900 dark:text-emerald-400 dark:hover:border-emerald-600`,children:`Connect`}),(0,A.jsxs)(`p`,{className:`mt-3 text-center text-xs text-zinc-400 dark:text-zinc-600`,children:[`Ask the operator for the token, or open the link containing `,(0,A.jsx)(`code`,{children:`?token=…`})]})]})})}var hV={todo:{icon:`○`,label:`To do`,className:`text-zinc-500`},in_progress:{icon:`●`,label:`In progress`,className:`text-blue-600 dark:text-blue-400`},done:{icon:`✓`,label:`Done`,className:`text-emerald-600 dark:text-emerald-400`},blocked:{icon:`!`,label:`Blocked`,className:`text-red-600 dark:text-red-400`},needs_review:{icon:`?`,label:`Needs review`,className:`text-amber-600 dark:text-amber-400`}},gV=8;function _V(e){let t=e.uri.startsWith(`workspace:`)?e.uri.slice(10):/^[a-z][a-z0-9+.-]*:/i.test(e.uri)?null:e.uri;return t===null||t===``||/^(?:[\\/]|[a-z]:[\\/])/i.test(t)||t.replaceAll(`\\`,`/`).split(`/`).includes(`..`)?null:t}function vV({plan:e,open:t,onToggle:n,onOpenWorkspace:r,requestedTaskId:i,onTaskRequestHandled:a}){let o=(0,d.useId)(),[s,c]=(0,d.useState)(!1),[l,u]=(0,d.useState)(null),[f,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{i&&(e.tasks.some(e=>e.id===i)?(u(i),p(null)):(u(null),p(i)),a?.())},[e.tasks,i,a]),(0,d.useEffect)(()=>{l!==null&&!e.tasks.some(e=>e.id===l)&&u(null)},[e,l]),(0,d.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&c(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let m=(0,d.useMemo)(()=>{let t=new Map;for(let n of e.tasks)t.set(n.parentId,[...t.get(n.parentId)??[],n]);return t},[e.tasks]),h=(0,d.useMemo)(()=>new Map(e.tasks.map(e=>[e.id,e])),[e.tasks]),g=(0,d.useMemo)(()=>{let e=[],t=(n,r)=>{for(let i of m.get(n)??[])e.push({task:i,depth:r}),t(i.id,r+1)};return t(void 0,0),e.slice(0,gV)},[m]),_=l?h.get(l):void 0,v=e.tasks.filter(e=>e.status===`done`).length,y=(e,t=0)=>(m.get(e)??[]).flatMap(e=>{let n=hV[e.status];return[(0,A.jsxs)(`button`,{type:`button`,role:`treeitem`,"aria-level":t+1,"aria-selected":l===e.id,onClick:()=>u(e.id),"aria-current":e.status===`in_progress`?`step`:void 0,className:`flex w-full items-start gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-zinc-100 dark:hover:bg-zinc-800 ${l===e.id?`bg-zinc-100 dark:bg-zinc-800`:``}`,style:{paddingLeft:`${.5+t*.85}rem`},children:[(0,A.jsx)(`span`,{className:`mt-px w-4 shrink-0 text-center font-semibold ${n.className}`,"aria-label":n.label,children:n.icon}),(0,A.jsx)(`span`,{className:e.status===`done`?`text-zinc-500 line-through`:`text-zinc-800 dark:text-zinc-200`,children:e.title})]},e.id),...y(e.id,t+1)]});return t?(0,A.jsxs)(`aside`,{"aria-label":`Work Plan`,className:`absolute inset-y-0 right-0 z-10 flex w-full flex-col border-l border-zinc-200 bg-white/95 shadow-lg backdrop-blur md:w-[23rem] dark:border-zinc-800 dark:bg-zinc-950/95`,children:[(0,A.jsxs)(`header`,{className:`border-b border-zinc-200 px-3 py-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,A.jsxs)(`div`,{className:`min-w-0`,children:[(0,A.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-zinc-500`,children:`Work Plan`}),(0,A.jsx)(`h2`,{className:`truncate text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.title})]}),(0,A.jsx)(`button`,{type:`button`,onClick:n,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,"aria-label":`Close Work Plan`,children:`×`})]}),(0,A.jsxs)(`div`,{className:`mt-2 text-xs text-zinc-500`,children:[`Progress: `,v,` / `,e.tasks.length]}),(0,A.jsx)(`div`,{className:`mt-1 h-1.5 overflow-hidden rounded-full bg-zinc-200 dark:bg-zinc-800`,"aria-hidden":!0,children:(0,A.jsx)(`div`,{className:`h-full bg-emerald-500`,style:{width:`${e.tasks.length===0?0:v/e.tasks.length*100}%`}})})]}),(0,A.jsx)(`div`,{role:`tree`,"aria-label":`Work Plan tasks`,className:`min-h-0 flex-1 overflow-y-auto p-2`,children:y(void 0)}),f&&(0,A.jsx)(`div`,{role:`status`,className:`border-t border-amber-200 bg-amber-50 p-3 text-xs text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300`,children:`That Outcome task no longer exists in the current Work Plan.`}),_&&(0,A.jsxs)(`section`,{"aria-label":`Task details`,className:`max-h-[45%] overflow-y-auto border-t border-zinc-200 p-3 text-xs dark:border-zinc-800`,children:[(0,A.jsx)(`div`,{className:`font-semibold ${hV[_.status].className}`,children:hV[_.status].label}),(0,A.jsx)(`h3`,{className:`mt-1 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:_.title}),_.description&&(0,A.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-zinc-600 dark:text-zinc-300`,children:_.description}),_.statusReason&&(0,A.jsx)(`p`,{className:`mt-2 rounded bg-zinc-100 p-2 text-zinc-700 dark:bg-zinc-900 dark:text-zinc-300`,children:_.statusReason}),_.dependsOn.length>0&&(0,A.jsxs)(`div`,{className:`mt-3`,children:[(0,A.jsx)(`span`,{className:`font-semibold`,children:`Depends on:`}),` `,_.dependsOn.map(e=>h.get(e)?.title??e).join(`, `)]}),_.resources.length>0&&(0,A.jsxs)(`div`,{className:`mt-3 space-y-1`,children:[(0,A.jsx)(`div`,{className:`font-semibold`,children:`Resources`}),_.resources.map(e=>{let t=_V(e),n=e.label??e.uri;return t===null?/^https?:/i.test(e.uri)?(0,A.jsx)(`a`,{href:e.uri,target:`_blank`,rel:`noreferrer`,className:`block truncate text-blue-600 hover:underline dark:text-blue-400`,children:n},e.uri):(0,A.jsx)(`span`,{className:`block truncate text-zinc-500`,title:`No navigator is available for this resource`,children:n},e.uri):(0,A.jsx)(`button`,{type:`button`,className:`block max-w-full truncate text-left text-blue-600 hover:underline dark:text-blue-400`,onClick:()=>r(t),children:n},e.uri)})]})]})]}):(0,A.jsxs)(`div`,{className:`absolute right-3 top-3 z-20`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocusCapture:()=>c(!0),onBlurCapture:()=>c(!1),children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{c(!1),n()},className:`rounded-md border border-zinc-300 bg-white px-2 py-1 text-xs shadow-sm dark:border-zinc-700 dark:bg-zinc-900`,"aria-label":`Open Work Plan`,"aria-describedby":o,children:[`Plan `,v,`/`,e.tasks.length]}),(0,A.jsx)(`div`,{id:o,role:`tooltip`,className:`absolute right-0 top-full w-72 pt-2 ${s?`block`:`hidden`}`,children:(0,A.jsxs)(`div`,{className:`rounded-md border border-zinc-200 bg-white p-2 shadow-lg dark:border-zinc-700 dark:bg-zinc-900`,children:[(0,A.jsx)(`ul`,{className:`space-y-1`,children:g.map(({task:e,depth:t})=>(0,A.jsxs)(`li`,{className:`flex min-w-0 items-start gap-1.5 text-xs`,style:{paddingLeft:`${t*.75}rem`},children:[(0,A.jsx)(`span`,{"aria-label":hV[e.status].label,className:`shrink-0 font-semibold ${hV[e.status].className}`,children:e.status===`done`?`☑`:`☐`}),(0,A.jsx)(`span`,{className:`truncate ${e.status===`done`?`text-zinc-500 line-through`:`text-zinc-800 dark:text-zinc-200`}`,children:e.title})]},e.id))}),e.tasks.length>g.length&&(0,A.jsxs)(`div`,{className:`mt-1 text-[11px] text-zinc-500`,children:[`+`,e.tasks.length-g.length,` more`]})]})})]})}var yV=Object.defineProperty,bV=Object.getOwnPropertyDescriptor,xV=(e,t)=>{for(var n in t)yV(e,n,{get:t[n],enumerable:!0})},SV=(e,t,n,r)=>{for(var i=r>1?void 0:r?bV(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&yV(t,n,i),i},CV=(e,t)=>(n,r)=>t(n,r,e),wV=`Terminal input`,TV={get:()=>wV,set:e=>wV=e},EV=`Too much output to announce, navigate to rows manually to read`,DV={get:()=>EV,set:e=>EV=e};function OV(e){return e.replace(/\r?\n/g,`\r`)}function kV(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function AV(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function jV(e,t,n,r){e.stopPropagation(),e.clipboardData&&MV(e.clipboardData.getData(`text/plain`),t,n,r)}function MV(e,t,n,r){e=OV(e),e=kV(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function NV(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function PV(e,t,n,r,i){NV(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function FV(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function IV(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var LV=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},RV=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},zV=``,BV=` `,VV=class e{constructor(){this.fg=0,this.bg=0,this.extended=new HV}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},HV=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},UV=class e extends VV{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new HV,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?FV(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},WV=`di$target`,GV=`di$dependencies`,KV=new Map;function qV(e){return e[GV]||[]}function JV(e){if(KV.has(e))return KV.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);YV(t,e,r)};return t._id=e,KV.set(e,t),t}function YV(e,t,n){t[WV]===t?t[GV].push({id:e,index:n}):(t[GV]=[{id:e,index:n}],t[WV]=t)}var XV=JV(`BufferService`),ZV=JV(`CoreMouseService`),QV=JV(`CoreService`),$V=JV(`CharsetService`),eH=JV(`InstantiationService`),tH=JV(`LogService`),nH=JV(`OptionsService`),rH=JV(`OscLinkService`),iH=JV(`UnicodeService`),aH=JV(`DecorationService`),oH=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new UV,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):sH(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};oH=SV([CV(0,XV),CV(1,nH),CV(2,rH)],oH);function sH(e,t){if(confirm(`Do you want to navigate to ${t}?
366
366
 
367
- WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var nH=HV(`CharSizeService`),rH=HV(`CoreBrowserService`),iH=HV(`MouseService`),aH=HV(`RenderService`),oH=HV(`SelectionService`),sH=HV(`CharacterJoinerService`),cH=HV(`ThemeService`),lH=HV(`LinkProviderService`),uH=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gH.isErrorNoTelemetry(e)?new gH(e.message+`
367
+ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var cH=JV(`CharSizeService`),lH=JV(`CoreBrowserService`),uH=JV(`MouseService`),dH=JV(`RenderService`),fH=JV(`SelectionService`),pH=JV(`CharacterJoinerService`),mH=JV(`ThemeService`),hH=JV(`LinkProviderService`),gH=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?SH.isErrorNoTelemetry(e)?new SH(e.message+`
368
368
 
369
369
  `+e.stack):Error(e.message+`
370
370
 
371
- `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function dH(e){pH(e)||uH.onUnexpectedError(e)}var fH=`Canceled`;function pH(e){return e instanceof mH||e instanceof Error&&e.name===fH&&e.message===fH}var mH=class extends Error{constructor(){super(fH),this.name=this.message}};function hH(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var gH=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},_H=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function vH(e,t=0){return e[e.length-(1+t)]}var yH;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(yH||={});var bH=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||yH.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};bH.empty=new bH(e=>{});function xH(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var SH;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(SH||={});var CH=null;function wH(e){return CH?.trackDisposable(e),e}function TH(e){CH?.markAsDisposed(e)}function EH(e,t){CH?.setParent(e,t)}function DH(e){return CH?.markAsSingleton(e),e}function OH(e){if(SH.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function kH(...e){return AH(()=>OH(e))}function AH(e){let t=wH({dispose:xH(()=>{TH(t),e()})});return t}var jH=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,wH(this)}dispose(){this._isDisposed||(TH(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{OH(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return EH(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),EH(e,null))}};jH.DISABLE_DISPOSED_WARNING=!1;var MH=jH,NH=class{constructor(){this._store=new MH,wH(this),EH(this._store,this)}dispose(){TH(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};NH.None=Object.freeze({dispose(){}});var PH=class{constructor(){this._isDisposed=!1,wH(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&EH(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,TH(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&EH(e,null),e}},FH=typeof window==`object`?window:globalThis,IH=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};IH.Undefined=new IH(void 0);var LH=IH,RH=class{constructor(){this._first=LH.Undefined,this._last=LH.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===LH.Undefined}clear(){let e=this._first;for(;e!==LH.Undefined;){let t=e.next;e.prev=LH.Undefined,e.next=LH.Undefined,e=t}this._first=LH.Undefined,this._last=LH.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new LH(e);if(this._first===LH.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==LH.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==LH.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==LH.Undefined&&e.next!==LH.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===LH.Undefined&&e.next===LH.Undefined?(this._first=LH.Undefined,this._last=LH.Undefined):e.next===LH.Undefined?(this._last=this._last.prev,this._last.next=LH.Undefined):e.prev===LH.Undefined&&(this._first=this._first.next,this._first.prev=LH.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==LH.Undefined;)yield e.element,e=e.next}},zH=globalThis.performance&&typeof globalThis.performance.now==`function`,BH=class e{static create(t){return new e(t)}constructor(e){this._now=zH&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},VH;(e=>{e.None=()=>NH.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(kH(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new $H({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new $H({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new $H({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new $H({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new $H({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new $H;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new $H(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function ee(e,t){return new T(e,t).emitter.event}e.fromObservable=ee;function E(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof MH?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=E})(VH||={});var HH=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new BH,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};HH.all=new Set,HH._idPool=0;var UH=HH,WH=-1,GH=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new JH(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};GH._idPool=1;var KH=GH,qH=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
371
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function _H(e){yH(e)||gH.onUnexpectedError(e)}var vH=`Canceled`;function yH(e){return e instanceof bH||e instanceof Error&&e.name===vH&&e.message===vH}var bH=class extends Error{constructor(){super(vH),this.name=this.message}};function xH(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var SH=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},CH=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function wH(e,t=0){return e[e.length-(1+t)]}var TH;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(TH||={});var EH=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||TH.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};EH.empty=new EH(e=>{});function DH(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var OH;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(OH||={});var kH=null;function AH(e){return kH?.trackDisposable(e),e}function jH(e){kH?.markAsDisposed(e)}function MH(e,t){kH?.setParent(e,t)}function NH(e){return kH?.markAsSingleton(e),e}function PH(e){if(OH.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function FH(...e){return IH(()=>PH(e))}function IH(e){let t=AH({dispose:DH(()=>{jH(t),e()})});return t}var LH=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,AH(this)}dispose(){this._isDisposed||(jH(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{PH(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return MH(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),MH(e,null))}};LH.DISABLE_DISPOSED_WARNING=!1;var RH=LH,zH=class{constructor(){this._store=new RH,AH(this),MH(this._store,this)}dispose(){jH(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};zH.None=Object.freeze({dispose(){}});var BH=class{constructor(){this._isDisposed=!1,AH(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&MH(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,jH(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&MH(e,null),e}},VH=typeof window==`object`?window:globalThis,HH=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};HH.Undefined=new HH(void 0);var UH=HH,WH=class{constructor(){this._first=UH.Undefined,this._last=UH.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===UH.Undefined}clear(){let e=this._first;for(;e!==UH.Undefined;){let t=e.next;e.prev=UH.Undefined,e.next=UH.Undefined,e=t}this._first=UH.Undefined,this._last=UH.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new UH(e);if(this._first===UH.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==UH.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==UH.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==UH.Undefined&&e.next!==UH.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===UH.Undefined&&e.next===UH.Undefined?(this._first=UH.Undefined,this._last=UH.Undefined):e.next===UH.Undefined?(this._last=this._last.prev,this._last.next=UH.Undefined):e.prev===UH.Undefined&&(this._first=this._first.next,this._first.prev=UH.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==UH.Undefined;)yield e.element,e=e.next}},GH=globalThis.performance&&typeof globalThis.performance.now==`function`,KH=class e{static create(t){return new e(t)}constructor(e){this._now=GH&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},qH;(e=>{e.None=()=>zH.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(FH(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new aU({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new aU({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new aU({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new aU({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new aU({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new aU;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new aU(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function ee(e,t){return new T(e,t).emitter.event}e.fromObservable=ee;function E(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof RH?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=E})(qH||={});var JH=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new KH,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};JH.all=new Set,JH._idPool=0;var YH=JH,XH=-1,ZH=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new eU(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};ZH._idPool=1;var QH=ZH,$H=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
372
372
  `).slice(2).join(`
373
- `))}},JH=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},YH=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},XH=0,ZH=class{constructor(e){this.value=e,this.id=XH++}},QH=2,$H=class{constructor(e){this._size=0,this._options=e,this._leakageMon=WH>0||this._options?.leakWarningThreshold?new KH(e?.onListenerError??dH,this._options?.leakWarningThreshold??WH):void 0,this._perfMon=this._options?._profName?new UH(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new YH(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||dH)(n),NH.None}if(this._disposed)return NH.None;t&&(e=e.bind(t));let r=new ZH(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=qH.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ZH?(this._deliveryQueue??=new eU,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=AH(()=>{i?.(),this._removeListener(r)});return n instanceof MH?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*QH<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||dH;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof ZH)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},eU=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},tU=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new $H,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new $H,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};tU.INSTANCE=new tU;var nU=tU;function rU(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}nU.INSTANCE.onDidChangeZoomLevel;function iU(e){return nU.INSTANCE.getZoomFactor(e)}nU.INSTANCE.onDidChangeFullscreen;var aU=typeof navigator==`object`?navigator.userAgent:``,oU=aU.indexOf(`Firefox`)>=0,sU=aU.indexOf(`AppleWebKit`)>=0,cU=aU.indexOf(`Chrome`)>=0,lU=!cU&&aU.indexOf(`Safari`)>=0;aU.indexOf(`Electron/`),aU.indexOf(`Android`);var uU=!1;if(typeof FH.matchMedia==`function`){let e=FH.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=FH.matchMedia(`(display-mode: fullscreen)`);uU=e.matches,rU(FH,e,({matches:e})=>{uU&&t.matches||(uU=e)})}function dU(){return uU}var fU=`en`,pU=!1,mU=!1,hU=!1,gU=!1,_U=!1,vU=fU,yU,bU=globalThis,xU;typeof bU.vscode<`u`&&typeof bU.vscode.process<`u`?xU=bU.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(xU=process);var SU=typeof xU?.versions?.electron==`string`&&xU?.type===`renderer`;if(typeof xU==`object`){pU=xU.platform===`win32`,mU=xU.platform===`darwin`,hU=xU.platform===`linux`,hU&&xU.env.SNAP&&xU.env.SNAP_REVISION,xU.env.CI||xU.env.BUILD_ARTIFACTSTAGINGDIRECTORY,vU=fU;let e=xU.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,vU=t.resolvedLanguage||fU,t.languagePack?.translationsConfigFile}catch{}gU=!0}else typeof navigator==`object`&&!SU?(yU=navigator.userAgent,pU=yU.indexOf(`Windows`)>=0,mU=yU.indexOf(`Macintosh`)>=0,(yU.indexOf(`Macintosh`)>=0||yU.indexOf(`iPad`)>=0||yU.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,hU=yU.indexOf(`Linux`)>=0,yU?.indexOf(`Mobi`),_U=!0,vU=globalThis._VSCODE_NLS_LANGUAGE||fU,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var CU=pU,wU=mU,TU=hU,EU=gU;_U&&typeof bU.importScripts==`function`&&bU.origin;var DU=yU,OU=vU,kU;(e=>{function t(){return OU}e.value=t;function n(){return OU.length===2?OU===`en`:OU.length>=3&&OU[0]===`e`&&OU[1]===`n`&&OU[2]===`-`}e.isDefaultVariant=n;function r(){return OU===`en`}e.isDefault=r})(kU||={});var AU=typeof bU.postMessage==`function`&&!bU.importScripts;(()=>{if(AU){let e=[];bU.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),bU.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var jU=!!(DU&&DU.indexOf(`Chrome`)>=0);DU&&DU.indexOf(`Firefox`),!jU&&DU&&DU.indexOf(`Safari`),DU&&DU.indexOf(`Edg/`),DU&&DU.indexOf(`Android`);var MU=typeof navigator==`object`?navigator:{};EU||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||MU&&MU.clipboard&&MU.clipboard.writeText,EU||MU&&MU.clipboard&&MU.clipboard.readText,EU||dU()||MU.keyboard,`ontouchstart`in FH||MU.maxTouchPoints,FH.PointerEvent&&(`ontouchstart`in FH||navigator.maxTouchPoints);var NU=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},PU=new NU,FU=new NU,IU=new NU,LU=Array(230),RU;(e=>{function t(e){return PU.keyCodeToStr(e)}e.toString=t;function n(e){return PU.strToKeyCode(e)}e.fromString=n;function r(e){return FU.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return IU.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return FU.strToKeyCode(e)||IU.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return PU.keyCodeToStr(e)}e.toElectronAccelerator=o})(RU||={});var zU=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new BU([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},BU=class{constructor(e){if(e.length===0)throw hH(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function VU(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return RU.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(oU)switch(t){case 59:return 85;case 60:if(TU)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(wU)return 57}else if(sU&&(wU&&t===93||!wU&&t===92))return 57;return LU[t]||0}var HU=wU?256:2048,UU=512,WU=1024,GU=wU?2048:256,KU=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=VU(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=HU),this.altKey&&(t|=UU),this.shiftKey&&(t|=WU),this.metaKey&&(t|=GU),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new zU(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},qU=new WeakMap;function JU(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var YU=class{static getSameOriginWindowChain(e){let t=qU.get(e);if(!t){t=[],qU.set(e,t);let n=e,r;do r=JU(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},XU=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=YU.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},ZU=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(cU){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?oU&&!wU?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=lU&&CU?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?oU&&!wU?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},QU=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),$U;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof eW?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:VH.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:QU})})($U||={});var eW=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?QU:(this._emitter||=new $H,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},tW=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new _H(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new _H(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},nW=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new _H(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=AH(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var rW;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(rW||={});var iW=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new $H,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await VH.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};iW.EMPTY=iW.fromArray([]);function aW(e){return oW(e,0)}function oW(e,t){switch(typeof e){case`object`:return e===null?sW(349,t):Array.isArray(e)?uW(e,t):dW(e,t);case`string`:return lW(e,t);case`boolean`:return cW(e,t);case`number`:return sW(e,t);case`undefined`:return sW(937,t);default:return sW(617,t)}}function sW(e,t){return(t<<5)-t+e|0}function cW(e,t){return sW(e?433:863,t)}function lW(e,t){t=sW(149417,t);for(let n=0,r=e.length;n<r;n++)t=sW(e.charCodeAt(n),t);return t}function uW(e,t){return t=sW(104579,t),e.reduce((e,t)=>oW(t,e),t)}function dW(e,t){return t=sW(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=lW(n,t),oW(e[n],t)),t)}var{registerWindow:fW,getWindow:pW,getDocument:mW,getWindows:hW,getWindowsCount:gW,getWindowId:_W,getWindowById:vW,hasWindow:yW,onDidRegisterWindow:bW,onWillUnregisterWindow:xW,onDidUnregisterWindow:SW}=function(){let e=new Map,t={window:FH,disposables:new MH};e.set(FH.vscodeWindowId,t);let n=new $H,r=new $H,i=new $H;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return NH.None;let a=new MH,o={window:t,disposables:a.add(new MH)};return e.set(t.vscodeWindowId,o),a.add(AH(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(wW(t,NW.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:FH},getDocument(e){return pW(e).document}}}(),CW=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function wW(e,t,n,r){return new CW(e,t,n,r)}function TW(e,t){return function(n){return t(new XU(e,n))}}function EW(e){return function(t){return e(new KU(t))}}var DW=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=TW(pW(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=EW(n)),wW(e,t,i,r)},OW,kW=class extends nW{constructor(e){super(),this.defaultTarget=e&&pW(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},AW=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){dH(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(AW.sort),a.shift().execute();r.set(i,!1)};OW=(t,r,a=0)=>{let o=_W(t),s=new AW(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var jW=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};jW.None=new jW(0,0);function MW(e){let t=e.getBoundingClientRect(),n=pW(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=aW(n),a=r.get(i);if(a)a.users+=1;else{let o=new $H,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(AH(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var NW={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:sU?`webkitAnimationStart`:`animationstart`,ANIMATION_END:sU?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:sU?`webkitAnimationIteration`:`animationiteration`},PW=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=FW(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=FW(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=FW(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=FW(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=FW(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=FW(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=FW(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=FW(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=FW(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=FW(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=FW(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=FW(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=FW(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=FW(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function FW(e){return typeof e==`number`?`${e}px`:e}function IW(e){return new PW(e)}var LW=class{constructor(){this._hooks=new MH,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(AH(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=pW(e)}this._hooks.add(wW(a,NW.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(wW(a,NW.POINTER_UP,e=>this.stopMonitoring(!0)))}};function RW(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var zW;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(zW||={});var BW=class e extends NH{constructor(){super(),this.dispatched=!1,this.targets=new RH,this.ignoreTargets=new RH,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(VH.runAndSubscribe(bW,({window:e,disposables:t})=>{t.add(wW(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(wW(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(wW(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:FH,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=DH(new e),AH(e.INSTANCE.targets.push(t))):NH.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=DH(new e),AH(e.INSTANCE.ignoreTargets.push(t))):NH.None}static isTouchDevice(){return`ontouchstart`in FH||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(zW.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-vH(s.rollingPageX))<30&&Math.abs(s.initialPageY-vH(s.rollingPageY))<30){let e=this.newGestureEvent(zW.Tap,s.initialTarget);e.pageX=vH(s.rollingPageX),e.pageY=vH(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-vH(s.rollingPageX))<30&&Math.abs(s.initialPageY-vH(s.rollingPageY))<30){let e=this.newGestureEvent(zW.Contextmenu,s.initialTarget);e.pageX=vH(s.rollingPageX),e.pageY=vH(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=vH(s.rollingPageX),n=vH(s.rollingPageY),i=vH(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(zW.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===zW.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zW.Change||t.type===zW.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=OW(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(zW.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(zW.Change,i.initialTarget);a.translationX=r.pageX-vH(i.rollingPageX),a.translationY=r.pageY-vH(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};BW.SCROLL_FRICTION=-.005,BW.HOLD_DELAY=700,BW.CLEAR_TAP_COUNT_TIME=400,gV([RW],BW,`isTouchDevice`,1);var VW=BW,HW=class extends NH{onclick(e,t){this._register(wW(e,NW.CLICK,n=>t(new XU(pW(e),n))))}onmousedown(e,t){this._register(wW(e,NW.MOUSE_DOWN,n=>t(new XU(pW(e),n))))}onmouseover(e,t){this._register(wW(e,NW.MOUSE_OVER,n=>t(new XU(pW(e),n))))}onmouseleave(e,t){this._register(wW(e,NW.MOUSE_LEAVE,n=>t(new XU(pW(e),n))))}onkeydown(e,t){this._register(wW(e,NW.KEY_DOWN,e=>t(new KU(e))))}onkeyup(e,t){this._register(wW(e,NW.KEY_UP,e=>t(new KU(e))))}oninput(e,t){this._register(wW(e,NW.INPUT,t))}onblur(e,t){this._register(wW(e,NW.BLUR,t))}onfocus(e,t){this._register(wW(e,NW.FOCUS,t))}onchange(e,t){this._register(wW(e,NW.CHANGE,t))}ignoreGesture(e){return VW.ignoreTarget(e)}},UW=11,WW=class extends HW{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=UW+`px`,this.domNode.style.height=UW+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new LW),this._register(DW(this.bgDomNode,NW.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(DW(this.domNode,NW.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new kW),this._pointerdownScheduleRepeatTimer=this._register(new tW)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,pW(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},GW=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},KW=class extends NH{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new $H),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new GW(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new XW(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=XW.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},qW=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function JW(e,t){let n=t-e;return function(t){return e+n*QW(t)}}function YW(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var XW=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),YW(JW(e,r),JW(i,t),.33)}return JW(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new qW(this.scrollLeft(t),this.scrollTop(t),!1):new qW(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function ZW(e){return e**3}function QW(e){return 1-ZW(1-e)}var $W=class extends NH{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new tW)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},eG=140,tG=class extends HW{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new $W(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new LW),this._shouldRender=!0,this.domNode=IW(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(wW(this.domNode.domNode,NW.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new WW(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=IW(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(wW(this.slider.domNode,NW.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=MW(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(CU&&a>eG){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},nG=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},rG=class extends tG{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new nG(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},iG=class extends tG{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new nG(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},aG=500,oG=50,sG=!0,cG=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},lG=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(cU){let t=iU(pW(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new cG(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};lG.INSTANCE=new lG;var uG=lG,dG=class extends HW{constructor(e,t,n){super(),this._onScroll=this._register(new $H),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new $H),this.onWillScroll=this._onWillScroll.event,this._options=pG(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new iG(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new rG(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=IW(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=IW(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=IW(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new tW),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=OH(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,wU&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new ZU(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=OH(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(wW(this._listenOnDomNode,NW.MOUSE_WHEEL,e=>{this._onMouseWheel(new ZU(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=uG.INSTANCE;sG&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!wU&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=oG*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=oG*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(sG&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),aG)}},fG=class extends dG{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function pG(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,wU&&(t.className+=` mac`),t}var mG=class extends NH{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new $H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new KW({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>OW(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new fG(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(VH.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(AH(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(AH(()=>this._styleElement.remove())),this._register(VH.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
374
- `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};mG=gV([_V(2,WV),_V(3,rH),_V(4,GV),_V(5,cH),_V(6,XV),_V(7,aH)],mG);var hG=class extends NH{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(AH(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};hG=gV([_V(1,WV),_V(2,rH),_V(3,$V),_V(4,aH)],hG);var gG=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},_G={full:0,left:0,center:0,right:0},vG={full:0,left:0,center:0,right:0},yG={full:0,left:0,center:0,right:0},bG=class extends NH{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new gG,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(AH(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);vG.full=this._canvas.width,vG.left=e,vG.center=t,vG.right=e,this._refreshDrawHeightConstants(),yG.full=1,yG.left=1,yG.center=1+vG.left,yG.right=1+vG.left+vG.center}_refreshDrawHeightConstants(){_G.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);_G.left=t,_G.center=t,_G.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*_G.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*_G.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*_G.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*_G.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(yG[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-_G[e.position||`full`]/2),vG[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+_G[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};bG=gV([_V(2,WV),_V(3,$V),_V(4,aH),_V(5,XV),_V(6,cH),_V(7,rH)],bG);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
375
- `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var xG;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(xG||={});var SG;(e=>e.ST=`${$.ESC}\\`)(SG||={});var CG=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};CG=gV([_V(2,WV),_V(3,XV),_V(4,KV),_V(5,aH)],CG);var wG=0,TG=0,EG=0,DG=0,OG={css:`#00000000`,rgba:0},kG;(e=>{function t(e,t,n,r){return r===void 0?`#${PG(e)}${PG(t)}${PG(n)}`:`#${PG(e)}${PG(t)}${PG(n)}${PG(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(kG||={});var AG;(e=>{function t(e,t){if(DG=(t.rgba&255)/255,DG===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return wG=a+Math.round((n-a)*DG),TG=o+Math.round((r-o)*DG),EG=s+Math.round((i-s)*DG),{css:kG.toCss(wG,TG,EG),rgba:kG.toRgba(wG,TG,EG)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=NG.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return kG.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[wG,TG,EG]=NG.toChannels(t),{css:kG.toCss(wG,TG,EG),rgba:t}}e.opaque=i;function a(e,t){return DG=Math.round(t*255),[wG,TG,EG]=NG.toChannels(e.rgba),{css:kG.toCss(wG,TG,EG,DG),rgba:kG.toRgba(wG,TG,EG,DG)}}e.opacity=a;function o(e,t){return DG=e.rgba&255,a(e,DG*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(AG||={});var jG;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return wG=parseInt(e.slice(1,2).repeat(2),16),TG=parseInt(e.slice(2,3).repeat(2),16),EG=parseInt(e.slice(3,4).repeat(2),16),kG.toColor(wG,TG,EG);case 5:return wG=parseInt(e.slice(1,2).repeat(2),16),TG=parseInt(e.slice(2,3).repeat(2),16),EG=parseInt(e.slice(3,4).repeat(2),16),DG=parseInt(e.slice(4,5).repeat(2),16),kG.toColor(wG,TG,EG,DG);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return wG=parseInt(r[1]),TG=parseInt(r[2]),EG=parseInt(r[3]),DG=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),kG.toColor(wG,TG,EG,DG);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[wG,TG,EG,DG]=t.getImageData(0,0,1,1).data,DG!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:kG.toRgba(wG,TG,EG,DG),css:e}}e.toColor=r})(jG||={});var MG;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(MG||={});var NG;(e=>{function t(e,t){if(DG=(t&255)/255,DG===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return wG=a+Math.round((n-a)*DG),TG=o+Math.round((r-o)*DG),EG=s+Math.round((i-s)*DG),kG.toRgba(wG,TG,EG)}e.blend=t;function n(e,t,n){let a=MG.relativeLuminance(e>>8),o=MG.relativeLuminance(t>>8);if(FG(a,o)<n){if(o<a){let o=r(e,t,n),s=FG(a,MG.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>FG(a,MG.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=FG(a,MG.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>FG(a,MG.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=FG(MG.relativeLuminance2(o,s,c),MG.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=FG(MG.relativeLuminance2(o,s,c),MG.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=FG(MG.relativeLuminance2(o,s,c),MG.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=FG(MG.relativeLuminance2(o,s,c),MG.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(NG||={});function PG(e){let t=e.toString(16);return t.length<2?`0`+t:t}function FG(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var IG=class extends FV{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},LG=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new LV}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||PV.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)LG._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||PV.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};LG=gV([_V(0,WV)],LG);function RG(e){return 57508<=e&&e<=57558}function zG(e){return 9472<=e&&e<=9631}function BG(e){return RG(e)||zG(e)}function VG(){return{css:{canvas:HG(),cell:HG()},device:{canvas:HG(),cell:HG(),char:{width:0,height:0,left:0,top:0}}}}function HG(){return{width:0,height:0}}var UG=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new LV,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,ee=0,E=[],te=l!==-1&&u!==-1;for(let D=0;D<m;D++){e.loadCell(D,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let ne=!1,re=D>=ee,ie=D,O=this._workCell;if(f.length>0&&D===f[0][0]&&re){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)re&&=i===this._isCellInSelection(v,t);re&&=!n||a<r[0]||a>=r[1],re?(ne=!0,O=new IG(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),ie=r[1]-1,m=O.getWidth()):ee=r[1]}let k=this._isCellInSelection(D,t),ae=n&&D===a,oe=te&&D>=l&&D<=u,se=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{se=!0});let ce=O.getChars()||PV;if(ce===` `&&(O.isUnderline()||O.isOverline())&&(ce=`\xA0`),T=m*s-c.get(ce,O.isBold(),O.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(k&&w||!k&&!w&&O.bg===y)&&(k&&w&&p.selectionForeground||O.fg===b)&&O.extended.ext===x&&oe===S&&T===C&&!ae&&!ne&&!se&&re){O.isInvisible()?_+=PV:_+=ce,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=O.bg,b=O.fg,x=O.extended.ext,S=oe,C=T,w=k,ne&&a>=D&&a<=ie&&(a=D),!this._coreService.isCursorHidden&&ae&&this._coreService.isCursorInitialized){if(E.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&E.push(`xterm-cursor-blink`),E.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:E.push(`xterm-cursor-outline`);break;case`block`:E.push(`xterm-cursor-block`);break;case`bar`:E.push(`xterm-cursor-bar`);break;case`underline`:E.push(`xterm-cursor-underline`)}}if(O.isBold()&&E.push(`xterm-bold`),O.isItalic()&&E.push(`xterm-italic`),O.isDim()&&E.push(`xterm-dim`),_=O.isInvisible()?PV:O.getChars()||PV,O.isUnderline()&&(E.push(`xterm-underline-${O.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!O.isUnderlineColorDefault())){if(O.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${FV.toColorRGB(O.getUnderlineColor()).join(`,`)})`;else{let e=O.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&O.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}O.isOverline()&&(E.push(`xterm-overline`),_===` `&&(_=`\xA0`)),O.isStrikethrough()&&E.push(`xterm-strikethrough`),oe&&(h.style.textDecoration=`underline`);let A=O.getFgColor(),le=O.getFgColorMode(),ue=O.getBgColor(),de=O.getBgColorMode(),j=!!O.isInverse();if(j){let e=A;A=ue,ue=e;let t=le;le=de,de=t}let fe,pe,me=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{e.options.layer!==`top`&&me||(e.backgroundColorRGB&&(de=50331648,ue=e.backgroundColorRGB.rgba>>8&16777215,fe=e.backgroundColorRGB),e.foregroundColorRGB&&(le=50331648,A=e.foregroundColorRGB.rgba>>8&16777215,pe=e.foregroundColorRGB),me=e.options.layer===`top`)}),!me&&k&&(fe=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,ue=fe.rgba>>8&16777215,de=50331648,me=!0,p.selectionForeground&&(le=50331648,A=p.selectionForeground.rgba>>8&16777215,pe=p.selectionForeground)),me&&E.push(`xterm-decoration-top`);let he;switch(de){case 16777216:case 33554432:he=p.ansi[ue],E.push(`xterm-bg-${ue}`);break;case 50331648:he=kG.toColor(ue>>16,ue>>8&255,ue&255),this._addStyle(h,`background-color:#${WG((ue>>>0).toString(16),`0`,6)}`);break;default:j?(he=p.foreground,E.push(`xterm-bg-257`)):he=p.background}switch(fe||O.isDim()&&(fe=AG.multiplyOpacity(he,.5)),le){case 16777216:case 33554432:O.isBold()&&A<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(A+=8),this._applyMinimumContrast(h,he,p.ansi[A],O,fe,void 0)||E.push(`xterm-fg-${A}`);break;case 50331648:let e=kG.toColor(A>>16&255,A>>8&255,A&255);this._applyMinimumContrast(h,he,e,O,fe,pe)||this._addStyle(h,`color:#${WG(A.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,he,p.foreground,O,fe,pe)||j&&E.push(`xterm-fg-257`)}E.length&&=(h.className=E.join(` `),0),!ae&&!ne&&!se&&re?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),D=ie}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||BG(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=AG.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};UG=gV([_V(1,sH),_V(2,XV),_V(3,rH),_V(4,KV),_V(5,$V),_V(6,cH)],UG);function WG(e,t,n){for(;e.length<n;)e=t+e;return e}var GG=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},KG=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function qG(){return new KG}var JG=`xterm-dom-renderer-owner-`,YG=`xterm-rows`,XG=`xterm-fg-`,ZG=`xterm-bg-`,QG=`xterm-focus`,$G=`xterm-selection`,eK=1,tK=class extends NH{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=eK++,this._rowElements=[],this._selectionRenderModel=qG(),this.onRequestRedraw=this._register(new $H).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(YG),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add($G),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=VG(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(UG,document),this._element.classList.add(JG+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(AH(()=>{this._element.classList.remove(JG+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new GG(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${YG} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${YG} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${YG} .xterm-dim { color: ${AG.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${YG}.${QG} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${YG}.${QG} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${YG}.${QG} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${YG} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${YG} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${YG} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${YG} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${YG} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${$G} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${$G} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${$G} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${XG}${n} { color: ${r.css}; }${this._terminalSelector} .${XG}${n}.xterm-dim { color: ${AG.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${ZG}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${XG}257 { color: ${AG.opaque(e.background).css}; }${this._terminalSelector} .${XG}257.xterm-dim { color: ${AG.multiplyOpacity(AG.opaque(e.background),.5).css}; }${this._terminalSelector} .${ZG}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(QG),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(QG),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${JG}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};tK=gV([_V(7,JV),_V(8,nH),_V(9,XV),_V(10,WV),_V(11,KV),_V(12,rH),_V(13,cH)],tK);var nK=class extends NH{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new $H),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new aK(this._optionsService))}catch{this._measureStrategy=this._register(new iK(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};nK=gV([_V(2,XV)],nK);var rK=class extends NH{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},iK=class extends rK{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},aK=class extends rK{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},oK=class extends NH{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new sK(this._window)),this._onDprChange=this._register(new $H),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new $H),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(VH.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(wW(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(wW(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},sK=class extends NH{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new PH),this._onDprChange=this._register(new $H),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(AH(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=wW(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},cK=class extends NH{constructor(){super(),this.linkProviders=[],this._register(AH(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function lK(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function uK(e,t,n,r,i,a,o,s,c){if(!a)return;let l=lK(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var dK=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return uK(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=lK(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};dK=gV([_V(0,aH),_V(1,nH)],dK);var fK=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},pK={};hV(pK,{getSafariVersion:()=>bK,isChromeOS:()=>EK,isFirefox:()=>_K,isIpad:()=>SK,isIphone:()=>CK,isLegacyEdge:()=>vK,isLinux:()=>TK,isMac:()=>xK,isNode:()=>mK,isSafari:()=>yK,isWindows:()=>wK});var mK=typeof process<`u`&&`title`in process,hK=mK?`node`:navigator.userAgent,gK=mK?`node`:navigator.platform,_K=hK.includes(`Firefox`),vK=hK.includes(`Edge`),yK=/^((?!chrome|android).)*safari/i.test(hK);function bK(){if(!yK)return 0;let e=hK.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var xK=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(gK),SK=gK===`iPad`,CK=gK===`iPhone`,wK=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(gK),TK=gK.indexOf(`Linux`)>=0,EK=/\bCrOS\b/.test(hK),DK=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},OK=class extends DK{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},kK=class extends DK{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},AK=!mK&&`requestIdleCallback`in window?kK:OK,jK=class{constructor(){this._queue=new AK}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},MK=class extends NH{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new PH),this._pausedResizeTask=new jK,this._observerDisposable=this._register(new PH),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new $H),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new $H),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new $H),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new $H),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new fK((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new NK(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(AH(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=AH(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};MK=gV([_V(2,XV),_V(3,nH),_V(4,KV),_V(5,$V),_V(6,WV),_V(7,rH),_V(8,cH)],MK);var NK=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function PK(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return LK(i,a,e,t,n,r)+RK(a,t,n,r)+zK(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,KK(Math.abs(i-e),GK(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return KK(IK(a>t?e:i,n)+(s-1)*n.cols+1+FK(a>t?i:e,n),GK(o,r))}function FK(e,t){return e-1}function IK(e,t){return t.cols-e}function LK(e,t,n,r,i,a){return RK(t,r,i,a).length===0?``:KK(WK(e,t,e,t-VK(t,i),!1,i).length,GK(`D`,a))}function RK(e,t,n,r){let i=e-VK(e,n),a=t-VK(t,n);return KK(Math.abs(i-a)-BK(e,t,n),GK(UK(e,t),r))}function zK(e,t,n,r,i,a){let o;o=RK(t,r,i,a).length>0?r-VK(r,i):t;let s=r,c=HK(e,t,n,r,i,a);return KK(WK(e,o,n,s,c===`C`,i).length,GK(c,a))}function BK(e,t,n){let r=0,i=e-VK(e,n),a=t-VK(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=UK(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function VK(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function HK(e,t,n,r,i,a){let o;return o=RK(n,r,i,a).length>0?r-VK(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function UK(e,t){return e>t?`A`:`B`}function WK(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function GK(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function KK(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var qK=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function JK(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var YK=50,XK=15,ZK=50,QK=500,$K=RegExp(`\xA0`,`g`),eq=class extends NH{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new LV,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new $H),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new $H),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new $H),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new $H),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new qK(this._bufferService),this._activeSelectionMode=0,this._register(AH(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace($K,` `)).join(wK?`\r
373
+ `))}},eU=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},tU=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},nU=0,rU=class{constructor(e){this.value=e,this.id=nU++}},iU=2,aU=class{constructor(e){this._size=0,this._options=e,this._leakageMon=XH>0||this._options?.leakWarningThreshold?new QH(e?.onListenerError??_H,this._options?.leakWarningThreshold??XH):void 0,this._perfMon=this._options?._profName?new YH(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new tU(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||_H)(n),zH.None}if(this._disposed)return zH.None;t&&(e=e.bind(t));let r=new rU(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=$H.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof rU?(this._deliveryQueue??=new oU,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=IH(()=>{i?.(),this._removeListener(r)});return n instanceof RH?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*iU<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||_H;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof rU)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},oU=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},sU=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new aU,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new aU,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};sU.INSTANCE=new sU;var cU=sU;function lU(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}cU.INSTANCE.onDidChangeZoomLevel;function uU(e){return cU.INSTANCE.getZoomFactor(e)}cU.INSTANCE.onDidChangeFullscreen;var dU=typeof navigator==`object`?navigator.userAgent:``,fU=dU.indexOf(`Firefox`)>=0,pU=dU.indexOf(`AppleWebKit`)>=0,mU=dU.indexOf(`Chrome`)>=0,hU=!mU&&dU.indexOf(`Safari`)>=0;dU.indexOf(`Electron/`),dU.indexOf(`Android`);var gU=!1;if(typeof VH.matchMedia==`function`){let e=VH.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=VH.matchMedia(`(display-mode: fullscreen)`);gU=e.matches,lU(VH,e,({matches:e})=>{gU&&t.matches||(gU=e)})}function _U(){return gU}var vU=`en`,yU=!1,bU=!1,xU=!1,SU=!1,CU=!1,wU=vU,TU,EU=globalThis,DU;typeof EU.vscode<`u`&&typeof EU.vscode.process<`u`?DU=EU.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(DU=process);var OU=typeof DU?.versions?.electron==`string`&&DU?.type===`renderer`;if(typeof DU==`object`){yU=DU.platform===`win32`,bU=DU.platform===`darwin`,xU=DU.platform===`linux`,xU&&DU.env.SNAP&&DU.env.SNAP_REVISION,DU.env.CI||DU.env.BUILD_ARTIFACTSTAGINGDIRECTORY,wU=vU;let e=DU.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,wU=t.resolvedLanguage||vU,t.languagePack?.translationsConfigFile}catch{}SU=!0}else typeof navigator==`object`&&!OU?(TU=navigator.userAgent,yU=TU.indexOf(`Windows`)>=0,bU=TU.indexOf(`Macintosh`)>=0,(TU.indexOf(`Macintosh`)>=0||TU.indexOf(`iPad`)>=0||TU.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,xU=TU.indexOf(`Linux`)>=0,TU?.indexOf(`Mobi`),CU=!0,wU=globalThis._VSCODE_NLS_LANGUAGE||vU,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var kU=yU,AU=bU,jU=xU,MU=SU;CU&&typeof EU.importScripts==`function`&&EU.origin;var NU=TU,PU=wU,FU;(e=>{function t(){return PU}e.value=t;function n(){return PU.length===2?PU===`en`:PU.length>=3&&PU[0]===`e`&&PU[1]===`n`&&PU[2]===`-`}e.isDefaultVariant=n;function r(){return PU===`en`}e.isDefault=r})(FU||={});var IU=typeof EU.postMessage==`function`&&!EU.importScripts;(()=>{if(IU){let e=[];EU.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),EU.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var LU=!!(NU&&NU.indexOf(`Chrome`)>=0);NU&&NU.indexOf(`Firefox`),!LU&&NU&&NU.indexOf(`Safari`),NU&&NU.indexOf(`Edg/`),NU&&NU.indexOf(`Android`);var RU=typeof navigator==`object`?navigator:{};MU||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||RU&&RU.clipboard&&RU.clipboard.writeText,MU||RU&&RU.clipboard&&RU.clipboard.readText,MU||_U()||RU.keyboard,`ontouchstart`in VH||RU.maxTouchPoints,VH.PointerEvent&&(`ontouchstart`in VH||navigator.maxTouchPoints);var zU=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},BU=new zU,VU=new zU,HU=new zU,UU=Array(230),WU;(e=>{function t(e){return BU.keyCodeToStr(e)}e.toString=t;function n(e){return BU.strToKeyCode(e)}e.fromString=n;function r(e){return VU.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return HU.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return VU.strToKeyCode(e)||HU.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return BU.keyCodeToStr(e)}e.toElectronAccelerator=o})(WU||={});var GU=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new KU([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},KU=class{constructor(e){if(e.length===0)throw xH(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function qU(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return WU.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(fU)switch(t){case 59:return 85;case 60:if(jU)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(AU)return 57}else if(pU&&(AU&&t===93||!AU&&t===92))return 57;return UU[t]||0}var JU=AU?256:2048,YU=512,XU=1024,ZU=AU?2048:256,QU=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=qU(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=JU),this.altKey&&(t|=YU),this.shiftKey&&(t|=XU),this.metaKey&&(t|=ZU),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new GU(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},$U=new WeakMap;function eW(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var tW=class{static getSameOriginWindowChain(e){let t=$U.get(e);if(!t){t=[],$U.set(e,t);let n=e,r;do r=eW(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},nW=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=tW.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},rW=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(mU){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?fU&&!AU?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=hU&&kU?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?fU&&!AU?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},iW=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),aW;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof oW?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:qH.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:iW})})(aW||={});var oW=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?iW:(this._emitter||=new aU,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},sW=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new CH(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new CH(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},cW=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new CH(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=IH(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var lW;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(lW||={});var uW=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new aU,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await qH.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};uW.EMPTY=uW.fromArray([]);function dW(e){return fW(e,0)}function fW(e,t){switch(typeof e){case`object`:return e===null?pW(349,t):Array.isArray(e)?gW(e,t):_W(e,t);case`string`:return hW(e,t);case`boolean`:return mW(e,t);case`number`:return pW(e,t);case`undefined`:return pW(937,t);default:return pW(617,t)}}function pW(e,t){return(t<<5)-t+e|0}function mW(e,t){return pW(e?433:863,t)}function hW(e,t){t=pW(149417,t);for(let n=0,r=e.length;n<r;n++)t=pW(e.charCodeAt(n),t);return t}function gW(e,t){return t=pW(104579,t),e.reduce((e,t)=>fW(t,e),t)}function _W(e,t){return t=pW(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=hW(n,t),fW(e[n],t)),t)}var{registerWindow:vW,getWindow:yW,getDocument:bW,getWindows:xW,getWindowsCount:SW,getWindowId:CW,getWindowById:wW,hasWindow:TW,onDidRegisterWindow:EW,onWillUnregisterWindow:DW,onDidUnregisterWindow:OW}=function(){let e=new Map,t={window:VH,disposables:new RH};e.set(VH.vscodeWindowId,t);let n=new aU,r=new aU,i=new aU;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return zH.None;let a=new RH,o={window:t,disposables:a.add(new RH)};return e.set(t.vscodeWindowId,o),a.add(IH(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(AW(t,zW.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:VH},getDocument(e){return yW(e).document}}}(),kW=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function AW(e,t,n,r){return new kW(e,t,n,r)}function jW(e,t){return function(n){return t(new nW(e,n))}}function MW(e){return function(t){return e(new QU(t))}}var NW=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=jW(yW(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=MW(n)),AW(e,t,i,r)},PW,FW=class extends cW{constructor(e){super(),this.defaultTarget=e&&yW(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},IW=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){_H(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(IW.sort),a.shift().execute();r.set(i,!1)};PW=(t,r,a=0)=>{let o=CW(t),s=new IW(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var LW=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};LW.None=new LW(0,0);function RW(e){let t=e.getBoundingClientRect(),n=yW(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=dW(n),a=r.get(i);if(a)a.users+=1;else{let o=new aU,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(IH(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var zW={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:pU?`webkitAnimationStart`:`animationstart`,ANIMATION_END:pU?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:pU?`webkitAnimationIteration`:`animationiteration`},BW=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=VW(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=VW(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=VW(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=VW(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=VW(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=VW(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=VW(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=VW(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=VW(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=VW(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=VW(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=VW(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=VW(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=VW(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function VW(e){return typeof e==`number`?`${e}px`:e}function HW(e){return new BW(e)}var UW=class{constructor(){this._hooks=new RH,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(IH(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=yW(e)}this._hooks.add(AW(a,zW.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(AW(a,zW.POINTER_UP,e=>this.stopMonitoring(!0)))}};function WW(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var GW;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(GW||={});var KW=class e extends zH{constructor(){super(),this.dispatched=!1,this.targets=new WH,this.ignoreTargets=new WH,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(qH.runAndSubscribe(EW,({window:e,disposables:t})=>{t.add(AW(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(AW(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(AW(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:VH,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=NH(new e),IH(e.INSTANCE.targets.push(t))):zH.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=NH(new e),IH(e.INSTANCE.ignoreTargets.push(t))):zH.None}static isTouchDevice(){return`ontouchstart`in VH||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(GW.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-wH(s.rollingPageX))<30&&Math.abs(s.initialPageY-wH(s.rollingPageY))<30){let e=this.newGestureEvent(GW.Tap,s.initialTarget);e.pageX=wH(s.rollingPageX),e.pageY=wH(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-wH(s.rollingPageX))<30&&Math.abs(s.initialPageY-wH(s.rollingPageY))<30){let e=this.newGestureEvent(GW.Contextmenu,s.initialTarget);e.pageX=wH(s.rollingPageX),e.pageY=wH(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=wH(s.rollingPageX),n=wH(s.rollingPageY),i=wH(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(GW.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===GW.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===GW.Change||t.type===GW.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=PW(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(GW.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(GW.Change,i.initialTarget);a.translationX=r.pageX-wH(i.rollingPageX),a.translationY=r.pageY-wH(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};KW.SCROLL_FRICTION=-.005,KW.HOLD_DELAY=700,KW.CLEAR_TAP_COUNT_TIME=400,SV([WW],KW,`isTouchDevice`,1);var qW=KW,JW=class extends zH{onclick(e,t){this._register(AW(e,zW.CLICK,n=>t(new nW(yW(e),n))))}onmousedown(e,t){this._register(AW(e,zW.MOUSE_DOWN,n=>t(new nW(yW(e),n))))}onmouseover(e,t){this._register(AW(e,zW.MOUSE_OVER,n=>t(new nW(yW(e),n))))}onmouseleave(e,t){this._register(AW(e,zW.MOUSE_LEAVE,n=>t(new nW(yW(e),n))))}onkeydown(e,t){this._register(AW(e,zW.KEY_DOWN,e=>t(new QU(e))))}onkeyup(e,t){this._register(AW(e,zW.KEY_UP,e=>t(new QU(e))))}oninput(e,t){this._register(AW(e,zW.INPUT,t))}onblur(e,t){this._register(AW(e,zW.BLUR,t))}onfocus(e,t){this._register(AW(e,zW.FOCUS,t))}onchange(e,t){this._register(AW(e,zW.CHANGE,t))}ignoreGesture(e){return qW.ignoreTarget(e)}},YW=11,XW=class extends JW{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=YW+`px`,this.domNode.style.height=YW+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new UW),this._register(NW(this.bgDomNode,zW.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(NW(this.domNode,zW.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new FW),this._pointerdownScheduleRepeatTimer=this._register(new sW)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,yW(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},ZW=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},QW=class extends zH{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new aU),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new ZW(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new nG(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=nG.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},$W=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function eG(e,t){let n=t-e;return function(t){return e+n*iG(t)}}function tG(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var nG=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),tG(eG(e,r),eG(i,t),.33)}return eG(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new $W(this.scrollLeft(t),this.scrollTop(t),!1):new $W(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function rG(e){return e**3}function iG(e){return 1-rG(1-e)}var aG=class extends zH{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new sW)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},oG=140,sG=class extends JW{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new aG(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new UW),this._shouldRender=!0,this.domNode=HW(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(AW(this.domNode.domNode,zW.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new XW(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=HW(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(AW(this.slider.domNode,zW.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=RW(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(kU&&a>oG){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},cG=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},lG=class extends sG{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new cG(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},uG=class extends sG{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new cG(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},dG=500,fG=50,pG=!0,mG=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},hG=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(mU){let t=uU(yW(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new mG(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};hG.INSTANCE=new hG;var gG=hG,_G=class extends JW{constructor(e,t,n){super(),this._onScroll=this._register(new aU),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new aU),this.onWillScroll=this._onWillScroll.event,this._options=yG(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new uG(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new lG(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=HW(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=HW(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=HW(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new sW),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=PH(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,AU&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new rW(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=PH(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(AW(this._listenOnDomNode,zW.MOUSE_WHEEL,e=>{this._onMouseWheel(new rW(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=gG.INSTANCE;pG&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!AU&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=fG*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=fG*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(pG&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),dG)}},vG=class extends _G{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function yG(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,AU&&(t.className+=` mac`),t}var bG=class extends zH{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new aU),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new QW({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>PW(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new vG(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(qH.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(IH(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(IH(()=>this._styleElement.remove())),this._register(qH.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
374
+ `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};bG=SV([CV(2,XV),CV(3,lH),CV(4,ZV),CV(5,mH),CV(6,nH),CV(7,dH)],bG);var xG=class extends zH{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(IH(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};xG=SV([CV(1,XV),CV(2,lH),CV(3,aH),CV(4,dH)],xG);var SG=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},CG={full:0,left:0,center:0,right:0},wG={full:0,left:0,center:0,right:0},TG={full:0,left:0,center:0,right:0},EG=class extends zH{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new SG,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(IH(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);wG.full=this._canvas.width,wG.left=e,wG.center=t,wG.right=e,this._refreshDrawHeightConstants(),TG.full=1,TG.left=1,TG.center=1+wG.left,TG.right=1+wG.left+wG.center}_refreshDrawHeightConstants(){CG.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);CG.left=t,CG.center=t,CG.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*CG.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*CG.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*CG.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*CG.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(TG[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-CG[e.position||`full`]/2),wG[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+CG[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};EG=SV([CV(2,XV),CV(3,aH),CV(4,dH),CV(5,nH),CV(6,mH),CV(7,lH)],EG);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
375
+ `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var DG;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(DG||={});var OG;(e=>e.ST=`${$.ESC}\\`)(OG||={});var kG=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};kG=SV([CV(2,XV),CV(3,nH),CV(4,QV),CV(5,dH)],kG);var AG=0,jG=0,MG=0,NG=0,PG={css:`#00000000`,rgba:0},FG;(e=>{function t(e,t,n,r){return r===void 0?`#${BG(e)}${BG(t)}${BG(n)}`:`#${BG(e)}${BG(t)}${BG(n)}${BG(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(FG||={});var IG;(e=>{function t(e,t){if(NG=(t.rgba&255)/255,NG===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return AG=a+Math.round((n-a)*NG),jG=o+Math.round((r-o)*NG),MG=s+Math.round((i-s)*NG),{css:FG.toCss(AG,jG,MG),rgba:FG.toRgba(AG,jG,MG)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=zG.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return FG.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[AG,jG,MG]=zG.toChannels(t),{css:FG.toCss(AG,jG,MG),rgba:t}}e.opaque=i;function a(e,t){return NG=Math.round(t*255),[AG,jG,MG]=zG.toChannels(e.rgba),{css:FG.toCss(AG,jG,MG,NG),rgba:FG.toRgba(AG,jG,MG,NG)}}e.opacity=a;function o(e,t){return NG=e.rgba&255,a(e,NG*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(IG||={});var LG;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return AG=parseInt(e.slice(1,2).repeat(2),16),jG=parseInt(e.slice(2,3).repeat(2),16),MG=parseInt(e.slice(3,4).repeat(2),16),FG.toColor(AG,jG,MG);case 5:return AG=parseInt(e.slice(1,2).repeat(2),16),jG=parseInt(e.slice(2,3).repeat(2),16),MG=parseInt(e.slice(3,4).repeat(2),16),NG=parseInt(e.slice(4,5).repeat(2),16),FG.toColor(AG,jG,MG,NG);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return AG=parseInt(r[1]),jG=parseInt(r[2]),MG=parseInt(r[3]),NG=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),FG.toColor(AG,jG,MG,NG);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[AG,jG,MG,NG]=t.getImageData(0,0,1,1).data,NG!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:FG.toRgba(AG,jG,MG,NG),css:e}}e.toColor=r})(LG||={});var RG;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(RG||={});var zG;(e=>{function t(e,t){if(NG=(t&255)/255,NG===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return AG=a+Math.round((n-a)*NG),jG=o+Math.round((r-o)*NG),MG=s+Math.round((i-s)*NG),FG.toRgba(AG,jG,MG)}e.blend=t;function n(e,t,n){let a=RG.relativeLuminance(e>>8),o=RG.relativeLuminance(t>>8);if(VG(a,o)<n){if(o<a){let o=r(e,t,n),s=VG(a,RG.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>VG(a,RG.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=VG(a,RG.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>VG(a,RG.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=VG(RG.relativeLuminance2(o,s,c),RG.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=VG(RG.relativeLuminance2(o,s,c),RG.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=VG(RG.relativeLuminance2(o,s,c),RG.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=VG(RG.relativeLuminance2(o,s,c),RG.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(zG||={});function BG(e){let t=e.toString(16);return t.length<2?`0`+t:t}function VG(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var HG=class extends VV{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},UG=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new UV}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||BV.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)UG._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||BV.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};UG=SV([CV(0,XV)],UG);function WG(e){return 57508<=e&&e<=57558}function GG(e){return 9472<=e&&e<=9631}function KG(e){return WG(e)||GG(e)}function qG(){return{css:{canvas:JG(),cell:JG()},device:{canvas:JG(),cell:JG(),char:{width:0,height:0,left:0,top:0}}}}function JG(){return{width:0,height:0}}var YG=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new UV,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,ee=0,E=[],te=l!==-1&&u!==-1;for(let D=0;D<m;D++){e.loadCell(D,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let ne=!1,re=D>=ee,ie=D,O=this._workCell;if(f.length>0&&D===f[0][0]&&re){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)re&&=i===this._isCellInSelection(v,t);re&&=!n||a<r[0]||a>=r[1],re?(ne=!0,O=new HG(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),ie=r[1]-1,m=O.getWidth()):ee=r[1]}let k=this._isCellInSelection(D,t),ae=n&&D===a,oe=te&&D>=l&&D<=u,se=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{se=!0});let ce=O.getChars()||BV;if(ce===` `&&(O.isUnderline()||O.isOverline())&&(ce=`\xA0`),T=m*s-c.get(ce,O.isBold(),O.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(k&&w||!k&&!w&&O.bg===y)&&(k&&w&&p.selectionForeground||O.fg===b)&&O.extended.ext===x&&oe===S&&T===C&&!ae&&!ne&&!se&&re){O.isInvisible()?_+=BV:_+=ce,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=O.bg,b=O.fg,x=O.extended.ext,S=oe,C=T,w=k,ne&&a>=D&&a<=ie&&(a=D),!this._coreService.isCursorHidden&&ae&&this._coreService.isCursorInitialized){if(E.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&E.push(`xterm-cursor-blink`),E.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:E.push(`xterm-cursor-outline`);break;case`block`:E.push(`xterm-cursor-block`);break;case`bar`:E.push(`xterm-cursor-bar`);break;case`underline`:E.push(`xterm-cursor-underline`)}}if(O.isBold()&&E.push(`xterm-bold`),O.isItalic()&&E.push(`xterm-italic`),O.isDim()&&E.push(`xterm-dim`),_=O.isInvisible()?BV:O.getChars()||BV,O.isUnderline()&&(E.push(`xterm-underline-${O.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!O.isUnderlineColorDefault())){if(O.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${VV.toColorRGB(O.getUnderlineColor()).join(`,`)})`;else{let e=O.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&O.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}O.isOverline()&&(E.push(`xterm-overline`),_===` `&&(_=`\xA0`)),O.isStrikethrough()&&E.push(`xterm-strikethrough`),oe&&(h.style.textDecoration=`underline`);let A=O.getFgColor(),le=O.getFgColorMode(),ue=O.getBgColor(),de=O.getBgColorMode(),j=!!O.isInverse();if(j){let e=A;A=ue,ue=e;let t=le;le=de,de=t}let fe,pe,me=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{e.options.layer!==`top`&&me||(e.backgroundColorRGB&&(de=50331648,ue=e.backgroundColorRGB.rgba>>8&16777215,fe=e.backgroundColorRGB),e.foregroundColorRGB&&(le=50331648,A=e.foregroundColorRGB.rgba>>8&16777215,pe=e.foregroundColorRGB),me=e.options.layer===`top`)}),!me&&k&&(fe=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,ue=fe.rgba>>8&16777215,de=50331648,me=!0,p.selectionForeground&&(le=50331648,A=p.selectionForeground.rgba>>8&16777215,pe=p.selectionForeground)),me&&E.push(`xterm-decoration-top`);let he;switch(de){case 16777216:case 33554432:he=p.ansi[ue],E.push(`xterm-bg-${ue}`);break;case 50331648:he=FG.toColor(ue>>16,ue>>8&255,ue&255),this._addStyle(h,`background-color:#${XG((ue>>>0).toString(16),`0`,6)}`);break;default:j?(he=p.foreground,E.push(`xterm-bg-257`)):he=p.background}switch(fe||O.isDim()&&(fe=IG.multiplyOpacity(he,.5)),le){case 16777216:case 33554432:O.isBold()&&A<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(A+=8),this._applyMinimumContrast(h,he,p.ansi[A],O,fe,void 0)||E.push(`xterm-fg-${A}`);break;case 50331648:let e=FG.toColor(A>>16&255,A>>8&255,A&255);this._applyMinimumContrast(h,he,e,O,fe,pe)||this._addStyle(h,`color:#${XG(A.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,he,p.foreground,O,fe,pe)||j&&E.push(`xterm-fg-257`)}E.length&&=(h.className=E.join(` `),0),!ae&&!ne&&!se&&re?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),D=ie}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||KG(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=IG.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};YG=SV([CV(1,pH),CV(2,nH),CV(3,lH),CV(4,QV),CV(5,aH),CV(6,mH)],YG);function XG(e,t,n){for(;e.length<n;)e=t+e;return e}var ZG=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},QG=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function $G(){return new QG}var eK=`xterm-dom-renderer-owner-`,tK=`xterm-rows`,nK=`xterm-fg-`,rK=`xterm-bg-`,iK=`xterm-focus`,aK=`xterm-selection`,oK=1,sK=class extends zH{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=oK++,this._rowElements=[],this._selectionRenderModel=$G(),this.onRequestRedraw=this._register(new aU).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(tK),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(aK),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=qG(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(YG,document),this._element.classList.add(eK+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(IH(()=>{this._element.classList.remove(eK+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new ZG(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tK} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tK} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tK} .xterm-dim { color: ${IG.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tK}.${iK} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${tK}.${iK} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${tK}.${iK} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tK} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tK} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tK} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tK} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tK} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${aK} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${aK} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${aK} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${nK}${n} { color: ${r.css}; }${this._terminalSelector} .${nK}${n}.xterm-dim { color: ${IG.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${rK}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${nK}257 { color: ${IG.opaque(e.background).css}; }${this._terminalSelector} .${nK}257.xterm-dim { color: ${IG.multiplyOpacity(IG.opaque(e.background),.5).css}; }${this._terminalSelector} .${rK}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(iK),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(iK),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${eK}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};sK=SV([CV(7,eH),CV(8,cH),CV(9,nH),CV(10,XV),CV(11,QV),CV(12,lH),CV(13,mH)],sK);var cK=class extends zH{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new aU),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new dK(this._optionsService))}catch{this._measureStrategy=this._register(new uK(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};cK=SV([CV(2,nH)],cK);var lK=class extends zH{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},uK=class extends lK{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},dK=class extends lK{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},fK=class extends zH{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new pK(this._window)),this._onDprChange=this._register(new aU),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new aU),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(qH.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(AW(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(AW(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},pK=class extends zH{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new BH),this._onDprChange=this._register(new aU),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(IH(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=AW(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},mK=class extends zH{constructor(){super(),this.linkProviders=[],this._register(IH(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function hK(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function gK(e,t,n,r,i,a,o,s,c){if(!a)return;let l=hK(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var _K=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return gK(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=hK(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};_K=SV([CV(0,dH),CV(1,cH)],_K);var vK=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},yK={};xV(yK,{getSafariVersion:()=>EK,isChromeOS:()=>MK,isFirefox:()=>CK,isIpad:()=>OK,isIphone:()=>kK,isLegacyEdge:()=>wK,isLinux:()=>jK,isMac:()=>DK,isNode:()=>bK,isSafari:()=>TK,isWindows:()=>AK});var bK=typeof process<`u`&&`title`in process,xK=bK?`node`:navigator.userAgent,SK=bK?`node`:navigator.platform,CK=xK.includes(`Firefox`),wK=xK.includes(`Edge`),TK=/^((?!chrome|android).)*safari/i.test(xK);function EK(){if(!TK)return 0;let e=xK.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var DK=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(SK),OK=SK===`iPad`,kK=SK===`iPhone`,AK=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(SK),jK=SK.indexOf(`Linux`)>=0,MK=/\bCrOS\b/.test(xK),NK=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},PK=class extends NK{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},FK=class extends NK{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},IK=!bK&&`requestIdleCallback`in window?FK:PK,LK=class{constructor(){this._queue=new IK}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},RK=class extends zH{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new BH),this._pausedResizeTask=new LK,this._observerDisposable=this._register(new BH),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new aU),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new aU),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new aU),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new aU),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new vK((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new zK(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(IH(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=IH(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};RK=SV([CV(2,nH),CV(3,cH),CV(4,QV),CV(5,aH),CV(6,XV),CV(7,lH),CV(8,mH)],RK);var zK=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function BK(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return UK(i,a,e,t,n,r)+WK(a,t,n,r)+GK(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,QK(Math.abs(i-e),ZK(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return QK(HK(a>t?e:i,n)+(s-1)*n.cols+1+VK(a>t?i:e,n),ZK(o,r))}function VK(e,t){return e-1}function HK(e,t){return t.cols-e}function UK(e,t,n,r,i,a){return WK(t,r,i,a).length===0?``:QK(XK(e,t,e,t-qK(t,i),!1,i).length,ZK(`D`,a))}function WK(e,t,n,r){let i=e-qK(e,n),a=t-qK(t,n);return QK(Math.abs(i-a)-KK(e,t,n),ZK(YK(e,t),r))}function GK(e,t,n,r,i,a){let o;o=WK(t,r,i,a).length>0?r-qK(r,i):t;let s=r,c=JK(e,t,n,r,i,a);return QK(XK(e,o,n,s,c===`C`,i).length,ZK(c,a))}function KK(e,t,n){let r=0,i=e-qK(e,n),a=t-qK(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=YK(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function qK(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function JK(e,t,n,r,i,a){let o;return o=WK(n,r,i,a).length>0?r-qK(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function YK(e,t){return e>t?`A`:`B`}function XK(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function ZK(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function QK(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var $K=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function eq(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var tq=50,nq=15,rq=50,iq=500,aq=RegExp(`\xA0`,`g`),oq=class extends zH{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new UV,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new aU),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new aU),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new aU),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new aU),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new $K(this._bufferService),this._activeSelectionMode=0,this._register(IH(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(aq,` `)).join(AK?`\r
376
376
  `:`
377
- `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),TK&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=JK(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=lK(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-YK),YK),t/=YK,t/Math.abs(t)+Math.round(t*(XK-1)))}shouldForceSelection(e){return xK?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),ZK)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(xK&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<QK&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=PK(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=JK(n,this._bufferService.cols)}};eq=gV([_V(3,WV),_V(4,KV),_V(5,iH),_V(6,XV),_V(7,aH),_V(8,rH)],eq);var tq=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},nq=class{constructor(){this._color=new tq,this._css=new tq}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},rq=Object.freeze((()=>{let e=[jG.toColor(`#2e3436`),jG.toColor(`#cc0000`),jG.toColor(`#4e9a06`),jG.toColor(`#c4a000`),jG.toColor(`#3465a4`),jG.toColor(`#75507b`),jG.toColor(`#06989a`),jG.toColor(`#d3d7cf`),jG.toColor(`#555753`),jG.toColor(`#ef2929`),jG.toColor(`#8ae234`),jG.toColor(`#fce94f`),jG.toColor(`#729fcf`),jG.toColor(`#ad7fa8`),jG.toColor(`#34e2e2`),jG.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:kG.toCss(r,i,a),rgba:kG.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:kG.toCss(n,n,n),rgba:kG.toRgba(n,n,n)})}return e})()),iq=jG.toColor(`#ffffff`),aq=jG.toColor(`#000000`),oq=jG.toColor(`#ffffff`),sq=aq,cq={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},lq=iq,uq=class extends NH{constructor(e){super(),this._optionsService=e,this._contrastCache=new nq,this._halfContrastCache=new nq,this._onChangeColors=this._register(new $H),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:iq,background:aq,cursor:oq,cursorAccent:sq,selectionForeground:void 0,selectionBackgroundTransparent:cq,selectionBackgroundOpaque:AG.blend(aq,cq),selectionInactiveBackgroundTransparent:cq,selectionInactiveBackgroundOpaque:AG.blend(aq,cq),scrollbarSliderBackground:AG.opacity(iq,.2),scrollbarSliderHoverBackground:AG.opacity(iq,.4),scrollbarSliderActiveBackground:AG.opacity(iq,.5),overviewRulerBorder:iq,ansi:rq.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=dq(e.foreground,iq),t.background=dq(e.background,aq),t.cursor=AG.blend(t.background,dq(e.cursor,oq)),t.cursorAccent=AG.blend(t.background,dq(e.cursorAccent,sq)),t.selectionBackgroundTransparent=dq(e.selectionBackground,cq),t.selectionBackgroundOpaque=AG.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=dq(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=AG.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?dq(e.selectionForeground,OG):void 0,t.selectionForeground===OG&&(t.selectionForeground=void 0),AG.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=AG.opacity(t.selectionBackgroundTransparent,.3)),AG.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=AG.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=dq(e.scrollbarSliderBackground,AG.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=dq(e.scrollbarSliderHoverBackground,AG.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=dq(e.scrollbarSliderActiveBackground,AG.opacity(t.foreground,.5)),t.overviewRulerBorder=dq(e.overviewRulerBorder,lq),t.ansi=rq.slice(),t.ansi[0]=dq(e.black,rq[0]),t.ansi[1]=dq(e.red,rq[1]),t.ansi[2]=dq(e.green,rq[2]),t.ansi[3]=dq(e.yellow,rq[3]),t.ansi[4]=dq(e.blue,rq[4]),t.ansi[5]=dq(e.magenta,rq[5]),t.ansi[6]=dq(e.cyan,rq[6]),t.ansi[7]=dq(e.white,rq[7]),t.ansi[8]=dq(e.brightBlack,rq[8]),t.ansi[9]=dq(e.brightRed,rq[9]),t.ansi[10]=dq(e.brightGreen,rq[10]),t.ansi[11]=dq(e.brightYellow,rq[11]),t.ansi[12]=dq(e.brightBlue,rq[12]),t.ansi[13]=dq(e.brightMagenta,rq[13]),t.ansi[14]=dq(e.brightCyan,rq[14]),t.ansi[15]=dq(e.brightWhite,rq[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=dq(e.extendedAnsi[r],rq[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};uq=gV([_V(0,XV)],uq);function dq(e,t){if(e!==void 0)try{return jG.toColor(e)}catch{}return t}var fq=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},pq=class{constructor(){this._services=new fq,this._services.set(JV,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=VV(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},mq={trace:0,debug:1,info:2,warn:3,error:4,off:5},hq=`xterm.js: `,gq=class extends NH{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),_q=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=mq[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:hq)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};gq=gV([_V(0,XV)],gq);var _q,vq=class extends NH{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new $H),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new $H),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new $H),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},yq=3,bq=Object.freeze(new FV),xq=0,Sq=2,Cq=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*yq);let r=t||LV.fromCharData([0,NV,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*yq+0],n=t&2097151;return[this._data[e*yq+1],t&2097152?this._combined[e]:n?kV(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*yq+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*yq+0]=e|2097152|t[2]<<22):this._data[e*yq+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*yq+0]>>22}hasWidth(e){return this._data[e*yq+0]&12582912}getFg(e){return this._data[e*yq+1]}getBg(e){return this._data[e*yq+2]}hasContent(e){return this._data[e*yq+0]&4194303}getCodePoint(e){let t=this._data[e*yq+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*yq+0]&2097152}getString(e){let t=this._data[e*yq+0];return t&2097152?this._combined[e]:t&2097151?kV(t&2097151):``}isProtected(e){return this._data[e*yq+2]&536870912}loadCell(e,t){return xq=e*yq,t.content=this._data[xq+0],t.fg=this._data[xq+1],t.bg=this._data[xq+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*yq+0]=t.content,this._data[e*yq+1]=t.fg,this._data[e*yq+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*yq+0]=t|n<<22,this._data[e*yq+1]=r.fg,this._data[e*yq+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*yq+0];r&2097152?this._combined[e]+=kV(t):r&2097151?(this._combined[e]=kV(r&2097151)+kV(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*yq+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new LV;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new LV;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*Sq<this._data.buffer.byteLength;let n=e*yq;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*Sq<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*Sq<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*yq+0]&4194303)return e+(this._data[e*yq+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*yq+0]&4194303||this._data[e*yq+2]&50331648)return e+(this._data[e*yq+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<yq;e++)this._data[(n+i)*yq+e]=a[(t+i)*yq+e];a[(t+i)*yq+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<yq;e++)this._data[(n+i)*yq+e]=a[(t+i)*yq+e];a[(t+i)*yq+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*yq+0],n=e&2097151,a=e&2097152?this._combined[t]:n?kV(n):PV;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function wq(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=Oq(u,d,t),p=1,m=0;for(;p<u.length;){let e=Oq(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function Tq(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function Eq(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function Dq(e,t,n){let r=[],i=e.map((n,r)=>Oq(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=Oq(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function Oq(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var kq=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new $H),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),OH(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};kq._nextId=1;var Aq=kq,jq={},Mq=jq.B;jq[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},jq.A={"#":`£`},jq.B=void 0,jq[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},jq.C=jq[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},jq.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},jq.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},jq.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},jq.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},jq.E=jq[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},jq.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},jq.H=jq[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},jq[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Nq=4294967295,Pq=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=bq.clone(),this.savedCharset=Mq,this.markers=[],this._nullCell=LV.fromCharData([0,NV,1,0]),this._whitespaceCell=LV.fromCharData([0,PV,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new AK,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new vq(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new IV),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new IV),this._whitespaceCell}getBlankLine(e,t){return new Cq(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Nq?Nq:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=bq);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new vq(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(bq),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new Cq(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new Cq(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=wq(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(bq),n);if(r.length>0){let n=Tq(this.lines,r);Eq(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(bq),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new Cq(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(bq),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=Dq(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(bq,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=Oq(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Aq(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Fq=class extends NH{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new $H),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Pq(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Pq(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Iq=2,Lq=1,Rq=class extends NH{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new $H),this.onResize=this._onResize.event,this._onScroll=this._register(new $H),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Iq),this.rows=Math.max(e.rawOptions.rows||0,Lq),this.buffers=this._register(new Fq(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Rq=gV([_V(0,XV)],Rq);var zq={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:xK,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Bq=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Vq=class extends NH{constructor(e){super(),this._onOptionChange=this._register(new $H),this.onOptionChange=this._onOptionChange.event;let t={...zq};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(AH(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in zq))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in zq))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=zq[e],!Hq(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=zq[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Bq.includes(t)?t:zq[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Hq(e){return e===`block`||e===`underline`||e===`bar`}function Uq(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Uq(e[r],t-1);return n}var Wq=Object.freeze({insertMode:!1}),Gq=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Kq=class extends NH{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new $H),this.onData=this._onData.event,this._onUserInput=this._register(new $H),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new $H),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new $H),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Uq(Wq),this.decPrivateModes=Uq(Gq)}reset(){this.modes=Uq(Wq),this.decPrivateModes=Uq(Gq)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Kq=gV([_V(0,WV),_V(1,YV),_V(2,XV)],Kq);var qq={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Jq(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Yq=String.fromCharCode,Xq={DEFAULT:e=>{let t=[Jq(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Yq(t[0])}${Yq(t[1])}${Yq(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Jq(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Jq(e,!0)};${e.x};${e.y}${t}`}},Zq=class extends NH{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new $H),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(qq))this.addProtocol(e,qq[e]);for(let e of Object.keys(Xq))this.addEncoding(e,Xq[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};Zq=gV([_V(0,WV),_V(1,KV),_V(2,XV)],Zq);var Qq=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],$q=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],eJ;function tJ(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var nJ=class{constructor(){if(this.version=`6`,!eJ){eJ=new Uint8Array(65536),eJ.fill(1),eJ[0]=0,eJ.fill(0,1,32),eJ.fill(0,127,160),eJ.fill(2,4352,4448),eJ[9001]=2,eJ[9002]=2,eJ.fill(2,11904,42192),eJ[12351]=1,eJ.fill(2,44032,55204),eJ.fill(2,63744,64256),eJ.fill(2,65040,65050),eJ.fill(2,65072,65136),eJ.fill(2,65280,65377),eJ.fill(2,65504,65511);for(let e=0;e<Qq.length;++e)eJ.fill(0,Qq[e][0],Qq[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?eJ[e]:tJ(e,$q)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=rJ.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return rJ.createPropertyValue(0,n,r)}},rJ=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new $H,this.onChange=this._onChange.event;let e=new nJ;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},iJ=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function aJ(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var oJ=2147483647,sJ=256,cJ=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>sJ)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>oJ?oJ:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>oJ?oJ:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,oJ):e}},lJ=[],uJ=class{constructor(){this._state=0,this._active=lJ,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=lJ}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=lJ,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lJ,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,AV(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=lJ,this._id=-1,this._state=0}}},dJ=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=AV(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},fJ=[],pJ=class{constructor(){this._handlers=Object.create(null),this._active=fJ,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fJ}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=fJ,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||fJ,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,AV(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=fJ,this._ident=0}},mJ=new cJ;mJ.addParam(0);var hJ=class{constructor(e){this._handler=e,this._data=``,this._params=mJ,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():mJ,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=AV(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=mJ,this._data=``,this._hitLimit=!1,e));return this._params=mJ,this._data=``,this._hitLimit=!1,t}},gJ=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},_J=160,vJ=function(){let e=new gJ(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(_J,0,2,0),e.add(_J,8,5,8),e.add(_J,6,0,6),e.add(_J,11,0,11),e.add(_J,13,13,13),e}(),yJ=class extends NH{constructor(e=vJ){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new cJ,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(AH(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new uJ),this._dcsParser=this._register(new pJ),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:_J)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<_J||++i>=t||(r=e[i])<32||r>126&&r<_J||++i>=t||(r=e[i])<32||r>126&&r<_J||++i>=t||(r=e[i])<32||r>126&&r<_J){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<_J){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<_J){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},bJ=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,xJ=/^[\da-f]+$/;function SJ(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=bJ.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),xJ.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function CJ(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function wJ(e,t=16){let[n,r,i]=e;return`rgb:${CJ(n,t)}/${CJ(r,t)}/${CJ(i,t)}`}var TJ={"(":0,")":1,"*":2,"+":3,"-":1,".":2},EJ=131072,DJ=10;function OJ(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var kJ=5e3,AJ=0,jJ=class extends NH{constructor(e,t,n,r,i,a,o,s,c=new yJ){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new jV,this._utf8Decoder=new MV,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=bq.clone(),this._eraseAttrDataInternal=bq.clone(),this._onRequestBell=this._register(new $H),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new $H),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new $H),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new $H),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new $H),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new $H),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new $H),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new $H),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new $H),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new $H),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new $H),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new $H),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new $H),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new MJ(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(xG.IND,()=>this.index()),this._parser.setExecuteHandler(xG.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(xG.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new dJ(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new dJ(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new dJ(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new dJ(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new dJ(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new dJ(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new dJ(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new dJ(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new dJ(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new dJ(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new dJ(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new dJ(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in jq)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new hJ((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),kJ))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${kJ} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>EJ&&(a=this._parseStack.position+EJ)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<EJ&&(this._parseBuffer=new Uint32Array(Math.min(e.length,EJ))),o||this._dirtyRowTracker.clearRange(),e.length>EJ)for(let t=a;t<e.length;t+=EJ){let a=t+EJ<e.length?t+EJ:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=rJ.extractWidth(t);let n=rJ.extractShouldJoin(t),m=n?rJ.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(kV(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof Cq&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!OJ(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new hJ(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new dJ(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(bq));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=rJ.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Mq),this._charsetService.setgCharset(1,Mq),this._charsetService.setgCharset(2,Mq),this._charsetService.setgCharset(3,Mq);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=FV.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=bq.fg,e.bg=bq.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=bq.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=bq.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=bq.fg&16777215,r.bg&=-67108864,r.bg|=bq.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=bq.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!OJ(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>DJ&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>DJ&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(NJ(n)){if(r===`?`)t.push({type:0,index:n});else{let e=SJ(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=SJ(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);NJ(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Mq),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(TJ[e[0]],jq[e[1]]||Mq),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=bq.clone(),this._eraseAttrDataInternal=bq.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new LV;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},MJ=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(AJ=e,e=t,t=AJ),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};MJ=gV([_V(0,WV)],MJ);function NJ(e){return 0<=e&&e<256}var PJ=5e7,FJ=12,IJ=50,LJ=class extends NH{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new $H),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>PJ)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=FJ?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=FJ)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>IJ&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},RJ=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};RJ=gV([_V(0,WV)],RJ);var zJ=!1,BJ=class extends NH{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new PH),this._onBinary=this._register(new $H),this.onBinary=this._onBinary.event,this._onData=this._register(new $H),this.onData=this._onData.event,this._onLineFeed=this._register(new $H),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new $H),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new $H),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new $H),this._instantiationService=new pq,this.optionsService=this._register(new Vq(e)),this._instantiationService.setService(XV,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Rq)),this._instantiationService.setService(WV,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gq)),this._instantiationService.setService(YV,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Kq)),this._instantiationService.setService(KV,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Zq)),this._instantiationService.setService(GV,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(rJ)),this._instantiationService.setService(QV,this.unicodeService),this._charsetService=this._instantiationService.createInstance(iJ),this._instantiationService.setService(qV,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(RJ),this._instantiationService.setService(ZV,this._oscLinkService),this._inputHandler=this._register(new jJ(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(VH.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(VH.forward(this._bufferService.onResize,this._onResize)),this._register(VH.forward(this.coreService.onData,this._onData)),this._register(VH.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new LJ((e,t)=>this._inputHandler.parse(e,t))),this._register(VH.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new $H),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!zJ&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),zJ=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Iq),t=Math.max(t,Lq),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(aJ.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(aJ(this._bufferService),!1))),this._windowsWrappingHeuristics.value=AH(()=>{for(let t of e)t.dispose()})}}},VJ={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function HJ(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=VJ[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var UJ=0,WJ=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new AK,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new AK,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(UJ=this._search(t),UJ===-1)||this._getKey(this._array[UJ])!==t)return!1;do if(this._array[UJ]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(UJ),!0;while(++UJ<this._array.length&&this._getKey(this._array[UJ])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(UJ=this._search(e),!(UJ<0||UJ>=this._array.length)&&this._getKey(this._array[UJ])===e))do yield this._array[UJ];while(++UJ<this._array.length&&this._getKey(this._array[UJ])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(UJ=this._search(e),!(UJ<0||UJ>=this._array.length)&&this._getKey(this._array[UJ])===e))do t(this._array[UJ]);while(++UJ<this._array.length&&this._getKey(this._array[UJ])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},GJ=0,KJ=0,qJ=class extends NH{constructor(){super(),this._decorations=new WJ(e=>e?.marker.line),this._onDecorationRegistered=this._register(new $H),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new $H),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(AH(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new JJ(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{GJ=t.options.x??0,KJ=GJ+(t.options.width??1),e>=GJ&&e<KJ&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},JJ=class extends MH{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new $H),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new $H),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?jG.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?jG.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},YJ=1e3,XJ=class{constructor(e,t=YJ){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},ZJ=20,QJ=class extends NH{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new XJ(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
378
- `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(wW(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(AH(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<ZJ+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
379
- `&&(this._liveRegionLineCount++,this._liveRegionLineCount===ZJ+1&&(this._liveRegion.textContent+=xV.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};QJ=gV([_V(1,JV),_V(2,rH),_V(3,aH)],QJ);var $J=class extends NH{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new $H),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new $H),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(AH(()=>{OH(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(wW(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(wW(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(wW(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(wW(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&eY(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,OH(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};$J=gV([_V(1,iH),_V(2,aH),_V(3,WV),_V(4,lH)],$J);function eY(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var tY=class extends BJ{constructor(e={}){super(e),this._linkifier=this._register(new PH),this.browser=pK,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new PH),this._onCursorMove=this._register(new $H),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new $H),this.onKey=this._onKey.event,this._onRender=this._register(new $H),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new $H),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new $H),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new $H),this.onBell=this._onBell.event,this._onFocus=this._register(new $H),this._onBlur=this._register(new $H),this._onA11yCharEmitter=this._register(new $H),this._onA11yTabEmitter=this._register(new $H),this._onWillOpen=this._register(new $H),this._setup(),this._decorationService=this._instantiationService.createInstance(qJ),this._instantiationService.setService($V,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(cK),this._instantiationService.setService(lH,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(eH)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(VH.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(VH.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(VH.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(VH.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(AH(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=AG.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${wJ(r)}${SG.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=kG.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=kG.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(QJ,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(wW(this.element,`copy`,e=>{this.hasSelection()&&wV(e,this._selectionService)}));let e=e=>TV(e,this.textarea,this.coreService,this.optionsService);this._register(wW(this.textarea,`paste`,e)),this._register(wW(this.element,`paste`,e)),_K?this._register(wW(this.element,`mousedown`,e=>{e.button===2&&OV(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(wW(this.element,`contextmenu`,e=>{OV(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),TK&&this._register(wW(this.element,`auxclick`,e=>{e.button===1&&DV(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(wW(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(wW(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(wW(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(wW(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(wW(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(wW(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(wW(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(wW(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,yV.get()),EK||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(oK,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(rH,this._coreBrowserService),this._register(wW(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(wW(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(nK,this._document,this._helperContainer),this._instantiationService.setService(nH,this._charSizeService),this._themeService=this._instantiationService.createInstance(uq),this._instantiationService.setService(cH,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(LG),this._instantiationService.setService(sH,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(MK,this.rows,this.screenElement)),this._instantiationService.setService(aH,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(CG,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dK),this._instantiationService.setService(iH,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance($J,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(mG,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(eq,this.element,this.screenElement,r)),this._instantiationService.setService(oH,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(VH.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(hG,this.screenElement)),this._register(wW(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(QJ,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bG,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bG,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(tK,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(wW(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(wW(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){EV(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=HJ(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(nY(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(bq));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function nY(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var rY=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},iY=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new LV)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},aY=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new iY(t)}getNullCell(){return new LV}},oY=class extends NH{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new $H),this.onBufferChange=this._onBufferChange.event,this._normal=new aY(this._core.buffers.normal,`normal`),this._alternate=new aY(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},sY=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},cY=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},lY=[`cols`,`rows`],uY=0,dY=class extends NH{constructor(e){super(),this._core=this._register(new tY(e)),this._addonManager=this._register(new rY),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(lY.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new sY(this._core),this._parser}get unicode(){return this._checkProposedApi(),new cY(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new oY(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
380
- `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return yV.get()},set promptLabel(e){yV.set(e)},get tooMuchOutput(){return xV.get()},set tooMuchOutput(e){xV.set(e)}}}_verifyIntegers(...e){for(uY of e)if(uY===1/0||isNaN(uY)||uY%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(uY of e)if(uY&&(uY===1/0||isNaN(uY)||uY%1!=0||uY<0))throw Error(`This API only accepts positive integers`)}},fY=2,pY=1,mY=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(fY,Math.floor(u/e.css.cell.width)),rows:Math.max(pY,Math.floor(l/e.css.cell.height))}}},hY=class{constructor(e,t,n,r={}){this._terminal=e,this._regex=t,this._handler=n,this._options=r}provideLinks(e,t){let n=_Y.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(n))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(t,n)=>{if(this._options.hover){let{range:r}=e;this._options.hover(t,n,r)}},e))}};function gY(e){try{let t=new URL(e),n=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(n.toLocaleLowerCase())}catch{return!1}}var _Y=class e{static computeLink(t,n,r,i){let a=new RegExp(n.source,(n.flags||``)+`g`),[o,s]=e._getWindowedLineStrings(t-1,r),c=o.join(``),l,u=[];for(;l=a.exec(c);){let t=l[0];if(!gY(t))continue;let[n,a]=e._mapStrIdx(r,s,0,l.index),[o,c]=e._mapStrIdx(r,n,a,t.length);if(n===-1||a===-1||o===-1||c===-1)continue;let d={start:{x:a+1,y:n+1},end:{x:c,y:o+1}};u.push({range:d,text:t,activate:i})}return u}static _getWindowedLineStrings(e,t){let n,r=e,i=e,a=0,o=``,s=[];if(n=t.buffer.active.getLine(e)){let e=n.translateToString(!0);if(n.isWrapped&&e[0]!==` `){for(a=0;(n=t.buffer.active.getLine(--r))&&a<2048&&(o=n.translateToString(!0),a+=o.length,s.push(o),n.isWrapped&&o.indexOf(` `)===-1););s.reverse()}for(s.push(e),a=0;(n=t.buffer.active.getLine(++i))&&n.isWrapped&&a<2048&&(o=n.translateToString(!0),a+=o.length,s.push(o),o.indexOf(` `)===-1););}return[s,r]}static _mapStrIdx(e,t,n,r){let i=e.buffer.active,a=i.getNullCell(),o=n;for(;r;){let e=i.getLine(t);if(!e)return[-1,-1];for(let n=o;n<e.length;++n){e.getCell(n,a);let o=a.getChars();if(a.getWidth()&&(r-=o.length||1,n===e.length-1&&o===``)){let e=i.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,a),a.getWidth()===2&&(r+=1))}if(r<0)return[t,n]}t++,o=0}return[t,o]}},vY=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function yY(e,t){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}var bY=class{constructor(e=yY,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;let t=this._options,n=t.urlRegex||vY;this._linkProvider=this._terminal.registerLinkProvider(new hY(this._terminal,n,this._handler,t))}dispose(){this._linkProvider?.dispose()}},xY={background:`#09090b`,foreground:`#f4f4f5`,cursor:`#38bdf8`,cursorAccent:`#09090b`,selectionBackground:`rgba(56, 189, 248, 0.3)`,black:`#27272a`,red:`#f87171`,green:`#4ade80`,yellow:`#facc15`,blue:`#60a5fa`,magenta:`#c084fc`,cyan:`#38bdf8`,white:`#f4f4f5`,brightBlack:`#52525b`,brightRed:`#ef4444`,brightGreen:`#22c55e`,brightYellow:`#eab308`,brightBlue:`#3b82f6`,brightMagenta:`#a855f7`,brightCyan:`#06b6d4`,brightWhite:`#ffffff`},SY={background:`#ffffff`,foreground:`#18181b`,cursor:`#0284c7`,cursorAccent:`#ffffff`,selectionBackground:`rgba(2, 132, 199, 0.2)`,black:`#18181b`,red:`#dc2626`,green:`#16a34a`,yellow:`#ca8a04`,blue:`#2563eb`,magenta:`#9333ea`,cyan:`#0891b2`,white:`#e4e4e7`,brightBlack:`#71717a`,brightRed:`#b91c1c`,brightGreen:`#15803d`,brightYellow:`#a16207`,brightBlue:`#1d4ed8`,brightMagenta:`#7e22ce`,brightCyan:`#0e7490`,brightWhite:`#27272a`};function CY(e){if(!e)return``;let t=e.split(/[\\/]/).filter(Boolean);return t.length<=3?e:`…/`+t.slice(-3).join(`/`)}function wY({id:e,cwd:t,isActive:n,isPanelOpen:r,renaming:i,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m}){let h=(0,d.useRef)(null),g=(0,d.useRef)(null),_=(0,d.useRef)(null),v=(0,d.useContext)(p)===`dark`,y=(0,d.useRef)({cwd:t,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m});return y.current={cwd:t,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m},(0,d.useEffect)(()=>{g.current&&(g.current.options.theme=v?xY:SY)},[v]),(0,d.useEffect)(()=>{if(!h.current)return;let t=new dY({cursorBlink:!0,cursorStyle:`block`,fontSize:13,fontFamily:`'JetBrains Mono', 'Fira Code', ui-monospace, Menlo, Monaco, 'Courier New', monospace`,lineHeight:1.2,theme:v?xY:SY}),n=new mY;t.loadAddon(n),t.loadAddon(new bY),t.open(h.current),n.fit(),g.current=t,_.current=n,y.current.registerClear(e,()=>{t.clear()}),y.current.openTerminal?.(e,y.current.cwd,t.cols,t.rows);let r=null,i=0,a=()=>{let t=Date.now();t-i<1e3?r||=setTimeout(()=>{r=null,i=Date.now(),y.current.getTerminalCwd?.(e)},1e3-(t-i)):(i=t,y.current.getTerminalCwd?.(e))},o=t.onData(t=>{y.current.sendTerminalInput?.(e,t),(t.includes(`\r`)||t.includes(`
381
- `))&&a()}),s=y.current.subscribeTerminal?.(e,{onData:n=>{t.write(n);let r=n.match(/\x1b\]7;file:\/\/[^/]*([^\x07\x1b]+)(?:\x07|\x1b\\)/);if(r&&r[1])try{let t=decodeURIComponent(r[1]);y.current.onCwdUpdate(e,t)}catch{}},onCwd:t=>{y.current.onCwdUpdate(e,t)},onExit:e=>{t.writeln(`\r\n\x1b[90m[Process completed (exit code ${e??0})]\x1b[0m`)},onError:e=>{t.writeln(`\r\n\x1b[31m[Terminal error: ${e}]\x1b[0m`)}})??(()=>{}),c=new ResizeObserver(()=>{if(h.current&&h.current.clientWidth>0&&h.current.clientHeight>0)try{n.fit(),t.cols>0&&t.rows>0&&y.current.resizeTerminal?.(e,t.cols,t.rows)}catch{}});return c.observe(h.current),()=>{o.dispose(),s(),c.disconnect(),t.dispose(),y.current.closeTerminal?.(e)}},[e]),(0,d.useEffect)(()=>{if(!i&&r&&n&&_.current&&g.current&&h.current){y.current.getTerminalCwd?.(e);let t=setTimeout(()=>{try{_.current?.fit(),g.current?.focus()}catch{}},50);return()=>clearTimeout(t)}},[r,n,e,i]),(0,A.jsx)(`div`,{ref:h,className:`h-full w-full p-2 bg-white dark:bg-zinc-950 overflow-hidden ${n?`block`:`hidden`}`})}function TY({open:e,onClose:t,cwd:n,confinedRoot:r,confinement:i,unavailable:a,onSetWorkspaceRoot:o,openTerminal:s,sendTerminalInput:c,getTerminalCwd:l,resizeTerminal:u,closeTerminal:f,subscribeTerminal:p}){let[m,h]=(0,d.useState)(e);(0,d.useEffect)(()=>{e&&h(!0)},[e]);let[g,_]=(0,d.useState)([{id:`term-1`,title:`terminal 1`}]),[v,y]=(0,d.useState)(`term-1`),[b,x]=(0,d.useState)(null),[S,C]=(0,d.useState)(``),[w,T]=(0,d.useState)({}),[ee,E]=(0,d.useState)(!1),[te,D]=(0,d.useState)(!1),ne=(0,d.useRef)(new Map),re=(0,d.useCallback)((e,t)=>{ne.current.set(e,t)},[]),ie=(0,d.useCallback)((e,t)=>{T(n=>({...n,[e]:t}))},[]),O=(0,d.useCallback)(()=>{let e=g.length+1,t=`term-${Date.now()}-${e}`,n={id:t,title:`terminal ${e}`};_(e=>[...e,n]),y(t)},[g.length]),k=(0,d.useCallback)((e,n)=>{n.stopPropagation(),g.length<=1?t():(_(t=>{let n=t.filter(t=>t.id!==e);if(v===e){let r=t.findIndex(t=>t.id===e),i=n[Math.max(0,r-1)]?.id??n[0]?.id;y(i)}return n}),ne.current.delete(e),T(t=>{let n={...t};return delete n[e],n}))},[g.length,v,t]),ae=(e,t)=>{t.stopPropagation(),x(e.id),C(e.title)},oe=()=>{if(b){let e=S.trim();e&&_(t=>t.map(t=>t.id===b?{...t,title:e}:t)),x(null)}},se=e=>{e.key===`Enter`?oe():e.key===`Escape`&&x(null)},ce=(0,d.useCallback)(()=>{let e=ne.current.get(v);e&&e()},[v]),le=w[v]||n||``;return m?(0,A.jsxs)(`div`,{className:`flex-col border-t border-zinc-200 dark:border-zinc-800 bg-zinc-100 dark:bg-zinc-900 transition-all duration-150 ${e?`flex`:`hidden`} ${ee?`h-[85vh]`:`h-72`} relative z-20`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-1 border-b border-zinc-200 dark:border-zinc-800 select-none bg-zinc-50 dark:bg-zinc-950 text-xs`,children:[(0,A.jsxs)(`div`,{className:`flex items-center space-x-1 overflow-x-auto min-w-0`,children:[(0,A.jsx)(`div`,{className:`flex items-center space-x-1`,children:g.map(e=>{let t=e.id===v,n=e.id===b;return(0,A.jsxs)(`div`,{onClick:()=>y(e.id),onDoubleClick:t=>ae(e,t),title:`Double-click to rename tab`,className:`flex items-center space-x-1 px-2.5 py-1 rounded text-xs cursor-pointer transition-colors ${t?`bg-zinc-200 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 font-medium shadow-sm`:`text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-200/50 dark:hover:bg-zinc-800/50`}`,children:[n?(0,A.jsx)(`input`,{type:`text`,"data-testid":`terminal-tab-rename-input`,value:S,autoFocus:!0,onChange:e=>C(e.target.value),onBlur:oe,onKeyDown:se,className:`bg-transparent border border-sky-500 rounded px-1 py-0 text-xs font-mono outline-none text-zinc-900 dark:text-zinc-100 w-24`}):(0,A.jsx)(`span`,{children:e.title}),g.length>1&&(0,A.jsx)(`span`,{onClick:t=>k(e.id,t),role:`button`,tabIndex:0,"aria-label":`Close terminal tab`,className:`ml-1 hover:text-red-500 rounded p-0.5 hover:bg-zinc-200 dark:hover:bg-zinc-700`,children:(0,A.jsx)(`svg`,{className:`w-3 h-3`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]},e.id)})}),(0,A.jsx)(`button`,{onClick:O,type:`button`,title:`New Terminal Tab`,className:`p-1 rounded text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 4v16m8-8H4`})})})]}),r&&!a&&(0,A.jsx)(LB,{verdict:i??{state:`checking`,runner:``},surface:`terminal`,root:CY(r)}),le&&(0,A.jsx)(`div`,{className:`hidden md:flex items-center space-x-1.5 px-2 text-xs font-mono text-zinc-500 dark:text-zinc-400`,children:o&&(0,A.jsx)(`button`,{onClick:()=>{if(le&&o){if((le===`/`||le===`\\`||/^[A-Za-z]:[\\/]?$/.test(le))&&!window.confirm(`Open root filesystem "${le}" as the workspace project?`))return;o(le),D(!0),setTimeout(()=>D(!1),2e3)}},type:`button`,title:`Open "${le}" as the workspace project and reposition the LLM agent`,className:`flex items-center space-x-1 px-1.5 py-0.5 rounded text-[11px] font-sans transition-colors ${te?`bg-emerald-500 text-white font-medium`:`bg-zinc-200/80 hover:bg-sky-500 hover:text-white dark:bg-zinc-800 dark:hover:bg-sky-600 dark:hover:text-white text-zinc-700 dark:text-zinc-300`}`,children:(0,A.jsx)(`span`,{children:te?`✓ Project opened`:`📁 ${CY(le)} → open as project`})})}),(0,A.jsxs)(`div`,{className:`flex items-center space-x-1 text-zinc-500 dark:text-zinc-400`,children:[(0,A.jsx)(`button`,{onClick:ce,type:`button`,title:`Clear Terminal Output`,className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16`})})}),(0,A.jsx)(`button`,{onClick:()=>E(e=>!e),type:`button`,title:ee?`Restore Terminal Panel`:`Maximize Terminal Panel`,className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:ee?(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})}):(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 15l7-7 7 7`})})}),(0,A.jsx)(`button`,{onClick:t,type:`button`,title:"Minimize Terminal Panel (Ctrl+`)",className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]})]}),(0,A.jsx)(`div`,{className:`flex-1 min-h-0 relative`,children:a?(0,A.jsxs)(`div`,{role:`status`,"data-testid":`terminal-unavailable`,className:`p-3 text-xs text-amber-700 dark:text-amber-300`,children:[(0,A.jsx)(`p`,{className:`font-medium`,children:`The terminal is unavailable.`}),(0,A.jsx)(`p`,{className:`mt-1 break-words font-mono`,children:a})]}):g.map(t=>(0,A.jsx)(wY,{id:t.id,cwd:n,isActive:t.id===v,isPanelOpen:e,renaming:b!==null,openTerminal:s,sendTerminalInput:c,getTerminalCwd:l,resizeTerminal:u,closeTerminal:f,subscribeTerminal:p,onCwdUpdate:ie,registerClear:re},t.id))})]}):null}var EY={todo:{label:`To do`,className:`text-zinc-500`},in_progress:{label:`In progress`,className:`text-blue-600 dark:text-blue-400`},done:{label:`Done`,className:`text-emerald-600 dark:text-emerald-400`},blocked:{label:`Blocked`,className:`text-red-600 dark:text-red-400`},needs_review:{label:`Needs review`,className:`text-amber-600 dark:text-amber-400`},passed:{label:`Passed`,className:`text-emerald-600 dark:text-emerald-400`},failed:{label:`Failed`,className:`text-red-600 dark:text-red-400`},inconclusive:{label:`Inconclusive`,className:`text-amber-600 dark:text-amber-400`},informational:{label:`Informational`,className:`text-zinc-500`},modified:{label:`Modified`,className:`text-blue-600 dark:text-blue-400`},added:{label:`Added`,className:`text-emerald-600 dark:text-emerald-400`},deleted:{label:`Deleted`,className:`text-red-600 dark:text-red-400`},untracked:{label:`Untracked`,className:`text-zinc-600 dark:text-zinc-300`},conflicted:{label:`Conflicted`,className:`text-red-600 dark:text-red-400`},unavailable:{label:`Unavailable`,className:`text-red-600 dark:text-red-400`},"not-recorded":{label:`Not recorded`,className:`text-zinc-500`}};function DY(e){return EY[e]??{label:e,className:`text-zinc-500`}}function OY({entry:e,onTarget:t}){let n=DY(e.status),r=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 break-words text-sm font-medium text-zinc-900 dark:text-zinc-100`,children:e.title}),(0,A.jsx)(`span`,{className:`shrink-0 text-[11px] font-semibold uppercase tracking-wide ${n.className}`,children:n.label})]}),e.group&&(0,A.jsx)(`div`,{className:`mt-0.5 text-[11px] text-zinc-500`,children:e.group}),e.detail&&(0,A.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap text-xs text-zinc-600 dark:text-zinc-300`,children:e.detail}),e.reference&&(0,A.jsx)(`div`,{className:`mt-1 truncate text-xs text-zinc-500`,children:e.reference}),(0,A.jsx)(`div`,{className:`mt-1 text-[10px] uppercase tracking-wide text-zinc-400`,children:e.source})]}),i=`block w-full rounded-md border border-zinc-200 p-2 text-left hover:bg-zinc-50 dark:border-zinc-800 dark:hover:bg-zinc-900`;return e.target?.kind===`external-url`?(0,A.jsx)(`a`,{href:e.target.url,target:`_blank`,rel:`noreferrer`,className:i,children:r}):e.target?(0,A.jsx)(`button`,{type:`button`,onClick:()=>t(e.target),className:i,children:r}):(0,A.jsx)(`div`,{className:`rounded-md border border-zinc-200 p-2 dark:border-zinc-800`,children:r})}function kY({state:e,onClose:t,onRefresh:n,onTarget:r}){return(0,A.jsxs)(`aside`,{"aria-label":`Workspace Outcome`,className:`absolute inset-y-0 right-0 z-10 flex w-full flex-col border-l border-zinc-200 bg-white/95 shadow-lg backdrop-blur md:w-[26rem] dark:border-zinc-800 dark:bg-zinc-950/95`,children:[(0,A.jsxs)(`header`,{className:`flex items-start justify-between gap-2 border-b border-zinc-200 px-3 py-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-zinc-500`,children:`Workspace review`}),(0,A.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:`Outcome`})]}),(0,A.jsxs)(`div`,{className:`flex gap-1`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:n,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:`Refresh`}),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,"aria-label":`Close Outcome`,children:`×`})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:e===null||e.status===`loading`?(0,A.jsx)(`div`,{role:`status`,className:`text-sm text-zinc-500`,children:`Loading Outcome…`}):e.status===`error`?(0,A.jsx)(`div`,{role:`alert`,className:`rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300`,children:e.message}):(0,A.jsx)(`div`,{className:`space-y-4`,children:e.outcome.sections.map(e=>(0,A.jsxs)(`section`,{"aria-labelledby":`outcome-${e.id}`,className:`rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`h3`,{id:`outcome-${e.id}`,className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.title}),e.availability===`partial`||e.availability===`unavailable`?(0,A.jsx)(`span`,{className:`text-[11px] font-semibold uppercase text-red-600 dark:text-red-400`,children:e.availability}):null]}),e.summary&&(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-600 dark:text-zinc-300`,children:e.summary}),e.entries.length>0&&(0,A.jsx)(`div`,{className:`mt-3 space-y-2`,children:e.entries.map(e=>(0,A.jsx)(OY,{entry:e,onTarget:r},e.id))})]},e.id))})})]})}function AY(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`));return`${t.slice(0,4).join(``)}-${t.slice(4,6).join(``)}-${t.slice(6,8).join(``)}-${t.slice(8,10).join(``)}-${t.slice(10).join(``)}`}var jY=`pi-outpost:token`;function MY(){let e=null;try{let t=new URL(window.location.href);return e=t.searchParams.get(`token`),e&&(localStorage.setItem(jY,e),t.searchParams.delete(`token`),window.history.replaceState(null,``,`${t.pathname}${t.search}${t.hash}`)),localStorage.getItem(jY)}catch{return e}}function NY(){try{return localStorage.getItem(jY)}catch{return null}}function PY(e){try{localStorage.setItem(jY,e)}catch{}}var FY=class extends Error{kind;constructor(e,t){super(e),this.name=`HistoryError`,this.kind=t}};async function IY(e,t){let n=[];for(;;){let r=await e(n.length,50);if(r.items.length===0||(n.unshift(...r.items),t?.(n.length),r.remaining===0))return n}}function LY(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function RY(e,t){return e.base.rev===t.base.rev&&e.base.path===t.base.path&&e.target.rev===t.target.rev&&e.target.path===t.target.path}function zY(){return{clonePath:null,preview:null,enrollment:null,refresh:null,updates:{},skills:{},removals:{}}}var BY={login:null,connected:!1,workspace:null,workspaces:[],workspaceLocked:!1,embedWorkspaceControls:`settings`,switching:!1,agentStarting:!1,authRequired:!1,brandingReady:!1,branding:{},sessionId:``,sessionName:null,model:``,thinkingLevel:`off`,modelSupportsReasoning:!1,models:[],commands:[],extensionsBinding:!1,sessions:null,sessionSearch:null,tree:null,isStreaming:!1,items:[],olderHistory:null,pendingPrompt:null,workPlan:null,replyConformance:{},structuredAppearance:null,outpostUpdate:null,piPackages:null,piPackageUpdate:null,serverRestarting:!1,restartNeeded:[],outcome:null,queue:{steering:[],followUp:[]},errors:[],contextUsage:null,isCompacting:!1,dialogQueue:[],notifications:[],statuses:{},widgets:{},editorPrefill:null,fileTree:{},directoryRequests:{},openFile:null,previewRevision:0,fileSearch:null,createError:null,created:null,fileOperation:null,extensionPaths:null,configuredExtensionPaths:[],userExtensionPaths:[],extensionLock:!1,tools:[],sandbox:null,terminal:null,userSkillPaths:[],serverBrowse:null,settingsApply:null,agentResources:null,agentResourceOperations:zY(),versions:null,gitAvailable:!1,gitUnavailable:null,credentials:null,gitStatus:null,gitDiff:null,gitBaseline:null,gitLog:null,gitShow:null,gitFileHistory:null,gitFileDiff:null};function VY(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.kind===`assistant`&&r.streaming){let i=[...e];return i[n]=t(r),i}}return[...e,t({kind:`assistant`,blocks:[],streaming:!0})]}function HY(e,t,n,r){for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.kind===`tool`&&i.toolCallId===t){let t=[...e];return t[n]={...i,...r},t}}return[...e,{kind:`tool`,toolCallId:t,toolName:n,args:{},output:``,running:!0,...r}]}function UY(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.kind===`tool`&&i.toolCallId===t){let t=[...e];return t[r]={...i,...n},t}}return e}function WY(e,t){if(t.type!==`hello`&&t.type!==`session_replaced`&&t.type!==`update_config_ack`&&t.type!==`workspace_switched`&&t.type!==`workspace_starting`)return e;let n=t.models.find(e=>`${e.provider}/${e.id}`===t.model);return{...e,replyConformance:{},structuredAppearance:t.type===`workspace_switched`||t.type===`workspace_starting`?null:e.structuredAppearance,agentStarting:t.agentStarting===!0,outpostUpdate:t.outpostUpdate??e.outpostUpdate,piPackages:t.piPackages??e.piPackages,serverRestarting:!1,restartNeeded:t.restartNeeded??[],connected:!0,brandingReady:!0,workspace:t.workspace??null,workspaces:t.workspaces??[],workspaceLocked:t.workspaceLocked===!0,embedWorkspaceControls:t.embedWorkspaceControls??`settings`,switching:!1,branding:t.branding,sessionId:t.sessionId,sessionName:t.sessionName??null,model:t.model,thinkingLevel:t.thinkingLevel,thinkingLevels:t.thinkingLevels,modelSupportsReasoning:n?.reasoning??!1,models:t.models,commands:t.commands,extensionsBinding:t.extensionsBinding===!0,isStreaming:t.isStreaming,items:t.items,olderHistory:t.olderItems?{remaining:t.olderItems,have:0,loading:!1,error:null}:null,pendingPrompt:null,workPlan:t.workPlan??null,outcome:null,queue:{steering:[],followUp:[]},errors:[],contextUsage:t.contextUsage??null,isCompacting:!1,dialogQueue:[],notifications:[],statuses:{},widgets:{},extensionTitle:void 0,editorPrefill:null,tree:null,fileTree:{},directoryRequests:{},fileOperation:null,writableRoot:t.writableRoot,docxTemplate:t.docxTemplate,gitAvailable:t.gitAvailable===!0,gitUnavailable:t.gitUnavailable??null,credentials:t.credentials??null,extensionPaths:t.extensionPaths??null,configuredExtensionPaths:t.configuredExtensionPaths??[],userExtensionPaths:t.userExtensionPaths??[],extensionLock:t.extensionLock===!0,tools:t.tools??[],sandbox:t.sandbox??null,terminal:t.terminal??null,confinement:t.confinement??null,userSkillPaths:t.userSkillPaths??[],serverBrowse:null,settingsApply:null,versions:t.versions??null,agentResources:t.agentResources??null,agentResourceOperations:t.type===`hello`||t.type===`workspace_switched`||t.type===`workspace_starting`?zY():e.agentResourceOperations}}function GY(e,t){if(t.type===`connected`)return{...e,connected:!0,authRequired:!1};if(t.type===`workspace_switching`)return{...e,switching:!0};if(t.type===`pi_package_update_started`)return{...e,piPackageUpdate:{requestId:t.requestId,source:t.source,status:`pending`}};if(t.type===`auth_required`)return{...e,connected:!1,authRequired:!0};if(t.type===`auth_retrying`)return{...e,authRequired:!1};if(t.type===`login_started`)return{...e,login:{flowId:t.flowId,provider:t.provider,method:t.method,events:[],prompt:null,done:null}};if(t.type===`login_answered`)return e.login?{...e,login:{...e.login,prompt:null}}:e;if(t.type===`login_dismissed`)return{...e,login:null};if(t.type===`disconnected`&&e.login&&!e.login.done&&(e={...e,login:{...e.login,prompt:null,done:{ok:!1,message:`Connection lost — the sign-in was stopped. Start it again.`}}}),t.type===`disconnected`){let t=e.openFile,n=t?.status===`loaded`&&t.pendingSave!==void 0?{...t,pendingSave:void 0,saveError:{message:`Connection lost while saving — try again`,conflict:!1}}:e.openFile,r=e.outcome?.status===`loading`?{...e.outcome,status:`error`,message:`Connection lost while loading Outcome.`}:e.outcome;return{...e,connected:!1,openFile:n,outcome:r}}if(t.type===`branding_settled`)return{...e,brandingReady:!0};if(t.type===`branding_loaded`)return{...e,brandingReady:!0,branding:t.branding};if(t.type===`prompt_sent`)return{...e,pendingPrompt:{text:t.text,...t.images?.length?{images:t.images}:{}}};if(t.type===`pending_prompt_cancelled`)return!t.restoreText||!e.pendingPrompt?e:{...e,editorPrefill:{text:e.pendingPrompt.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};if(t.type===`dismiss_notification`)return{...e,notifications:e.notifications.filter(e=>e.id!==t.id)};if(t.type===`dialog_answered`)return{...e,dialogQueue:e.dialogQueue.slice(1)};if(t.type===`dir_list_started`){let n=e.fileTree[t.path];return{...e,fileTree:{...e.fileTree,[t.path]:t.preserveEntries&&Array.isArray(n)?n:`loading`},directoryRequests:{...e.directoryRequests,[t.path]:t.requestId}}}if(t.type===`raw_preview_changed`)return e.openFile?.path===t.path?{...e,previewRevision:e.previewRevision+1}:e;if(t.type===`file_read_started`){let n=e.openFile;return t.preserveContent&&n?.status===`loaded`&&n.path===t.path?{...e,openFile:{...n,refreshRequestId:t.requestId}}:{...e,openFile:{status:`loading`,path:t.path,requestId:t.requestId}}}if(t.type===`file_save_started`){let n=e.openFile;return!e.connected||n?.status!==`loaded`||n.path!==t.path?e:{...e,openFile:{...n,pendingSave:{requestId:t.requestId,content:t.content},saveError:void 0}}}if(t.type===`close_file_preview`)return{...e,openFile:null};if(t.type===`file_search_started`)return{...e,fileSearch:{status:`loading`,query:t.query,requestId:t.requestId,results:[]}};if(t.type===`file_search_cleared`)return{...e,fileSearch:null};if(t.type===`file_create_started`)return{...e,createError:null,created:null};if(t.type===`file_operation_started`)return{...e,fileOperation:{status:`pending`,operation:t.operation,path:t.path,requestId:t.requestId}};if(t.type===`session_search_started`)return{...e,sessionSearch:{status:`loading`,query:t.query,requestId:t.requestId,results:[]}};if(t.type===`session_search_cleared`)return{...e,sessionSearch:null};if(t.type===`history_load_started`)return e.olderHistory?{...e,olderHistory:{...e.olderHistory,loading:!0,error:null}}:e;if(t.type===`history_loaded`)return e.olderHistory?{...e,items:[...t.items,...e.items],olderHistory:{remaining:t.remaining,have:e.olderHistory.have+t.items.length,loading:!1,error:null}}:e;if(t.type===`history_load_failed`)return e.olderHistory?{...e,olderHistory:{...e.olderHistory,loading:!1,error:t.message}}:e;if(t.type===`git_diff_started`||t.type===`git_diff_cleared`)return{...e,gitDiff:null};if(t.type===`git_baseline_started`){let n=e.gitBaseline?.path===t.path?e.gitBaseline.text:void 0;return{...e,gitBaseline:{path:t.path,requestId:t.requestId,...n===void 0?{}:{text:n}}}}if(t.type===`git_baseline_cleared`)return{...e,gitBaseline:null};if(t.type===`git_show_cleared`)return{...e,gitShow:null,gitLog:e.gitLog};if(t.type===`git_file_history_started`)return{...e,gitFileHistory:{path:t.path,status:`loading`,entries:[],requestId:t.requestId},gitFileDiff:null};if(t.type===`git_file_history_closed`)return{...e,gitFileHistory:null,gitFileDiff:null};if(t.type===`git_file_diff_started`)return{...e,gitFileDiff:{base:t.base,target:t.target,status:`loading`,beforeText:e.gitFileDiff?.beforeText??``,afterText:e.gitFileDiff?.afterText??``,requestId:t.requestId}};if(t.type===`git_file_diff_cleared`)return{...e,gitFileDiff:null};if(t.type===`server_browse_started`)return{...e,serverBrowse:{status:`loading`,path:e.serverBrowse?.path??t.path,parent:e.serverBrowse?.parent??null,entries:e.serverBrowse?.entries??[],requestId:t.requestId}};if(t.type===`server_browse_closed`)return{...e,serverBrowse:null};if(t.type===`settings_apply_started`)return{...e,settingsApply:{status:`applying`}};if(t.type===`resource_clone_path_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,clonePath:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_preview_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,preview:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_enrollment_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,enrollment:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_refresh_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,refresh:{requestId:t.requestId,status:`loading`,...t.repositoryId?{repositoryId:t.repositoryId}:{}}}};if(t.type===`resource_update_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,updates:{...e.agentResourceOperations.updates,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}};if(t.type===`resource_skills_started`){let n=e.agentResourceOperations;return{...e,agentResourceOperations:{...n,skills:{...n.skills,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}}}if(t.type===`resource_removal_started`){let n=e.agentResourceOperations;return{...e,agentResourceOperations:{...n,removals:{...n.removals,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}}}if(t.type===`outcome_started`)return{...e,outcome:{status:`loading`,requestId:t.requestId,workspaceRoot:t.workspaceRoot,sessionId:t.sessionId}};if(t.type===`outcome_failed`){let n=e.outcome;return n===null||n.status!==`loading`||n.requestId!==t.requestId?e:{...e,outcome:{...n,status:`error`,message:t.message}}}let n=t.message;if(n.type===`workspace_switched`&&e.agentStarting&&e.workspace&&n.workspace&&kI(n.workspace)===kI(e.workspace))return{...WY(e,n),openFile:e.openFile,gitDiff:e.gitDiff,gitBaseline:e.gitBaseline,fileTree:e.fileTree,directoryRequests:e.directoryRequests};switch(n.type){case`workspace_switched`:case`hello`:case`session_replaced`:case`update_config_ack`:case`workspace_starting`:return{...WY(e,n),openFile:null,gitDiff:null,gitBaseline:null,fileTree:{},directoryRequests:{}};case`workspace_activity`:return{...e,workspaces:n.workspaces,workspace:(e.workspace&&n.workspaces.find(t=>kI(t)===kI(e.workspace)))??e.workspace};case`agent_resource_clone_path`:{let t=e.agentResourceOperations.clonePath;return t?.requestId===n.requestId?{...e,agentResourceOperations:{...e.agentResourceOperations,clonePath:{...t,status:`ready`,path:n.path}}}:e}case`agent_resource_preview`:{let t=e.agentResourceOperations.preview;return t?.requestId===n.requestId?{...e,agentResourceOperations:{...e.agentResourceOperations,preview:{...t,status:`ready`,preview:n.preview}}}:e}case`agent_resource_enrolled`:{let t=e.agentResourceOperations.enrollment;return t?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...e.agentResourceOperations,preview:null,enrollment:{...t,status:`ready`}}}:e}case`agent_resource_assessments`:{let t=e.agentResourceOperations.refresh;if(t?.requestId!==n.requestId||!e.agentResources)return e;let r=new Map(n.assessments.map(e=>[e.repositoryId,e]));return{...e,agentResources:{...e.agentResources,repositories:e.agentResources.repositories.map(e=>({...e,assessment:r.get(e.id)??e.assessment}))},agentResourceOperations:{...e.agentResourceOperations,refresh:{...t,status:`ready`}}}}case`agent_resource_inventory`:return{...e,agentResources:n.inventory};case`agent_resource_update_result`:{let t=n.result.repositoryId;if(!t)return e;let r=e.agentResourceOperations.updates[t];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...e.agentResourceOperations,updates:{...e.agentResourceOperations.updates,[t]:{...r,status:`ready`,result:n.result}}}}:e}case`agent_resource_skills_applied`:{let t=e.agentResourceOperations,r=t.skills[n.repositoryId];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...t,skills:{...t.skills,[n.repositoryId]:{...r,status:`ready`}}}}:e}case`agent_resource_removed`:{let t=e.agentResourceOperations,r=t.removals[n.repositoryId];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...t,removals:{...t.removals,[n.repositoryId]:{...r,status:`ready`,result:n.result}}}}:e}case`agent_resource_error`:{let t=e=>e?.requestId===n.requestId?{...e,status:`error`,message:n.message}:null,r=t(e.agentResourceOperations.clonePath),i=t(e.agentResourceOperations.preview),a=t(e.agentResourceOperations.enrollment),o=t(e.agentResourceOperations.refresh),s=e=>{let t=Object.entries(e).find(([,e])=>e.requestId===n.requestId);return t?{...e,[t[0]]:{...t[1],status:`error`,message:n.message}}:null},c=s(e.agentResourceOperations.updates),l=s(e.agentResourceOperations.skills),u=s(e.agentResourceOperations.removals);return!r&&!i&&!a&&!o&&!c&&!l&&!u?e:{...e,agentResourceOperations:{...e.agentResourceOperations,...r?{clonePath:r}:{},...i?{preview:i}:{},...a?{enrollment:a}:{},...o?{refresh:o}:{},...c?{updates:c}:{},...l?{skills:l}:{},...u?{removals:u}:{}}}}case`workspace_error`:return{...e,switching:!1,errors:[...e.errors,n.message]};case`sessions`:return{...e,sessions:n.sessions};case`session_search_results`:return e.sessionSearch?.requestId===n.requestId?{...e,sessionSearch:{...e.sessionSearch,status:`loaded`,results:n.sessions}}:e;case`tree`:return{...e,tree:n.roots};case`editor_prefill`:return{...e,editorPrefill:{text:n.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};case`model_changed`:return{...e,model:n.model,modelSupportsReasoning:n.reasoning,thinkingLevels:n.thinkingLevels};case`login_event`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,events:[...e.login.events,n.event]}}:e;case`login_prompt`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,prompt:{promptId:n.promptId,prompt:n.prompt}}}:e;case`login_prompt_cancelled`:return e.login?.flowId!==n.flowId||e.login.prompt?.promptId!==n.promptId?e:{...e,login:{...e.login,prompt:null}};case`login_done`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,prompt:null,done:{ok:n.ok,...n.cancelled?{cancelled:!0}:{},...n.message?{message:n.message}:{}}}}:e;case`credentials_changed`:{let t=n.models.find(e=>`${e.provider}/${e.id}`===n.model);return{...e,models:n.models,model:n.model,modelSupportsReasoning:t?.reasoning??!1,thinkingLevels:void 0,credentials:n.credentials}}case`extensions_bound`:return{...e,commands:n.commands,tools:n.tools??e.tools,extensionsBinding:!1};case`thinking_changed`:return{...e,thinkingLevel:n.level};case`work_plan_changed`:return{...e,workPlan:n.workPlan};case`workspace_outcome`:{let t=e.outcome;return t===null||t.requestId!==n.requestId||t.sessionId!==e.sessionId||n.outcome.sessionId!==e.sessionId||t.workspaceRoot!==null&&n.outcome.workspaceRoot!==t.workspaceRoot?e:{...e,outcome:{...t,status:`loaded`,outcome:n.outcome}}}case`workspace_outcome_error`:{let t=e.outcome;return t===null||t.status!==`loading`||t.requestId!==n.requestId?e:{...e,outcome:{...t,status:`error`,message:n.message}}}case`user`:return{...e,pendingPrompt:null,items:[...e.items,{kind:`user`,text:n.text,...n.images?{images:n.images}:{}}]};case`user_entries`:{let{entries:t}=n,r=e.items.flatMap((e,t)=>e.kind===`user`?[t]:[]),i=new Map;for(let n=r.length-1,a=t.length-1;n>=0&&a>=0;n--,a--){let o=e.items[r[n]];if(o.kind!==`user`||o.text!==t[a].text)break;i.set(r[n],t[a].entryId)}return{...e,items:e.items.map((e,t)=>{if(e.kind!==`user`)return e;let n=i.get(t);if(n===e.entryId)return e;if(n===void 0){let{entryId:t,...n}=e;return n}return{...e,entryId:n}})}}case`agent_start`:return{...e,isStreaming:!0,errors:[]};case`agent_end`:return{...e,isStreaming:!1,queue:{steering:[],followUp:[]},items:e.items.map(e=>e.kind===`tool`&&e.running?{...e,running:!1}:e.kind===`assistant`&&e.streaming?{...e,streaming:!1}:e)};case`assistant_start`:return{...e,items:[...e.items,{kind:`assistant`,blocks:[],streaming:!0}]};case`block_delta`:return{...e,items:VY(e.items,e=>{let t=[...e.blocks],r=t.findIndex(e=>e.contentIndex===n.contentIndex);return r>=0?t[r]={...t[r],text:t[r].text+n.delta}:t.push({type:n.block,text:n.delta,contentIndex:n.contentIndex}),{...e,blocks:t,streaming:!0}})};case`assistant_end`:return{...e,items:VY(e.items,()=>n.item)};case`custom_message`:return{...e,items:[...e.items,n.item]};case`tool_start`:return{...e,items:HY(e.items,n.toolCallId,n.toolName,{toolName:n.toolName,args:n.args,running:!0,callHtml:n.callHtml})};case`tool_update`:return{...e,items:HY(e.items,n.toolCallId,`tool`,{output:n.text,...n.outputHtml===void 0?{}:{outputHtml:n.outputHtml,outputHtmlCollapsed:n.outputHtmlCollapsed},...typeof n.progress==`number`?{progress:n.progress}:{}})};case`tool_end`:return{...e,items:HY(e.items,n.toolCallId,`tool`,{output:n.text,isError:n.isError,running:!1,outputHtml:n.outputHtml,outputHtmlCollapsed:n.outputHtmlCollapsed,structured:n.structured})};case`structured_conformance`:return{...e,items:UY(e.items,n.toolCallId,{structuredConformance:n.conformance})};case`structured_appearance`:return{...e,structuredAppearance:n.appearance};case`outpost_update`:return{...e,outpostUpdate:n.notice};case`pi_packages`:return{...e,piPackages:n.packages};case`pi_package_update_result`:{let t=e.piPackageUpdate;return t?.requestId===n.requestId?{...e,piPackageUpdate:{requestId:n.requestId,source:t.source,status:n.outcome,message:n.message}}:e}case`restart_needed`:return{...e,restartNeeded:n.reasons};case`server_restarting`:return{...e,serverRestarting:!0,piPackageUpdate:null};case`reply_structured_conformance`:return{...e,replyConformance:{...e.replyConformance,[n.key]:n.conformance}};case`queue`:return{...e,queue:{steering:n.steering,followUp:n.followUp}};case`context_usage`:return{...e,contextUsage:n.usage};case`confinement`:return{...e,confinement:n.confinement};case`compaction_start`:return{...e,isCompacting:!0};case`compaction_end`:return{...e,isCompacting:!1,errors:n.errorMessage?[...e.errors,n.errorMessage]:e.errors};case`error`:return{...e,errors:[...e.errors,n.message],pendingPrompt:null,settingsApply:e.settingsApply?.status===`applying`?{status:`error`,message:n.message}:e.settingsApply};case`server_directory`:return e.serverBrowse?.requestId===n.requestId?{...e,serverBrowse:{status:`loaded`,path:n.path,parent:n.parent,entries:n.entries,requestId:n.requestId}}:e;case`server_directory_error`:return e.serverBrowse?.requestId===n.requestId?{...e,serverBrowse:{...e.serverBrowse,status:`error`,error:n.message}}:e;case`directory_listing`:return n.requestId.startsWith(`dir:`)&&e.directoryRequests[n.path]!==n.requestId?e:{...e,fileTree:{...e.fileTree,[n.path]:n.entries},...n.requestId.startsWith(`create:`)?{created:n.path,createError:null}:{}};case`file_content`:{let t=e.openFile,r=t?.status===`loading`&&t.requestId===n.requestId,i=t?.status===`loaded`&&t.refreshRequestId===n.requestId;return!r&&!i?e:{...e,openFile:{status:`loaded`,path:n.path,content:n.content,size:n.size,mtimeMs:n.mtimeMs,...n.documentIssues===void 0?{}:{documentIssues:n.documentIssues}}}}case`file_written`:{if(n.requestId.startsWith(`create:`))return{...e,createError:null,created:n.path,openFile:{status:`loaded`,path:n.path,content:``,size:n.size,mtimeMs:n.mtimeMs,justCreated:!0}};let t=e.openFile;return t?.status!==`loaded`||t.pendingSave?.requestId!==n.requestId?e:{...e,openFile:{status:`loaded`,path:t.path,content:t.pendingSave.content,size:n.size,mtimeMs:n.mtimeMs}}}case`file_operation_result`:{if(e.fileOperation?.status!==`pending`||e.fileOperation.requestId!==n.requestId)return e;let t=n.previousPath??n.path,r=n.operation===`delete_file`&&e.openFile?.path===n.path?null:e.openFile?.path===t?{...e.openFile,path:n.path}:e.openFile,i=e.gitFileHistory?.path===t||e.gitFileHistory?.path===n.path,a=e.gitDiff?.path===t||e.gitDiff?.path===n.path,o=e.gitBaseline?.path===t||e.gitBaseline?.path===n.path;return{...e,openFile:r,gitFileHistory:i?null:e.gitFileHistory,gitFileDiff:i?null:e.gitFileDiff,gitDiff:a?null:e.gitDiff,gitBaseline:o?null:e.gitBaseline,fileOperation:{status:`succeeded`,operation:n.operation,path:e.fileOperation.path,resultPath:n.path,requestId:n.requestId}}}case`file_browser_error`:if(n.requestId.startsWith(`dir:`))return e.directoryRequests[n.path]===n.requestId?{...e,fileTree:{...e.fileTree,[n.path]:{error:n.message}}}:e;if(n.requestId.startsWith(`create:`))return{...e,createError:{path:n.path,message:n.message}};if(n.requestId.startsWith(`write:`)){let t=e.openFile;return t?.status!==`loaded`||t.pendingSave?.requestId!==n.requestId?e:{...e,openFile:{...t,pendingSave:void 0,saveError:{message:n.message,conflict:n.reason===`conflict`}}}}return n.requestId.startsWith(`fileop:`)?e.fileOperation?.status!==`pending`||e.fileOperation.requestId!==n.requestId?e:{...e,fileOperation:{status:`error`,operation:e.fileOperation.operation,path:e.fileOperation.path,message:n.message,requestId:n.requestId}}:e.openFile?.status===`loading`&&e.openFile.requestId===n.requestId?{...e,openFile:{status:`error`,path:n.path,message:n.message}}:e.openFile?.status===`loaded`&&e.openFile.refreshRequestId===n.requestId?{...e,openFile:{...e.openFile,refreshRequestId:void 0}}:e;case`file_search_results`:return e.fileSearch?.requestId===n.requestId?{...e,fileSearch:{...e.fileSearch,status:`loaded`,results:n.results}}:e;case`git_status`:{let t={};for(let e of n.files)t[e.path]=e.status;let r=e.gitStatus;if(n.repo===void 0||r===null)return{...e,gitStatus:{repos:n.repos,files:t}};let i={};for(let[e,t]of Object.entries(r.files))_L(r.repos,e)?.repo!==n.repo&&(i[e]=t);let a=r.repos.map(e=>n.repos.find(t=>t.repo===e.repo)??e);return{...e,gitStatus:{repos:a,files:{...i,...t}}}}case`git_repositories_changed`:return{...e,gitAvailable:n.available,gitUnavailable:n.available?null:n.unavailable??null,gitStatus:n.available?e.gitStatus:null};case`git_diff`:return n.requestId.startsWith(`gitbase:`)?e.gitBaseline?.requestId===n.requestId?{...e,gitBaseline:{...e.gitBaseline,text:n.before}}:e:{...e,gitDiff:{path:n.path,before:n.before,after:n.after}};case`git_log`:return{...e,gitLog:{repo:n.repo,entries:n.entries}};case`git_show`:return{...e,gitShow:{sha:n.sha,patch:n.patch,truncated:n.truncated}};case`git_file_log`:return e.gitFileHistory?.requestId===n.requestId?{...e,gitFileHistory:{...e.gitFileHistory,status:`loaded`,entries:n.entries}}:e;case`git_file_diff`:return e.gitFileDiff===null||!RY(e.gitFileDiff,n)?e:{...e,gitFileDiff:{...e.gitFileDiff,status:`loaded`,beforeText:n.beforeText,afterText:n.afterText}};case`git_error`:return n.requestId.startsWith(`gitbase:`)?e.gitBaseline?.requestId===n.requestId?{...e,gitBaseline:null}:e:n.requestId.startsWith(`gitdiff:`)?{...e,gitDiff:e.openFile?{path:e.openFile.path,error:n.message}:null}:n.requestId===e.gitFileHistory?.requestId?{...e,gitFileHistory:{...e.gitFileHistory,status:`error`,error:n.message}}:n.requestId===e.gitFileDiff?.requestId?{...e,gitFileDiff:{...e.gitFileDiff,status:`error`,error:n.message}}:{...e,errors:[...e.errors,`git: ${n.message}`]};case`extension_ui_request`:switch(n.method){case`select`:case`confirm`:case`input`:case`editor`:return{...e,dialogQueue:[...e.dialogQueue,n]};case`notify`:return{...e,notifications:[...e.notifications,{id:n.id,message:n.message,notifyType:n.notifyType}]};case`setStatus`:{let t={...e.statuses};return n.statusText===void 0?delete t[n.statusKey]:t[n.statusKey]=n.statusText,{...e,statuses:t}}case`setWidget`:{let t={...e.widgets};return n.widgetLines===void 0?delete t[n.widgetKey]:t[n.widgetKey]={lines:n.widgetLines,placement:n.widgetPlacement??`aboveEditor`},{...e,widgets:t}}case`setTitle`:return{...e,extensionTitle:n.title};case`set_editor_text`:return{...e,editorPrefill:{text:n.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};default:return e}default:return e}}function KY(e,t,n){let r=e?`${e.replace(/^http/,`ws`)}/ws`:`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/ws`,i=new URLSearchParams;t&&i.set(`token`,t),n&&i.set(`workspace`,n);let a=i.toString();return a?`${r}?${a}`:r}var qY=12e4,JY=2e4,YY=45e3,XY=4401,ZY=1e3;function QY(e=``,t,n=!1,r){let[i,a]=(0,d.useReducer)(GY,BY),o=(0,d.useRef)(null),[s,c]=(0,d.useState)(0),l=(0,d.useRef)(null),u=(0,d.useRef)(null);s===0&&l.current===null&&(l.current=t??(n?NY():MY()));let f=(0,d.useRef)(i.fileTree),p=(0,d.useRef)(i.openFile);(0,d.useEffect)(()=>{f.current=i.fileTree},[i.fileTree]),(0,d.useEffect)(()=>{p.current=i.openFile},[i.openFile]);let m=(0,d.useRef)(null);(0,d.useEffect)(()=>{m.current=i.gitDiff?.path??null},[i.gitDiff]);let h=(0,d.useRef)(new Map),g=(0,d.useRef)(new Map),_=(0,d.useRef)(i.sessionId);(0,d.useEffect)(()=>{_.current=i.sessionId},[i.sessionId]);let v=(0,d.useRef)(!1),y=(0,d.useRef)(i.olderHistory);(0,d.useEffect)(()=>{y.current=i.olderHistory},[i.olderHistory]);let b=(0,d.useRef)(i.writableRoot);(0,d.useEffect)(()=>{b.current=i.writableRoot},[i.writableRoot]);let x=(0,d.useRef)(!1),S=(0,d.useRef)(new Map),C=i.workspace?kI(i.workspace):null,w=(0,d.useRef)({workspaceRoot:C,sessionId:i.sessionId});(0,d.useEffect)(()=>{w.current={workspaceRoot:C,sessionId:i.sessionId}},[C,i.sessionId]);let T=(0,d.useCallback)(e=>{let t=o.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},[]),ee=(0,d.useRef)(!1),E=(0,d.useRef)(null),te=(0,d.useRef)(!1),D=(0,d.useRef)(null),ne=(0,d.useRef)(()=>{}),re=(0,d.useCallback)(()=>{E.current=null,D.current!==null&&(clearTimeout(D.current),D.current=null)},[]),k=(0,d.useCallback)(()=>{let e=o.current;if(!e||e.readyState!==WebSocket.OPEN)return;if(E.current!==null){te.current=!0;return}let t=`outcome:${AY()}`;E.current=t;let n=w.current;a({type:`outcome_started`,requestId:t,...n}),T({type:`get_outcome`,requestId:t}),D.current=setTimeout(()=>{E.current===t&&(re(),te.current=!1,a({type:`outcome_failed`,requestId:t,message:`The Outcome took too long to answer — try again.`}))},YY)},[T,re]);ne.current=k;let ae=(0,d.useCallback)(()=>{ee.current&&ne.current()},[]),oe=(0,d.useCallback)(e=>{ee.current=e,e?k():te.current=!1},[k]),se=(0,d.useCallback)((e,t=!1)=>{e===``&&(x.current=!0);let n=`dir:${AY()}`;a({type:`dir_list_started`,path:e,requestId:n,preserveEntries:t}),T({type:`list_directory`,path:e,requestId:n})},[T]),ce=(0,d.useRef)(!1),A=(0,d.useRef)([]);(0,d.useEffect)(()=>{A.current=i.gitStatus?.repos??[]},[i.gitStatus]);let le=(0,d.useRef)(new Set),ue=(0,d.useRef)(new Set),de=(0,d.useRef)(new Map),j=(0,d.useCallback)(e=>{if(!ce.current)return;let t=e??``;if(le.current.has(t)){ue.current.add(t);return}le.current.add(t);let n=`git:${AY()}`;de.current.set(n,t),T({type:`git_status`,...e===void 0?{}:{repo:e},requestId:n})},[T]),fe=(0,d.useCallback)(e=>{let t=de.current.get(e)??``;de.current.delete(e),le.current.delete(t),ue.current.delete(t)&&j(t===``?void 0:t)},[j]),pe=(0,d.useCallback)(e=>{f.current[e]!==void 0&&se(e,!0)},[se]),me=(0,d.useCallback)(()=>{se(``,!0);for(let e of Object.keys(f.current))e!==``&&pe(e)},[pe,se]);(0,d.useEffect)(()=>{i.connected&&x.current&&f.current[``]===void 0&&se(``)},[i.connected,i.fileTree,se]),(0,d.useEffect)(()=>{i.connected&&ee.current&&E.current===null&&ne.current()},[i.connected]);let he=i.openFile?.path??null,ge=he===null?void 0:i.gitStatus?.files[he],_e=i.gitBaseline!==null;(0,d.useEffect)(()=>{let e=ge===`modified`||ge===`added`||ge===`conflicted`;if(!i.connected||he===null||!e){_e&&a({type:`git_baseline_cleared`});return}let t=`gitbase:${AY()}`;a({type:`git_baseline_started`,path:he,requestId:t}),T({type:`git_diff`,path:he,requestId:t})},[i.connected,he,ge,i.gitStatus,T]),(0,d.useEffect)(()=>{let t=!1;return fetch(`${e}/branding`,{headers:l.current?{Authorization:`Bearer ${l.current}`}:{}}).then(e=>e.ok?e.json():null).then(e=>{t||a(e?{type:`branding_loaded`,branding:e}:{type:`branding_settled`})}).catch(()=>{t||a({type:`branding_settled`})}),()=>{t=!0}},[e,s]),(0,d.useEffect)(()=>{let t,n=!1;function i(){let s=new WebSocket(KY(e,l.current,r));o.current=s,s.onopen=()=>{o.current===s&&a({type:`connected`})},s.onmessage=e=>{if(o.current!==s)return;let t;try{t=JSON.parse(e.data)}catch{return}if(t.type===`terminal_data`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onData)n(t.data)}else if(t.type===`terminal_cwd`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onCwd)n(t.cwd)}else if(t.type===`terminal_exit`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onExit)n(t.exitCode)}else if(t.type===`terminal_error`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onError)n(t.message)}else if(t.type===`history_items`){let e=g.current.get(t.requestId);e&&(g.current.delete(t.requestId),e.resolve({items:t.items,remaining:t.remaining}))}else if(t.type===`history_unavailable`){let e=g.current.get(t.requestId);e&&(g.current.delete(t.requestId),e.reject(new FY(t.reason,t.kind)))}else if(t.type===`file_uploaded`){let e=h.current.get(t.requestId);e&&(h.current.delete(t.requestId),e.resolve(t.path))}else if(t.type===`file_browser_error`&&h.current.has(t.requestId)){let e=h.current.get(t.requestId);h.current.delete(t.requestId),e.reject(new CL(t.message,t.reason))}else if(t.type===`file_changed`){ae(),pe(LY(t.path));let e=p.current;if(e?.status===`loaded`&&e.path===t.path){let e=`file:${AY()}`;a({type:`file_read_started`,path:t.path,requestId:e,preserveContent:!0}),T({type:`read_file`,path:t.path,requestId:e})}m.current===t.path&&T({type:`git_diff`,path:t.path,requestId:`gitdiff:${AY()}`}),j(_L(A.current,t.path)?.repo)}else if(t.type===`directory_changed`){ae(),pe(t.path);let e=p.current;if(e!==null&&LY(e.path)===t.path){if(ie(e.path)||O(e.path))a({type:`raw_preview_changed`,path:e.path});else if(e.status===`loaded`){let t=`file:${AY()}`;a({type:`file_read_started`,path:e.path,requestId:t,preserveContent:!0}),T({type:`read_file`,path:e.path,requestId:t})}}let n=m.current;n!==null&&LY(n)===t.path&&T({type:`git_diff`,path:n,requestId:`gitdiff:${AY()}`}),j()}else{if((t.type===`hello`||t.type===`session_replaced`||t.type===`workspace_switched`||t.type===`workspace_starting`)&&(ce.current=t.gitAvailable===!0,t.type!==`session_replaced`&&j()),t.type===`agent_end`&&(j(),ae()),t.type===`git_repositories_changed`&&(ae(),ce.current=t.available,t.available&&j()),t.type===`git_changed`&&(ae(),j(t.repo===``?void 0:t.repo)),(t.type===`git_status`||t.type===`git_error`&&t.requestId.startsWith(`git:`))&&fe(t.requestId),t.type===`work_plan_changed`&&ae(),(t.type===`workspace_outcome`||t.type===`workspace_outcome_error`)&&E.current===t.requestId&&(re(),te.current&&(te.current=!1,queueMicrotask(()=>ne.current()))),t.type===`hello`||t.type===`session_replaced`||t.type===`workspace_switched`||t.type===`workspace_starting`||t.type===`update_config_ack`){re(),te.current=!1;let e=w.current,n=t.sessionId===e.sessionId,r=(t.workspace?kI(t.workspace):null)===e.workspaceRoot;ee.current&&n&&r&&queueMicrotask(()=>ne.current())}if(t.type===`file_operation_result`){let e=t.previousPath??t.path,n=p.current;t.operation===`delete_file`&&n?.path===t.path?p.current=null:n?.path===e&&(p.current={...n,path:t.path})}a({type:`server`,message:t}),t.type===`session_replaced`&&se(``)}},s.onclose=e=>{if(o.current===s){le.current.clear(),ue.current.clear(),de.current.clear(),re(),te.current=!1;for(let e of h.current.values())e.reject(new CL(`The connection dropped before the upload finished`));h.current.clear();for(let e of g.current.values())e.reject(new FY(`the connection dropped before the older messages arrived`,`failed`));g.current.clear(),e.code===XY?a({type:`auth_required`}):(a({type:`disconnected`}),n||(t=window.setTimeout(i,1500)))}}}return i(),()=>{n=!0,t!==void 0&&clearTimeout(t);let e=o.current;o.current=null,e?.close()}},[T,e,j,fe,pe,se,ae,re,s,r]);let ve=(0,d.useCallback)((e,t)=>{let n=o.current;if(!n||n.readyState!==WebSocket.OPEN)return Promise.reject(new FY(`not connected to the server`,`failed`));let r=`history:${AY()}`;return new Promise((n,i)=>{let a=window.setTimeout(()=>{g.current.delete(r)&&i(new FY(`the older messages did not arrive`,`failed`))},JY),o=e=>t=>{clearTimeout(a),e(t)};g.current.set(r,{resolve:o(n),reject:o(i)}),T({type:`history_before`,sessionId:_.current,have:e,count:t,requestId:r})})},[T]),ye=(0,d.useCallback)(async()=>{let e=y.current;if(!(!e||e.loading||v.current||e.remaining<=0)){v.current=!0,a({type:`history_load_started`});try{let t=await ve(e.have,50);a({type:`history_loaded`,items:t.items,remaining:t.remaining})}catch(e){if(e instanceof FY&&e.kind===`stale`){a({type:`history_load_failed`,message:``});return}a({type:`history_load_failed`,message:e instanceof Error?e.message:`the older messages could not be loaded`})}finally{v.current=!1}}},[ve]);return{state:i,setOutcomeActive:oe,refreshOutcome:k,authToken:l.current,switchWorkspace:(e,t)=>{((t??e)!==C||i.switching)&&(a({type:`workspace_switching`}),T({type:`switch_workspace`,root:e,...t!==void 0&&t!==e?{id:t}:{}}))},openProject:e=>{a({type:`workspace_switching`}),T({type:`open_project`,root:e})},closeProject:(e,t)=>T({type:`close_project`,root:e,...t!==void 0&&t!==e?{id:t}:{}}),checkPiPackages:()=>T({type:`check_pi_packages`}),updatePiPackage:e=>{let t=`pkg:${AY()}`;a({type:`pi_package_update_started`,requestId:t,source:e}),T({type:`update_pi_package`,source:e,requestId:t})},restartServer:()=>T({type:`restart_server`}),openSideSession:e=>{a({type:`workspace_switching`}),T({type:`open_side_session`,root:e})},submitToken:e=>{PY(e),l.current=e,a({type:`auth_retrying`}),c(e=>e+1)},prompt:(e,t)=>{a({type:`prompt_sent`,text:e,...t?.length?{images:t}:{}}),T({type:`prompt`,text:e,...t?.length?{images:t}:{}})},abort:()=>T({type:`abort`}),cancelPendingPrompt:e=>{a({type:`pending_prompt_cancelled`,restoreText:e}),T({type:`abort`})},setModel:(e,t)=>T({type:`set_model`,provider:e,id:t}),setThinking:e=>T({type:`set_thinking`,level:e}),newSession:()=>T({type:`new_session`}),switchSession:e=>T({type:`switch_session`,path:e}),deleteSession:e=>T({type:`delete_session`,path:e}),listSessions:()=>T({type:`list_sessions`}),renameSession:(e,t)=>T({type:`rename_session`,path:e,name:t}),searchSessions:e=>{let t=`sessions:${AY()}`;a({type:`session_search_started`,query:e,requestId:t}),T({type:`search_sessions`,query:e,requestId:t})},clearSessionSearch:()=>a({type:`session_search_cleared`}),listTree:()=>T({type:`list_tree`}),navigateTree:e=>T({type:`navigate_tree`,entryId:e}),forkSession:e=>T({type:`fork_session`,entryId:e}),editPrompt:(e,t,n)=>T({type:`edit_prompt`,entryId:e,text:t,...n?.length?{images:n}:{}}),compact:()=>T({type:`compact`}),fetchOlderItems:ve,loadOlderItems:ye,respondToDialog:e=>{T({type:`extension_ui_response`,...e}),a({type:`dialog_answered`})},dismissNotification:e=>a({type:`dismiss_notification`,id:e}),listDirectory:e=>se(e),refreshFileTree:me,readFile:(e,t)=>{let n=`file:${AY()}`;a({type:`file_read_started`,path:e,requestId:n}),T({type:`read_file`,path:e,requestId:n,...t===void 0?{}:{sha256:t}})},closeFilePreview:()=>a({type:`close_file_preview`}),writeFile:(e,t,n,r=!1)=>{let i=`write:${AY()}`;a({type:`file_save_started`,path:e,requestId:i,content:t}),T({type:`write_file`,path:e,content:t,expectedMtimeMs:n,...r?{force:r}:{},requestId:i})},createFile:e=>{a({type:`file_create_started`}),T({type:`create_file`,path:e,requestId:`create:${AY()}`})},uploadFile:(e,t)=>{let n=b.current;if(n===null)return Promise.reject(new CL(`the workspace is read-only`,`denied`));let r=o.current;if(!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new CL(`not connected to the server`));let i=n?`${n}/${SL}`:SL,a=`upload:${AY()}`;return new Promise((n,r)=>{let o=window.setTimeout(()=>{h.current.delete(a)&&r(new CL(`the upload timed out`))},qY),s=e=>t=>{clearTimeout(o),e(t)};h.current.set(a,{resolve:s(n),reject:s(r)}),T({type:`upload_file`,destinationDirectory:i,name:e,contentBase64:t,requestId:a})})},createDirectory:e=>{a({type:`file_create_started`}),T({type:`create_directory`,path:e,requestId:`create:${AY()}`})},openNative:e=>{let t=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`open_native`,path:e,requestId:t}),T({type:`open_native`,path:e,requestId:t})},revealNative:e=>{let t=Date.now();if(u.current?.path===e&&t-u.current.at<ZY)return;u.current={path:e,at:t};let n=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`reveal_native`,path:e,requestId:n}),T({type:`reveal_native`,path:e,requestId:n})},renameFile:(e,t)=>{let n=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`rename_file`,path:e,requestId:n}),T({type:`rename_file`,path:e,name:t,requestId:n})},deleteFile:e=>{let t=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`delete_file`,path:e,requestId:t}),T({type:`delete_file`,path:e,requestId:t})},moveFile:(e,t)=>{let n=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`move_file`,path:e,requestId:n}),T({type:`move_file`,path:e,destinationDirectory:t,requestId:n})},copyFile:(e,t)=>{let n=`fileop:${AY()}`;a({type:`file_operation_started`,operation:`copy_file`,path:e,requestId:n}),T({type:`copy_file`,path:e,destinationDirectory:t,requestId:n})},searchFiles:e=>{let t=`search:${AY()}`;a({type:`file_search_started`,query:e,requestId:t}),T({type:`search_files`,query:e,requestId:t})},clearFileSearch:()=>a({type:`file_search_cleared`}),fetchGitStatus:()=>j(),fetchGitDiff:e=>{let t=`gitdiff:${AY()}`;a({type:`git_diff_started`,path:e,requestId:t}),T({type:`git_diff`,path:e,requestId:t})},clearGitDiff:()=>a({type:`git_diff_cleared`}),fetchGitLog:(e,t)=>T({type:`git_log`,repo:e,...t?{limit:t}:{},requestId:`gitlog:${AY()}`}),fetchGitShow:(e,t)=>T({type:`git_show`,repo:e,sha:t,requestId:`gitshow:${AY()}`}),clearGitShow:()=>a({type:`git_show_cleared`}),fetchGitFileHistory:(e,t)=>{let n=`gitfilelog:${AY()}`;a({type:`git_file_history_started`,path:e,requestId:n}),T({type:`git_file_log`,path:e,...t?{limit:t}:{},requestId:n})},closeGitFileHistory:()=>a({type:`git_file_history_closed`}),fetchGitFileDiff:(e,t)=>{let n=`gitfilediff:${AY()}`;a({type:`git_file_diff_started`,base:e,target:t,requestId:n}),T({type:`git_file_diff`,base:e,target:t,requestId:n})},clearGitFileDiff:()=>a({type:`git_file_diff_cleared`}),setCredential:(e,t)=>T({type:`set_credential`,provider:e,apiKey:t}),startLogin:(e,t)=>{let n=AY();a({type:`login_started`,flowId:n,provider:e,method:t}),T({type:`start_login`,flowId:n,provider:e,method:t})},answerLogin:e=>{let t=i.login;t?.prompt&&(T({type:`login_answer`,flowId:t.flowId,promptId:t.prompt.promptId,value:e}),a({type:`login_answered`}))},cancelLogin:()=>{let e=i.login;e&&!e.done&&T({type:`cancel_login`,flowId:e.flowId})},dismissLogin:()=>a({type:`login_dismissed`}),logoutProvider:e=>T({type:`logout_provider`,provider:e}),declareProvider:e=>T({type:`declare_provider`,...e}),browseServerDirectory:e=>{let t=`serverdir:${AY()}`;a({type:`server_browse_started`,path:e,requestId:t}),T({type:`browse_server_directory`,path:e,requestId:t})},closeServerBrowser:()=>a({type:`server_browse_closed`}),suggestAgentResourceClonePath:e=>{let t=`resource-clone-path:${AY()}`;a({type:`resource_clone_path_started`,requestId:t}),T({type:`suggest_agent_resource_clone_path`,repositoryUrl:e,requestId:t})},cloneAgentResourceRepository:(e,t)=>{let n=`resource-preview:${AY()}`;a({type:`resource_preview_started`,requestId:n}),T({type:`clone_agent_resource_repository`,repositoryUrl:e,destinationPath:t,requestId:n})},enrollAgentResourceRepository:(e,t,n,r)=>{let i=`resource-enroll:${AY()}`;a({type:`resource_enrollment_started`,requestId:i}),T({type:`enroll_agent_resource_repository`,previewToken:e,skillRoots:t,extensionRoots:n,...r?{enabledSkills:r}:{},requestId:i})},setAgentResourceSkills:(e,t)=>{let n=`resource-skills:${AY()}`;a({type:`resource_skills_started`,requestId:n,repositoryId:e}),T({type:`set_agent_resource_skills`,repositoryId:e,enabledSkills:t,requestId:n})},removeAgentResourceRepository:e=>{let t=`resource-remove:${AY()}`;a({type:`resource_removal_started`,requestId:t,repositoryId:e}),T({type:`remove_agent_resource_repository`,repositoryId:e,requestId:t})},refreshAgentResourceRepositories:e=>{let t=`resource-refresh:${AY()}`;a({type:`resource_refresh_started`,requestId:t,...e?{repositoryId:e}:{}}),T({type:`refresh_agent_resource_repositories`,...e?{repositoryId:e}:{},requestId:t})},updateAgentResourceRepository:(e,t,n,r,i=!1)=>{let o=`resource-update:${AY()}`;a({type:`resource_update_started`,requestId:o,repositoryId:e}),T({type:`update_agent_resource_repository`,repositoryId:e,assessmentToken:t,localRevision:n,upstreamRevision:r,...i?{allowExecutableChanges:!0}:{},requestId:o})},updateConfig:e=>{a({type:`settings_apply_started`}),T({type:`update_config`,...e})},openTerminal:(e,t,n,r)=>T({type:`terminal_open`,terminalId:e,cwd:t,cols:n,rows:r}),sendTerminalInput:(e,t)=>T({type:`terminal_input`,terminalId:e,data:t}),getTerminalCwd:e=>T({type:`terminal_get_cwd`,terminalId:e}),resizeTerminal:(e,t,n)=>T({type:`terminal_resize`,terminalId:e,cols:t,rows:n}),closeTerminal:e=>{T({type:`terminal_close`,terminalId:e}),S.current.delete(e)},subscribeTerminal:(e,t)=>{let n=S.current.get(e);return n||(n={onData:new Set,onCwd:new Set,onExit:new Set,onError:new Set},S.current.set(e,n)),t.onData&&n.onData.add(t.onData),t.onCwd&&n.onCwd.add(t.onCwd),t.onExit&&n.onExit.add(t.onExit),t.onError&&n.onError.add(t.onError),()=>{t.onData&&n?.onData.delete(t.onData),t.onCwd&&n?.onCwd.delete(t.onCwd),t.onExit&&n?.onExit.delete(t.onExit),t.onError&&n?.onError.delete(t.onError)}}}}var $Y=120;function eX({label:e}){return(0,A.jsx)(`div`,{className:`flex justify-end px-4`,role:`status`,"aria-live":`polite`,children:(0,A.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,A.jsx)(`span`,{className:`inline-block h-4 w-4 animate-spin rounded-full border-[3px] border-zinc-300 border-t-blue-500 dark:border-zinc-600 dark:border-t-blue-400 motion-reduce:animate-pulse`}),(0,A.jsx)(`span`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:e})]})})}var tX=(0,d.forwardRef)(function({serverUrl:e=``,rootElement:t,initialTheme:n,token:r,workspace:i},a){let o=t!==void 0,s=t??document.documentElement,{state:c,authToken:l,submitToken:u,prompt:f,abort:m,cancelPendingPrompt:h,setModel:g,setThinking:_,newSession:v,switchSession:b,deleteSession:x,listSessions:S,renameSession:C,searchSessions:w,clearSessionSearch:T,listTree:ee,navigateTree:E,forkSession:te,editPrompt:D,compact:ne,loadOlderItems:re,fetchOlderItems:se,respondToDialog:ce,dismissNotification:le,listDirectory:ue,refreshFileTree:de,readFile:j,writeFile:fe,createFile:pe,createDirectory:he,uploadFile:ge,openNative:_e,revealNative:ve,renameFile:ye,deleteFile:be,moveFile:xe,copyFile:Se,closeFilePreview:Ce,searchFiles:we,clearFileSearch:Te,fetchGitDiff:Ee,clearGitDiff:De,fetchGitLog:Oe,fetchGitShow:ke,clearGitShow:Ae,fetchGitFileHistory:je,closeGitFileHistory:Me,fetchGitFileDiff:Ne,clearGitFileDiff:Pe,setCredential:Fe,startLogin:Ie,answerLogin:Le,cancelLogin:Re,dismissLogin:ze,logoutProvider:Be,declareProvider:Ve,updateConfig:He,suggestAgentResourceClonePath:Ue,cloneAgentResourceRepository:We,enrollAgentResourceRepository:Ge,setAgentResourceSkills:Ke,removeAgentResourceRepository:qe,refreshAgentResourceRepositories:Ye,updateAgentResourceRepository:Xe,browseServerDirectory:Ze,closeServerBrowser:Qe,switchWorkspace:$e,openProject:et,closeProject:tt,openSideSession:nt,checkPiPackages:rt,updatePiPackage:it,restartServer:at,openTerminal:ot,sendTerminalInput:st,getTerminalCwd:ct,resizeTerminal:lt,closeTerminal:ut,subscribeTerminal:dt,setOutcomeActive:ft,refreshOutcome:pt}=QY(e,r,o,i),mt=oe(c.workspace);MB(c.workspaces,c.workspace?kI(c.workspace):null);let ht=c.workspace?kI(c.workspace):null;(0,d.useEffect)(()=>{yt([]),dn([]),En.current&&(En.current.scrollTop=0)},[ht]);let[gt,_t]=(0,d.useState)(!1),[vt,yt]=(0,d.useState)([]),[bt,xt]=(0,d.useState)([]),[St,Ct]=(0,d.useState)(null),[wt,Tt]=(0,d.useState)(null),[Et,Dt]=(0,d.useState)(null),[Ot,kt]=(0,d.useState)(!1),[At,jt]=(0,d.useState)(null),[Mt,Nt]=(0,d.useState)(null),Pt=At===`project`,Ft=e=>jt(e?`project`:null),It=c.embedWorkspaceControls===`projects`?`projects`:c.embedWorkspaceControls===`root`?`root`:`none`,Lt=(0,d.useRef)({}),Rt=(0,d.useRef)([]),zt=(0,d.useRef)(null),Bt=(0,d.useRef)(null),[Vt,Ht]=(0,d.useState)(!1),[Ut,Wt]=(0,d.useState)(mL),Gt=(0,d.useCallback)((e,t)=>{hL(e,t),Wt(n=>({...n,[e]:t}))},[]),[Kt,qt]=(0,d.useState)(!1),[Jt,Yt]=(0,d.useState)(!0),[Xt,Zt]=(0,d.useState)(!1),Qt=c.terminal?.enabled??!1;(0,d.useEffect)(()=>{let e=e=>{Qt&&(e.ctrlKey||e.metaKey)&&e.key==="`"&&(e.preventDefault(),Zt(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Qt]);let[$t,en]=(0,d.useState)(!1),[tn,nn]=(0,d.useState)(null),rn=(0,d.useCallback)(()=>nn(null),[]);function an(){let e=!Kt;qt(e),e&&(Yt(!1),en(!1))}function on(){let e=!Jt;Yt(e),e&&(qt(!1),en(!1))}function sn(){let e=!$t;en(e),e&&(qt(!1),Yt(!1))}(0,d.useEffect)(()=>(ft($t),()=>ft(!1)),[$t,ft,c.sessionId,ht]),(0,d.useEffect)(()=>{en(!1),nn(null)},[ht]);let[cn,ln]=(0,d.useState)([]),[un,dn]=(0,d.useState)([]),fn=(0,d.useRef)(0),pn=(0,d.useRef)(0),[mn,hn]=(0,d.useState)(0);async function gn(e){let t=[...e],n=t.filter(DL).map(e=>({id:`${fn.current++}`,name:e.name}));n.length>0&&dn(e=>[...e,...n]),pn.current===0&&ln([]),pn.current++;try{let{attachments:e,errors:n}=await FL(t,ge);e.length>0&&yt(t=>[...t,...e]),n.length>0&&ln(e=>[...e,...n])}finally{if(pn.current--,n.length>0){let e=new Set(n.map(e=>e.id));dn(t=>t.filter(t=>!e.has(t.id)))}}}(0,d.useEffect)(()=>{Rt.current=vt},[vt]),(0,d.useEffect)(()=>{let t=c.openFile;if(!t)return;let n=t.path,r=t.status===`loaded`,i=t.status===`error`&&t.message===`Binary file — preview not supported`&&k(n);if(zt.current!==n&&(zt.current=n,Bt.current=null,yt(e=>e.filter(e=>e.source!==`preview`)),Ct(null),Tt(null),Dt(null)),Bt.current===n)return;(ie(n)||O(n))&&yt(e=>e.filter(e=>e.source!==`preview`));let a=!1;async function o(){let t=ie(n)?wt===n?await VL(n,ae(e,n,l,c.previewRevision,mt)):null:O(n)?Et?.path===n&&Et.revision===c.previewRevision?LL(n):null:i||r?IL(n):null;a||t===null||zt.current!==n||Bt.current===n||(typeof t==`string`?Ct(t):(Ct(null),yt(e=>WL(e,t))))}return o(),()=>{a=!0}},[c.openFile,c.previewRevision,e,l,mt,wt,Et]);function _n(){zt.current=null,Bt.current=null,Ce()}let vn=(0,d.useMemo)(()=>[...vt.filter(e=>e.kind===`path`).map(e=>e.data),...bt],[vt,bt]);function yn(e){let t=Rt.current.findIndex(t=>t.kind===`path`&&t.data===e);t>=0?bn(t):bt.includes(e)||yt(t=>UL(t,e))}function bn(e){let t=Rt.current[e];t?.source===`preview`&&(Bt.current=t.previewPath??zt.current,Ct(null)),yt(t=>GL(t,e))}function xn(e,t){f(e,t),yt([]),ln([]),Ct(null),Ot||_n()}function Sn(e){e.preventDefault(),hn(0),e.dataTransfer.files.length>0&&gn(Array.from(e.dataTransfer.files))}let{theme:Cn,toggle:wn,setTheme:Tn}=y(c.branding.defaultTheme??`system`,c.branding.allowThemeToggle!==!1,s,n);(0,d.useImperativeHandle)(a,()=>({setTheme:Tn}),[Tn]);let En=(0,d.useRef)(null),[Dn,On]=(0,d.useState)(null),kn=(0,d.useCallback)(e=>{En.current=e,On(e)},[]),An=(0,d.useRef)(null),jn=(0,d.useRef)(!0),[Mn,Nn]=(0,d.useState)(!0),Pn=(0,d.useCallback)(e=>{e!==jn.current&&Nn(e),jn.current=e},[]),Fn=(0,d.useCallback)(()=>{let e=En.current;e&&Pn(e.scrollHeight-e.scrollTop-e.clientHeight<$Y)},[Pn]),In=(0,d.useRef)(null),Ln=(0,d.useCallback)(()=>{let e=En.current;e&&(e.scrollHeight-e.scrollTop-e.clientHeight<$Y||(In.current=e.scrollTop))},[]),Rn=(0,d.useCallback)(()=>{let e=En.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<$Y,n=In.current;if(n!==null){if(e.scrollTop<n)In.current=null;else if(In.current=t?null:e.scrollTop,!t)return}Pn(t)},[Pn]);function zn(){In.current=null}(0,d.useEffect)(()=>{let e=Dn;if(!e)return;let t=()=>{In.current=null,Rn()};e.addEventListener(`scrollend`,t);let n;return typeof ResizeObserver<`u`&&(n=new ResizeObserver(()=>{jn.current?(Ln(),An.current?.scrollIntoView({behavior:`auto`})):Rn()}),n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild)),()=>{e.removeEventListener(`scrollend`,t),n?.disconnect()}},[Dn,Rn,Ln]);let Bn=(0,d.useCallback)(()=>{Pn(!0),Ln();let e=window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1;An.current?.scrollIntoView({behavior:e?`auto`:`smooth`})},[Pn,Ln]);(0,d.useEffect)(()=>{jn.current?(Ln(),An.current?.scrollIntoView({behavior:`smooth`})):Fn()},[c.items,Fn,Ln]);let Vn=(0,d.useMemo)(()=>PI(c.items),[c.items]),Hn=(0,d.useMemo)(()=>Kt?WI(c.items):null,[Kt,c.items]),Un=(0,d.useMemo)(()=>UF({readFile:(e,t)=>{Ht(!1),j(e,t)},fetchGitFileHistory:e=>je(e),fetchGitDiff:e=>{Ht(!0),j(e)},searchFiles:e=>we(e)}),[j,je,we]),Wn=(0,d.useCallback)(()=>Gt(`tools`,!0),[Gt]),Gn=(0,d.useCallback)(e=>{let t=En.current;if(t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=r.top>=n.top&&r.bottom<=n.bottom,a=t.scrollHeight-t.scrollTop-t.clientHeight<$Y;if(i&&a)return}Pn(!1)},[Pn]),[Kn,qn]=(0,d.useState)(null),[Jn,Yn]=(0,d.useState)(null),Xn=(0,d.useMemo)(()=>{let e=c.sessions?.find(e=>e.id===c.sessionId);return c.sessionName?.trim()||e?.name?.trim()||e?.firstMessage?.trim()||c.sessionId},[c.sessionName,c.sessions,c.sessionId]),Zn=(0,d.useCallback)(async()=>{Yn(null),qn(`preparing…`);try{let{exportConversation:t}=await me(async()=>{let{exportConversation:e}=await import(`./conversationExport-jN-MYzY9.js`);return{exportConversation:e}},__vite__mapDeps([26,21,1,25]));await t({items:c.items,olderItems:c.olderHistory?.remaining??0,...c.olderHistory?{fetchOlderItems:se}:{},connection:{serverUrl:e,token:l,workspace:mt},meta:{...c.workspace?{project:c.workspace.name}:{},session:Xn,model:c.model,exportedAt:new Date},onProgress:(e,t,n)=>qn(e===`collecting`?`reading ${t}/${n}…`:`writing ${t}/${n}…`)})}catch(e){Yn(e instanceof Error?e.message:`the conversation could not be exported`)}finally{qn(null)}},[c.items,c.olderHistory,c.workspace,c.model,Xn,se,e,l,mt]),{jumpToItem:Qn,highlightIndex:$n}=lL({items:c.items,scrollerRef:En,hideTools:!Ut.tools,onShowTools:Wn,onJump:Gn}),er=(0,d.useRef)(null),tr=(0,d.useRef)(c.olderHistory?.have??0),nr=(0,d.useCallback)(()=>{let e=En.current;e&&(er.current={height:e.scrollHeight,top:e.scrollTop}),re()},[re]);return(0,d.useLayoutEffect)(()=>{let e=c.olderHistory?.have??0,t=tr.current;tr.current=e;let n=er.current;if(er.current=null,!n||e<=t)return;let r=En.current;r&&(r.scrollTop=n.top+(r.scrollHeight-n.height))},[c.olderHistory?.have]),(0,d.useEffect)(()=>{if(!o){let e=c.extensionTitle??c.branding.title??`pi`;document.title=c.workspace?`${c.workspace.name} — ${e}`:e}c.branding.accentColor&&s.style.setProperty(`--accent`,c.branding.accentColor)},[c.branding,c.extensionTitle,c.workspace?.name,o,s]),o&&!c.brandingReady?null:c.authRequired?(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(cV,{title:c.branding.title,onSubmit:u})}):c.credentials&&!c.credentials.usableModel?(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(GB,{title:c.branding.title,credentials:c.credentials,onSetCredential:Fe,onStartLogin:Ie,login:c.login,onAnswerLogin:Le,onCancelLogin:Re,onDismissLogin:ze,onDeclareProvider:Ve,errors:c.errors})}):(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(Hf.Provider,{value:c.replyConformance,children:(0,A.jsxs)(gf.Provider,{value:c.structuredAppearance,children:[(0,A.jsxs)(`div`,{className:`relative flex h-full`,onDragEnter:e=>{e.dataTransfer.types.includes(`Files`)&&hn(e=>e+1)},onDragLeave:()=>hn(e=>Math.max(0,e-1)),onDragOver:e=>e.preventDefault(),onDrop:Sn,children:[mn>0&&(0,A.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-40 flex items-center justify-center border-2 border-dashed bg-white/70 backdrop-blur-sm dark:bg-zinc-950/70`,style:{borderColor:`var(--accent, #3b82f6)`},children:(0,A.jsx)(`p`,{className:`text-lg font-medium text-zinc-700 dark:text-zinc-200`,children:`Drop files to attach (images, documents & text)`})}),gt&&(0,A.jsx)(sV,{tree:c.fileTree,openFile:c.openFile,writableRoot:c.writableRoot,gitFiles:c.gitStatus?.files,attachedPaths:vn,onExpand:ue,onSelectDirectory:Nt,onRefresh:de,onSelectFile:e=>{Ht(!1),Nt(e),j(e)},onSelectDiff:e=>{Ht(!0),Nt(e),j(e)},onToggleAttachPath:yn,onCreateFile:e=>{Ht(!1),pe(e)},onCreateDirectory:he,onOpenNative:_e,onRevealNative:ve,onRenameFile:ye,onDeleteFile:be,onMoveFile:xe,onCopyFile:Se,fileOperation:c.fileOperation,createError:c.createError,created:c.created}),(0,A.jsxs)(`div`,{className:`flex h-full min-w-0 flex-1 flex-col`,children:[Pt&&(0,A.jsx)(Rz,{label:`Choose a project directory`,browse:c.serverBrowse,onBrowse:Ze,onSelect:e=>{Ft(!1),Qe(),et(e)},onCancel:()=>{Ft(!1),Qe()}}),!o&&c.outpostUpdate&&(0,A.jsx)(OI,{notice:c.outpostUpdate}),(0,A.jsx)(jB,{workspace:c.workspace,workspaces:c.workspaces,workspaceLocked:c.workspaceLocked,workspaceControl:o?It:`projects`,rootControl:{sandbox:c.sandbox,browse:c.serverBrowse,applyState:c.settingsApply,blocked:At!==null&&At!==`root`,onBrowse:Ze,onCloseBrowser:()=>{jt(null),Qe()},onOpened:()=>jt(`root`),onSelect:e=>He({sandbox:{root:e,allowWrite:c.sandbox?.allowWrite??!1,allowBash:c.sandbox?.allowBash??!1,...c.sandbox?.writableRoot?{writableRoot:c.sandbox.writableRoot}:{}}})},onSwitchWorkspace:$e,onOpenProject:()=>{Ft(!0),Ze(``)},onCloseProject:tt,onOpenSideSession:nt,piPackages:c.piPackages,piPackageUpdate:c.piPackageUpdate,canRestartServer:!o,serverRestarting:c.serverRestarting,onCheckPiPackages:rt,onUpdatePiPackage:it,onRestartServer:at,restartNeeded:c.restartNeeded,title:c.branding.title,credentials:c.credentials,login:c.login,onStartLogin:Ie,onAnswerLogin:Le,onCancelLogin:Re,onDismissLogin:ze,onLogoutProvider:Be,sessions:c.sessions,sessionSearch:c.sessionSearch,sessionId:c.sessionId,tree:c.tree,isStreaming:c.isStreaming,connected:c.connected,theme:Cn,showThemeToggle:c.branding.allowThemeToggle!==!1,statuses:c.statuses,sidebarOpen:gt,outcomeOpen:$t,filters:Ut,onToggleSidebar:()=>_t(!gt),onToggleOutcome:sn,onFilterChange:Gt,...c.items.length>0?{onExportConversation:()=>void Zn()}:{},exportProgress:Kn,onToggleTheme:wn,onNewSession:v,onSwitchSession:b,onDeleteSession:x,onListSessions:S,onRenameSession:C,onSearchSessions:w,onClearSessionSearch:T,onListTree:ee,onNavigateTree:E,onForkSession:te,gitAvailable:c.gitAvailable,gitStatus:c.gitStatus,gitSelectedPath:Mt,gitLog:c.gitLog,extensionPaths:c.extensionPaths,configuredExtensionPaths:c.configuredExtensionPaths,userExtensionPaths:c.userExtensionPaths,extensionLock:c.extensionLock,tools:c.tools,commands:c.commands,sandbox:c.sandbox,gitUnavailable:c.gitUnavailable,userSkillPaths:c.userSkillPaths,serverBrowse:c.serverBrowse,settingsApply:c.settingsApply,agentResources:c.agentResources,agentResourceOperations:c.agentResourceOperations,versions:c.versions,onBrowseServerPath:Ze,onCloseServerBrowser:Qe,settingsPickerBlocked:At!==null&&At!==`settings`,onSettingsPickerOpened:()=>jt(`settings`),onUpdateConfig:He,onSuggestAgentResourceClonePath:Ue,onCloneAgentResourceRepository:We,onEnrollAgentResourceRepository:Ge,onSetAgentResourceSkills:Ke,onRemoveAgentResourceRepository:qe,onRefreshAgentResourceRepositories:Ye,onUpdateAgentResourceRepository:Xe,onFetchGitLog:Oe,onShowCommit:ke,terminalOpen:Xt,onToggleTerminal:Qt?()=>Zt(e=>!e):void 0}),(0,A.jsxs)(`div`,{className:`relative z-0 flex min-h-0 flex-1 flex-col`,children:[c.workPlan&&(0,A.jsx)(fV,{plan:c.workPlan,open:Jt,onToggle:on,onOpenWorkspace:e=>{Ht(!1),j(e)},requestedTaskId:tn,onTaskRequestHandled:rn}),$t&&(0,A.jsx)(kY,{state:c.outcome,onClose:()=>en(!1),onRefresh:pt,onTarget:e=>{e.kind===`work-plan-task`?(nn(e.taskId),en(!1),qt(!1),Yt(!0)):e.kind===`workspace-file`?(Ht(!1),j(e.path)):e.kind===`workspace-diff`&&(Ht(!0),j(e.path))}}),c.openFile&&(0,A.jsx)(QR,{file:c.openFile,writableRoot:c.writableRoot,docxTemplate:c.docxTemplate,isStreaming:c.isStreaming,onDirtyChange:kt,gitState:c.gitStatus?.files[c.openFile.path],initialShowGitDiff:Vt,gitDiff:c.gitDiff,gitBaseline:c.gitBaseline?.path===c.openFile.path?c.gitBaseline.text??null:null,onFetchGitDiff:Ee,onClearGitDiff:De,inRepository:_L(c.gitStatus?.repos??[],c.openFile.path)!==null,onOpenGitHistory:je,onClose:_n,onReload:j,onSave:fe,serverUrl:e,token:l,workspace:mt,onImageLoad:Tt,onPdfLoad:e=>Dt({path:e,revision:c.previewRevision}),rawRevision:c.previewRevision},c.openFile.path),c.gitFileHistory&&(0,A.jsx)(wz,{history:c.gitFileHistory,diff:c.gitFileDiff,dirty:c.gitStatus?.files[c.gitFileHistory.path]!==void 0,onFetchDiff:Ne,onClearDiff:Pe,onClose:Me}),c.gitShow&&(0,A.jsx)(ez,{show:c.gitShow,onClose:Ae}),Hn&&(0,A.jsx)(sL,{analysis:Hn,onJump:Qn,onClose:()=>qt(!1)}),(0,A.jsx)(`main`,{ref:kn,onScroll:Rn,onWheel:zn,onTouchStart:zn,onKeyDown:zn,className:`flex-1 overflow-y-auto transition-opacity duration-150 ${c.switching?`opacity-40`:`opacity-100`} ${Kt?`md:pr-[26rem]`:c.workPlan&&Jt?`md:pr-[23rem]`:``}`,children:(0,A.jsxs)(`div`,{className:`mx-auto flex max-w-3xl flex-col gap-3 px-4 py-6`,children:[c.items.length===0&&(0,A.jsxs)(`div`,{className:`mt-24 text-center text-zinc-500 dark:text-zinc-600`,children:[(0,A.jsx)(`div`,{className:`mb-2 text-4xl`,children:c.branding.title??`π`}),c.agentStarting?(0,A.jsx)(`p`,{className:`text-sm`,role:`status`,"data-testid":`agent-starting`,children:`Starting the agent… The project's files are ready.`}):(0,A.jsx)(`p`,{className:`text-sm`,children:c.branding.welcome??`Send a message to start the agent.`})]}),c.olderHistory&&(0,A.jsx)(MI,{older:c.olderHistory,onLoad:nr}),c.items.map((t,n)=>{let r=`${c.sessionId}:${n}`,i=(e,t=r)=>(0,A.jsx)(`div`,{"data-item-index":n,className:`flex flex-col gap-3 rounded-lg transition-shadow ${$n===n?`ring-2 ring-blue-400 dark:ring-blue-500`:``}`,children:e},t);return t.kind===`user`?i((0,A.jsx)(Je,{item:t,canEdit:!t.readOnly&&!c.isStreaming&&c.connected,onEdit:D})):t.kind===`compaction`?i((0,A.jsx)(jI,{item:t})):t.kind===`tool`?Ut.tools?i((0,A.jsx)(wI,{item:t,dispatch:Un}),t.toolCallId?`${c.sessionId}:${t.toolCallId}`:r):null:t.kind===`custom`?i((0,A.jsx)(TI,{item:t})):(Ut.reasoning?t.blocks:t.blocks.filter(e=>e.type!==`thinking`)).length===0&&!t.errorMessage?(0,A.jsx)(`div`,{"data-item-index":n,className:`sr-only`,"aria-hidden":!0},r):i((0,A.jsx)(BF,{item:t,hideReasoning:!Ut.reasoning,serverUrl:e,token:l,workspace:mt,onOpenFile:e=>{Ht(!1),j(e)}}))}),c.pendingPrompt&&(0,A.jsxs)(`div`,{className:`flex flex-col gap-3 opacity-60`,"data-pending-prompt":!0,children:[(0,A.jsx)(Je,{item:{kind:`user`,...c.pendingPrompt},canEdit:!1,onEdit:()=>{}}),c.extensionsBinding?(0,A.jsxs)(`div`,{className:`flex items-center gap-3`,"data-testid":`prompt-waiting-for-extensions`,children:[(0,A.jsx)(eX,{label:`waiting for extensions to start…`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>h(!Lt.current[ht??``]),className:`text-xs text-zinc-500 underline hover:text-zinc-700 dark:hover:text-zinc-300`,children:`cancel`})]}):(0,A.jsx)(eX,{label:`sending…`})]}),c.isStreaming&&!c.pendingPrompt&&(0,A.jsx)(eX,{label:`working…`}),(c.queue.steering.length>0||c.queue.followUp.length>0)&&(0,A.jsxs)(`div`,{className:`rounded-lg border border-dashed border-zinc-300 px-3 py-2 text-xs text-zinc-500 dark:border-zinc-700`,children:[c.queue.steering.map((e,t)=>(0,A.jsxs)(`div`,{children:[`⏩ steering: `,e]},`s${t}`)),c.queue.followUp.map((e,t)=>(0,A.jsxs)(`div`,{children:[`⏭ follow-up: `,e]},`f${t}`))]}),cn.map((e,t)=>(0,A.jsx)(`div`,{className:`rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:e},`att${t}`)),St&&(0,A.jsx)(`div`,{className:`rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:St}),Jn&&(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:Jn}),c.errors.map((e,t)=>(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e},t)),(0,A.jsx)(`div`,{ref:An})]})}),(0,A.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-4 z-0 flex justify-center ${Kt||$t?`md:pr-[26rem]`:c.workPlan&&Jt?`md:pr-[23rem]`:``}`,children:!Mn&&(0,A.jsxs)(`button`,{type:`button`,onClick:Bn,"aria-label":`Scroll to the latest message`,className:`pointer-events-auto flex items-center gap-1.5 rounded-full border border-zinc-300 bg-white/95 px-3 py-1.5 text-xs text-zinc-600 shadow-lg backdrop-blur transition-colors hover:bg-zinc-50 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900/95 dark:text-zinc-300 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,children:`↓`}),`Latest`]})})]}),Qt&&(0,A.jsx)(TY,{open:Xt,onClose:()=>Zt(!1),cwd:c.workspace?.root,confinedRoot:c.terminal?.confined?c.sandbox?.root??c.workspace?.root:void 0,confinement:c.confinement?.terminal,unavailable:c.terminal?.unavailable,onSetWorkspaceRoot:e=>{et&&!o?et(e):c.sandbox?He({sandbox:{root:e,allowWrite:c.sandbox.allowWrite,allowBash:c.sandbox.allowBash,...c.sandbox.writableRoot?{writableRoot:c.sandbox.writableRoot}:{}}}):He({sandbox:{root:e,allowWrite:!0,allowBash:!0}})},openTerminal:ot,sendTerminalInput:st,getTerminalCwd:ct,resizeTerminal:lt,closeTerminal:ut,subscribeTerminal:dt}),(0,A.jsx)(`footer`,{className:`border-t border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:(0,A.jsxs)(`div`,{className:`mx-auto max-w-3xl`,children:[(0,A.jsx)(bR,{widgets:c.widgets,placement:`aboveEditor`}),(0,A.jsx)($L,{initialDraft:Lt.current[ht??``]??``,onDraftChange:e=>{Lt.current[ht??``]=e},isStreaming:c.isStreaming,connected:c.connected,commands:c.commands,fileSearch:c.fileSearch,prefill:c.editorPrefill,attachments:vt,pendingUploads:un,onAttach:e=>void gn(e),onMentionPaths:xt,onRemoveAttachment:bn,onSend:xn,onAbort:m,onSearchFiles:we,onClearFileSearch:Te},ht??``),(0,A.jsx)(bR,{widgets:c.widgets,placement:`belowEditor`}),(0,A.jsx)(HB,{model:c.model,models:c.models,thinkingLevel:c.thinkingLevel,thinkingLevels:c.thinkingLevels,modelSupportsReasoning:c.modelSupportsReasoning,isStreaming:c.isStreaming,contextUsage:c.contextUsage,shellConfinement:c.confinement?.bash,sessionUsage:Vn,analysisOpen:Kt,onToggleAnalysis:an,isCompacting:c.isCompacting,onSetModel:g,onSetThinking:_,onCompact:ne})]})})]})]}),c.dialogQueue[0]&&(0,A.jsx)(lR,{request:c.dialogQueue[0],onRespond:ce}),(0,A.jsx)(pR,{notifications:c.notifications,onDismiss:le})]})})})});(0,f.createRoot)(document.getElementById(`root`)).render((0,A.jsx)(d.StrictMode,{children:(0,A.jsx)(tX,{})}));export{re as A,qf as C,ce as D,me as E,i as M,ne as O,$f as S,Fe as T,O_ as _,NF as a,Pp as b,yM as c,mD as d,eD as f,Kv as g,by as h,IF as i,E as j,ae as k,eM as l,Fb as m,zR as n,xF as o,ZE as p,VR as r,bM as s,IY as t,OD as u,Ip as v,yd as w,Ap as x,Np as y};
377
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),jK&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=eq(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=hK(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-tq),tq),t/=tq,t/Math.abs(t)+Math.round(t*(nq-1)))}shouldForceSelection(e){return DK?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),rq)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(DK&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<iq&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=BK(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=eq(n,this._bufferService.cols)}};oq=SV([CV(3,XV),CV(4,QV),CV(5,uH),CV(6,nH),CV(7,dH),CV(8,lH)],oq);var sq=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},cq=class{constructor(){this._color=new sq,this._css=new sq}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},lq=Object.freeze((()=>{let e=[LG.toColor(`#2e3436`),LG.toColor(`#cc0000`),LG.toColor(`#4e9a06`),LG.toColor(`#c4a000`),LG.toColor(`#3465a4`),LG.toColor(`#75507b`),LG.toColor(`#06989a`),LG.toColor(`#d3d7cf`),LG.toColor(`#555753`),LG.toColor(`#ef2929`),LG.toColor(`#8ae234`),LG.toColor(`#fce94f`),LG.toColor(`#729fcf`),LG.toColor(`#ad7fa8`),LG.toColor(`#34e2e2`),LG.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:FG.toCss(r,i,a),rgba:FG.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:FG.toCss(n,n,n),rgba:FG.toRgba(n,n,n)})}return e})()),uq=LG.toColor(`#ffffff`),dq=LG.toColor(`#000000`),fq=LG.toColor(`#ffffff`),pq=dq,mq={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},hq=uq,gq=class extends zH{constructor(e){super(),this._optionsService=e,this._contrastCache=new cq,this._halfContrastCache=new cq,this._onChangeColors=this._register(new aU),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:uq,background:dq,cursor:fq,cursorAccent:pq,selectionForeground:void 0,selectionBackgroundTransparent:mq,selectionBackgroundOpaque:IG.blend(dq,mq),selectionInactiveBackgroundTransparent:mq,selectionInactiveBackgroundOpaque:IG.blend(dq,mq),scrollbarSliderBackground:IG.opacity(uq,.2),scrollbarSliderHoverBackground:IG.opacity(uq,.4),scrollbarSliderActiveBackground:IG.opacity(uq,.5),overviewRulerBorder:uq,ansi:lq.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=_q(e.foreground,uq),t.background=_q(e.background,dq),t.cursor=IG.blend(t.background,_q(e.cursor,fq)),t.cursorAccent=IG.blend(t.background,_q(e.cursorAccent,pq)),t.selectionBackgroundTransparent=_q(e.selectionBackground,mq),t.selectionBackgroundOpaque=IG.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=_q(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=IG.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?_q(e.selectionForeground,PG):void 0,t.selectionForeground===PG&&(t.selectionForeground=void 0),IG.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=IG.opacity(t.selectionBackgroundTransparent,.3)),IG.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=IG.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=_q(e.scrollbarSliderBackground,IG.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=_q(e.scrollbarSliderHoverBackground,IG.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=_q(e.scrollbarSliderActiveBackground,IG.opacity(t.foreground,.5)),t.overviewRulerBorder=_q(e.overviewRulerBorder,hq),t.ansi=lq.slice(),t.ansi[0]=_q(e.black,lq[0]),t.ansi[1]=_q(e.red,lq[1]),t.ansi[2]=_q(e.green,lq[2]),t.ansi[3]=_q(e.yellow,lq[3]),t.ansi[4]=_q(e.blue,lq[4]),t.ansi[5]=_q(e.magenta,lq[5]),t.ansi[6]=_q(e.cyan,lq[6]),t.ansi[7]=_q(e.white,lq[7]),t.ansi[8]=_q(e.brightBlack,lq[8]),t.ansi[9]=_q(e.brightRed,lq[9]),t.ansi[10]=_q(e.brightGreen,lq[10]),t.ansi[11]=_q(e.brightYellow,lq[11]),t.ansi[12]=_q(e.brightBlue,lq[12]),t.ansi[13]=_q(e.brightMagenta,lq[13]),t.ansi[14]=_q(e.brightCyan,lq[14]),t.ansi[15]=_q(e.brightWhite,lq[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=_q(e.extendedAnsi[r],lq[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};gq=SV([CV(0,nH)],gq);function _q(e,t){if(e!==void 0)try{return LG.toColor(e)}catch{}return t}var vq=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},yq=class{constructor(){this._services=new vq,this._services.set(eH,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=qV(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},bq={trace:0,debug:1,info:2,warn:3,error:4,off:5},xq=`xterm.js: `,Sq=class extends zH{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),Cq=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=bq[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:xq)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};Sq=SV([CV(0,nH)],Sq);var Cq,wq=class extends zH{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new aU),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new aU),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new aU),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Tq=3,Eq=Object.freeze(new VV),Dq=0,Oq=2,kq=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*Tq);let r=t||UV.fromCharData([0,zV,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*Tq+0],n=t&2097151;return[this._data[e*Tq+1],t&2097152?this._combined[e]:n?FV(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*Tq+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*Tq+0]=e|2097152|t[2]<<22):this._data[e*Tq+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*Tq+0]>>22}hasWidth(e){return this._data[e*Tq+0]&12582912}getFg(e){return this._data[e*Tq+1]}getBg(e){return this._data[e*Tq+2]}hasContent(e){return this._data[e*Tq+0]&4194303}getCodePoint(e){let t=this._data[e*Tq+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*Tq+0]&2097152}getString(e){let t=this._data[e*Tq+0];return t&2097152?this._combined[e]:t&2097151?FV(t&2097151):``}isProtected(e){return this._data[e*Tq+2]&536870912}loadCell(e,t){return Dq=e*Tq,t.content=this._data[Dq+0],t.fg=this._data[Dq+1],t.bg=this._data[Dq+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*Tq+0]=t.content,this._data[e*Tq+1]=t.fg,this._data[e*Tq+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*Tq+0]=t|n<<22,this._data[e*Tq+1]=r.fg,this._data[e*Tq+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*Tq+0];r&2097152?this._combined[e]+=FV(t):r&2097151?(this._combined[e]=FV(r&2097151)+FV(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*Tq+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new UV;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new UV;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*Oq<this._data.buffer.byteLength;let n=e*Tq;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*Oq<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*Oq<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*Tq+0]&4194303)return e+(this._data[e*Tq+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*Tq+0]&4194303||this._data[e*Tq+2]&50331648)return e+(this._data[e*Tq+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<Tq;e++)this._data[(n+i)*Tq+e]=a[(t+i)*Tq+e];a[(t+i)*Tq+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<Tq;e++)this._data[(n+i)*Tq+e]=a[(t+i)*Tq+e];a[(t+i)*Tq+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*Tq+0],n=e&2097151,a=e&2097152?this._combined[t]:n?FV(n):BV;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function Aq(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=Pq(u,d,t),p=1,m=0;for(;p<u.length;){let e=Pq(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function jq(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function Mq(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function Nq(e,t,n){let r=[],i=e.map((n,r)=>Pq(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=Pq(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function Pq(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Fq=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new aU),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),PH(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Fq._nextId=1;var Iq=Fq,Lq={},Rq=Lq.B;Lq[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Lq.A={"#":`£`},Lq.B=void 0,Lq[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Lq.C=Lq[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Lq.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Lq.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Lq.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Lq.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Lq.E=Lq[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Lq.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Lq.H=Lq[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Lq[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var zq=4294967295,Bq=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Eq.clone(),this.savedCharset=Rq,this.markers=[],this._nullCell=UV.fromCharData([0,zV,1,0]),this._whitespaceCell=UV.fromCharData([0,BV,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new IK,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new wq(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new HV),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new HV),this._whitespaceCell}getBlankLine(e,t){return new kq(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>zq?zq:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Eq);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new wq(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(Eq),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new kq(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new kq(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=Aq(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Eq),n);if(r.length>0){let n=jq(this.lines,r);Mq(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(Eq),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new kq(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(Eq),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=Nq(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(Eq,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=Pq(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Iq(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Vq=class extends zH{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new aU),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Bq(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Bq(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Hq=2,Uq=1,Wq=class extends zH{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new aU),this.onResize=this._onResize.event,this._onScroll=this._register(new aU),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Hq),this.rows=Math.max(e.rawOptions.rows||0,Uq),this.buffers=this._register(new Vq(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Wq=SV([CV(0,nH)],Wq);var Gq={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:DK,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Kq=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],qq=class extends zH{constructor(e){super(),this._onOptionChange=this._register(new aU),this.onOptionChange=this._onOptionChange.event;let t={...Gq};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(IH(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Gq))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Gq))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Gq[e],!Jq(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Gq[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Kq.includes(t)?t:Gq[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Jq(e){return e===`block`||e===`underline`||e===`bar`}function Yq(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Yq(e[r],t-1);return n}var Xq=Object.freeze({insertMode:!1}),Zq=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Qq=class extends zH{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new aU),this.onData=this._onData.event,this._onUserInput=this._register(new aU),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new aU),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new aU),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Yq(Xq),this.decPrivateModes=Yq(Zq)}reset(){this.modes=Yq(Xq),this.decPrivateModes=Yq(Zq)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Qq=SV([CV(0,XV),CV(1,tH),CV(2,nH)],Qq);var $q={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function eJ(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var tJ=String.fromCharCode,nJ={DEFAULT:e=>{let t=[eJ(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${tJ(t[0])}${tJ(t[1])}${tJ(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${eJ(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${eJ(e,!0)};${e.x};${e.y}${t}`}},rJ=class extends zH{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new aU),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys($q))this.addProtocol(e,$q[e]);for(let e of Object.keys(nJ))this.addEncoding(e,nJ[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};rJ=SV([CV(0,XV),CV(1,QV),CV(2,nH)],rJ);var iJ=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],aJ=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],oJ;function sJ(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var cJ=class{constructor(){if(this.version=`6`,!oJ){oJ=new Uint8Array(65536),oJ.fill(1),oJ[0]=0,oJ.fill(0,1,32),oJ.fill(0,127,160),oJ.fill(2,4352,4448),oJ[9001]=2,oJ[9002]=2,oJ.fill(2,11904,42192),oJ[12351]=1,oJ.fill(2,44032,55204),oJ.fill(2,63744,64256),oJ.fill(2,65040,65050),oJ.fill(2,65072,65136),oJ.fill(2,65280,65377),oJ.fill(2,65504,65511);for(let e=0;e<iJ.length;++e)oJ.fill(0,iJ[e][0],iJ[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?oJ[e]:sJ(e,aJ)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=lJ.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return lJ.createPropertyValue(0,n,r)}},lJ=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new aU,this.onChange=this._onChange.event;let e=new cJ;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},uJ=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function dJ(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var fJ=2147483647,pJ=256,mJ=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>pJ)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>fJ?fJ:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>fJ?fJ:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,fJ):e}},hJ=[],gJ=class{constructor(){this._state=0,this._active=hJ,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=hJ}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=hJ,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||hJ,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,IV(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=hJ,this._id=-1,this._state=0}}},_J=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=IV(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},vJ=[],yJ=class{constructor(){this._handlers=Object.create(null),this._active=vJ,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vJ}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=vJ,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vJ,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,IV(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=vJ,this._ident=0}},bJ=new mJ;bJ.addParam(0);var xJ=class{constructor(e){this._handler=e,this._data=``,this._params=bJ,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():bJ,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=IV(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=bJ,this._data=``,this._hitLimit=!1,e));return this._params=bJ,this._data=``,this._hitLimit=!1,t}},SJ=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},CJ=160,wJ=function(){let e=new SJ(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(CJ,0,2,0),e.add(CJ,8,5,8),e.add(CJ,6,0,6),e.add(CJ,11,0,11),e.add(CJ,13,13,13),e}(),TJ=class extends zH{constructor(e=wJ){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new mJ,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(IH(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new gJ),this._dcsParser=this._register(new yJ),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:CJ)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<CJ||++i>=t||(r=e[i])<32||r>126&&r<CJ||++i>=t||(r=e[i])<32||r>126&&r<CJ||++i>=t||(r=e[i])<32||r>126&&r<CJ){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<CJ){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<CJ){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},EJ=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,DJ=/^[\da-f]+$/;function OJ(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=EJ.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),DJ.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function kJ(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function AJ(e,t=16){let[n,r,i]=e;return`rgb:${kJ(n,t)}/${kJ(r,t)}/${kJ(i,t)}`}var jJ={"(":0,")":1,"*":2,"+":3,"-":1,".":2},MJ=131072,NJ=10;function PJ(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var FJ=5e3,IJ=0,LJ=class extends zH{constructor(e,t,n,r,i,a,o,s,c=new TJ){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new LV,this._utf8Decoder=new RV,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Eq.clone(),this._eraseAttrDataInternal=Eq.clone(),this._onRequestBell=this._register(new aU),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new aU),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new aU),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new aU),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new aU),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new aU),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new aU),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new aU),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new aU),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new aU),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new aU),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new aU),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new aU),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new RJ(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(DG.IND,()=>this.index()),this._parser.setExecuteHandler(DG.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(DG.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new _J(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new _J(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new _J(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new _J(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new _J(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new _J(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new _J(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new _J(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new _J(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new _J(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new _J(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new _J(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in Lq)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new xJ((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),FJ))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${FJ} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>MJ&&(a=this._parseStack.position+MJ)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<MJ&&(this._parseBuffer=new Uint32Array(Math.min(e.length,MJ))),o||this._dirtyRowTracker.clearRange(),e.length>MJ)for(let t=a;t<e.length;t+=MJ){let a=t+MJ<e.length?t+MJ:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=lJ.extractWidth(t);let n=lJ.extractShouldJoin(t),m=n?lJ.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(FV(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof kq&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!PJ(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new xJ(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _J(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Eq));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=lJ.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Rq),this._charsetService.setgCharset(1,Rq),this._charsetService.setgCharset(2,Rq),this._charsetService.setgCharset(3,Rq);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=VV.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Eq.fg,e.bg=Eq.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=Eq.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=Eq.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=Eq.fg&16777215,r.bg&=-67108864,r.bg|=Eq.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Eq.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!PJ(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>NJ&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>NJ&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(zJ(n)){if(r===`?`)t.push({type:0,index:n});else{let e=OJ(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=OJ(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);zJ(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Rq),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(jJ[e[0]],Lq[e[1]]||Rq),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Eq.clone(),this._eraseAttrDataInternal=Eq.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new UV;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},RJ=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(IJ=e,e=t,t=IJ),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};RJ=SV([CV(0,XV)],RJ);function zJ(e){return 0<=e&&e<256}var BJ=5e7,VJ=12,HJ=50,UJ=class extends zH{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new aU),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>BJ)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=VJ?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=VJ)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>HJ&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},WJ=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};WJ=SV([CV(0,XV)],WJ);var GJ=!1,KJ=class extends zH{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new BH),this._onBinary=this._register(new aU),this.onBinary=this._onBinary.event,this._onData=this._register(new aU),this.onData=this._onData.event,this._onLineFeed=this._register(new aU),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new aU),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new aU),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new aU),this._instantiationService=new yq,this.optionsService=this._register(new qq(e)),this._instantiationService.setService(nH,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Wq)),this._instantiationService.setService(XV,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Sq)),this._instantiationService.setService(tH,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Qq)),this._instantiationService.setService(QV,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(rJ)),this._instantiationService.setService(ZV,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(lJ)),this._instantiationService.setService(iH,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uJ),this._instantiationService.setService($V,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(WJ),this._instantiationService.setService(rH,this._oscLinkService),this._inputHandler=this._register(new LJ(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(qH.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(qH.forward(this._bufferService.onResize,this._onResize)),this._register(qH.forward(this.coreService.onData,this._onData)),this._register(qH.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new UJ((e,t)=>this._inputHandler.parse(e,t))),this._register(qH.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new aU),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!GJ&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),GJ=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Hq),t=Math.max(t,Uq),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(dJ.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(dJ(this._bufferService),!1))),this._windowsWrappingHeuristics.value=IH(()=>{for(let t of e)t.dispose()})}}},qJ={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function JJ(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=qJ[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var YJ=0,XJ=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new IK,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new IK,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(YJ=this._search(t),YJ===-1)||this._getKey(this._array[YJ])!==t)return!1;do if(this._array[YJ]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(YJ),!0;while(++YJ<this._array.length&&this._getKey(this._array[YJ])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(YJ=this._search(e),!(YJ<0||YJ>=this._array.length)&&this._getKey(this._array[YJ])===e))do yield this._array[YJ];while(++YJ<this._array.length&&this._getKey(this._array[YJ])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(YJ=this._search(e),!(YJ<0||YJ>=this._array.length)&&this._getKey(this._array[YJ])===e))do t(this._array[YJ]);while(++YJ<this._array.length&&this._getKey(this._array[YJ])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},ZJ=0,QJ=0,$J=class extends zH{constructor(){super(),this._decorations=new XJ(e=>e?.marker.line),this._onDecorationRegistered=this._register(new aU),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new aU),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(IH(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new eY(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{ZJ=t.options.x??0,QJ=ZJ+(t.options.width??1),e>=ZJ&&e<QJ&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},eY=class extends RH{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new aU),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new aU),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?LG.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?LG.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},tY=1e3,nY=class{constructor(e,t=tY){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},rY=20,iY=class extends zH{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new nY(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
378
+ `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(AW(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(IH(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<rY+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
379
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===rY+1&&(this._liveRegion.textContent+=DV.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};iY=SV([CV(1,eH),CV(2,lH),CV(3,dH)],iY);var aY=class extends zH{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new aU),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new aU),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(IH(()=>{PH(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(AW(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(AW(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(AW(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(AW(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&oY(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,PH(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};aY=SV([CV(1,uH),CV(2,dH),CV(3,XV),CV(4,hH)],aY);function oY(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var sY=class extends KJ{constructor(e={}){super(e),this._linkifier=this._register(new BH),this.browser=yK,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new BH),this._onCursorMove=this._register(new aU),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new aU),this.onKey=this._onKey.event,this._onRender=this._register(new aU),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new aU),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new aU),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new aU),this.onBell=this._onBell.event,this._onFocus=this._register(new aU),this._onBlur=this._register(new aU),this._onA11yCharEmitter=this._register(new aU),this._onA11yTabEmitter=this._register(new aU),this._onWillOpen=this._register(new aU),this._setup(),this._decorationService=this._instantiationService.createInstance($J),this._instantiationService.setService(aH,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(mK),this._instantiationService.setService(hH,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(oH)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(qH.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(qH.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(qH.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(qH.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(IH(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=IG.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${AJ(r)}${OG.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=FG.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=FG.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(iY,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(AW(this.element,`copy`,e=>{this.hasSelection()&&AV(e,this._selectionService)}));let e=e=>jV(e,this.textarea,this.coreService,this.optionsService);this._register(AW(this.textarea,`paste`,e)),this._register(AW(this.element,`paste`,e)),CK?this._register(AW(this.element,`mousedown`,e=>{e.button===2&&PV(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(AW(this.element,`contextmenu`,e=>{PV(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),jK&&this._register(AW(this.element,`auxclick`,e=>{e.button===1&&NV(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(AW(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(AW(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(AW(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(AW(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(AW(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(AW(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(AW(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(AW(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,TV.get()),MK||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(fK,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(lH,this._coreBrowserService),this._register(AW(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(AW(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(cK,this._document,this._helperContainer),this._instantiationService.setService(cH,this._charSizeService),this._themeService=this._instantiationService.createInstance(gq),this._instantiationService.setService(mH,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(UG),this._instantiationService.setService(pH,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(RK,this.rows,this.screenElement)),this._instantiationService.setService(dH,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(kG,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(_K),this._instantiationService.setService(uH,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(aY,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(bG,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(oq,this.element,this.screenElement,r)),this._instantiationService.setService(fH,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(qH.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(xG,this.screenElement)),this._register(AW(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(iY,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(EG,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(EG,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(sK,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(AW(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(AW(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){MV(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=JJ(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(cY(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(Eq));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function cY(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var lY=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},uY=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new UV)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},dY=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new uY(t)}getNullCell(){return new UV}},fY=class extends zH{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new aU),this.onBufferChange=this._onBufferChange.event,this._normal=new dY(this._core.buffers.normal,`normal`),this._alternate=new dY(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},pY=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},mY=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},hY=[`cols`,`rows`],gY=0,_Y=class extends zH{constructor(e){super(),this._core=this._register(new sY(e)),this._addonManager=this._register(new lY),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(hY.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new pY(this._core),this._parser}get unicode(){return this._checkProposedApi(),new mY(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new fY(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
380
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return TV.get()},set promptLabel(e){TV.set(e)},get tooMuchOutput(){return DV.get()},set tooMuchOutput(e){DV.set(e)}}}_verifyIntegers(...e){for(gY of e)if(gY===1/0||isNaN(gY)||gY%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(gY of e)if(gY&&(gY===1/0||isNaN(gY)||gY%1!=0||gY<0))throw Error(`This API only accepts positive integers`)}},vY=2,yY=1,bY=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(vY,Math.floor(u/e.css.cell.width)),rows:Math.max(yY,Math.floor(l/e.css.cell.height))}}},xY=class{constructor(e,t,n,r={}){this._terminal=e,this._regex=t,this._handler=n,this._options=r}provideLinks(e,t){let n=CY.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(n))}_addCallbacks(e){return e.map(e=>(e.leave=this._options.leave,e.hover=(t,n)=>{if(this._options.hover){let{range:r}=e;this._options.hover(t,n,r)}},e))}};function SY(e){try{let t=new URL(e),n=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(n.toLocaleLowerCase())}catch{return!1}}var CY=class e{static computeLink(t,n,r,i){let a=new RegExp(n.source,(n.flags||``)+`g`),[o,s]=e._getWindowedLineStrings(t-1,r),c=o.join(``),l,u=[];for(;l=a.exec(c);){let t=l[0];if(!SY(t))continue;let[n,a]=e._mapStrIdx(r,s,0,l.index),[o,c]=e._mapStrIdx(r,n,a,t.length);if(n===-1||a===-1||o===-1||c===-1)continue;let d={start:{x:a+1,y:n+1},end:{x:c,y:o+1}};u.push({range:d,text:t,activate:i})}return u}static _getWindowedLineStrings(e,t){let n,r=e,i=e,a=0,o=``,s=[];if(n=t.buffer.active.getLine(e)){let e=n.translateToString(!0);if(n.isWrapped&&e[0]!==` `){for(a=0;(n=t.buffer.active.getLine(--r))&&a<2048&&(o=n.translateToString(!0),a+=o.length,s.push(o),n.isWrapped&&o.indexOf(` `)===-1););s.reverse()}for(s.push(e),a=0;(n=t.buffer.active.getLine(++i))&&n.isWrapped&&a<2048&&(o=n.translateToString(!0),a+=o.length,s.push(o),o.indexOf(` `)===-1););}return[s,r]}static _mapStrIdx(e,t,n,r){let i=e.buffer.active,a=i.getNullCell(),o=n;for(;r;){let e=i.getLine(t);if(!e)return[-1,-1];for(let n=o;n<e.length;++n){e.getCell(n,a);let o=a.getChars();if(a.getWidth()&&(r-=o.length||1,n===e.length-1&&o===``)){let e=i.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,a),a.getWidth()===2&&(r+=1))}if(r<0)return[t,n]}t++,o=0}return[t,o]}},wY=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function TY(e,t){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}var EY=class{constructor(e=TY,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;let t=this._options,n=t.urlRegex||wY;this._linkProvider=this._terminal.registerLinkProvider(new xY(this._terminal,n,this._handler,t))}dispose(){this._linkProvider?.dispose()}},DY={background:`#09090b`,foreground:`#f4f4f5`,cursor:`#38bdf8`,cursorAccent:`#09090b`,selectionBackground:`rgba(56, 189, 248, 0.3)`,black:`#27272a`,red:`#f87171`,green:`#4ade80`,yellow:`#facc15`,blue:`#60a5fa`,magenta:`#c084fc`,cyan:`#38bdf8`,white:`#f4f4f5`,brightBlack:`#52525b`,brightRed:`#ef4444`,brightGreen:`#22c55e`,brightYellow:`#eab308`,brightBlue:`#3b82f6`,brightMagenta:`#a855f7`,brightCyan:`#06b6d4`,brightWhite:`#ffffff`},OY={background:`#ffffff`,foreground:`#18181b`,cursor:`#0284c7`,cursorAccent:`#ffffff`,selectionBackground:`rgba(2, 132, 199, 0.2)`,black:`#18181b`,red:`#dc2626`,green:`#16a34a`,yellow:`#ca8a04`,blue:`#2563eb`,magenta:`#9333ea`,cyan:`#0891b2`,white:`#e4e4e7`,brightBlack:`#71717a`,brightRed:`#b91c1c`,brightGreen:`#15803d`,brightYellow:`#a16207`,brightBlue:`#1d4ed8`,brightMagenta:`#7e22ce`,brightCyan:`#0e7490`,brightWhite:`#27272a`};function kY(e){if(!e)return``;let t=e.split(/[\\/]/).filter(Boolean);return t.length<=3?e:`…/`+t.slice(-3).join(`/`)}function AY({id:e,cwd:t,isActive:n,isPanelOpen:r,renaming:i,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m}){let h=(0,d.useRef)(null),g=(0,d.useRef)(null),_=(0,d.useRef)(null),v=(0,d.useContext)(p)===`dark`,y=(0,d.useRef)({cwd:t,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m});return y.current={cwd:t,openTerminal:a,sendTerminalInput:o,getTerminalCwd:s,resizeTerminal:c,closeTerminal:l,subscribeTerminal:u,onCwdUpdate:f,registerClear:m},(0,d.useEffect)(()=>{g.current&&(g.current.options.theme=v?DY:OY)},[v]),(0,d.useEffect)(()=>{if(!h.current)return;let t=new _Y({cursorBlink:!0,cursorStyle:`block`,fontSize:13,fontFamily:`'JetBrains Mono', 'Fira Code', ui-monospace, Menlo, Monaco, 'Courier New', monospace`,lineHeight:1.2,theme:v?DY:OY}),n=new bY;t.loadAddon(n),t.loadAddon(new EY),t.open(h.current),n.fit(),g.current=t,_.current=n,y.current.registerClear(e,()=>{t.clear()}),y.current.openTerminal?.(e,y.current.cwd,t.cols,t.rows);let r=null,i=0,a=()=>{let t=Date.now();t-i<1e3?r||=setTimeout(()=>{r=null,i=Date.now(),y.current.getTerminalCwd?.(e)},1e3-(t-i)):(i=t,y.current.getTerminalCwd?.(e))},o=t.onData(t=>{y.current.sendTerminalInput?.(e,t),(t.includes(`\r`)||t.includes(`
381
+ `))&&a()}),s=y.current.subscribeTerminal?.(e,{onData:n=>{t.write(n);let r=n.match(/\x1b\]7;file:\/\/[^/]*([^\x07\x1b]+)(?:\x07|\x1b\\)/);if(r&&r[1])try{let t=decodeURIComponent(r[1]);y.current.onCwdUpdate(e,t)}catch{}},onCwd:t=>{y.current.onCwdUpdate(e,t)},onExit:e=>{t.writeln(`\r\n\x1b[90m[Process completed (exit code ${e??0})]\x1b[0m`)},onError:e=>{t.writeln(`\r\n\x1b[31m[Terminal error: ${e}]\x1b[0m`)}})??(()=>{}),c=new ResizeObserver(()=>{if(h.current&&h.current.clientWidth>0&&h.current.clientHeight>0)try{n.fit(),t.cols>0&&t.rows>0&&y.current.resizeTerminal?.(e,t.cols,t.rows)}catch{}});return c.observe(h.current),()=>{o.dispose(),s(),c.disconnect(),t.dispose(),y.current.closeTerminal?.(e)}},[e]),(0,d.useEffect)(()=>{if(!i&&r&&n&&_.current&&g.current&&h.current){y.current.getTerminalCwd?.(e);let t=setTimeout(()=>{try{_.current?.fit(),g.current?.focus()}catch{}},50);return()=>clearTimeout(t)}},[r,n,e,i]),(0,A.jsx)(`div`,{ref:h,className:`h-full w-full p-2 bg-white dark:bg-zinc-950 overflow-hidden ${n?`block`:`hidden`}`})}function jY({open:e,onClose:t,cwd:n,confinedRoot:r,confinement:i,unavailable:a,onSetWorkspaceRoot:o,openTerminal:s,sendTerminalInput:c,getTerminalCwd:l,resizeTerminal:u,closeTerminal:f,subscribeTerminal:p}){let[m,h]=(0,d.useState)(e);(0,d.useEffect)(()=>{e&&h(!0)},[e]);let[g,_]=(0,d.useState)([{id:`term-1`,title:`terminal 1`}]),[v,y]=(0,d.useState)(`term-1`),[b,x]=(0,d.useState)(null),[S,C]=(0,d.useState)(``),[w,T]=(0,d.useState)({}),[ee,E]=(0,d.useState)(!1),[te,D]=(0,d.useState)(!1),ne=(0,d.useRef)(new Map),re=(0,d.useCallback)((e,t)=>{ne.current.set(e,t)},[]),ie=(0,d.useCallback)((e,t)=>{T(n=>({...n,[e]:t}))},[]),O=(0,d.useCallback)(()=>{let e=g.length+1,t=`term-${Date.now()}-${e}`,n={id:t,title:`terminal ${e}`};_(e=>[...e,n]),y(t)},[g.length]),k=(0,d.useCallback)((e,n)=>{n.stopPropagation(),g.length<=1?t():(_(t=>{let n=t.filter(t=>t.id!==e);if(v===e){let r=t.findIndex(t=>t.id===e),i=n[Math.max(0,r-1)]?.id??n[0]?.id;y(i)}return n}),ne.current.delete(e),T(t=>{let n={...t};return delete n[e],n}))},[g.length,v,t]),ae=(e,t)=>{t.stopPropagation(),x(e.id),C(e.title)},oe=()=>{if(b){let e=S.trim();e&&_(t=>t.map(t=>t.id===b?{...t,title:e}:t)),x(null)}},se=e=>{e.key===`Enter`?oe():e.key===`Escape`&&x(null)},ce=(0,d.useCallback)(()=>{let e=ne.current.get(v);e&&e()},[v]),le=w[v]||n||``;return m?(0,A.jsxs)(`div`,{className:`flex-col border-t border-zinc-200 dark:border-zinc-800 bg-zinc-100 dark:bg-zinc-900 transition-all duration-150 ${e?`flex`:`hidden`} ${ee?`h-[85vh]`:`h-72`} relative z-20`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-1 border-b border-zinc-200 dark:border-zinc-800 select-none bg-zinc-50 dark:bg-zinc-950 text-xs`,children:[(0,A.jsxs)(`div`,{className:`flex items-center space-x-1 overflow-x-auto min-w-0`,children:[(0,A.jsx)(`div`,{className:`flex items-center space-x-1`,children:g.map(e=>{let t=e.id===v,n=e.id===b;return(0,A.jsxs)(`div`,{onClick:()=>y(e.id),onDoubleClick:t=>ae(e,t),title:`Double-click to rename tab`,className:`flex items-center space-x-1 px-2.5 py-1 rounded text-xs cursor-pointer transition-colors ${t?`bg-zinc-200 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 font-medium shadow-sm`:`text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-200/50 dark:hover:bg-zinc-800/50`}`,children:[n?(0,A.jsx)(`input`,{type:`text`,"data-testid":`terminal-tab-rename-input`,value:S,autoFocus:!0,onChange:e=>C(e.target.value),onBlur:oe,onKeyDown:se,className:`bg-transparent border border-sky-500 rounded px-1 py-0 text-xs font-mono outline-none text-zinc-900 dark:text-zinc-100 w-24`}):(0,A.jsx)(`span`,{children:e.title}),g.length>1&&(0,A.jsx)(`span`,{onClick:t=>k(e.id,t),role:`button`,tabIndex:0,"aria-label":`Close terminal tab`,className:`ml-1 hover:text-red-500 rounded p-0.5 hover:bg-zinc-200 dark:hover:bg-zinc-700`,children:(0,A.jsx)(`svg`,{className:`w-3 h-3`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]},e.id)})}),(0,A.jsx)(`button`,{onClick:O,type:`button`,title:`New Terminal Tab`,className:`p-1 rounded text-zinc-500 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 4v16m8-8H4`})})})]}),r&&!a&&(0,A.jsx)(UB,{verdict:i??{state:`checking`,runner:``},surface:`terminal`,root:kY(r)}),le&&(0,A.jsx)(`div`,{className:`hidden md:flex items-center space-x-1.5 px-2 text-xs font-mono text-zinc-500 dark:text-zinc-400`,children:o&&(0,A.jsx)(`button`,{onClick:()=>{if(le&&o){if((le===`/`||le===`\\`||/^[A-Za-z]:[\\/]?$/.test(le))&&!window.confirm(`Open root filesystem "${le}" as the workspace project?`))return;o(le),D(!0),setTimeout(()=>D(!1),2e3)}},type:`button`,title:`Open "${le}" as the workspace project and reposition the LLM agent`,className:`flex items-center space-x-1 px-1.5 py-0.5 rounded text-[11px] font-sans transition-colors ${te?`bg-emerald-500 text-white font-medium`:`bg-zinc-200/80 hover:bg-sky-500 hover:text-white dark:bg-zinc-800 dark:hover:bg-sky-600 dark:hover:text-white text-zinc-700 dark:text-zinc-300`}`,children:(0,A.jsx)(`span`,{children:te?`✓ Project opened`:`📁 ${kY(le)} → open as project`})})}),(0,A.jsxs)(`div`,{className:`flex items-center space-x-1 text-zinc-500 dark:text-zinc-400`,children:[(0,A.jsx)(`button`,{onClick:ce,type:`button`,title:`Clear Terminal Output`,className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16`})})}),(0,A.jsx)(`button`,{onClick:()=>E(e=>!e),type:`button`,title:ee?`Restore Terminal Panel`:`Maximize Terminal Panel`,className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:ee?(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})}):(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 15l7-7 7 7`})})}),(0,A.jsx)(`button`,{onClick:t,type:`button`,title:"Minimize Terminal Panel (Ctrl+`)",className:`p-1 rounded hover:text-zinc-800 dark:hover:text-zinc-200 hover:bg-zinc-200/60 dark:hover:bg-zinc-800/60`,children:(0,A.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,A.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]})]}),(0,A.jsx)(`div`,{className:`flex-1 min-h-0 relative`,children:a?(0,A.jsxs)(`div`,{role:`status`,"data-testid":`terminal-unavailable`,className:`p-3 text-xs text-amber-700 dark:text-amber-300`,children:[(0,A.jsx)(`p`,{className:`font-medium`,children:`The terminal is unavailable.`}),(0,A.jsx)(`p`,{className:`mt-1 break-words font-mono`,children:a})]}):g.map(t=>(0,A.jsx)(AY,{id:t.id,cwd:n,isActive:t.id===v,isPanelOpen:e,renaming:b!==null,openTerminal:s,sendTerminalInput:c,getTerminalCwd:l,resizeTerminal:u,closeTerminal:f,subscribeTerminal:p,onCwdUpdate:ie,registerClear:re},t.id))})]}):null}var MY={todo:{label:`To do`,className:`text-zinc-500`},in_progress:{label:`In progress`,className:`text-blue-600 dark:text-blue-400`},done:{label:`Done`,className:`text-emerald-600 dark:text-emerald-400`},blocked:{label:`Blocked`,className:`text-red-600 dark:text-red-400`},needs_review:{label:`Needs review`,className:`text-amber-600 dark:text-amber-400`},passed:{label:`Passed`,className:`text-emerald-600 dark:text-emerald-400`},failed:{label:`Failed`,className:`text-red-600 dark:text-red-400`},inconclusive:{label:`Inconclusive`,className:`text-amber-600 dark:text-amber-400`},informational:{label:`Informational`,className:`text-zinc-500`},modified:{label:`Modified`,className:`text-blue-600 dark:text-blue-400`},added:{label:`Added`,className:`text-emerald-600 dark:text-emerald-400`},deleted:{label:`Deleted`,className:`text-red-600 dark:text-red-400`},untracked:{label:`Untracked`,className:`text-zinc-600 dark:text-zinc-300`},conflicted:{label:`Conflicted`,className:`text-red-600 dark:text-red-400`},unavailable:{label:`Unavailable`,className:`text-red-600 dark:text-red-400`},"not-recorded":{label:`Not recorded`,className:`text-zinc-500`}};function NY(e){return MY[e]??{label:e,className:`text-zinc-500`}}function PY({entry:e,onTarget:t}){let n=NY(e.status),r=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 break-words text-sm font-medium text-zinc-900 dark:text-zinc-100`,children:e.title}),(0,A.jsx)(`span`,{className:`shrink-0 text-[11px] font-semibold uppercase tracking-wide ${n.className}`,children:n.label})]}),e.group&&(0,A.jsx)(`div`,{className:`mt-0.5 text-[11px] text-zinc-500`,children:e.group}),e.detail&&(0,A.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap text-xs text-zinc-600 dark:text-zinc-300`,children:e.detail}),e.reference&&(0,A.jsx)(`div`,{className:`mt-1 truncate text-xs text-zinc-500`,children:e.reference}),(0,A.jsx)(`div`,{className:`mt-1 text-[10px] uppercase tracking-wide text-zinc-400`,children:e.source})]}),i=`block w-full rounded-md border border-zinc-200 p-2 text-left hover:bg-zinc-50 dark:border-zinc-800 dark:hover:bg-zinc-900`;return e.target?.kind===`external-url`?(0,A.jsx)(`a`,{href:e.target.url,target:`_blank`,rel:`noreferrer`,className:i,children:r}):e.target?(0,A.jsx)(`button`,{type:`button`,onClick:()=>t(e.target),className:i,children:r}):(0,A.jsx)(`div`,{className:`rounded-md border border-zinc-200 p-2 dark:border-zinc-800`,children:r})}function FY({state:e,onClose:t,onRefresh:n,onTarget:r}){return(0,A.jsxs)(`aside`,{"aria-label":`Workspace Outcome`,className:`absolute inset-y-0 right-0 z-10 flex w-full flex-col border-l border-zinc-200 bg-white/95 shadow-lg backdrop-blur md:w-[26rem] dark:border-zinc-800 dark:bg-zinc-950/95`,children:[(0,A.jsxs)(`header`,{className:`flex items-start justify-between gap-2 border-b border-zinc-200 px-3 py-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-zinc-500`,children:`Workspace review`}),(0,A.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:`Outcome`})]}),(0,A.jsxs)(`div`,{className:`flex gap-1`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:n,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,children:`Refresh`}),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`rounded px-2 py-1 text-xs text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800`,"aria-label":`Close Outcome`,children:`×`})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:e===null||e.status===`loading`?(0,A.jsx)(`div`,{role:`status`,className:`text-sm text-zinc-500`,children:`Loading Outcome…`}):e.status===`error`?(0,A.jsx)(`div`,{role:`alert`,className:`rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300`,children:e.message}):(0,A.jsx)(`div`,{className:`space-y-4`,children:e.outcome.sections.map(e=>(0,A.jsxs)(`section`,{"aria-labelledby":`outcome-${e.id}`,className:`rounded-lg border border-zinc-200 p-3 dark:border-zinc-800`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`h3`,{id:`outcome-${e.id}`,className:`text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:e.title}),e.availability===`partial`||e.availability===`unavailable`?(0,A.jsx)(`span`,{className:`text-[11px] font-semibold uppercase text-red-600 dark:text-red-400`,children:e.availability}):null]}),e.summary&&(0,A.jsx)(`p`,{className:`mt-1 text-xs text-zinc-600 dark:text-zinc-300`,children:e.summary}),e.entries.length>0&&(0,A.jsx)(`div`,{className:`mt-3 space-y-2`,children:e.entries.map(e=>(0,A.jsx)(PY,{entry:e,onTarget:r},e.id))})]},e.id))})})]})}function IY(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`));return`${t.slice(0,4).join(``)}-${t.slice(4,6).join(``)}-${t.slice(6,8).join(``)}-${t.slice(8,10).join(``)}-${t.slice(10).join(``)}`}var LY=`pi-outpost:token`;function RY(){let e=null;try{let t=new URL(window.location.href);return e=t.searchParams.get(`token`),e&&(localStorage.setItem(LY,e),t.searchParams.delete(`token`),window.history.replaceState(null,``,`${t.pathname}${t.search}${t.hash}`)),localStorage.getItem(LY)}catch{return e}}function zY(){try{return localStorage.getItem(LY)}catch{return null}}function BY(e){try{localStorage.setItem(LY,e)}catch{}}var VY=class extends Error{kind;constructor(e,t){super(e),this.name=`HistoryError`,this.kind=t}};async function HY(e,t){let n=[];for(;;){let r=await e(n.length,50);if(r.items.length===0||(n.unshift(...r.items),t?.(n.length),r.remaining===0))return n}}function UY(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function WY(e,t){return e.base.rev===t.base.rev&&e.base.path===t.base.path&&e.target.rev===t.target.rev&&e.target.path===t.target.path}function GY(){return{clonePath:null,preview:null,enrollment:null,refresh:null,updates:{},skills:{},removals:{}}}var KY={login:null,connected:!1,workspace:null,workspaces:[],workspaceLocked:!1,embedWorkspaceControls:`settings`,switching:!1,agentStarting:!1,authRequired:!1,brandingReady:!1,branding:{},sessionId:``,sessionName:null,model:``,thinkingLevel:`off`,modelSupportsReasoning:!1,models:[],commands:[],extensionsBinding:!1,sessions:null,sessionSearch:null,tree:null,isStreaming:!1,items:[],olderHistory:null,pendingPrompt:null,workPlan:null,replyConformance:{},structuredAppearance:null,outpostUpdate:null,outpostChanges:null,piPackages:null,piPackageUpdate:null,serverRestarting:!1,restartNeeded:[],outcome:null,queue:{steering:[],followUp:[]},errors:[],contextUsage:null,isCompacting:!1,dialogQueue:[],notifications:[],statuses:{},widgets:{},editorPrefill:null,fileTree:{},directoryRequests:{},openFile:null,previewRevision:0,fileSearch:null,createError:null,created:null,fileOperation:null,extensionPaths:null,configuredExtensionPaths:[],userExtensionPaths:[],extensionLock:!1,tools:[],sandbox:null,terminal:null,userSkillPaths:[],serverBrowse:null,settingsApply:null,agentResources:null,agentResourceOperations:GY(),versions:null,gitAvailable:!1,gitUnavailable:null,credentials:null,gitStatus:null,gitDiff:null,gitBaseline:null,gitLog:null,gitShow:null,gitFileHistory:null,gitFileDiff:null};function qY(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.kind===`assistant`&&r.streaming){let i=[...e];return i[n]=t(r),i}}return[...e,t({kind:`assistant`,blocks:[],streaming:!0})]}function JY(e,t,n,r){for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.kind===`tool`&&i.toolCallId===t){let t=[...e];return t[n]={...i,...r},t}}return[...e,{kind:`tool`,toolCallId:t,toolName:n,args:{},output:``,running:!0,...r}]}function YY(e,t,n){for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.kind===`tool`&&i.toolCallId===t){let t=[...e];return t[r]={...i,...n},t}}return e}function XY(e,t){if(t.type!==`hello`&&t.type!==`session_replaced`&&t.type!==`update_config_ack`&&t.type!==`workspace_switched`&&t.type!==`workspace_starting`)return e;let n=t.models.find(e=>`${e.provider}/${e.id}`===t.model);return{...e,replyConformance:{},structuredAppearance:t.type===`workspace_switched`||t.type===`workspace_starting`?null:e.structuredAppearance,agentStarting:t.agentStarting===!0,outpostUpdate:t.outpostUpdate??e.outpostUpdate,outpostChanges:t.outpostChanges??e.outpostChanges,piPackages:t.piPackages??e.piPackages,serverRestarting:!1,restartNeeded:t.restartNeeded??[],connected:!0,brandingReady:!0,workspace:t.workspace??null,workspaces:t.workspaces??[],workspaceLocked:t.workspaceLocked===!0,embedWorkspaceControls:t.embedWorkspaceControls??`settings`,switching:!1,branding:t.branding,sessionId:t.sessionId,sessionName:t.sessionName??null,model:t.model,thinkingLevel:t.thinkingLevel,thinkingLevels:t.thinkingLevels,modelSupportsReasoning:n?.reasoning??!1,models:t.models,commands:t.commands,extensionsBinding:t.extensionsBinding===!0,isStreaming:t.isStreaming,items:t.items,olderHistory:t.olderItems?{remaining:t.olderItems,have:0,loading:!1,error:null}:null,pendingPrompt:null,workPlan:t.workPlan??null,outcome:null,queue:{steering:[],followUp:[]},errors:[],contextUsage:t.contextUsage??null,isCompacting:!1,dialogQueue:[],notifications:[],statuses:{},widgets:{},extensionTitle:void 0,editorPrefill:null,tree:null,fileTree:{},directoryRequests:{},fileOperation:null,writableRoot:t.writableRoot,docxTemplate:t.docxTemplate,gitAvailable:t.gitAvailable===!0,gitUnavailable:t.gitUnavailable??null,credentials:t.credentials??null,extensionPaths:t.extensionPaths??null,configuredExtensionPaths:t.configuredExtensionPaths??[],userExtensionPaths:t.userExtensionPaths??[],extensionLock:t.extensionLock===!0,tools:t.tools??[],sandbox:t.sandbox??null,terminal:t.terminal??null,confinement:t.confinement??null,userSkillPaths:t.userSkillPaths??[],serverBrowse:null,settingsApply:null,versions:t.versions??null,agentResources:t.agentResources??null,agentResourceOperations:t.type===`hello`||t.type===`workspace_switched`||t.type===`workspace_starting`?GY():e.agentResourceOperations}}function ZY(e,t){if(t.type===`connected`)return{...e,connected:!0,authRequired:!1};if(t.type===`workspace_switching`)return{...e,switching:!0};if(t.type===`pi_package_update_started`)return{...e,piPackageUpdate:{requestId:t.requestId,source:t.source,status:`pending`}};if(t.type===`auth_required`)return{...e,connected:!1,authRequired:!0};if(t.type===`auth_retrying`)return{...e,authRequired:!1};if(t.type===`login_started`)return{...e,login:{flowId:t.flowId,provider:t.provider,method:t.method,events:[],prompt:null,done:null}};if(t.type===`login_answered`)return e.login?{...e,login:{...e.login,prompt:null}}:e;if(t.type===`login_dismissed`)return{...e,login:null};if(t.type===`disconnected`&&e.login&&!e.login.done&&(e={...e,login:{...e.login,prompt:null,done:{ok:!1,message:`Connection lost — the sign-in was stopped. Start it again.`}}}),t.type===`disconnected`){let t=e.openFile,n=t?.status===`loaded`&&t.pendingSave!==void 0?{...t,pendingSave:void 0,saveError:{message:`Connection lost while saving — try again`,conflict:!1}}:e.openFile,r=e.outcome?.status===`loading`?{...e.outcome,status:`error`,message:`Connection lost while loading Outcome.`}:e.outcome;return{...e,connected:!1,openFile:n,outcome:r}}if(t.type===`branding_settled`)return{...e,brandingReady:!0};if(t.type===`branding_loaded`)return{...e,brandingReady:!0,branding:t.branding};if(t.type===`prompt_sent`)return{...e,pendingPrompt:{text:t.text,...t.images?.length?{images:t.images}:{}}};if(t.type===`pending_prompt_cancelled`)return!t.restoreText||!e.pendingPrompt?e:{...e,editorPrefill:{text:e.pendingPrompt.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};if(t.type===`dismiss_notification`)return{...e,notifications:e.notifications.filter(e=>e.id!==t.id)};if(t.type===`dialog_answered`)return{...e,dialogQueue:e.dialogQueue.slice(1)};if(t.type===`dir_list_started`){let n=e.fileTree[t.path];return{...e,fileTree:{...e.fileTree,[t.path]:t.preserveEntries&&Array.isArray(n)?n:`loading`},directoryRequests:{...e.directoryRequests,[t.path]:t.requestId}}}if(t.type===`raw_preview_changed`)return e.openFile?.path===t.path?{...e,previewRevision:e.previewRevision+1}:e;if(t.type===`file_read_started`){let n=e.openFile;return t.preserveContent&&n?.status===`loaded`&&n.path===t.path?{...e,openFile:{...n,refreshRequestId:t.requestId}}:{...e,openFile:{status:`loading`,path:t.path,requestId:t.requestId}}}if(t.type===`file_save_started`){let n=e.openFile;return!e.connected||n?.status!==`loaded`||n.path!==t.path?e:{...e,openFile:{...n,pendingSave:{requestId:t.requestId,content:t.content},saveError:void 0}}}if(t.type===`close_file_preview`)return{...e,openFile:null};if(t.type===`file_search_started`)return{...e,fileSearch:{status:`loading`,query:t.query,requestId:t.requestId,results:[]}};if(t.type===`file_search_cleared`)return{...e,fileSearch:null};if(t.type===`file_create_started`)return{...e,createError:null,created:null};if(t.type===`file_operation_started`)return{...e,fileOperation:{status:`pending`,operation:t.operation,path:t.path,requestId:t.requestId}};if(t.type===`session_search_started`)return{...e,sessionSearch:{status:`loading`,query:t.query,requestId:t.requestId,results:[]}};if(t.type===`session_search_cleared`)return{...e,sessionSearch:null};if(t.type===`history_load_started`)return e.olderHistory?{...e,olderHistory:{...e.olderHistory,loading:!0,error:null}}:e;if(t.type===`history_loaded`)return e.olderHistory?{...e,items:[...t.items,...e.items],olderHistory:{remaining:t.remaining,have:e.olderHistory.have+t.items.length,loading:!1,error:null}}:e;if(t.type===`history_load_failed`)return e.olderHistory?{...e,olderHistory:{...e.olderHistory,loading:!1,error:t.message}}:e;if(t.type===`git_diff_started`||t.type===`git_diff_cleared`)return{...e,gitDiff:null};if(t.type===`git_baseline_started`){let n=e.gitBaseline?.path===t.path?e.gitBaseline.text:void 0;return{...e,gitBaseline:{path:t.path,requestId:t.requestId,...n===void 0?{}:{text:n}}}}if(t.type===`git_baseline_cleared`)return{...e,gitBaseline:null};if(t.type===`git_show_cleared`)return{...e,gitShow:null,gitLog:e.gitLog};if(t.type===`git_file_history_started`)return{...e,gitFileHistory:{path:t.path,status:`loading`,entries:[],requestId:t.requestId},gitFileDiff:null};if(t.type===`git_file_history_closed`)return{...e,gitFileHistory:null,gitFileDiff:null};if(t.type===`git_file_diff_started`)return{...e,gitFileDiff:{base:t.base,target:t.target,status:`loading`,beforeText:e.gitFileDiff?.beforeText??``,afterText:e.gitFileDiff?.afterText??``,requestId:t.requestId}};if(t.type===`git_file_diff_cleared`)return{...e,gitFileDiff:null};if(t.type===`server_browse_started`)return{...e,serverBrowse:{status:`loading`,path:e.serverBrowse?.path??t.path,parent:e.serverBrowse?.parent??null,entries:e.serverBrowse?.entries??[],requestId:t.requestId}};if(t.type===`server_browse_closed`)return{...e,serverBrowse:null};if(t.type===`settings_apply_started`)return{...e,settingsApply:{status:`applying`}};if(t.type===`resource_clone_path_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,clonePath:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_preview_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,preview:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_enrollment_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,enrollment:{requestId:t.requestId,status:`loading`}}};if(t.type===`resource_refresh_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,refresh:{requestId:t.requestId,status:`loading`,...t.repositoryId?{repositoryId:t.repositoryId}:{}}}};if(t.type===`resource_update_started`)return{...e,agentResourceOperations:{...e.agentResourceOperations,updates:{...e.agentResourceOperations.updates,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}};if(t.type===`resource_skills_started`){let n=e.agentResourceOperations;return{...e,agentResourceOperations:{...n,skills:{...n.skills,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}}}if(t.type===`resource_removal_started`){let n=e.agentResourceOperations;return{...e,agentResourceOperations:{...n,removals:{...n.removals,[t.repositoryId]:{requestId:t.requestId,status:`loading`}}}}}if(t.type===`outcome_started`)return{...e,outcome:{status:`loading`,requestId:t.requestId,workspaceRoot:t.workspaceRoot,sessionId:t.sessionId}};if(t.type===`outcome_failed`){let n=e.outcome;return n===null||n.status!==`loading`||n.requestId!==t.requestId?e:{...e,outcome:{...n,status:`error`,message:t.message}}}let n=t.message;if(n.type===`workspace_switched`&&e.agentStarting&&e.workspace&&n.workspace&&NI(n.workspace)===NI(e.workspace))return{...XY(e,n),openFile:e.openFile,gitDiff:e.gitDiff,gitBaseline:e.gitBaseline,fileTree:e.fileTree,directoryRequests:e.directoryRequests};switch(n.type){case`workspace_switched`:case`hello`:case`session_replaced`:case`update_config_ack`:case`workspace_starting`:return{...XY(e,n),openFile:null,gitDiff:null,gitBaseline:null,fileTree:{},directoryRequests:{}};case`workspace_activity`:return{...e,workspaces:n.workspaces,workspace:(e.workspace&&n.workspaces.find(t=>NI(t)===NI(e.workspace)))??e.workspace};case`agent_resource_clone_path`:{let t=e.agentResourceOperations.clonePath;return t?.requestId===n.requestId?{...e,agentResourceOperations:{...e.agentResourceOperations,clonePath:{...t,status:`ready`,path:n.path}}}:e}case`agent_resource_preview`:{let t=e.agentResourceOperations.preview;return t?.requestId===n.requestId?{...e,agentResourceOperations:{...e.agentResourceOperations,preview:{...t,status:`ready`,preview:n.preview}}}:e}case`agent_resource_enrolled`:{let t=e.agentResourceOperations.enrollment;return t?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...e.agentResourceOperations,preview:null,enrollment:{...t,status:`ready`}}}:e}case`agent_resource_assessments`:{let t=e.agentResourceOperations.refresh;if(t?.requestId!==n.requestId||!e.agentResources)return e;let r=new Map(n.assessments.map(e=>[e.repositoryId,e]));return{...e,agentResources:{...e.agentResources,repositories:e.agentResources.repositories.map(e=>({...e,assessment:r.get(e.id)??e.assessment}))},agentResourceOperations:{...e.agentResourceOperations,refresh:{...t,status:`ready`}}}}case`agent_resource_inventory`:return{...e,agentResources:n.inventory};case`agent_resource_update_result`:{let t=n.result.repositoryId;if(!t)return e;let r=e.agentResourceOperations.updates[t];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...e.agentResourceOperations,updates:{...e.agentResourceOperations.updates,[t]:{...r,status:`ready`,result:n.result}}}}:e}case`agent_resource_skills_applied`:{let t=e.agentResourceOperations,r=t.skills[n.repositoryId];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...t,skills:{...t.skills,[n.repositoryId]:{...r,status:`ready`}}}}:e}case`agent_resource_removed`:{let t=e.agentResourceOperations,r=t.removals[n.repositoryId];return r?.requestId===n.requestId?{...e,agentResources:n.inventory,agentResourceOperations:{...t,removals:{...t.removals,[n.repositoryId]:{...r,status:`ready`,result:n.result}}}}:e}case`agent_resource_error`:{let t=e=>e?.requestId===n.requestId?{...e,status:`error`,message:n.message}:null,r=t(e.agentResourceOperations.clonePath),i=t(e.agentResourceOperations.preview),a=t(e.agentResourceOperations.enrollment),o=t(e.agentResourceOperations.refresh),s=e=>{let t=Object.entries(e).find(([,e])=>e.requestId===n.requestId);return t?{...e,[t[0]]:{...t[1],status:`error`,message:n.message}}:null},c=s(e.agentResourceOperations.updates),l=s(e.agentResourceOperations.skills),u=s(e.agentResourceOperations.removals);return!r&&!i&&!a&&!o&&!c&&!l&&!u?e:{...e,agentResourceOperations:{...e.agentResourceOperations,...r?{clonePath:r}:{},...i?{preview:i}:{},...a?{enrollment:a}:{},...o?{refresh:o}:{},...c?{updates:c}:{},...l?{skills:l}:{},...u?{removals:u}:{}}}}case`workspace_error`:return{...e,switching:!1,errors:[...e.errors,n.message]};case`sessions`:return{...e,sessions:n.sessions};case`session_search_results`:return e.sessionSearch?.requestId===n.requestId?{...e,sessionSearch:{...e.sessionSearch,status:`loaded`,results:n.sessions}}:e;case`tree`:return{...e,tree:n.roots};case`editor_prefill`:return{...e,editorPrefill:{text:n.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};case`model_changed`:return{...e,model:n.model,modelSupportsReasoning:n.reasoning,thinkingLevels:n.thinkingLevels};case`login_event`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,events:[...e.login.events,n.event]}}:e;case`login_prompt`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,prompt:{promptId:n.promptId,prompt:n.prompt}}}:e;case`login_prompt_cancelled`:return e.login?.flowId!==n.flowId||e.login.prompt?.promptId!==n.promptId?e:{...e,login:{...e.login,prompt:null}};case`login_done`:return e.login?.flowId===n.flowId?{...e,login:{...e.login,prompt:null,done:{ok:n.ok,...n.cancelled?{cancelled:!0}:{},...n.message?{message:n.message}:{}}}}:e;case`credentials_changed`:{let t=n.models.find(e=>`${e.provider}/${e.id}`===n.model);return{...e,models:n.models,model:n.model,modelSupportsReasoning:t?.reasoning??!1,thinkingLevels:void 0,credentials:n.credentials}}case`extensions_bound`:return{...e,commands:n.commands,tools:n.tools??e.tools,extensionsBinding:!1};case`thinking_changed`:return{...e,thinkingLevel:n.level};case`work_plan_changed`:return{...e,workPlan:n.workPlan};case`workspace_outcome`:{let t=e.outcome;return t===null||t.requestId!==n.requestId||t.sessionId!==e.sessionId||n.outcome.sessionId!==e.sessionId||t.workspaceRoot!==null&&n.outcome.workspaceRoot!==t.workspaceRoot?e:{...e,outcome:{...t,status:`loaded`,outcome:n.outcome}}}case`workspace_outcome_error`:{let t=e.outcome;return t===null||t.status!==`loading`||t.requestId!==n.requestId?e:{...e,outcome:{...t,status:`error`,message:n.message}}}case`user`:return{...e,pendingPrompt:null,items:[...e.items,{kind:`user`,text:n.text,...n.images?{images:n.images}:{}}]};case`user_entries`:{let{entries:t}=n,r=e.items.flatMap((e,t)=>e.kind===`user`?[t]:[]),i=new Map;for(let n=r.length-1,a=t.length-1;n>=0&&a>=0;n--,a--){let o=e.items[r[n]];if(o.kind!==`user`||o.text!==t[a].text)break;i.set(r[n],t[a].entryId)}return{...e,items:e.items.map((e,t)=>{if(e.kind!==`user`)return e;let n=i.get(t);if(n===e.entryId)return e;if(n===void 0){let{entryId:t,...n}=e;return n}return{...e,entryId:n}})}}case`agent_start`:return{...e,isStreaming:!0,errors:[]};case`agent_end`:return{...e,isStreaming:!1,queue:{steering:[],followUp:[]},items:e.items.map(e=>e.kind===`tool`&&e.running?{...e,running:!1}:e.kind===`assistant`&&e.streaming?{...e,streaming:!1}:e)};case`assistant_start`:return{...e,items:[...e.items,{kind:`assistant`,blocks:[],streaming:!0}]};case`block_delta`:return{...e,items:qY(e.items,e=>{let t=[...e.blocks],r=t.findIndex(e=>e.contentIndex===n.contentIndex);return r>=0?t[r]={...t[r],text:t[r].text+n.delta}:t.push({type:n.block,text:n.delta,contentIndex:n.contentIndex}),{...e,blocks:t,streaming:!0}})};case`assistant_end`:return{...e,items:qY(e.items,()=>n.item)};case`custom_message`:return{...e,items:[...e.items,n.item]};case`tool_start`:return{...e,items:JY(e.items,n.toolCallId,n.toolName,{toolName:n.toolName,args:n.args,running:!0,callHtml:n.callHtml})};case`tool_update`:return{...e,items:JY(e.items,n.toolCallId,`tool`,{output:n.text,...n.outputHtml===void 0?{}:{outputHtml:n.outputHtml,outputHtmlCollapsed:n.outputHtmlCollapsed},...typeof n.progress==`number`?{progress:n.progress}:{}})};case`tool_end`:return{...e,items:JY(e.items,n.toolCallId,`tool`,{output:n.text,isError:n.isError,running:!1,outputHtml:n.outputHtml,outputHtmlCollapsed:n.outputHtmlCollapsed,structured:n.structured})};case`structured_conformance`:return{...e,items:YY(e.items,n.toolCallId,{structuredConformance:n.conformance})};case`structured_appearance`:return{...e,structuredAppearance:n.appearance};case`outpost_update`:return{...e,outpostUpdate:n.notice};case`outpost_changes`:return{...e,outpostChanges:n.changes};case`pi_packages`:return{...e,piPackages:n.packages};case`pi_package_update_result`:{let t=e.piPackageUpdate;return t?.requestId===n.requestId?{...e,piPackageUpdate:{requestId:n.requestId,source:t.source,status:n.outcome,message:n.message}}:e}case`restart_needed`:return{...e,restartNeeded:n.reasons};case`server_restarting`:return{...e,serverRestarting:!0,piPackageUpdate:null};case`reply_structured_conformance`:return{...e,replyConformance:{...e.replyConformance,[n.key]:n.conformance}};case`queue`:return{...e,queue:{steering:n.steering,followUp:n.followUp}};case`context_usage`:return{...e,contextUsage:n.usage};case`confinement`:return{...e,confinement:n.confinement};case`compaction_start`:return{...e,isCompacting:!0};case`compaction_end`:return{...e,isCompacting:!1,errors:n.errorMessage?[...e.errors,n.errorMessage]:e.errors};case`error`:return{...e,errors:[...e.errors,n.message],pendingPrompt:null,settingsApply:e.settingsApply?.status===`applying`?{status:`error`,message:n.message}:e.settingsApply};case`server_directory`:return e.serverBrowse?.requestId===n.requestId?{...e,serverBrowse:{status:`loaded`,path:n.path,parent:n.parent,entries:n.entries,requestId:n.requestId}}:e;case`server_directory_error`:return e.serverBrowse?.requestId===n.requestId?{...e,serverBrowse:{...e.serverBrowse,status:`error`,error:n.message}}:e;case`directory_listing`:return n.requestId.startsWith(`dir:`)&&e.directoryRequests[n.path]!==n.requestId?e:{...e,fileTree:{...e.fileTree,[n.path]:n.entries},...n.requestId.startsWith(`create:`)?{created:n.path,createError:null}:{}};case`file_content`:{let t=e.openFile,r=t?.status===`loading`&&t.requestId===n.requestId,i=t?.status===`loaded`&&t.refreshRequestId===n.requestId;return!r&&!i?e:{...e,openFile:{status:`loaded`,path:n.path,content:n.content,size:n.size,mtimeMs:n.mtimeMs,...n.documentIssues===void 0?{}:{documentIssues:n.documentIssues}}}}case`file_written`:{if(n.requestId.startsWith(`create:`))return{...e,createError:null,created:n.path,openFile:{status:`loaded`,path:n.path,content:``,size:n.size,mtimeMs:n.mtimeMs,justCreated:!0}};let t=e.openFile;return t?.status!==`loaded`||t.pendingSave?.requestId!==n.requestId?e:{...e,openFile:{status:`loaded`,path:t.path,content:t.pendingSave.content,size:n.size,mtimeMs:n.mtimeMs}}}case`file_operation_result`:{if(e.fileOperation?.status!==`pending`||e.fileOperation.requestId!==n.requestId)return e;let t=n.previousPath??n.path,r=n.operation===`delete_file`&&e.openFile?.path===n.path?null:e.openFile?.path===t?{...e.openFile,path:n.path}:e.openFile,i=e.gitFileHistory?.path===t||e.gitFileHistory?.path===n.path,a=e.gitDiff?.path===t||e.gitDiff?.path===n.path,o=e.gitBaseline?.path===t||e.gitBaseline?.path===n.path;return{...e,openFile:r,gitFileHistory:i?null:e.gitFileHistory,gitFileDiff:i?null:e.gitFileDiff,gitDiff:a?null:e.gitDiff,gitBaseline:o?null:e.gitBaseline,fileOperation:{status:`succeeded`,operation:n.operation,path:e.fileOperation.path,resultPath:n.path,requestId:n.requestId}}}case`file_browser_error`:if(n.requestId.startsWith(`dir:`))return e.directoryRequests[n.path]===n.requestId?{...e,fileTree:{...e.fileTree,[n.path]:{error:n.message}}}:e;if(n.requestId.startsWith(`create:`))return{...e,createError:{path:n.path,message:n.message}};if(n.requestId.startsWith(`write:`)){let t=e.openFile;return t?.status!==`loaded`||t.pendingSave?.requestId!==n.requestId?e:{...e,openFile:{...t,pendingSave:void 0,saveError:{message:n.message,conflict:n.reason===`conflict`}}}}return n.requestId.startsWith(`fileop:`)?e.fileOperation?.status!==`pending`||e.fileOperation.requestId!==n.requestId?e:{...e,fileOperation:{status:`error`,operation:e.fileOperation.operation,path:e.fileOperation.path,message:n.message,requestId:n.requestId}}:e.openFile?.status===`loading`&&e.openFile.requestId===n.requestId?{...e,openFile:{status:`error`,path:n.path,message:n.message}}:e.openFile?.status===`loaded`&&e.openFile.refreshRequestId===n.requestId?{...e,openFile:{...e.openFile,refreshRequestId:void 0}}:e;case`file_search_results`:return e.fileSearch?.requestId===n.requestId?{...e,fileSearch:{...e.fileSearch,status:`loaded`,results:n.results}}:e;case`git_status`:{let t={};for(let e of n.files)t[e.path]=e.status;let r=e.gitStatus;if(n.repo===void 0||r===null)return{...e,gitStatus:{repos:n.repos,files:t}};let i={};for(let[e,t]of Object.entries(r.files))xL(r.repos,e)?.repo!==n.repo&&(i[e]=t);let a=r.repos.map(e=>n.repos.find(t=>t.repo===e.repo)??e);return{...e,gitStatus:{repos:a,files:{...i,...t}}}}case`git_repositories_changed`:return{...e,gitAvailable:n.available,gitUnavailable:n.available?null:n.unavailable??null,gitStatus:n.available?e.gitStatus:null};case`git_diff`:return n.requestId.startsWith(`gitbase:`)?e.gitBaseline?.requestId===n.requestId?{...e,gitBaseline:{...e.gitBaseline,text:n.before}}:e:{...e,gitDiff:{path:n.path,before:n.before,after:n.after}};case`git_log`:return{...e,gitLog:{repo:n.repo,entries:n.entries}};case`git_show`:return{...e,gitShow:{sha:n.sha,patch:n.patch,truncated:n.truncated}};case`git_file_log`:return e.gitFileHistory?.requestId===n.requestId?{...e,gitFileHistory:{...e.gitFileHistory,status:`loaded`,entries:n.entries}}:e;case`git_file_diff`:return e.gitFileDiff===null||!WY(e.gitFileDiff,n)?e:{...e,gitFileDiff:{...e.gitFileDiff,status:`loaded`,beforeText:n.beforeText,afterText:n.afterText}};case`git_error`:return n.requestId.startsWith(`gitbase:`)?e.gitBaseline?.requestId===n.requestId?{...e,gitBaseline:null}:e:n.requestId.startsWith(`gitdiff:`)?{...e,gitDiff:e.openFile?{path:e.openFile.path,error:n.message}:null}:n.requestId===e.gitFileHistory?.requestId?{...e,gitFileHistory:{...e.gitFileHistory,status:`error`,error:n.message}}:n.requestId===e.gitFileDiff?.requestId?{...e,gitFileDiff:{...e.gitFileDiff,status:`error`,error:n.message}}:{...e,errors:[...e.errors,`git: ${n.message}`]};case`extension_ui_request`:switch(n.method){case`select`:case`confirm`:case`input`:case`editor`:return{...e,dialogQueue:[...e.dialogQueue,n]};case`notify`:return{...e,notifications:[...e.notifications,{id:n.id,message:n.message,notifyType:n.notifyType}]};case`setStatus`:{let t={...e.statuses};return n.statusText===void 0?delete t[n.statusKey]:t[n.statusKey]=n.statusText,{...e,statuses:t}}case`setWidget`:{let t={...e.widgets};return n.widgetLines===void 0?delete t[n.widgetKey]:t[n.widgetKey]={lines:n.widgetLines,placement:n.widgetPlacement??`aboveEditor`},{...e,widgets:t}}case`setTitle`:return{...e,extensionTitle:n.title};case`set_editor_text`:return{...e,editorPrefill:{text:n.text,nonce:e.editorPrefill?e.editorPrefill.nonce+1:1}};default:return e}default:return e}}function QY(e,t,n){let r=e?`${e.replace(/^http/,`ws`)}/ws`:`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/ws`,i=new URLSearchParams;t&&i.set(`token`,t),n&&i.set(`workspace`,n);let a=i.toString();return a?`${r}?${a}`:r}var $Y=12e4,eX=2e4,tX=45e3,nX=4401,rX=1e3;function iX(e=``,t,n=!1,r){let[i,a]=(0,d.useReducer)(ZY,KY),o=(0,d.useRef)(null),[s,c]=(0,d.useState)(0),l=(0,d.useRef)(null),u=(0,d.useRef)(null);s===0&&l.current===null&&(l.current=t??(n?zY():RY()));let f=(0,d.useRef)(i.fileTree),p=(0,d.useRef)(i.openFile);(0,d.useEffect)(()=>{f.current=i.fileTree},[i.fileTree]),(0,d.useEffect)(()=>{p.current=i.openFile},[i.openFile]);let m=(0,d.useRef)(null);(0,d.useEffect)(()=>{m.current=i.gitDiff?.path??null},[i.gitDiff]);let h=(0,d.useRef)(new Map),g=(0,d.useRef)(new Map),_=(0,d.useRef)(i.sessionId);(0,d.useEffect)(()=>{_.current=i.sessionId},[i.sessionId]);let v=(0,d.useRef)(!1),y=(0,d.useRef)(i.olderHistory);(0,d.useEffect)(()=>{y.current=i.olderHistory},[i.olderHistory]);let b=(0,d.useRef)(i.writableRoot);(0,d.useEffect)(()=>{b.current=i.writableRoot},[i.writableRoot]);let x=(0,d.useRef)(!1),S=(0,d.useRef)(new Map),C=i.workspace?NI(i.workspace):null,w=(0,d.useRef)({workspaceRoot:C,sessionId:i.sessionId});(0,d.useEffect)(()=>{w.current={workspaceRoot:C,sessionId:i.sessionId}},[C,i.sessionId]);let T=(0,d.useCallback)(e=>{let t=o.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},[]),ee=(0,d.useRef)(!1),E=(0,d.useRef)(null),te=(0,d.useRef)(!1),D=(0,d.useRef)(null),ne=(0,d.useRef)(()=>{}),re=(0,d.useCallback)(()=>{E.current=null,D.current!==null&&(clearTimeout(D.current),D.current=null)},[]),k=(0,d.useCallback)(()=>{let e=o.current;if(!e||e.readyState!==WebSocket.OPEN)return;if(E.current!==null){te.current=!0;return}let t=`outcome:${IY()}`;E.current=t;let n=w.current;a({type:`outcome_started`,requestId:t,...n}),T({type:`get_outcome`,requestId:t}),D.current=setTimeout(()=>{E.current===t&&(re(),te.current=!1,a({type:`outcome_failed`,requestId:t,message:`The Outcome took too long to answer — try again.`}))},tX)},[T,re]);ne.current=k;let ae=(0,d.useCallback)(()=>{ee.current&&ne.current()},[]),oe=(0,d.useCallback)(e=>{ee.current=e,e?k():te.current=!1},[k]),se=(0,d.useCallback)((e,t=!1)=>{e===``&&(x.current=!0);let n=`dir:${IY()}`;a({type:`dir_list_started`,path:e,requestId:n,preserveEntries:t}),T({type:`list_directory`,path:e,requestId:n})},[T]),ce=(0,d.useRef)(!1),A=(0,d.useRef)(null),le=(0,d.useRef)([]);(0,d.useEffect)(()=>{le.current=i.gitStatus?.repos??[]},[i.gitStatus]);let ue=(0,d.useRef)(new Set),de=(0,d.useRef)(new Set),j=(0,d.useRef)(new Map),fe=(0,d.useCallback)(e=>{if(!ce.current)return;let t=e??``;if(ue.current.has(t)){de.current.add(t);return}ue.current.add(t);let n=`git:${IY()}`;j.current.set(n,t),T({type:`git_status`,...e===void 0?{}:{repo:e},requestId:n})},[T]),pe=(0,d.useCallback)(e=>{let t=j.current.get(e)??``;j.current.delete(e),ue.current.delete(t),de.current.delete(t)&&fe(t===``?void 0:t)},[fe]),me=(0,d.useCallback)(e=>{f.current[e]!==void 0&&se(e,!0)},[se]),he=(0,d.useCallback)(()=>{se(``,!0);for(let e of Object.keys(f.current))e!==``&&me(e)},[me,se]);(0,d.useEffect)(()=>{i.connected&&x.current&&f.current[``]===void 0&&se(``)},[i.connected,i.fileTree,se]),(0,d.useEffect)(()=>{i.connected&&ee.current&&E.current===null&&ne.current()},[i.connected]);let ge=i.openFile?.path??null,_e=ge===null?void 0:i.gitStatus?.files[ge],ve=i.gitBaseline!==null;(0,d.useEffect)(()=>{let e=_e===`modified`||_e===`added`||_e===`conflicted`;if(!i.connected||ge===null||!e){ve&&a({type:`git_baseline_cleared`});return}let t=`gitbase:${IY()}`;a({type:`git_baseline_started`,path:ge,requestId:t}),T({type:`git_diff`,path:ge,requestId:t})},[i.connected,ge,_e,i.gitStatus,T]),(0,d.useEffect)(()=>{let t=!1;return fetch(`${e}/branding`,{headers:l.current?{Authorization:`Bearer ${l.current}`}:{}}).then(e=>e.ok?e.json():null).then(e=>{t||a(e?{type:`branding_loaded`,branding:e}:{type:`branding_settled`})}).catch(()=>{t||a({type:`branding_settled`})}),()=>{t=!0}},[e,s]),(0,d.useEffect)(()=>{let t,n=!1;function i(){let s=new WebSocket(QY(e,l.current,r));o.current=s,s.onopen=()=>{o.current===s&&a({type:`connected`})},s.onmessage=e=>{if(o.current!==s)return;let t;try{t=JSON.parse(e.data)}catch{return}if(t.type===`terminal_data`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onData)n(t.data)}else if(t.type===`terminal_cwd`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onCwd)n(t.cwd)}else if(t.type===`terminal_exit`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onExit)n(t.exitCode)}else if(t.type===`terminal_error`){let e=S.current.get(t.terminalId);if(e)for(let n of e.onError)n(t.message)}else if(t.type===`history_items`){let e=g.current.get(t.requestId);e&&(g.current.delete(t.requestId),e.resolve({items:t.items,remaining:t.remaining}))}else if(t.type===`history_unavailable`){let e=g.current.get(t.requestId);e&&(g.current.delete(t.requestId),e.reject(new VY(t.reason,t.kind)))}else if(t.type===`file_uploaded`){let e=h.current.get(t.requestId);e&&(h.current.delete(t.requestId),e.resolve(t.path))}else if(t.type===`file_browser_error`&&h.current.has(t.requestId)){let e=h.current.get(t.requestId);h.current.delete(t.requestId),e.reject(new DL(t.message,t.reason))}else if(t.type===`file_changed`){ae(),me(UY(t.path));let e=p.current;if(e?.status===`loaded`&&e.path===t.path){let e=`file:${IY()}`;a({type:`file_read_started`,path:t.path,requestId:e,preserveContent:!0}),T({type:`read_file`,path:t.path,requestId:e})}m.current===t.path&&T({type:`git_diff`,path:t.path,requestId:`gitdiff:${IY()}`}),fe(xL(le.current,t.path)?.repo)}else if(t.type===`directory_changed`){ae(),me(t.path);let e=p.current;if(e!==null&&UY(e.path)===t.path){if(ie(e.path)||O(e.path))a({type:`raw_preview_changed`,path:e.path});else if(e.status===`loaded`){let t=`file:${IY()}`;a({type:`file_read_started`,path:e.path,requestId:t,preserveContent:!0}),T({type:`read_file`,path:e.path,requestId:t})}}let n=m.current;n!==null&&UY(n)===t.path&&T({type:`git_diff`,path:n,requestId:`gitdiff:${IY()}`}),fe()}else{if((t.type===`hello`||t.type===`session_replaced`||t.type===`workspace_switched`||t.type===`workspace_starting`)&&(ce.current=t.gitAvailable===!0,t.type!==`session_replaced`&&fe()),t.type===`agent_end`&&(fe(),ae()),t.type===`git_repositories_changed`&&(ae(),ce.current=t.available,t.available&&fe()),t.type===`git_changed`){ae(),fe(t.repo===``?void 0:t.repo);let e=A.current;e!==null&&e.repo===t.repo&&T({type:`git_log`,repo:e.repo,...e.limit?{limit:e.limit}:{},requestId:`gitlog:${IY()}`})}if((t.type===`git_status`||t.type===`git_error`&&t.requestId.startsWith(`git:`))&&pe(t.requestId),t.type===`work_plan_changed`&&ae(),(t.type===`workspace_outcome`||t.type===`workspace_outcome_error`)&&E.current===t.requestId&&(re(),te.current&&(te.current=!1,queueMicrotask(()=>ne.current()))),t.type===`hello`||t.type===`session_replaced`||t.type===`workspace_switched`||t.type===`workspace_starting`||t.type===`update_config_ack`){re(),te.current=!1;let e=w.current,n=t.sessionId===e.sessionId,r=(t.workspace?NI(t.workspace):null)===e.workspaceRoot;ee.current&&n&&r&&queueMicrotask(()=>ne.current())}if(t.type===`file_operation_result`){let e=t.previousPath??t.path,n=p.current;t.operation===`delete_file`&&n?.path===t.path?p.current=null:n?.path===e&&(p.current={...n,path:t.path})}a({type:`server`,message:t}),t.type===`session_replaced`&&se(``)}},s.onclose=e=>{if(o.current===s){ue.current.clear(),de.current.clear(),j.current.clear(),re(),te.current=!1;for(let e of h.current.values())e.reject(new DL(`The connection dropped before the upload finished`));h.current.clear();for(let e of g.current.values())e.reject(new VY(`the connection dropped before the older messages arrived`,`failed`));g.current.clear(),e.code===nX?a({type:`auth_required`}):(a({type:`disconnected`}),n||(t=window.setTimeout(i,1500)))}}}return i(),()=>{n=!0,t!==void 0&&clearTimeout(t);let e=o.current;o.current=null,e?.close()}},[T,e,fe,pe,me,se,ae,re,s,r]);let ye=(0,d.useCallback)((e,t)=>{let n=o.current;if(!n||n.readyState!==WebSocket.OPEN)return Promise.reject(new VY(`not connected to the server`,`failed`));let r=`history:${IY()}`;return new Promise((n,i)=>{let a=window.setTimeout(()=>{g.current.delete(r)&&i(new VY(`the older messages did not arrive`,`failed`))},eX),o=e=>t=>{clearTimeout(a),e(t)};g.current.set(r,{resolve:o(n),reject:o(i)}),T({type:`history_before`,sessionId:_.current,have:e,count:t,requestId:r})})},[T]),be=(0,d.useCallback)(async()=>{let e=y.current;if(!(!e||e.loading||v.current||e.remaining<=0)){v.current=!0,a({type:`history_load_started`});try{let t=await ye(e.have,50);a({type:`history_loaded`,items:t.items,remaining:t.remaining})}catch(e){if(e instanceof VY&&e.kind===`stale`){a({type:`history_load_failed`,message:``});return}a({type:`history_load_failed`,message:e instanceof Error?e.message:`the older messages could not be loaded`})}finally{v.current=!1}}},[ye]);return{state:i,setOutcomeActive:oe,refreshOutcome:k,authToken:l.current,switchWorkspace:(e,t)=>{((t??e)!==C||i.switching)&&(a({type:`workspace_switching`}),T({type:`switch_workspace`,root:e,...t!==void 0&&t!==e?{id:t}:{}}))},openProject:e=>{a({type:`workspace_switching`}),T({type:`open_project`,root:e})},closeProject:(e,t)=>T({type:`close_project`,root:e,...t!==void 0&&t!==e?{id:t}:{}}),checkPiPackages:()=>T({type:`check_pi_packages`}),updatePiPackage:e=>{let t=`pkg:${IY()}`;a({type:`pi_package_update_started`,requestId:t,source:e}),T({type:`update_pi_package`,source:e,requestId:t})},restartServer:()=>T({type:`restart_server`}),openSideSession:e=>{a({type:`workspace_switching`}),T({type:`open_side_session`,root:e})},submitToken:e=>{BY(e),l.current=e,a({type:`auth_retrying`}),c(e=>e+1)},prompt:(e,t)=>{a({type:`prompt_sent`,text:e,...t?.length?{images:t}:{}}),T({type:`prompt`,text:e,...t?.length?{images:t}:{}})},abort:()=>T({type:`abort`}),cancelPendingPrompt:e=>{a({type:`pending_prompt_cancelled`,restoreText:e}),T({type:`abort`})},setModel:(e,t)=>T({type:`set_model`,provider:e,id:t}),setThinking:e=>T({type:`set_thinking`,level:e}),newSession:()=>T({type:`new_session`}),switchSession:e=>T({type:`switch_session`,path:e}),deleteSession:e=>T({type:`delete_session`,path:e}),listSessions:()=>T({type:`list_sessions`}),renameSession:(e,t)=>T({type:`rename_session`,path:e,name:t}),searchSessions:e=>{let t=`sessions:${IY()}`;a({type:`session_search_started`,query:e,requestId:t}),T({type:`search_sessions`,query:e,requestId:t})},clearSessionSearch:()=>a({type:`session_search_cleared`}),listTree:()=>T({type:`list_tree`}),navigateTree:e=>T({type:`navigate_tree`,entryId:e}),forkSession:e=>T({type:`fork_session`,entryId:e}),editPrompt:(e,t,n)=>T({type:`edit_prompt`,entryId:e,text:t,...n?.length?{images:n}:{}}),compact:()=>T({type:`compact`}),fetchOlderItems:ye,loadOlderItems:be,respondToDialog:e=>{T({type:`extension_ui_response`,...e}),a({type:`dialog_answered`})},dismissNotification:e=>a({type:`dismiss_notification`,id:e}),listDirectory:e=>se(e),refreshFileTree:he,readFile:(e,t)=>{let n=`file:${IY()}`;a({type:`file_read_started`,path:e,requestId:n}),T({type:`read_file`,path:e,requestId:n,...t===void 0?{}:{sha256:t}})},closeFilePreview:()=>a({type:`close_file_preview`}),writeFile:(e,t,n,r=!1)=>{let i=`write:${IY()}`;a({type:`file_save_started`,path:e,requestId:i,content:t}),T({type:`write_file`,path:e,content:t,expectedMtimeMs:n,...r?{force:r}:{},requestId:i})},createFile:e=>{a({type:`file_create_started`}),T({type:`create_file`,path:e,requestId:`create:${IY()}`})},uploadFile:(e,t)=>{let n=b.current;if(n===null)return Promise.reject(new DL(`the workspace is read-only`,`denied`));let r=o.current;if(!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new DL(`not connected to the server`));let i=n?`${n}/${EL}`:EL,a=`upload:${IY()}`;return new Promise((n,r)=>{let o=window.setTimeout(()=>{h.current.delete(a)&&r(new DL(`the upload timed out`))},$Y),s=e=>t=>{clearTimeout(o),e(t)};h.current.set(a,{resolve:s(n),reject:s(r)}),T({type:`upload_file`,destinationDirectory:i,name:e,contentBase64:t,requestId:a})})},createDirectory:e=>{a({type:`file_create_started`}),T({type:`create_directory`,path:e,requestId:`create:${IY()}`})},openNative:e=>{let t=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`open_native`,path:e,requestId:t}),T({type:`open_native`,path:e,requestId:t})},revealNative:e=>{let t=Date.now();if(u.current?.path===e&&t-u.current.at<rX)return;u.current={path:e,at:t};let n=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`reveal_native`,path:e,requestId:n}),T({type:`reveal_native`,path:e,requestId:n})},renameFile:(e,t)=>{let n=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`rename_file`,path:e,requestId:n}),T({type:`rename_file`,path:e,name:t,requestId:n})},deleteFile:e=>{let t=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`delete_file`,path:e,requestId:t}),T({type:`delete_file`,path:e,requestId:t})},moveFile:(e,t)=>{let n=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`move_file`,path:e,requestId:n}),T({type:`move_file`,path:e,destinationDirectory:t,requestId:n})},copyFile:(e,t)=>{let n=`fileop:${IY()}`;a({type:`file_operation_started`,operation:`copy_file`,path:e,requestId:n}),T({type:`copy_file`,path:e,destinationDirectory:t,requestId:n})},searchFiles:e=>{let t=`search:${IY()}`;a({type:`file_search_started`,query:e,requestId:t}),T({type:`search_files`,query:e,requestId:t})},clearFileSearch:()=>a({type:`file_search_cleared`}),fetchGitStatus:()=>fe(),fetchGitDiff:e=>{let t=`gitdiff:${IY()}`;a({type:`git_diff_started`,path:e,requestId:t}),T({type:`git_diff`,path:e,requestId:t})},clearGitDiff:()=>a({type:`git_diff_cleared`}),fetchGitLog:(e,t)=>{A.current={repo:e,limit:t},T({type:`git_log`,repo:e,...t?{limit:t}:{},requestId:`gitlog:${IY()}`})},fetchGitShow:(e,t)=>T({type:`git_show`,repo:e,sha:t,requestId:`gitshow:${IY()}`}),clearGitShow:()=>a({type:`git_show_cleared`}),fetchGitFileHistory:(e,t)=>{let n=`gitfilelog:${IY()}`;a({type:`git_file_history_started`,path:e,requestId:n}),T({type:`git_file_log`,path:e,...t?{limit:t}:{},requestId:n})},closeGitFileHistory:()=>a({type:`git_file_history_closed`}),fetchGitFileDiff:(e,t)=>{let n=`gitfilediff:${IY()}`;a({type:`git_file_diff_started`,base:e,target:t,requestId:n}),T({type:`git_file_diff`,base:e,target:t,requestId:n})},clearGitFileDiff:()=>a({type:`git_file_diff_cleared`}),setCredential:(e,t)=>T({type:`set_credential`,provider:e,apiKey:t}),startLogin:(e,t)=>{let n=IY();a({type:`login_started`,flowId:n,provider:e,method:t}),T({type:`start_login`,flowId:n,provider:e,method:t})},answerLogin:e=>{let t=i.login;t?.prompt&&(T({type:`login_answer`,flowId:t.flowId,promptId:t.prompt.promptId,value:e}),a({type:`login_answered`}))},cancelLogin:()=>{let e=i.login;e&&!e.done&&T({type:`cancel_login`,flowId:e.flowId})},dismissLogin:()=>a({type:`login_dismissed`}),logoutProvider:e=>T({type:`logout_provider`,provider:e}),declareProvider:e=>T({type:`declare_provider`,...e}),browseServerDirectory:e=>{let t=`serverdir:${IY()}`;a({type:`server_browse_started`,path:e,requestId:t}),T({type:`browse_server_directory`,path:e,requestId:t})},closeServerBrowser:()=>a({type:`server_browse_closed`}),suggestAgentResourceClonePath:e=>{let t=`resource-clone-path:${IY()}`;a({type:`resource_clone_path_started`,requestId:t}),T({type:`suggest_agent_resource_clone_path`,repositoryUrl:e,requestId:t})},cloneAgentResourceRepository:(e,t)=>{let n=`resource-preview:${IY()}`;a({type:`resource_preview_started`,requestId:n}),T({type:`clone_agent_resource_repository`,repositoryUrl:e,destinationPath:t,requestId:n})},enrollAgentResourceRepository:(e,t,n,r)=>{let i=`resource-enroll:${IY()}`;a({type:`resource_enrollment_started`,requestId:i}),T({type:`enroll_agent_resource_repository`,previewToken:e,skillRoots:t,extensionRoots:n,...r?{enabledSkills:r}:{},requestId:i})},setAgentResourceSkills:(e,t)=>{let n=`resource-skills:${IY()}`;a({type:`resource_skills_started`,requestId:n,repositoryId:e}),T({type:`set_agent_resource_skills`,repositoryId:e,enabledSkills:t,requestId:n})},removeAgentResourceRepository:e=>{let t=`resource-remove:${IY()}`;a({type:`resource_removal_started`,requestId:t,repositoryId:e}),T({type:`remove_agent_resource_repository`,repositoryId:e,requestId:t})},refreshAgentResourceRepositories:e=>{let t=`resource-refresh:${IY()}`;a({type:`resource_refresh_started`,requestId:t,...e?{repositoryId:e}:{}}),T({type:`refresh_agent_resource_repositories`,...e?{repositoryId:e}:{},requestId:t})},updateAgentResourceRepository:(e,t,n,r,i=!1)=>{let o=`resource-update:${IY()}`;a({type:`resource_update_started`,requestId:o,repositoryId:e}),T({type:`update_agent_resource_repository`,repositoryId:e,assessmentToken:t,localRevision:n,upstreamRevision:r,...i?{allowExecutableChanges:!0}:{},requestId:o})},updateConfig:e=>{a({type:`settings_apply_started`}),T({type:`update_config`,...e})},openTerminal:(e,t,n,r)=>T({type:`terminal_open`,terminalId:e,cwd:t,cols:n,rows:r}),sendTerminalInput:(e,t)=>T({type:`terminal_input`,terminalId:e,data:t}),getTerminalCwd:e=>T({type:`terminal_get_cwd`,terminalId:e}),resizeTerminal:(e,t,n)=>T({type:`terminal_resize`,terminalId:e,cols:t,rows:n}),closeTerminal:e=>{T({type:`terminal_close`,terminalId:e}),S.current.delete(e)},subscribeTerminal:(e,t)=>{let n=S.current.get(e);return n||(n={onData:new Set,onCwd:new Set,onExit:new Set,onError:new Set},S.current.set(e,n)),t.onData&&n.onData.add(t.onData),t.onCwd&&n.onCwd.add(t.onCwd),t.onExit&&n.onExit.add(t.onExit),t.onError&&n.onError.add(t.onError),()=>{t.onData&&n?.onData.delete(t.onData),t.onCwd&&n?.onCwd.delete(t.onCwd),t.onExit&&n?.onExit.delete(t.onExit),t.onError&&n?.onError.delete(t.onError)}}}}var aX=120;function oX({label:e}){return(0,A.jsx)(`div`,{className:`flex justify-end px-4`,role:`status`,"aria-live":`polite`,children:(0,A.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,A.jsx)(`span`,{className:`inline-block h-4 w-4 animate-spin rounded-full border-[3px] border-zinc-300 border-t-blue-500 dark:border-zinc-600 dark:border-t-blue-400 motion-reduce:animate-pulse`}),(0,A.jsx)(`span`,{className:`text-xs text-zinc-400 dark:text-zinc-500`,children:e})]})})}var sX=(0,d.forwardRef)(function({serverUrl:e=``,rootElement:t,initialTheme:n,token:r,workspace:i},a){let o=t!==void 0,s=t??document.documentElement,{state:c,authToken:l,submitToken:u,prompt:f,abort:m,cancelPendingPrompt:h,setModel:g,setThinking:_,newSession:v,switchSession:b,deleteSession:x,listSessions:S,renameSession:C,searchSessions:w,clearSessionSearch:T,listTree:ee,navigateTree:E,forkSession:te,editPrompt:D,compact:ne,loadOlderItems:re,fetchOlderItems:se,respondToDialog:ce,dismissNotification:le,listDirectory:ue,refreshFileTree:de,readFile:j,writeFile:fe,createFile:pe,createDirectory:he,uploadFile:ge,openNative:_e,revealNative:ve,renameFile:ye,deleteFile:be,moveFile:xe,copyFile:Se,closeFilePreview:Ce,searchFiles:we,clearFileSearch:Te,fetchGitDiff:Ee,clearGitDiff:De,fetchGitLog:Oe,fetchGitShow:ke,clearGitShow:Ae,fetchGitFileHistory:je,closeGitFileHistory:Me,fetchGitFileDiff:Ne,clearGitFileDiff:Pe,setCredential:Fe,startLogin:Ie,answerLogin:Le,cancelLogin:Re,dismissLogin:ze,logoutProvider:Be,declareProvider:Ve,updateConfig:He,suggestAgentResourceClonePath:Ue,cloneAgentResourceRepository:We,enrollAgentResourceRepository:Ge,setAgentResourceSkills:Ke,removeAgentResourceRepository:qe,refreshAgentResourceRepositories:Ye,updateAgentResourceRepository:Xe,browseServerDirectory:Ze,closeServerBrowser:Qe,switchWorkspace:$e,openProject:et,closeProject:tt,openSideSession:nt,checkPiPackages:rt,updatePiPackage:it,restartServer:at,openTerminal:ot,sendTerminalInput:st,getTerminalCwd:ct,resizeTerminal:lt,closeTerminal:ut,subscribeTerminal:dt,setOutcomeActive:ft,refreshOutcome:pt}=iX(e,r,o,i),mt=oe(c.workspace);RB(c.workspaces,c.workspace?NI(c.workspace):null);let ht=c.workspace?NI(c.workspace):null;(0,d.useEffect)(()=>{yt([]),dn([]),En.current&&(En.current.scrollTop=0)},[ht]);let[gt,_t]=(0,d.useState)(!1),[vt,yt]=(0,d.useState)([]),[bt,xt]=(0,d.useState)([]),[St,Ct]=(0,d.useState)(null),[wt,Tt]=(0,d.useState)(null),[Et,Dt]=(0,d.useState)(null),[Ot,kt]=(0,d.useState)(!1),[At,jt]=(0,d.useState)(null),[Mt,Nt]=(0,d.useState)(null),Pt=At===`project`,Ft=e=>jt(e?`project`:null),It=c.embedWorkspaceControls===`projects`?`projects`:c.embedWorkspaceControls===`root`?`root`:`none`,Lt=(0,d.useRef)({}),Rt=(0,d.useRef)([]),zt=(0,d.useRef)(null),Bt=(0,d.useRef)(null),[Vt,Ht]=(0,d.useState)(!1),[Ut,Wt]=(0,d.useState)(vL),Gt=(0,d.useCallback)((e,t)=>{yL(e,t),Wt(n=>({...n,[e]:t}))},[]),[Kt,qt]=(0,d.useState)(!1),[Jt,Yt]=(0,d.useState)(!0),[Xt,Zt]=(0,d.useState)(!1),Qt=c.terminal?.enabled??!1;(0,d.useEffect)(()=>{let e=e=>{Qt&&(e.ctrlKey||e.metaKey)&&e.key==="`"&&(e.preventDefault(),Zt(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Qt]);let[$t,en]=(0,d.useState)(!1),[tn,nn]=(0,d.useState)(null),rn=(0,d.useCallback)(()=>nn(null),[]);function an(){let e=!Kt;qt(e),e&&(Yt(!1),en(!1))}function on(){let e=!Jt;Yt(e),e&&(qt(!1),en(!1))}function sn(){let e=!$t;en(e),e&&(qt(!1),Yt(!1))}(0,d.useEffect)(()=>(ft($t),()=>ft(!1)),[$t,ft,c.sessionId,ht]),(0,d.useEffect)(()=>{en(!1),nn(null)},[ht]);let[cn,ln]=(0,d.useState)([]),[un,dn]=(0,d.useState)([]),fn=(0,d.useRef)(0),pn=(0,d.useRef)(0),[mn,hn]=(0,d.useState)(0);async function gn(e){let t=[...e],n=t.filter(jL).map(e=>({id:`${fn.current++}`,name:e.name}));n.length>0&&dn(e=>[...e,...n]),pn.current===0&&ln([]),pn.current++;try{let{attachments:e,errors:n}=await zL(t,ge);e.length>0&&yt(t=>[...t,...e]),n.length>0&&ln(e=>[...e,...n])}finally{if(pn.current--,n.length>0){let e=new Set(n.map(e=>e.id));dn(t=>t.filter(t=>!e.has(t.id)))}}}(0,d.useEffect)(()=>{Rt.current=vt},[vt]),(0,d.useEffect)(()=>{let t=c.openFile;if(!t)return;let n=t.path,r=t.status===`loaded`,i=t.status===`error`&&t.message===`Binary file — preview not supported`&&k(n);if(zt.current!==n&&(zt.current=n,Bt.current=null,yt(e=>e.filter(e=>e.source!==`preview`)),Ct(null),Tt(null),Dt(null)),Bt.current===n)return;(ie(n)||O(n))&&yt(e=>e.filter(e=>e.source!==`preview`));let a=!1;async function o(){let t=ie(n)?wt===n?await GL(n,ae(e,n,l,c.previewRevision,mt)):null:O(n)?Et?.path===n&&Et.revision===c.previewRevision?VL(n):null:i||r?BL(n):null;a||t===null||zt.current!==n||Bt.current===n||(typeof t==`string`?Ct(t):(Ct(null),yt(e=>JL(e,t))))}return o(),()=>{a=!0}},[c.openFile,c.previewRevision,e,l,mt,wt,Et]);function _n(){zt.current=null,Bt.current=null,Ce()}let vn=(0,d.useMemo)(()=>[...vt.filter(e=>e.kind===`path`).map(e=>e.data),...bt],[vt,bt]);function yn(e){let t=Rt.current.findIndex(t=>t.kind===`path`&&t.data===e);t>=0?bn(t):bt.includes(e)||yt(t=>qL(t,e))}function bn(e){let t=Rt.current[e];t?.source===`preview`&&(Bt.current=t.previewPath??zt.current,Ct(null)),yt(t=>YL(t,e))}function xn(e,t){f(e,t),yt([]),ln([]),Ct(null),Ot||_n()}function Sn(e){e.preventDefault(),hn(0),e.dataTransfer.files.length>0&&gn(Array.from(e.dataTransfer.files))}let{theme:Cn,toggle:wn,setTheme:Tn}=y(c.branding.defaultTheme??`system`,c.branding.allowThemeToggle!==!1,s,n);(0,d.useImperativeHandle)(a,()=>({setTheme:Tn}),[Tn]);let En=(0,d.useRef)(null),[Dn,On]=(0,d.useState)(null),kn=(0,d.useCallback)(e=>{En.current=e,On(e)},[]),An=(0,d.useRef)(null),jn=(0,d.useRef)(!0),[Mn,Nn]=(0,d.useState)(!0),Pn=(0,d.useCallback)(e=>{e!==jn.current&&Nn(e),jn.current=e},[]),Fn=(0,d.useCallback)(()=>{let e=En.current;e&&Pn(e.scrollHeight-e.scrollTop-e.clientHeight<aX)},[Pn]),In=(0,d.useRef)(null),Ln=(0,d.useCallback)(()=>{let e=En.current;e&&(e.scrollHeight-e.scrollTop-e.clientHeight<aX||(In.current=e.scrollTop))},[]),Rn=(0,d.useCallback)(()=>{let e=En.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<aX,n=In.current;if(n!==null){if(e.scrollTop<n)In.current=null;else if(In.current=t?null:e.scrollTop,!t)return}Pn(t)},[Pn]);function zn(){In.current=null}(0,d.useEffect)(()=>{let e=Dn;if(!e)return;let t=()=>{In.current=null,Rn()};e.addEventListener(`scrollend`,t);let n;return typeof ResizeObserver<`u`&&(n=new ResizeObserver(()=>{jn.current?(Ln(),An.current?.scrollIntoView({behavior:`auto`})):Rn()}),n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild)),()=>{e.removeEventListener(`scrollend`,t),n?.disconnect()}},[Dn,Rn,Ln]);let Bn=(0,d.useCallback)(()=>{Pn(!0),Ln();let e=window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1;An.current?.scrollIntoView({behavior:e?`auto`:`smooth`})},[Pn,Ln]);(0,d.useEffect)(()=>{jn.current?(Ln(),An.current?.scrollIntoView({behavior:`smooth`})):Fn()},[c.items,Fn,Ln]);let Vn=(0,d.useMemo)(()=>RI(c.items),[c.items]),Hn=(0,d.useMemo)(()=>Kt?JI(c.items):null,[Kt,c.items]),Un=(0,d.useMemo)(()=>UF({readFile:(e,t)=>{Ht(!1),j(e,t)},fetchGitFileHistory:e=>je(e),fetchGitDiff:e=>{Ht(!0),j(e)},searchFiles:e=>we(e)}),[j,je,we]),Wn=(0,d.useCallback)(()=>Gt(`tools`,!0),[Gt]),Gn=(0,d.useCallback)(e=>{let t=En.current;if(t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=r.top>=n.top&&r.bottom<=n.bottom,a=t.scrollHeight-t.scrollTop-t.clientHeight<aX;if(i&&a)return}Pn(!1)},[Pn]),[Kn,qn]=(0,d.useState)(null),[Jn,Yn]=(0,d.useState)(null),Xn=(0,d.useMemo)(()=>{let e=c.sessions?.find(e=>e.id===c.sessionId);return c.sessionName?.trim()||e?.name?.trim()||e?.firstMessage?.trim()||c.sessionId},[c.sessionName,c.sessions,c.sessionId]),Zn=(0,d.useCallback)(async()=>{Yn(null),qn(`preparing…`);try{let{exportConversation:t}=await me(async()=>{let{exportConversation:e}=await import(`./conversationExport-ew4uMgY-.js`);return{exportConversation:e}},__vite__mapDeps([26,21,1,25]));await t({items:c.items,olderItems:c.olderHistory?.remaining??0,...c.olderHistory?{fetchOlderItems:se}:{},connection:{serverUrl:e,token:l,workspace:mt},meta:{...c.workspace?{project:c.workspace.name}:{},session:Xn,model:c.model,exportedAt:new Date},onProgress:(e,t,n)=>qn(e===`collecting`?`reading ${t}/${n}…`:`writing ${t}/${n}…`)})}catch(e){Yn(e instanceof Error?e.message:`the conversation could not be exported`)}finally{qn(null)}},[c.items,c.olderHistory,c.workspace,c.model,Xn,se,e,l,mt]),{jumpToItem:Qn,highlightIndex:$n}=pL({items:c.items,scrollerRef:En,hideTools:!Ut.tools,onShowTools:Wn,onJump:Gn}),er=(0,d.useRef)(null),tr=(0,d.useRef)(c.olderHistory?.have??0),nr=(0,d.useCallback)(()=>{let e=En.current;e&&(er.current={height:e.scrollHeight,top:e.scrollTop}),re()},[re]);return(0,d.useLayoutEffect)(()=>{let e=c.olderHistory?.have??0,t=tr.current;tr.current=e;let n=er.current;if(er.current=null,!n||e<=t)return;let r=En.current;r&&(r.scrollTop=n.top+(r.scrollHeight-n.height))},[c.olderHistory?.have]),(0,d.useEffect)(()=>{if(!o){let e=c.extensionTitle??c.branding.title??`pi`;document.title=c.workspace?`${c.workspace.name} — ${e}`:e}c.branding.accentColor&&s.style.setProperty(`--accent`,c.branding.accentColor)},[c.branding,c.extensionTitle,c.workspace?.name,o,s]),o&&!c.brandingReady?null:c.authRequired?(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(mV,{title:c.branding.title,onSubmit:u})}):c.credentials&&!c.credentials.usableModel?(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(ZB,{title:c.branding.title,credentials:c.credentials,onSetCredential:Fe,onStartLogin:Ie,login:c.login,onAnswerLogin:Le,onCancelLogin:Re,onDismissLogin:ze,onDeclareProvider:Ve,errors:c.errors})}):(0,A.jsx)(p.Provider,{value:Cn,children:(0,A.jsx)(Hf.Provider,{value:c.replyConformance,children:(0,A.jsxs)(gf.Provider,{value:c.structuredAppearance,children:[(0,A.jsxs)(`div`,{className:`relative flex h-full`,onDragEnter:e=>{e.dataTransfer.types.includes(`Files`)&&hn(e=>e+1)},onDragLeave:()=>hn(e=>Math.max(0,e-1)),onDragOver:e=>e.preventDefault(),onDrop:Sn,children:[mn>0&&(0,A.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-40 flex items-center justify-center border-2 border-dashed bg-white/70 backdrop-blur-sm dark:bg-zinc-950/70`,style:{borderColor:`var(--accent, #3b82f6)`},children:(0,A.jsx)(`p`,{className:`text-lg font-medium text-zinc-700 dark:text-zinc-200`,children:`Drop files to attach (images, documents & text)`})}),gt&&(0,A.jsx)(pV,{tree:c.fileTree,openFile:c.openFile,writableRoot:c.writableRoot,gitFiles:c.gitStatus?.files,attachedPaths:vn,onExpand:ue,onSelectDirectory:Nt,onRefresh:de,onSelectFile:e=>{Ht(!1),Nt(e),j(e)},onSelectDiff:e=>{Ht(!0),Nt(e),j(e)},onToggleAttachPath:yn,onCreateFile:e=>{Ht(!1),pe(e)},onCreateDirectory:he,onOpenNative:_e,onRevealNative:ve,onRenameFile:ye,onDeleteFile:be,onMoveFile:xe,onCopyFile:Se,fileOperation:c.fileOperation,createError:c.createError,created:c.created}),(0,A.jsxs)(`div`,{className:`flex h-full min-w-0 flex-1 flex-col`,children:[Pt&&(0,A.jsx)(Wz,{label:`Choose a project directory`,browse:c.serverBrowse,onBrowse:Ze,onSelect:e=>{Ft(!1),Qe(),et(e)},onCancel:()=>{Ft(!1),Qe()}}),!o&&c.outpostUpdate&&(0,A.jsx)(OI,{notice:c.outpostUpdate}),!o&&c.outpostChanges&&(0,A.jsx)(MI,{changes:c.outpostChanges}),(0,A.jsx)(LB,{workspace:c.workspace,workspaces:c.workspaces,workspaceLocked:c.workspaceLocked,workspaceControl:o?It:`projects`,rootControl:{sandbox:c.sandbox,browse:c.serverBrowse,applyState:c.settingsApply,blocked:At!==null&&At!==`root`,onBrowse:Ze,onCloseBrowser:()=>{jt(null),Qe()},onOpened:()=>jt(`root`),onSelect:e=>He({sandbox:{root:e,allowWrite:c.sandbox?.allowWrite??!1,allowBash:c.sandbox?.allowBash??!1,...c.sandbox?.writableRoot?{writableRoot:c.sandbox.writableRoot}:{}}})},onSwitchWorkspace:$e,onOpenProject:()=>{Ft(!0),Ze(``)},onCloseProject:tt,onOpenSideSession:nt,piPackages:c.piPackages,piPackageUpdate:c.piPackageUpdate,canRestartServer:!o,serverRestarting:c.serverRestarting,onCheckPiPackages:rt,onUpdatePiPackage:it,onRestartServer:at,restartNeeded:c.restartNeeded,title:c.branding.title,credentials:c.credentials,login:c.login,onStartLogin:Ie,onAnswerLogin:Le,onCancelLogin:Re,onDismissLogin:ze,onLogoutProvider:Be,sessions:c.sessions,sessionSearch:c.sessionSearch,sessionId:c.sessionId,tree:c.tree,isStreaming:c.isStreaming,connected:c.connected,theme:Cn,showThemeToggle:c.branding.allowThemeToggle!==!1,statuses:c.statuses,sidebarOpen:gt,outcomeOpen:$t,filters:Ut,onToggleSidebar:()=>_t(!gt),onToggleOutcome:sn,onFilterChange:Gt,...c.items.length>0?{onExportConversation:()=>void Zn()}:{},exportProgress:Kn,onToggleTheme:wn,onNewSession:v,onSwitchSession:b,onDeleteSession:x,onListSessions:S,onRenameSession:C,onSearchSessions:w,onClearSessionSearch:T,onListTree:ee,onNavigateTree:E,onForkSession:te,gitAvailable:c.gitAvailable,gitStatus:c.gitStatus,gitSelectedPath:Mt,gitLog:c.gitLog,extensionPaths:c.extensionPaths,configuredExtensionPaths:c.configuredExtensionPaths,userExtensionPaths:c.userExtensionPaths,extensionLock:c.extensionLock,tools:c.tools,commands:c.commands,sandbox:c.sandbox,gitUnavailable:c.gitUnavailable,userSkillPaths:c.userSkillPaths,serverBrowse:c.serverBrowse,settingsApply:c.settingsApply,agentResources:c.agentResources,agentResourceOperations:c.agentResourceOperations,versions:c.versions,onBrowseServerPath:Ze,onCloseServerBrowser:Qe,settingsPickerBlocked:At!==null&&At!==`settings`,onSettingsPickerOpened:()=>jt(`settings`),onUpdateConfig:He,onSuggestAgentResourceClonePath:Ue,onCloneAgentResourceRepository:We,onEnrollAgentResourceRepository:Ge,onSetAgentResourceSkills:Ke,onRemoveAgentResourceRepository:qe,onRefreshAgentResourceRepositories:Ye,onUpdateAgentResourceRepository:Xe,onFetchGitLog:Oe,onShowCommit:ke,terminalOpen:Xt,onToggleTerminal:Qt?()=>Zt(e=>!e):void 0}),(0,A.jsxs)(`div`,{className:`relative z-0 flex min-h-0 flex-1 flex-col`,children:[c.workPlan&&(0,A.jsx)(vV,{plan:c.workPlan,open:Jt,onToggle:on,onOpenWorkspace:e=>{Ht(!1),j(e)},requestedTaskId:tn,onTaskRequestHandled:rn}),$t&&(0,A.jsx)(FY,{state:c.outcome,onClose:()=>en(!1),onRefresh:pt,onTarget:e=>{e.kind===`work-plan-task`?(nn(e.taskId),en(!1),qt(!1),Yt(!0)):e.kind===`workspace-file`?(Ht(!1),j(e.path)):e.kind===`workspace-diff`&&(Ht(!0),j(e.path))}}),c.openFile&&(0,A.jsx)(nz,{file:c.openFile,writableRoot:c.writableRoot,docxTemplate:c.docxTemplate,isStreaming:c.isStreaming,onDirtyChange:kt,gitState:c.gitStatus?.files[c.openFile.path],initialShowGitDiff:Vt,gitDiff:c.gitDiff,gitBaseline:c.gitBaseline?.path===c.openFile.path?c.gitBaseline.text??null:null,onFetchGitDiff:Ee,onClearGitDiff:De,inRepository:xL(c.gitStatus?.repos??[],c.openFile.path)!==null,onOpenGitHistory:je,onClose:_n,onReload:j,onSave:fe,serverUrl:e,token:l,workspace:mt,onImageLoad:Tt,onPdfLoad:e=>Dt({path:e,revision:c.previewRevision}),rawRevision:c.previewRevision},c.openFile.path),c.gitFileHistory&&(0,A.jsx)(Az,{history:c.gitFileHistory,diff:c.gitFileDiff,dirty:c.gitStatus?.files[c.gitFileHistory.path]!==void 0,onFetchDiff:Ne,onClearDiff:Pe,onClose:Me}),c.gitShow&&(0,A.jsx)(iz,{show:c.gitShow,onClose:Ae}),Hn&&(0,A.jsx)(dL,{analysis:Hn,onJump:Qn,onClose:()=>qt(!1)}),(0,A.jsx)(`main`,{ref:kn,onScroll:Rn,onWheel:zn,onTouchStart:zn,onKeyDown:zn,className:`flex-1 overflow-y-auto transition-opacity duration-150 ${c.switching?`opacity-40`:`opacity-100`} ${Kt?`md:pr-[26rem]`:c.workPlan&&Jt?`md:pr-[23rem]`:``}`,children:(0,A.jsxs)(`div`,{className:`mx-auto flex max-w-3xl flex-col gap-3 px-4 py-6`,children:[c.items.length===0&&(0,A.jsxs)(`div`,{className:`mt-24 text-center text-zinc-500 dark:text-zinc-600`,children:[(0,A.jsx)(`div`,{className:`mb-2 text-4xl`,children:c.branding.title??`π`}),c.agentStarting?(0,A.jsx)(`p`,{className:`text-sm`,role:`status`,"data-testid":`agent-starting`,children:`Starting the agent… The project's files are ready.`}):(0,A.jsx)(`p`,{className:`text-sm`,children:c.branding.welcome??`Send a message to start the agent.`})]}),c.olderHistory&&(0,A.jsx)(II,{older:c.olderHistory,onLoad:nr}),c.items.map((t,n)=>{let r=`${c.sessionId}:${n}`,i=(e,t=r)=>(0,A.jsx)(`div`,{"data-item-index":n,className:`flex flex-col gap-3 rounded-lg transition-shadow ${$n===n?`ring-2 ring-blue-400 dark:ring-blue-500`:``}`,children:e},t);return t.kind===`user`?i((0,A.jsx)(Je,{item:t,canEdit:!t.readOnly&&!c.isStreaming&&c.connected,onEdit:D})):t.kind===`compaction`?i((0,A.jsx)(FI,{item:t})):t.kind===`tool`?Ut.tools?i((0,A.jsx)(wI,{item:t,dispatch:Un}),t.toolCallId?`${c.sessionId}:${t.toolCallId}`:r):null:t.kind===`custom`?i((0,A.jsx)(TI,{item:t})):(Ut.reasoning?t.blocks:t.blocks.filter(e=>e.type!==`thinking`)).length===0&&!t.errorMessage?(0,A.jsx)(`div`,{"data-item-index":n,className:`sr-only`,"aria-hidden":!0},r):i((0,A.jsx)(BF,{item:t,hideReasoning:!Ut.reasoning,serverUrl:e,token:l,workspace:mt,onOpenFile:e=>{Ht(!1),j(e)}}))}),c.pendingPrompt&&(0,A.jsxs)(`div`,{className:`flex flex-col gap-3 opacity-60`,"data-pending-prompt":!0,children:[(0,A.jsx)(Je,{item:{kind:`user`,...c.pendingPrompt},canEdit:!1,onEdit:()=>{}}),c.extensionsBinding?(0,A.jsxs)(`div`,{className:`flex items-center gap-3`,"data-testid":`prompt-waiting-for-extensions`,children:[(0,A.jsx)(oX,{label:`waiting for extensions to start…`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>h(!Lt.current[ht??``]),className:`text-xs text-zinc-500 underline hover:text-zinc-700 dark:hover:text-zinc-300`,children:`cancel`})]}):(0,A.jsx)(oX,{label:`sending…`})]}),c.isStreaming&&!c.pendingPrompt&&(0,A.jsx)(oX,{label:`working…`}),(c.queue.steering.length>0||c.queue.followUp.length>0)&&(0,A.jsxs)(`div`,{className:`rounded-lg border border-dashed border-zinc-300 px-3 py-2 text-xs text-zinc-500 dark:border-zinc-700`,children:[c.queue.steering.map((e,t)=>(0,A.jsxs)(`div`,{children:[`⏩ steering: `,e]},`s${t}`)),c.queue.followUp.map((e,t)=>(0,A.jsxs)(`div`,{children:[`⏭ follow-up: `,e]},`f${t}`))]}),cn.map((e,t)=>(0,A.jsx)(`div`,{className:`rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:e},`att${t}`)),St&&(0,A.jsx)(`div`,{className:`rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300`,children:St}),Jn&&(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:Jn}),c.errors.map((e,t)=>(0,A.jsx)(`div`,{className:`rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300`,children:e},t)),(0,A.jsx)(`div`,{ref:An})]})}),(0,A.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-4 z-0 flex justify-center ${Kt||$t?`md:pr-[26rem]`:c.workPlan&&Jt?`md:pr-[23rem]`:``}`,children:!Mn&&(0,A.jsxs)(`button`,{type:`button`,onClick:Bn,"aria-label":`Scroll to the latest message`,className:`pointer-events-auto flex items-center gap-1.5 rounded-full border border-zinc-300 bg-white/95 px-3 py-1.5 text-xs text-zinc-600 shadow-lg backdrop-blur transition-colors hover:bg-zinc-50 motion-reduce:transition-none dark:border-zinc-700 dark:bg-zinc-900/95 dark:text-zinc-300 dark:hover:bg-zinc-800`,children:[(0,A.jsx)(`span`,{"aria-hidden":!0,children:`↓`}),`Latest`]})})]}),Qt&&(0,A.jsx)(jY,{open:Xt,onClose:()=>Zt(!1),cwd:c.workspace?.root,confinedRoot:c.terminal?.confined?c.sandbox?.root??c.workspace?.root:void 0,confinement:c.confinement?.terminal,unavailable:c.terminal?.unavailable,onSetWorkspaceRoot:e=>{et&&!o?et(e):c.sandbox?He({sandbox:{root:e,allowWrite:c.sandbox.allowWrite,allowBash:c.sandbox.allowBash,...c.sandbox.writableRoot?{writableRoot:c.sandbox.writableRoot}:{}}}):He({sandbox:{root:e,allowWrite:!0,allowBash:!0}})},openTerminal:ot,sendTerminalInput:st,getTerminalCwd:ct,resizeTerminal:lt,closeTerminal:ut,subscribeTerminal:dt}),(0,A.jsx)(`footer`,{className:`border-t border-zinc-200 px-4 py-3 dark:border-zinc-800`,children:(0,A.jsxs)(`div`,{className:`mx-auto max-w-3xl`,children:[(0,A.jsx)(wR,{widgets:c.widgets,placement:`aboveEditor`}),(0,A.jsx)(rR,{initialDraft:Lt.current[ht??``]??``,onDraftChange:e=>{Lt.current[ht??``]=e},isStreaming:c.isStreaming,connected:c.connected,commands:c.commands,fileSearch:c.fileSearch,prefill:c.editorPrefill,attachments:vt,pendingUploads:un,onAttach:e=>void gn(e),onMentionPaths:xt,onRemoveAttachment:bn,onSend:xn,onAbort:m,onSearchFiles:we,onClearFileSearch:Te},ht??``),(0,A.jsx)(wR,{widgets:c.widgets,placement:`belowEditor`}),(0,A.jsx)(JB,{model:c.model,models:c.models,thinkingLevel:c.thinkingLevel,thinkingLevels:c.thinkingLevels,modelSupportsReasoning:c.modelSupportsReasoning,isStreaming:c.isStreaming,contextUsage:c.contextUsage,shellConfinement:c.confinement?.bash,sessionUsage:Vn,analysisOpen:Kt,onToggleAnalysis:an,isCompacting:c.isCompacting,onSetModel:g,onSetThinking:_,onCompact:ne})]})})]})]}),c.dialogQueue[0]&&(0,A.jsx)(pR,{request:c.dialogQueue[0],onRespond:ce}),(0,A.jsx)(_R,{notifications:c.notifications,onDismiss:le})]})})})});(0,f.createRoot)(document.getElementById(`root`)).render((0,A.jsx)(d.StrictMode,{children:(0,A.jsx)(sX,{})}));export{re as A,qf as C,ce as D,me as E,i as M,ne as O,$f as S,Fe as T,O_ as _,NF as a,Pp as b,yM as c,mD as d,eD as f,Kv as g,by as h,IF as i,E as j,ae as k,eM as l,Fb as m,UR as n,xF as o,ZE as p,GR as r,bM as s,HY as t,OD as u,Ip as v,yd as w,Ap as x,Np as y};