@fideliosai/server 0.0.13 → 0.0.15

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 (76) hide show
  1. package/dist/onboarding-assets/ceo/HEARTBEAT.md +2 -2
  2. package/package.json +13 -13
  3. package/ui-dist/assets/{_basePickBy-Bz1lMRr1.js → _basePickBy-WTG-5iPh.js} +1 -1
  4. package/ui-dist/assets/{_baseUniq-Cz0DIzBh.js → _baseUniq-B3ZmOxI0.js} +1 -1
  5. package/ui-dist/assets/{arc-B03KhCd2.js → arc-BuOXwwts.js} +1 -1
  6. package/ui-dist/assets/{architectureDiagram-VXUJARFQ-Bd-fd33T.js → architectureDiagram-VXUJARFQ-DfcznbHq.js} +1 -1
  7. package/ui-dist/assets/{blockDiagram-VD42YOAC-CXaFl4cP.js → blockDiagram-VD42YOAC-Cv0yxshe.js} +1 -1
  8. package/ui-dist/assets/{c4Diagram-YG6GDRKO-DaDthSB7.js → c4Diagram-YG6GDRKO-CDtuAUfg.js} +1 -1
  9. package/ui-dist/assets/channel-CRigOsGI.js +1 -0
  10. package/ui-dist/assets/{chunk-4BX2VUAB-CJnPL87r.js → chunk-4BX2VUAB-LC9pLgF0.js} +1 -1
  11. package/ui-dist/assets/{chunk-55IACEB6-CJNMJX2n.js → chunk-55IACEB6-CsvVEoD5.js} +1 -1
  12. package/ui-dist/assets/{chunk-B4BG7PRW-DIkK9Mlj.js → chunk-B4BG7PRW-uarVITkT.js} +1 -1
  13. package/ui-dist/assets/{chunk-DI55MBZ5-DSmF2iXg.js → chunk-DI55MBZ5-BO9PksSh.js} +1 -1
  14. package/ui-dist/assets/{chunk-FMBD7UC4-gfze-lvJ.js → chunk-FMBD7UC4-Bs5nkvmr.js} +1 -1
  15. package/ui-dist/assets/{chunk-QN33PNHL-Ddo3zVqT.js → chunk-QN33PNHL-CZD_eEDJ.js} +1 -1
  16. package/ui-dist/assets/{chunk-QZHKN3VN-BPSHvZyX.js → chunk-QZHKN3VN-Kh_REucx.js} +1 -1
  17. package/ui-dist/assets/{chunk-TZMSLE5B-C7wuUAs7.js → chunk-TZMSLE5B-BPOWcY4y.js} +1 -1
  18. package/ui-dist/assets/classDiagram-2ON5EDUG-DwuhXgWi.js +1 -0
  19. package/ui-dist/assets/classDiagram-v2-WZHVMYZB-DwuhXgWi.js +1 -0
  20. package/ui-dist/assets/clone-CU3WTXfN.js +1 -0
  21. package/ui-dist/assets/{cose-bilkent-S5V4N54A-io2ht7Tg.js → cose-bilkent-S5V4N54A-BqNJNgQb.js} +1 -1
  22. package/ui-dist/assets/{dagre-6UL2VRFP-CFH5DFm7.js → dagre-6UL2VRFP-3gexLp24.js} +1 -1
  23. package/ui-dist/assets/{diagram-PSM6KHXK-CPQXpnTx.js → diagram-PSM6KHXK-Dw6qFcD-.js} +1 -1
  24. package/ui-dist/assets/{diagram-QEK2KX5R-BbyOPiaB.js → diagram-QEK2KX5R-C1HDGzZ0.js} +1 -1
  25. package/ui-dist/assets/{diagram-S2PKOQOG-D6BCeM_j.js → diagram-S2PKOQOG-PmGAgdTe.js} +1 -1
  26. package/ui-dist/assets/{erDiagram-Q2GNP2WA-C69wMd1X.js → erDiagram-Q2GNP2WA-DsvjLBRe.js} +1 -1
  27. package/ui-dist/assets/{flowDiagram-NV44I4VS-CKJK9Bqb.js → flowDiagram-NV44I4VS-Bsf0P7_C.js} +1 -1
  28. package/ui-dist/assets/{ganttDiagram-JELNMOA3-CPfA5Aye.js → ganttDiagram-JELNMOA3-BB5P513B.js} +1 -1
  29. package/ui-dist/assets/{gitGraphDiagram-V2S2FVAM-DZaZg_GO.js → gitGraphDiagram-V2S2FVAM-9khmEy7U.js} +1 -1
  30. package/ui-dist/assets/{graph-DhWILner.js → graph-DdyATLzF.js} +1 -1
  31. package/ui-dist/assets/{index-ypuEcx6t.js → index-B4V8seHJ.js} +4 -4
  32. package/ui-dist/assets/{index-CDX_vTiv.js → index-BCiTpvW7.js} +1 -1
  33. package/ui-dist/assets/{index-C0eJUuhF.js → index-BFpb1Uts.js} +1 -1
  34. package/ui-dist/assets/{index-DErU01-2.js → index-BmLtaZGd.js} +1 -1
  35. package/ui-dist/assets/{index-lCZF_3wT.js → index-BtbG7lJJ.js} +1 -1
  36. package/ui-dist/assets/{index-D2T0iIrx.js → index-Bwrg3TbX.js} +1 -1
  37. package/ui-dist/assets/{index-CoA6TNOP.js → index-BxRp1P-l.js} +1 -1
  38. package/ui-dist/assets/{index-CHuh0SWm.js → index-C7QbOdJg.js} +1 -1
  39. package/ui-dist/assets/{index-0wF5nWs7.js → index-CDlfoOW4.js} +1 -1
  40. package/ui-dist/assets/{index-IWMCpuKI.js → index-CE0HSzds.js} +1 -1
  41. package/ui-dist/assets/{index-DOD72BH5.js → index-CN2ALQ8u.js} +1 -1
  42. package/ui-dist/assets/{index-Bw34OrlI.js → index-CgdLFP5M.js} +1 -1
  43. package/ui-dist/assets/{index-BA22JOVS.js → index-CuspQbA8.js} +1 -1
  44. package/ui-dist/assets/{index-samEGEZm.js → index-D323YpVi.js} +1 -1
  45. package/ui-dist/assets/{index-ChbF-4_t.js → index-D3U0l9Rd.js} +1 -1
  46. package/ui-dist/assets/{index-CE0NQXcf.js → index-DC95VDCB.js} +1 -1
  47. package/ui-dist/assets/{index-BpI5gD12.js → index-DKLd1OBJ.js} +1 -1
  48. package/ui-dist/assets/{index-BYLf-CL8.js → index-DeRNQk7z.js} +1 -1
  49. package/ui-dist/assets/{index-DnxtFtFx.js → index-DxMMWvuC.js} +1 -1
  50. package/ui-dist/assets/{index-BYNiNvTL.js → index-MmSDJweg.js} +1 -1
  51. package/ui-dist/assets/{index-DM_ccx3O.js → index-Ub77KksK.js} +1 -1
  52. package/ui-dist/assets/{index-CPbbQZoC.js → index-h3EfCr48.js} +1 -1
  53. package/ui-dist/assets/{index-T3Zr4GMI.js → index-wl4NFr0G.js} +1 -1
  54. package/ui-dist/assets/{infoDiagram-HS3SLOUP-LnZP2Iev.js → infoDiagram-HS3SLOUP-B0E38ipA.js} +1 -1
  55. package/ui-dist/assets/{journeyDiagram-XKPGCS4Q-TeWCkroV.js → journeyDiagram-XKPGCS4Q-DkOH2_m_.js} +1 -1
  56. package/ui-dist/assets/{kanban-definition-3W4ZIXB7-BnVAyHyB.js → kanban-definition-3W4ZIXB7-ChtiOHjM.js} +1 -1
  57. package/ui-dist/assets/{layout-B6TLG_zF.js → layout-ynr_t5n1.js} +1 -1
  58. package/ui-dist/assets/{linear-Dyb-7GvO.js → linear-CcwI8_8p.js} +1 -1
  59. package/ui-dist/assets/{mermaid.core-CpCDuAY2.js → mermaid.core-DuMJwP7Z.js} +4 -4
  60. package/ui-dist/assets/{mindmap-definition-VGOIOE7T-YN4fDnoi.js → mindmap-definition-VGOIOE7T-wNGEXdAs.js} +1 -1
  61. package/ui-dist/assets/{pieDiagram-ADFJNKIX-Jt-577aV.js → pieDiagram-ADFJNKIX-BAMZWTBd.js} +1 -1
  62. package/ui-dist/assets/{quadrantDiagram-AYHSOK5B-CGgFva_d.js → quadrantDiagram-AYHSOK5B-DFJFnWSj.js} +1 -1
  63. package/ui-dist/assets/{requirementDiagram-UZGBJVZJ-DdBYxuTR.js → requirementDiagram-UZGBJVZJ-D5VWj7pp.js} +1 -1
  64. package/ui-dist/assets/{sankeyDiagram-TZEHDZUN-CykYs1PD.js → sankeyDiagram-TZEHDZUN-CbXptxoT.js} +1 -1
  65. package/ui-dist/assets/{sequenceDiagram-WL72ISMW-CDK1H21a.js → sequenceDiagram-WL72ISMW-CnMQxdsY.js} +1 -1
  66. package/ui-dist/assets/{stateDiagram-FKZM4ZOC-CUqmB-ze.js → stateDiagram-FKZM4ZOC-BplnyCPl.js} +1 -1
  67. package/ui-dist/assets/stateDiagram-v2-4FDKWEC3-vc8kyaY_.js +1 -0
  68. package/ui-dist/assets/{timeline-definition-IT6M3QCI-CM3R1w9U.js → timeline-definition-IT6M3QCI-ByAuPylm.js} +1 -1
  69. package/ui-dist/assets/{treemap-GDKQZRPO-Ddo-4aIO.js → treemap-GDKQZRPO-D8jm92yP.js} +1 -1
  70. package/ui-dist/assets/{xychartDiagram-PRI3JC2R-BBxPoZv5.js → xychartDiagram-PRI3JC2R-BT1hUEEX.js} +1 -1
  71. package/ui-dist/index.html +1 -1
  72. package/ui-dist/assets/channel-DyOjp3LQ.js +0 -1
  73. package/ui-dist/assets/classDiagram-2ON5EDUG-BtJMQosd.js +0 -1
  74. package/ui-dist/assets/classDiagram-v2-WZHVMYZB-BtJMQosd.js +0 -1
  75. package/ui-dist/assets/clone-CXFUP-5d.js +0 -1
  76. package/ui-dist/assets/stateDiagram-v2-4FDKWEC3-ST-nIdhL.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C0eJUuhF.js","assets/index-CHuh0SWm.js","assets/index-Bw34OrlI.js","assets/index-samEGEZm.js","assets/index-IWMCpuKI.js","assets/index-D2T0iIrx.js","assets/index-ChbF-4_t.js","assets/index-CE0NQXcf.js","assets/index-lCZF_3wT.js","assets/index-CDX_vTiv.js","assets/index-DErU01-2.js","assets/index-CoA6TNOP.js","assets/index-BYNiNvTL.js","assets/index-DM_ccx3O.js","assets/index-0wF5nWs7.js","assets/index-DnxtFtFx.js","assets/index-T3Zr4GMI.js","assets/index-CPbbQZoC.js","assets/index-BYLf-CL8.js","assets/index-BpI5gD12.js","assets/dockerfile-BKs6k2Af.js","assets/simple-mode-GW_nhZxv.js","assets/factor-kuTfRLto.js","assets/nsis-LdVXkNf5.js","assets/pug-DeIclll2.js","assets/javascript-iXu5QeM3.js","assets/index-BA22JOVS.js","assets/index-DOD72BH5.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BFpb1Uts.js","assets/index-C7QbOdJg.js","assets/index-CgdLFP5M.js","assets/index-D323YpVi.js","assets/index-CE0HSzds.js","assets/index-Bwrg3TbX.js","assets/index-D3U0l9Rd.js","assets/index-DC95VDCB.js","assets/index-BtbG7lJJ.js","assets/index-BCiTpvW7.js","assets/index-BmLtaZGd.js","assets/index-BxRp1P-l.js","assets/index-MmSDJweg.js","assets/index-Ub77KksK.js","assets/index-CDlfoOW4.js","assets/index-DxMMWvuC.js","assets/index-wl4NFr0G.js","assets/index-h3EfCr48.js","assets/index-DeRNQk7z.js","assets/index-DKLd1OBJ.js","assets/dockerfile-BKs6k2Af.js","assets/simple-mode-GW_nhZxv.js","assets/factor-kuTfRLto.js","assets/nsis-LdVXkNf5.js","assets/pug-DeIclll2.js","assets/javascript-iXu5QeM3.js","assets/index-CuspQbA8.js","assets/index-CN2ALQ8u.js"])))=>i.map(i=>d[i]);
2
2
  var uge=Object.defineProperty;var $F=t=>{throw TypeError(t)};var dge=(t,e,n)=>e in t?uge(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Xi=(t,e,n)=>dge(t,typeof e!="symbol"?e+"":e,n),ZA=(t,e,n)=>e.has(t)||$F("Cannot "+n);var he=(t,e,n)=>(ZA(t,e,"read from private field"),n?n.call(t):e.get(t)),Ot=(t,e,n)=>e.has(t)?$F("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),ht=(t,e,n,r)=>(ZA(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),an=(t,e,n)=>(ZA(t,e,"access private method"),n);var mC=(t,e,n,r)=>({set _(s){ht(t,e,s,n)},get _(){return he(t,e,r)}});function AY(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in t)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var FF=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function rlt(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var XA={exports:{}},vb={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -1005,7 +1005,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${e.do
1005
1005
  `))};if((At.mac||At.android)&&h.from==a-1&&/^\. ?$/.test(r.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(h={from:l,to:c,insert:pr.of([r.text.replace("."," ")])}),this.pendingContextChange=h,!e.state.readOnly){let p=this.to-this.from+(h.to-h.from+h.insert.length);WL(e,h,Qe.single(this.toEditorPos(r.selectionStart,p),this.toEditorPos(r.selectionEnd,p)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),h.from<h.to&&!h.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(n.text.slice(Math.max(0,r.updateRangeStart-1),Math.min(n.text.length,r.updateRangeStart+1)))&&this.handlers.compositionend(r)},this.handlers.characterboundsupdate=r=>{let s=[],i=null;for(let a=this.toEditorPos(r.rangeStart),l=this.toEditorPos(r.rangeEnd);a<l;a++){let c=e.coordsForChar(a);i=c&&new DOMRect(c.left,c.top,c.right-c.left,c.bottom-c.top)||i||new DOMRect,s.push(i)}n.updateCharacterBounds(r.rangeStart,s)},this.handlers.textformatupdate=r=>{let s=[];for(let i of r.getTextFormats()){let a=i.underlineStyle,l=i.underlineThickness;if(!/none/i.test(a)&&!/none/i.test(l)){let c=this.toEditorPos(i.rangeStart),u=this.toEditorPos(i.rangeEnd);if(c<u){let f=`text-decoration: underline ${/^[a-z]/.test(a)?a+" ":a=="Dashed"?"dashed ":a=="Squiggle"?"wavy ":""}${/thin/i.test(l)?1:2}px`;s.push(Qt.mark({attributes:{style:f}}).range(c,u))}}}e.dispatch({effects:Zle.of(Qt.set(s))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:r}=this.composing;this.composing=null,r&&this.reset(e.state)}};for(let r in this.handlers)n.addEventListener(r,this.handlers[r]);this.measureReq={read:r=>{this.editContext.updateControlBounds(r.contentDOM.getBoundingClientRect());let s=k1(r.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let n=0,r=!1,s=this.pendingContextChange;return e.changes.iterChanges((i,a,l,c,u)=>{if(r)return;let f=u.length-(a-i);if(s&&a>=s.to)if(s.from==i&&s.to==a&&s.insert.eq(u)){s=this.pendingContextChange=null,n+=f,this.to+=f;return}else s=null,this.revertPending(e.state);if(i+=n,a+=n,a<=this.from)this.from+=f,this.to+=f;else if(i<this.to){if(i<this.from||a>this.to||this.to-this.from+u.length>3e4){r=!0;return}this.editContext.updateText(this.toContextPos(i),this.toContextPos(a),u.toString()),this.to+=f}n+=f}),s&&!r&&this.revertPending(e.state),!r}update(e){let n=this.pendingContextChange,r=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(r.from,r.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||n)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:n}=e.selection.main;this.from=Math.max(0,n-1e4),this.to=Math.min(e.doc.length,n+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let n=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(n.from),this.toContextPos(n.from+n.insert.length),e.doc.sliceString(n.from,n.to))}setSelection(e){let{main:n}=e.selection,r=this.toContextPos(Math.max(this.from,Math.min(this.to,n.anchor))),s=this.toContextPos(n.head);(this.editContext.selectionStart!=r||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(r,s)}rangeIsValid(e){let{head:n}=e.selection.main;return!(this.from>0&&n-this.from<500||this.to<e.doc.length&&this.to-n<500||this.to-this.from>1e4*3)}toEditorPos(e,n=this.to-this.from){e=Math.min(e,n);let r=this.composing;return r&&r.drifted?r.editorBase+(e-r.contextBase):e+this.from}toContextPos(e){let n=this.composing;return n&&n.drifted?n.contextBase+(e-n.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class Nt{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var n;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:r}=e;this.dispatchTransactions=e.dispatchTransactions||r&&(s=>s.forEach(i=>r(i,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||OBe(e.parent)||document,this.viewState=new Lq(e.state||Zn.create(e)),e.scrollTo&&e.scrollTo.is(YC)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(_x).map(s=>new E3(s));for(let s of this.plugins)s.update(this);this.observer=new rUe(this),this.inputState=new Sze(this),this.inputState.ensureHandlers(this.plugins),this.docView=new jq(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((n=document.fonts)===null||n===void 0)&&n.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let n=e.length==1&&e[0]instanceof Zs?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(n,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let n=!1,r=!1,s,i=this.state;for(let p of e){if(p.startState!=i)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");i=p.state}if(this.destroyed){this.viewState.state=i;return}let a=this.hasFocus,l=0,c=null;e.some(p=>p.annotation(mce))?(this.inputState.notifiedFocused=a,l=1):a!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=a,c=pce(i,a),c||(l=1));let u=this.observer.delayedAndroidKey,f=null;if(u?(this.observer.clearDelayedAndroidKey(),f=this.observer.readChange(),(f&&!this.state.doc.eq(i.doc)||!this.state.selection.eq(i.selection))&&(f=null)):this.observer.clear(),i.facet(Zn.phrases)!=this.state.facet(Zn.phrases))return this.setState(i);s=HN.create(this,i,e),s.flags|=l;let h=this.viewState.scrollTarget;try{this.updateState=2;for(let p of e){if(h&&(h=h.map(p.changes)),p.scrollIntoView){let{main:g}=p.state.selection;h=new Wx(g.empty?g:Qe.cursor(g.head,g.head>g.anchor?-1:1))}for(let g of p.effects)g.is(YC)&&(h=g.value.clip(this.state))}this.viewState.update(s,h),this.bidiCache=YN.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),n=this.docView.update(s),this.state.facet(nv)!=this.styleModules&&this.mountStyles(),r=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(n,e.some(p=>p.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(t2)!=s.state.facet(t2)&&(this.viewState.mustMeasureContent=!0),(n||r||h||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),n&&this.docViewUpdate(),!s.empty)for(let p of this.state.facet(zR))try{p(s)}catch(g){aa(this.state,g,"update listener")}(c||f)&&Promise.resolve().then(()=>{c&&this.state==c.startState&&this.dispatch(c),f&&!ace(this,f)&&u.force&&Kx(this.contentDOM,u.key,u.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let n=this.hasFocus;try{for(let r of this.plugins)r.destroy(this);this.viewState=new Lq(e),this.plugins=e.facet(_x).map(r=>new E3(r)),this.pluginMap.clear();for(let r of this.plugins)r.update(this);this.docView.destroy(),this.docView=new jq(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}n&&this.focus(),this.requestMeasure()}updatePlugins(e){let n=e.startState.facet(_x),r=e.state.facet(_x);if(n!=r){let s=[];for(let i of r){let a=n.indexOf(i);if(a<0)s.push(new E3(i));else{let l=this.plugins[a];l.mustUpdate=e,s.push(l)}}for(let i of this.plugins)i.mustUpdate!=e&&i.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s<this.plugins.length;s++)this.plugins[s].update(this);n!=r&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let n=e.value;if(n&&n.docViewUpdate)try{n.docViewUpdate(this)}catch(r){aa(this.state,r,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let n=null,r=this.scrollDOM,s=r.scrollTop*this.scaleY,{scrollAnchorPos:i,scrollAnchorHeight:a}=this.viewState;Math.abs(s-this.viewState.scrollTop)>1&&(a=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(a<0)if(Dle(r))i=-1,a=this.viewState.heightMap.height;else{let g=this.viewState.scrollAnchorAt(s);i=g.from,a=g.top}this.updateState=1;let c=this.viewState.measure(this);if(!c&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let u=[];c&4||([this.measureRequests,u]=[u,this.measureRequests]);let f=u.map(g=>{try{return g.read(this)}catch(b){return aa(this.state,b),Uq}}),h=HN.create(this,this.state,[]),p=!1;h.flags|=c,n?n.flags|=c:n=h,this.updateState=2,h.empty||(this.updatePlugins(h),this.inputState.update(h),this.updateAttrs(),p=this.docView.update(h),p&&this.docViewUpdate());for(let g=0;g<u.length;g++)if(f[g]!=Uq)try{let b=u[g];b.write&&b.write(f[g],this)}catch(b){aa(this.state,b)}if(p&&this.docView.updateSelection(!0),!h.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,a=-1;continue}else{let b=(i<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(i).top)-a;if(b>1||b<-1){s=s+b,r.scrollTop=s/this.scaleY,a=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(n&&!n.empty)for(let l of this.state.facet(zR))l(n)}get themeClasses(){return WR+" "+(this.state.facet(KR)?bce:yce)+" "+this.state.facet(t2)}updateAttrs(){let e=Vq(this,Xle,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),n={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(hd)?"true":"false",class:"cm-content",style:`${At.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(n["aria-readonly"]="true"),Vq(this,HL,n);let r=this.observer.ignore(()=>{let s=yq(this.contentDOM,this.contentAttrs,n),i=yq(this.dom,this.editorAttrs,e);return s||i});return this.editorAttrs=e,this.contentAttrs=n,r}showAnnouncements(e){let n=!0;for(let r of e)for(let s of r.effects)if(s.is(Nt.announce)){n&&(this.announceDOM.textContent=""),n=!1;let i=this.announceDOM.appendChild(document.createElement("div"));i.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(nv);let e=this.state.facet(Nt.cspNonce);zh.mount(this.root,this.styleModules.concat(tUe).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let n=0;n<this.measureRequests.length;n++)if(this.measureRequests[n].key===e.key){this.measureRequests[n]=e;return}}this.measureRequests.push(e)}}plugin(e){let n=this.pluginMap.get(e);return(n===void 0||n&&n.plugin!=e)&&this.pluginMap.set(e,n=this.plugins.find(r=>r.plugin==e)||null),n&&n.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,n,r){return I3(this,e,Nq(this,e,n,r))}moveByGroup(e,n){return I3(this,e,Nq(this,e,n,r=>gze(this,e.head,r)))}visualLineSide(e,n){let r=this.bidiSpans(e),s=this.textDirectionAt(e.from),i=r[n?r.length-1:0];return Qe.cursor(i.side(n,s)+e.from,i.forward(!n,s)?1:-1)}moveToLineBoundary(e,n,r=!0){return pze(this,e,n,r)}moveVertically(e,n,r){return I3(this,e,xze(this,e,n,r))}domAtPos(e,n=1){return this.docView.domAtPos(e,n)}posAtDOM(e,n=0){return this.docView.posFromDOM(e,n)}posAtCoords(e,n=!0){this.readMeasured();let r=HR(this,e,n);return r&&r.pos}posAndSideAtCoords(e,n=!0){return this.readMeasured(),HR(this,e,n)}coordsAtPos(e,n=1){this.readMeasured();let r=this.docView.coordsAt(e,n);if(!r||r.left==r.right)return r;let s=this.state.doc.lineAt(e),i=this.bidiSpans(s),a=i[Qc.find(i,e-s.from,-1,n)];return VN(r,a.dir==Kr.LTR==n>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Yle)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>oUe)return zle(e.length);let n=this.textDirectionAt(e.from),r;for(let i of this.bidiCache)if(i.from==e.from&&i.dir==n&&(i.fresh||Ble(i.isolates,r=wq(this,e))))return i.order;r||(r=wq(this,e));let s=UBe(e.text,n,r);return this.bidiCache.push(new YN(e.from,e.to,n,r,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||At.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Ole(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,n={}){return YC.of(new Wx(typeof e=="number"?Qe.cursor(e):e,n.y,n.x,n.yMargin,n.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:n}=this.scrollDOM,r=this.viewState.scrollAnchorAt(e);return YC.of(new Wx(Qe.cursor(r.from),"start","start",r.top-e,n,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return ti.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ti.define(()=>({}),{eventObservers:e})}static theme(e,n){let r=zh.newName(),s=[t2.of(r),nv.of(GR(`.${r}`,e))];return n&&n.dark&&s.push(KR.of(!0)),s}static baseTheme(e){return um.lowest(nv.of(GR("."+WR,e,vce)))}static findFromDOM(e){var n;let r=e.querySelector(".cm-content"),s=r&&ei.get(r)||ei.get(e);return((n=s==null?void 0:s.root)===null||n===void 0?void 0:n.view)||null}}Nt.styleModule=nv;Nt.inputHandler=Wle;Nt.clipboardInputFilter=UL;Nt.clipboardOutputFilter=VL;Nt.scrollHandler=Qle;Nt.focusChangeEffect=Gle;Nt.perLineTextDirection=Yle;Nt.exceptionSink=Kle;Nt.updateListener=zR;Nt.editable=hd;Nt.mouseSelectionStyle=qle;Nt.dragMovesSelection=Hle;Nt.clickAddsSelectionRange=Vle;Nt.decorations=b5;Nt.blockWrappers=ece;Nt.outerDecorations=qL;Nt.atomicRanges=Uw;Nt.bidiIsolatedRanges=tce;Nt.scrollMargins=nce;Nt.darkTheme=KR;Nt.cspNonce=_t.define({combine:t=>t.length?t[0]:""});Nt.contentAttributes=HL;Nt.editorAttributes=Xle;Nt.lineWrapping=Nt.contentAttributes.of({class:"cm-lineWrapping"});Nt.announce=pn.define();const oUe=4096,Uq={};class YN{constructor(e,n,r,s,i,a){this.from=e,this.to=n,this.dir=r,this.isolates=s,this.fresh=i,this.order=a}static update(e,n){if(n.empty&&!e.some(i=>i.fresh))return e;let r=[],s=e.length?e[e.length-1].dir:Kr.LTR;for(let i=Math.max(0,e.length-10);i<e.length;i++){let a=e[i];a.dir==s&&!n.touchesRange(a.from,a.to)&&r.push(new YN(n.mapPos(a.from,1),n.mapPos(a.to,-1),a.dir,a.isolates,!1,a.order))}return r}}function Vq(t,e,n){for(let r=t.state.facet(e),s=r.length-1;s>=0;s--){let i=r[s],a=typeof i=="function"?i(t):i;a&&FL(a,n)}return n}const aUe=At.mac?"mac":At.windows?"win":At.linux?"linux":"key";function lUe(t,e){const n=t.split(/-(?!$)/);let r=n[n.length-1];r=="Space"&&(r=" ");let s,i,a,l;for(let c=0;c<n.length-1;++c){const u=n[c];if(/^(cmd|meta|m)$/i.test(u))l=!0;else if(/^a(lt)?$/i.test(u))s=!0;else if(/^(c|ctrl|control)$/i.test(u))i=!0;else if(/^s(hift)?$/i.test(u))a=!0;else if(/^mod$/i.test(u))e=="mac"?l=!0:i=!0;else throw new Error("Unrecognized modifier name: "+u)}return s&&(r="Alt-"+r),i&&(r="Ctrl-"+r),l&&(r="Meta-"+r),a&&(r="Shift-"+r),r}function n2(t,e,n){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n!==!1&&e.shiftKey&&(t="Shift-"+t),t}const cUe=um.default(Nt.domEventHandlers({keydown(t,e){return kce(wce(e.state),t,e,"editor")}})),Vw=_t.define({enables:cUe}),Hq=new WeakMap;function wce(t){let e=t.facet(Vw),n=Hq.get(e);return n||Hq.set(e,n=fUe(e.reduce((r,s)=>r.concat(s),[]))),n}function uUe(t,e,n){return kce(wce(t.state),e,t,n)}let qf=null;const dUe=4e3;function fUe(t,e=aUe){let n=Object.create(null),r=Object.create(null),s=(a,l)=>{let c=r[a];if(c==null)r[a]=l;else if(c!=l)throw new Error("Key binding "+a+" is used both as a regular binding and as a multi-stroke prefix")},i=(a,l,c,u,f)=>{var h,p;let g=n[a]||(n[a]=Object.create(null)),b=l.split(/ (?!$)/).map(j=>lUe(j,e));for(let j=1;j<b.length;j++){let C=b.slice(0,j).join(" ");s(C,!0),g[C]||(g[C]={preventDefault:!0,stopPropagation:!1,run:[N=>{let S=qf={view:N,prefix:C,scope:a};return setTimeout(()=>{qf==S&&(qf=null)},dUe),!0}]})}let v=b.join(" ");s(v,!1);let w=g[v]||(g[v]={preventDefault:!1,stopPropagation:!1,run:((p=(h=g._any)===null||h===void 0?void 0:h.run)===null||p===void 0?void 0:p.slice())||[]});c&&w.run.push(c),u&&(w.preventDefault=!0),f&&(w.stopPropagation=!0)};for(let a of t){let l=a.scope?a.scope.split(" "):["editor"];if(a.any)for(let u of l){let f=n[u]||(n[u]=Object.create(null));f._any||(f._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:h}=a;for(let p in f)f[p].run.push(g=>h(g,YR))}let c=a[e]||a.key;if(c)for(let u of l)i(u,c,a.run,a.preventDefault,a.stopPropagation),a.shift&&i(u,"Shift-"+c,a.shift,a.preventDefault,a.stopPropagation)}return n}let YR=null;function kce(t,e,n,r){YR=e;let s=NBe(e),i=na(s,0),a=qc(i)==s.length&&s!=" ",l="",c=!1,u=!1,f=!1;qf&&qf.view==n&&qf.scope==r&&(l=qf.prefix+" ",uce.indexOf(e.keyCode)<0&&(u=!0,qf=null));let h=new Set,p=w=>{if(w){for(let j of w.run)if(!h.has(j)&&(h.add(j),j(n)))return w.stopPropagation&&(f=!0),!0;w.preventDefault&&(w.stopPropagation&&(f=!0),u=!0)}return!1},g=t[r],b,v;return g&&(p(g[l+n2(s,e,!a)])?c=!0:a&&(e.altKey||e.metaKey||e.ctrlKey)&&!(At.windows&&e.ctrlKey&&e.altKey)&&!(At.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(b=Uh[e.keyCode])&&b!=s?(p(g[l+n2(b,e,!0)])||e.shiftKey&&(v=v1[e.keyCode])!=s&&v!=b&&p(g[l+n2(v,e,!1)]))&&(c=!0):a&&e.shiftKey&&p(g[l+n2(s,e,!0)])&&(c=!0),!c&&p(g._any)&&(c=!0)),u&&(c=!0),c&&f&&e.stopPropagation(),YR=null,c}class Hw{constructor(e,n,r,s,i){this.className=e,this.left=n,this.top=r,this.width=s,this.height=i}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,n){return n.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,n,r){if(r.empty){let s=e.coordsAtPos(r.head,r.assoc||1);if(!s)return[];let i=Cce(e);return[new Hw(n,s.left-i.left,s.top-i.top,null,s.bottom-s.top)]}else return hUe(e,n,r)}}function Cce(t){let e=t.scrollDOM.getBoundingClientRect();return{left:(t.textDirection==Kr.LTR?e.left:e.right-t.scrollDOM.clientWidth*t.scaleX)-t.scrollDOM.scrollLeft*t.scaleX,top:e.top-t.scrollDOM.scrollTop*t.scaleY}}function qq(t,e,n,r){let s=t.coordsAtPos(e,n*2);if(!s)return r;let i=t.dom.getBoundingClientRect(),a=(s.top+s.bottom)/2,l=t.posAtCoords({x:i.left+1,y:a}),c=t.posAtCoords({x:i.right-1,y:a});return l==null||c==null?r:{from:Math.max(r.from,Math.min(l,c)),to:Math.min(r.to,Math.max(l,c))}}function hUe(t,e,n){if(n.to<=t.viewport.from||n.from>=t.viewport.to)return[];let r=Math.max(n.from,t.viewport.from),s=Math.min(n.to,t.viewport.to),i=t.textDirection==Kr.LTR,a=t.contentDOM,l=a.getBoundingClientRect(),c=Cce(t),u=a.querySelector(".cm-line"),f=u&&window.getComputedStyle(u),h=l.left+(f?parseInt(f.paddingLeft)+Math.min(0,parseInt(f.textIndent)):0),p=l.right-(f?parseInt(f.paddingRight):0),g=VR(t,r,1),b=VR(t,s,-1),v=g.type==Yi.Text?g:null,w=b.type==Yi.Text?b:null;if(v&&(t.lineWrapping||g.widgetLineBreaks)&&(v=qq(t,r,1,v)),w&&(t.lineWrapping||b.widgetLineBreaks)&&(w=qq(t,s,-1,w)),v&&w&&v.from==w.from&&v.to==w.to)return C(N(n.from,n.to,v));{let T=v?N(n.from,null,v):S(g,!1),_=w?N(null,n.to,w):S(b,!0),A=[];return(v||g).to<(w||b).from-(v&&w?1:0)||g.widgetLineBreaks>1&&T.bottom+t.defaultLineHeight/2<_.top?A.push(j(h,T.bottom,p,_.top)):T.bottom<_.top&&t.elementAtHeight((T.bottom+_.top)/2).type==Yi.Text&&(T.bottom=_.top=(T.bottom+_.top)/2),C(T).concat(A).concat(C(_))}function j(T,_,A,M){return new Hw(e,T-c.left,_-c.top,Math.max(0,A-T),M-_)}function C({top:T,bottom:_,horizontal:A}){let M=[];for(let I=0;I<A.length;I+=2)M.push(j(A[I],T,A[I+1],_));return M}function N(T,_,A){let M=1e9,I=-1e9,L=[];function D(Z,Q,q,O,z){let V=t.coordsAtPos(Z,Z==A.to?-2:2),$=t.coordsAtPos(q,q==A.from?2:-2);!V||!$||(M=Math.min(V.top,$.top,M),I=Math.max(V.bottom,$.bottom,I),z==Kr.LTR?L.push(i&&Q?h:V.left,i&&O?p:$.right):L.push(!i&&O?h:$.left,!i&&Q?p:V.right))}let P=T??A.from,B=_??A.to;for(let Z of t.visibleRanges)if(Z.to>P&&Z.from<B)for(let Q=Math.max(Z.from,P),q=Math.min(Z.to,B);;){let O=t.state.doc.lineAt(Q);for(let z of t.bidiSpans(O)){let V=z.from+O.from,$=z.to+O.from;if(V>=q)break;$>Q&&D(Math.max(V,Q),T==null&&V<=P,Math.min($,q),_==null&&$>=B,z.dir)}if(Q=O.to+1,Q>=q)break}return L.length==0&&D(P,T==null,B,_==null,t.textDirection),{top:M,bottom:I,horizontal:L}}function S(T,_){let A=l.top+(_?T.top:T.bottom);return{top:A,bottom:A,horizontal:[]}}}function mUe(t,e){return t.constructor==e.constructor&&t.eq(e)}class pUe{constructor(e,n){this.view=e,this.layer=n,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),n.above&&this.dom.classList.add("cm-layer-above"),n.class&&this.dom.classList.add(n.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),n.mount&&n.mount(this.dom,e)}update(e){e.startState.facet(aj)!=e.state.facet(aj)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let n=0,r=e.facet(aj);for(;n<r.length&&r[n]!=this.layer;)n++;this.dom.style.zIndex=String((this.layer.above?150:-1)-n)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:n}=this.view;(e!=this.scaleX||n!=this.scaleY)&&(this.scaleX=e,this.scaleY=n,this.dom.style.transform=`scale(${1/e}, ${1/n})`)}draw(e){if(e.length!=this.drawn.length||e.some((n,r)=>!mUe(n,this.drawn[r]))){let n=this.dom.firstChild,r=0;for(let s of e)s.update&&n&&s.constructor&&this.drawn[r].constructor&&s.update(n,this.drawn[r])?(n=n.nextSibling,r++):this.dom.insertBefore(s.draw(),n);for(;n;){let s=n.nextSibling;n.remove(),n=s}this.drawn=e,At.safari&&At.safari_version>=26&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const aj=_t.define();function jce(t){return[ti.define(e=>new pUe(e,t)),aj.of(t)]}const j1=_t.define({combine(t){return Cu(t,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,n)=>Math.min(e,n),drawRangeCursor:(e,n)=>e||n})}});function gUe(t={}){return[j1.of(t),xUe,yUe,bUe,Jle.of(!0)]}function Nce(t){return t.startState.facet(j1)!=t.state.facet(j1)}const xUe=jce({above:!0,markers(t){let{state:e}=t,n=e.facet(j1),r=[];for(let s of e.selection.ranges){let i=s==e.selection.main;if(s.empty||n.drawRangeCursor){let a=i?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=s.empty?s:Qe.cursor(s.head,s.head>s.anchor?-1:1);for(let c of Hw.forRange(t,a,l))r.push(c)}}return r},update(t,e){t.transactions.some(r=>r.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let n=Nce(t);return n&&Kq(t.state,e),t.docChanged||t.selectionSet||n},mount(t,e){Kq(e.state,t)},class:"cm-cursorLayer"});function Kq(t,e){e.style.animationDuration=t.facet(j1).cursorBlinkRate+"ms"}const yUe=jce({above:!1,markers(t){return t.state.selection.ranges.map(e=>e.empty?[]:Hw.forRange(t,"cm-selectionBackground",e)).reduce((e,n)=>e.concat(n))},update(t,e){return t.docChanged||t.selectionSet||t.viewportChanged||Nce(t)},class:"cm-selectionLayer"}),bUe=um.highest(Nt.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Sce=pn.define({map(t,e){return t==null?null:e.mapPos(t)}}),iv=Oi.define({create(){return null},update(t,e){return t!=null&&(t=e.changes.mapPos(t)),e.effects.reduce((n,r)=>r.is(Sce)?r.value:n,t)}}),vUe=ti.fromClass(class{constructor(t){this.view=t,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(t){var e;let n=t.state.field(iv);n==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(t.startState.field(iv)!=n||t.docChanged||t.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:t}=this,e=t.state.field(iv),n=e!=null&&t.coordsAtPos(e);if(!n)return null;let r=t.scrollDOM.getBoundingClientRect();return{left:n.left-r.left+t.scrollDOM.scrollLeft*t.scaleX,top:n.top-r.top+t.scrollDOM.scrollTop*t.scaleY,height:n.bottom-n.top}}drawCursor(t){if(this.cursor){let{scaleX:e,scaleY:n}=this.view;t?(this.cursor.style.left=t.left/e+"px",this.cursor.style.top=t.top/n+"px",this.cursor.style.height=t.height/n+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(t){this.view.state.field(iv)!=t&&this.view.dispatch({effects:Sce.of(t)})}},{eventObservers:{dragover(t){this.setDropPos(this.view.posAtCoords({x:t.clientX,y:t.clientY}))},dragleave(t){(t.target==this.view.contentDOM||!this.view.contentDOM.contains(t.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function wUe(){return[iv,vUe]}function Wq(t,e,n,r,s){e.lastIndex=0;for(let i=t.iterRange(n,r),a=n,l;!i.next().done;a+=i.value.length)if(!i.lineBreak)for(;l=e.exec(i.value);)s(a+l.index,l)}function kUe(t,e){let n=t.visibleRanges;if(n.length==1&&n[0].from==t.viewport.from&&n[0].to==t.viewport.to)return n;let r=[];for(let{from:s,to:i}of n)s=Math.max(t.state.doc.lineAt(s).from,s-e),i=Math.min(t.state.doc.lineAt(i).to,i+e),r.length&&r[r.length-1].to>=s?r[r.length-1].to=i:r.push({from:s,to:i});return r}class CUe{constructor(e){const{regexp:n,decoration:r,decorate:s,boundary:i,maxLength:a=1e3}=e;if(!n.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=n,s)this.addMatch=(l,c,u,f)=>s(f,u,u+l[0].length,l,c);else if(typeof r=="function")this.addMatch=(l,c,u,f)=>{let h=r(l,c,u);h&&f(u,u+l[0].length,h)};else if(r)this.addMatch=(l,c,u,f)=>f(u,u+l[0].length,r);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=i,this.maxLength=a}createDeco(e){let n=new zd,r=n.add.bind(n);for(let{from:s,to:i}of kUe(e,this.maxLength))Wq(e.state.doc,this.regexp,s,i,(a,l)=>this.addMatch(l,e,a,r));return n.finish()}updateDeco(e,n){let r=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((i,a,l,c)=>{c>=e.view.viewport.from&&l<=e.view.viewport.to&&(r=Math.min(l,r),s=Math.max(c,s))}),e.viewportMoved||s-r>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,n.map(e.changes),r,s):n}updateRange(e,n,r,s){for(let i of e.visibleRanges){let a=Math.max(i.from,r),l=Math.min(i.to,s);if(l>=a){let c=e.state.doc.lineAt(a),u=c.to<l?e.state.doc.lineAt(l):c,f=Math.max(i.from,c.from),h=Math.min(i.to,u.to);if(this.boundary){for(;a>c.from;a--)if(this.boundary.test(c.text[a-1-c.from])){f=a;break}for(;l<u.to;l++)if(this.boundary.test(u.text[l-u.from])){h=l;break}}let p=[],g,b=(v,w,j)=>p.push(j.range(v,w));if(c==u)for(this.regexp.lastIndex=f-c.from;(g=this.regexp.exec(c.text))&&g.index<h-c.from;)this.addMatch(g,e,g.index+c.from,b);else Wq(e.state.doc,this.regexp,f,h,(v,w)=>this.addMatch(w,e,v,b));n=n.update({filterFrom:f,filterTo:h,filter:(v,w)=>v<f||w>h,add:p})}}return n}}const JR=/x/.unicode!=null?"gu":"g",jUe=new RegExp(`[\0-\b
1006
1006
  --Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,JR),NUe={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let D3=null;function SUe(){var t;if(D3==null&&typeof document<"u"&&document.body){let e=document.body.style;D3=((t=e.tabSize)!==null&&t!==void 0?t:e.MozTabSize)!=null}return D3||!1}const lj=_t.define({combine(t){let e=Cu(t,{render:null,specialChars:jUe,addSpecialChars:null});return(e.replaceTabs=!SUe())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,JR)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,JR)),e}});function _Ue(t={}){return[lj.of(t),EUe()]}let Gq=null;function EUe(){return Gq||(Gq=ti.fromClass(class{constructor(t){this.view=t,this.decorations=Qt.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(t.state.facet(lj)),this.decorations=this.decorator.createDeco(t)}makeDecorator(t){return new CUe({regexp:t.specialChars,decoration:(e,n,r)=>{let{doc:s}=n.state,i=na(e[0],0);if(i==9){let a=s.lineAt(r),l=n.state.tabSize,c=N0(a.text,l,r-a.from);return Qt.replace({widget:new IUe((l-c%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[i]||(this.decorationCache[i]=Qt.replace({widget:new MUe(t,i)}))},boundary:t.replaceTabs?void 0:/[^]/})}update(t){let e=t.state.facet(lj);t.startState.facet(lj)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(t.view)):this.decorations=this.decorator.updateDeco(t,this.decorations)}},{decorations:t=>t.decorations}))}const AUe="•";function TUe(t){return t>=32?AUe:t==10?"␤":String.fromCharCode(9216+t)}class MUe extends ju{constructor(e,n){super(),this.options=e,this.code=n}eq(e){return e.code==this.code}toDOM(e){let n=TUe(this.code),r=e.state.phrase("Control character")+" "+(NUe[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,r,n);if(s)return s;let i=document.createElement("span");return i.textContent=n,i.title=r,i.setAttribute("aria-label",r),i.className="cm-specialChar",i}ignoreEvent(){return!1}}class IUe extends ju{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function RUe(){return DUe}const OUe=Qt.line({class:"cm-activeLine"}),DUe=ti.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.docChanged||t.selectionSet)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=-1,n=[];for(let r of t.state.selection.ranges){let s=t.lineBlockAt(r.head);s.from>e&&(n.push(OUe.range(s.from)),e=s.from)}return Qt.set(n)}},{decorations:t=>t.decorations}),QR=2e3;function PUe(t,e,n){let r=Math.min(e.line,n.line),s=Math.max(e.line,n.line),i=[];if(e.off>QR||n.off>QR||e.col<0||n.col<0){let a=Math.min(e.off,n.off),l=Math.max(e.off,n.off);for(let c=r;c<=s;c++){let u=t.doc.line(c);u.length<=l&&i.push(Qe.range(u.from+a,u.to+l))}}else{let a=Math.min(e.col,n.col),l=Math.max(e.col,n.col);for(let c=r;c<=s;c++){let u=t.doc.line(c),f=TR(u.text,a,t.tabSize,!0);if(f<0)i.push(Qe.cursor(u.to));else{let h=TR(u.text,l,t.tabSize);i.push(Qe.range(u.from+f,u.from+h))}}}return i}function LUe(t,e){let n=t.coordsAtPos(t.viewport.from);return n?Math.round(Math.abs((n.left-e)/t.defaultCharacterWidth)):-1}function Yq(t,e){let n=t.posAtCoords({x:e.clientX,y:e.clientY},!1),r=t.state.doc.lineAt(n),s=n-r.from,i=s>QR?-1:s==r.length?LUe(t,e.clientX):N0(r.text,t.state.tabSize,n-r.from);return{line:r.number,col:i,off:s}}function $Ue(t,e){let n=Yq(t,e),r=t.state.selection;return n?{update(s){if(s.docChanged){let i=s.changes.mapPos(s.startState.doc.line(n.line).from),a=s.state.doc.lineAt(i);n={line:a.number,col:n.col,off:Math.min(n.off,a.length)},r=r.map(s.changes)}},get(s,i,a){let l=Yq(t,s);if(!l)return r;let c=PUe(t.state,n,l);return c.length?a?Qe.create(c.concat(r.ranges)):Qe.create(c):r}}:null}function FUe(t){let e=(n=>n.altKey&&n.button==0);return Nt.mouseSelectionStyle.of((n,r)=>e(r)?$Ue(n,r):null)}const BUe={Alt:[18,t=>!!t.altKey],Control:[17,t=>!!t.ctrlKey],Shift:[16,t=>!!t.shiftKey],Meta:[91,t=>!!t.metaKey]},zUe={style:"cursor: crosshair"};function UUe(t={}){let[e,n]=BUe[t.key||"Alt"],r=ti.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||n(s))},keyup(s){(s.keyCode==e||!n(s))&&this.set(!1)},mousemove(s){this.set(n(s))}}});return[r,Nt.contentAttributes.of(s=>{var i;return!((i=s.plugin(r))===null||i===void 0)&&i.isDown?zUe:null})]}const r2="-10000px";class _ce{constructor(e,n,r,s){this.facet=n,this.createTooltipView=r,this.removeTooltipView=s,this.input=e.state.facet(n),this.tooltips=this.input.filter(a=>a);let i=null;this.tooltipViews=this.tooltips.map(a=>i=r(a,i))}update(e,n){var r;let s=e.state.facet(this.facet),i=s.filter(c=>c);if(s===this.input){for(let c of this.tooltipViews)c.update&&c.update(e);return!1}let a=[],l=n?[]:null;for(let c=0;c<i.length;c++){let u=i[c],f=-1;if(u){for(let h=0;h<this.tooltips.length;h++){let p=this.tooltips[h];p&&p.create==u.create&&(f=h)}if(f<0)a[c]=this.createTooltipView(u,c?a[c-1]:null),l&&(l[c]=!!u.above);else{let h=a[c]=this.tooltipViews[f];l&&(l[c]=n[f]),h.update&&h.update(e)}}}for(let c of this.tooltipViews)a.indexOf(c)<0&&(this.removeTooltipView(c),(r=c.destroy)===null||r===void 0||r.call(c));return n&&(l.forEach((c,u)=>n[u]=c),n.length=l.length),this.input=s,this.tooltips=i,this.tooltipViews=a,!0}}function VUe(t){let e=t.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const P3=_t.define({combine:t=>{var e,n,r;return{position:At.ios?"absolute":((e=t.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((n=t.find(s=>s.parent))===null||n===void 0?void 0:n.parent)||null,tooltipSpace:((r=t.find(s=>s.tooltipSpace))===null||r===void 0?void 0:r.tooltipSpace)||VUe}}}),Jq=new WeakMap,JL=ti.fromClass(class{constructor(t){this.view=t,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=t.state.facet(P3);this.position=e.position,this.parent=e.parent,this.classes=t.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new _ce(t,QL,(n,r)=>this.createTooltip(n,r),n=>{this.resizeObserver&&this.resizeObserver.unobserve(n.dom),n.dom.remove()}),this.above=this.manager.tooltips.map(n=>!!n.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(n=>{Date.now()>this.lastTransaction-50&&n.length>0&&n[n.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),t.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let t of this.manager.tooltipViews)this.intersectionObserver.observe(t.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(t){t.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(t,this.above);e&&this.observeIntersection();let n=e||t.geometryChanged,r=t.state.facet(P3);if(r.position!=this.position&&!this.madeAbsolute){this.position=r.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;n=!0}if(r.parent!=this.parent){this.parent&&this.container.remove(),this.parent=r.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);n=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);n&&this.maybeMeasure()}createTooltip(t,e){let n=t.create(this.view),r=e?e.dom:null;if(n.dom.classList.add("cm-tooltip"),t.arrow&&!n.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",n.dom.appendChild(s)}return n.dom.style.position=this.position,n.dom.style.top=r2,n.dom.style.left="0px",this.container.insertBefore(n.dom,r),n.mount&&n.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(n.dom),n}destroy(){var t,e,n;this.view.win.removeEventListener("resize",this.measureSoon);for(let r of this.manager.tooltipViews)r.dom.remove(),(t=r.destroy)===null||t===void 0||t.call(r);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(n=this.intersectionObserver)===null||n===void 0||n.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let t=1,e=1,n=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:i}=this.manager.tooltipViews[0];if(At.safari){let a=i.getBoundingClientRect();n=Math.abs(a.top+1e4)>1||Math.abs(a.left)>1}else n=!!i.offsetParent&&i.offsetParent!=this.container.ownerDocument.body}if(n||this.position=="absolute")if(this.parent){let i=this.parent.getBoundingClientRect();i.width&&i.height&&(t=i.width/this.parent.offsetWidth,e=i.height/this.parent.offsetHeight)}else({scaleX:t,scaleY:e}=this.view.viewState);let r=this.view.scrollDOM.getBoundingClientRect(),s=KL(this.view);return{visible:{left:r.left+s.left,top:r.top+s.top,right:r.right-s.right,bottom:r.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((i,a)=>{let l=this.manager.tooltipViews[a];return l.getCoords?l.getCoords(i.pos):this.view.coordsAtPos(i.pos)}),size:this.manager.tooltipViews.map(({dom:i})=>i.getBoundingClientRect()),space:this.view.state.facet(P3).tooltipSpace(this.view),scaleX:t,scaleY:e,makeAbsolute:n}}writeMeasure(t){var e;if(t.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:n,space:r,scaleX:s,scaleY:i}=t,a=[];for(let l=0;l<this.manager.tooltips.length;l++){let c=this.manager.tooltips[l],u=this.manager.tooltipViews[l],{dom:f}=u,h=t.pos[l],p=t.size[l];if(!h||c.clip!==!1&&(h.bottom<=Math.max(n.top,r.top)||h.top>=Math.min(n.bottom,r.bottom)||h.right<Math.max(n.left,r.left)-.1||h.left>Math.min(n.right,r.right)+.1)){f.style.top=r2;continue}let g=c.arrow?u.dom.querySelector(".cm-tooltip-arrow"):null,b=g?7:0,v=p.right-p.left,w=(e=Jq.get(u))!==null&&e!==void 0?e:p.bottom-p.top,j=u.offset||qUe,C=this.view.textDirection==Kr.LTR,N=p.width>r.right-r.left?C?r.left:r.right-p.width:C?Math.max(r.left,Math.min(h.left-(g?14:0)+j.x,r.right-v)):Math.min(Math.max(r.left,h.left-v+(g?14:0)-j.x),r.right-v),S=this.above[l];!c.strictSide&&(S?h.top-w-b-j.y<r.top:h.bottom+w+b+j.y>r.bottom)&&S==r.bottom-h.bottom>h.top-r.top&&(S=this.above[l]=!S);let T=(S?h.top-r.top:r.bottom-h.bottom)-b;if(T<w&&u.resize!==!1){if(T<this.view.defaultLineHeight){f.style.top=r2;continue}Jq.set(u,w),f.style.height=(w=T)/i+"px"}else f.style.height&&(f.style.height="");let _=S?h.top-w-b-j.y:h.bottom+b+j.y,A=N+v;if(u.overlap!==!0)for(let M of a)M.left<A&&M.right>N&&M.top<_+w&&M.bottom>_&&(_=S?M.top-w-2-b:M.bottom+b+2);if(this.position=="absolute"?(f.style.top=(_-t.parent.top)/i+"px",Qq(f,(N-t.parent.left)/s)):(f.style.top=_/i+"px",Qq(f,N/s)),g){let M=h.left+(C?j.x:-j.x)-(N+14-7);g.style.left=M/s+"px"}u.overlap!==!0&&a.push({left:N,top:_,right:A,bottom:_+w}),f.classList.toggle("cm-tooltip-above",S),f.classList.toggle("cm-tooltip-below",!S),u.positioned&&u.positioned(t.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let t of this.manager.tooltipViews)t.dom.style.top=r2}},{eventObservers:{scroll(){this.maybeMeasure()}}});function Qq(t,e){let n=parseInt(t.style.left,10);(isNaN(n)||Math.abs(e-n)>1)&&(t.style.left=e+"px")}const HUe=Nt.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),qUe={x:0,y:0},QL=_t.define({enables:[JL,HUe]}),JN=_t.define({combine:t=>t.reduce((e,n)=>e.concat(n),[])});class C5{static create(e){return new C5(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new _ce(e,JN,(n,r)=>this.createHostedView(n,r),n=>n.dom.remove())}createHostedView(e,n){let r=e.create(this.view);return r.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(r.dom,n?n.dom.nextSibling:this.dom.firstChild),this.mounted&&r.mount&&r.mount(this.view),r}mount(e){for(let n of this.manager.tooltipViews)n.mount&&n.mount(e);this.mounted=!0}positioned(e){for(let n of this.manager.tooltipViews)n.positioned&&n.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let n of this.manager.tooltipViews)(e=n.destroy)===null||e===void 0||e.call(n)}passProp(e){let n;for(let r of this.manager.tooltipViews){let s=r[e];if(s!==void 0){if(n===void 0)n=s;else if(n!==s)return}}return n}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const KUe=QL.compute([JN],t=>{let e=t.facet(JN);return e.length===0?null:{pos:Math.min(...e.map(n=>n.pos)),end:Math.max(...e.map(n=>{var r;return(r=n.end)!==null&&r!==void 0?r:n.pos})),create:C5.create,above:e[0].above,arrow:e.some(n=>n.arrow)}});class WUe{constructor(e,n,r,s,i){this.view=e,this.source=n,this.field=r,this.setHover=s,this.hoverTime=i,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;e<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-e):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:e,lastMove:n}=this,r=e.docView.tile.nearest(n.target);if(!r)return;let s,i=1;if(r.isWidget())s=r.posAtStart;else{if(s=e.posAtCoords(n),s==null)return;let l=e.coordsAtPos(s);if(!l||n.y<l.top||n.y>l.bottom||n.x<l.left-e.defaultCharacterWidth||n.x>l.right+e.defaultCharacterWidth)return;let c=e.bidiSpans(e.state.doc.lineAt(s)).find(f=>f.from<=s&&f.to>=s),u=c&&c.dir==Kr.RTL?-1:1;i=n.x<l.left?-u:u}let a=this.source(e,s,i);if(a!=null&&a.then){let l=this.pending={pos:s};a.then(c=>{this.pending==l&&(this.pending=null,c&&!(Array.isArray(c)&&!c.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(c)?c:[c])}))},c=>aa(e.state,c,"hover tooltip"))}else a&&!(Array.isArray(a)&&!a.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(a)?a:[a])})}get tooltip(){let e=this.view.plugin(JL),n=e?e.manager.tooltips.findIndex(r=>r.create==C5.create):-1;return n>-1?e.manager.tooltipViews[n]:null}mousemove(e){var n,r;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:i}=this;if(s.length&&i&&!GUe(i.dom,e)||this.pending){let{pos:a}=s[0]||this.pending,l=(r=(n=s[0])===null||n===void 0?void 0:n.end)!==null&&r!==void 0?r:a;(a==l?this.view.posAtCoords(this.lastMove)!=a:!YUe(this.view,a,l,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:n}=this;if(n.length){let{tooltip:r}=this;r&&r.dom.contains(e.relatedTarget)?this.watchTooltipLeave(r.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let n=r=>{e.removeEventListener("mouseleave",n),this.active.length&&!this.view.dom.contains(r.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",n)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const s2=4;function GUe(t,e){let{left:n,right:r,top:s,bottom:i}=t.getBoundingClientRect(),a;if(a=t.querySelector(".cm-tooltip-arrow")){let l=a.getBoundingClientRect();s=Math.min(l.top,s),i=Math.max(l.bottom,i)}return e.clientX>=n-s2&&e.clientX<=r+s2&&e.clientY>=s-s2&&e.clientY<=i+s2}function YUe(t,e,n,r,s,i){let a=t.scrollDOM.getBoundingClientRect(),l=t.documentTop+t.documentPadding.top+t.contentHeight;if(a.left>r||a.right<r||a.top>s||Math.min(a.bottom,l)<s)return!1;let c=t.posAtCoords({x:r,y:s},!1);return c>=e&&c<=n}function JUe(t,e={}){let n=pn.define(),r=Oi.define({create(){return[]},update(s,i){if(s.length&&(e.hideOnChange&&(i.docChanged||i.selection)?s=[]:e.hideOn&&(s=s.filter(a=>!e.hideOn(i,a))),i.docChanged)){let a=[];for(let l of s){let c=i.changes.mapPos(l.pos,-1,qi.TrackDel);if(c!=null){let u=Object.assign(Object.create(null),l);u.pos=c,u.end!=null&&(u.end=i.changes.mapPos(u.end)),a.push(u)}}s=a}for(let a of i.effects)a.is(n)&&(s=a.value),a.is(QUe)&&(s=[]);return s},provide:s=>JN.from(s)});return{active:r,extension:[r,ti.define(s=>new WUe(s,t,r,n,e.hoverTime||300)),KUe]}}function Ece(t,e){let n=t.plugin(JL);if(!n)return null;let r=n.manager.tooltips.indexOf(e);return r<0?null:n.manager.tooltipViews[r]}const QUe=pn.define(),Zq=_t.define({combine(t){let e,n;for(let r of t)e=e||r.topContainer,n=n||r.bottomContainer;return{topContainer:e,bottomContainer:n}}});function ZL(t,e){let n=t.plugin(Ace),r=n?n.specs.indexOf(e):-1;return r>-1?n.panels[r]:null}const Ace=ti.fromClass(class{constructor(t){this.input=t.state.facet(N1),this.specs=this.input.filter(n=>n),this.panels=this.specs.map(n=>n(t));let e=t.state.facet(Zq);this.top=new i2(t,!0,e.topContainer),this.bottom=new i2(t,!1,e.bottomContainer),this.top.sync(this.panels.filter(n=>n.top)),this.bottom.sync(this.panels.filter(n=>!n.top));for(let n of this.panels)n.dom.classList.add("cm-panel"),n.mount&&n.mount()}update(t){let e=t.state.facet(Zq);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new i2(t.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new i2(t.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let n=t.state.facet(N1);if(n!=this.input){let r=n.filter(c=>c),s=[],i=[],a=[],l=[];for(let c of r){let u=this.specs.indexOf(c),f;u<0?(f=c(t.view),l.push(f)):(f=this.panels[u],f.update&&f.update(t)),s.push(f),(f.top?i:a).push(f)}this.specs=r,this.panels=s,this.top.sync(i),this.bottom.sync(a);for(let c of l)c.dom.classList.add("cm-panel"),c.mount&&c.mount()}else for(let r of this.panels)r.update&&r.update(t)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:t=>Nt.scrollMargins.of(e=>{let n=e.plugin(t);return n&&{top:n.top.scrollMargin(),bottom:n.bottom.scrollMargin()}})});class i2{constructor(e,n,r){this.view=e,this.top=n,this.container=r,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let n of this.panels)n.destroy&&e.indexOf(n)<0&&n.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let n=this.container||this.view.dom;n.insertBefore(this.dom,this.top?n.firstChild:null)}let e=this.dom.firstChild;for(let n of this.panels)if(n.dom.parentNode==this.dom){for(;e!=n.dom;)e=Xq(e);e=e.nextSibling}else this.dom.insertBefore(n.dom,e);for(;e;)e=Xq(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function Xq(t){let e=t.nextSibling;return t.remove(),e}const N1=_t.define({enables:Ace});function ZUe(t,e){let n,r=new Promise(a=>n=a),s=a=>XUe(a,e,n);t.state.field(L3,!1)?t.dispatch({effects:Tce.of(s)}):t.dispatch({effects:pn.appendConfig.of(L3.init(()=>[s]))});let i=Mce.of(s);return{close:i,result:r.then(a=>((t.win.queueMicrotask||(c=>t.win.setTimeout(c,10)))(()=>{t.state.field(L3).indexOf(s)>-1&&t.dispatch({effects:i})}),a))}}const L3=Oi.define({create(){return[]},update(t,e){for(let n of e.effects)n.is(Tce)?t=[n.value].concat(t):n.is(Mce)&&(t=t.filter(r=>r!=n.value));return t},provide:t=>N1.computeN([t],e=>e.field(t))}),Tce=pn.define(),Mce=pn.define();function XUe(t,e,n){let r=e.content?e.content(t,()=>a(null)):null;if(!r){if(r=Dr("form"),e.input){let l=Dr("input",e.input);/^(text|password|number|email|tel|url)$/.test(l.type)&&l.classList.add("cm-textfield"),l.name||(l.name="input"),r.appendChild(Dr("label",(e.label||"")+": ",l))}else r.appendChild(document.createTextNode(e.label||""));r.appendChild(document.createTextNode(" ")),r.appendChild(Dr("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=r.nodeName=="FORM"?[r]:r.querySelectorAll("form");for(let l=0;l<s.length;l++){let c=s[l];c.addEventListener("keydown",u=>{u.keyCode==27?(u.preventDefault(),a(null)):u.keyCode==13&&(u.preventDefault(),a(c))}),c.addEventListener("submit",u=>{u.preventDefault(),a(c)})}let i=Dr("div",r,Dr("button",{onclick:()=>a(null),"aria-label":t.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(i.className=e.class),i.classList.add("cm-dialog");function a(l){i.contains(i.ownerDocument.activeElement)&&t.focus(),n(l)}return{dom:i,top:e.top,mount:()=>{if(e.focus){let l;typeof e.focus=="string"?l=r.querySelector(e.focus):l=r.querySelector("input")||r.querySelector("button"),l&&"select"in l?l.select():l&&"focus"in l&&l.focus()}}}}class Vd extends Bh{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Vd.prototype.elementClass="";Vd.prototype.toDOM=void 0;Vd.prototype.mapMode=qi.TrackBefore;Vd.prototype.startSide=Vd.prototype.endSide=-1;Vd.prototype.point=!0;const cj=_t.define(),eVe=_t.define(),tVe={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>Bn.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},Mv=_t.define();function nVe(t){return[Ice(),Mv.of({...tVe,...t})]}const eK=_t.define({combine:t=>t.some(e=>e)});function Ice(t){return[rVe]}const rVe=ti.fromClass(class{constructor(t){this.view=t,this.domAfter=null,this.prevViewport=t.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=t.state.facet(Mv).map(e=>new nK(t,e)),this.fixed=!t.state.facet(eK);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),t.scrollDOM.insertBefore(this.dom,t.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(t){if(this.updateGutters(t)){let e=this.prevViewport,n=t.view.viewport,r=Math.min(e.to,n.to)-Math.max(e.from,n.from);this.syncGutters(r<(n.to-n.from)*.8)}if(t.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(eK)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=t.view.viewport}syncGutters(t){let e=this.dom.nextSibling;t&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let n=Bn.iter(this.view.state.facet(cj),this.view.viewport.from),r=[],s=this.gutters.map(i=>new sVe(i,this.view.viewport,-this.view.documentPadding.top));for(let i of this.view.viewportLineBlocks)if(r.length&&(r=[]),Array.isArray(i.type)){let a=!0;for(let l of i.type)if(l.type==Yi.Text&&a){ZR(n,r,l.from);for(let c of s)c.line(this.view,l,r);a=!1}else if(l.widget)for(let c of s)c.widget(this.view,l)}else if(i.type==Yi.Text){ZR(n,r,i.from);for(let a of s)a.line(this.view,i,r)}else if(i.widget)for(let a of s)a.widget(this.view,i);for(let i of s)i.finish();t&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(t){let e=t.startState.facet(Mv),n=t.state.facet(Mv),r=t.docChanged||t.heightChanged||t.viewportChanged||!Bn.eq(t.startState.facet(cj),t.state.facet(cj),t.view.viewport.from,t.view.viewport.to);if(e==n)for(let s of this.gutters)s.update(t)&&(r=!0);else{r=!0;let s=[];for(let i of n){let a=e.indexOf(i);a<0?s.push(new nK(this.view,i)):(this.gutters[a].update(t),s.push(this.gutters[a]))}for(let i of this.gutters)i.dom.remove(),s.indexOf(i)<0&&i.destroy();for(let i of s)i.config.side=="after"?this.getDOMAfter().appendChild(i.dom):this.dom.appendChild(i.dom);this.gutters=s}return r}destroy(){for(let t of this.gutters)t.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:t=>Nt.scrollMargins.of(e=>{let n=e.plugin(t);if(!n||n.gutters.length==0||!n.fixed)return null;let r=n.dom.offsetWidth*e.scaleX,s=n.domAfter?n.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==Kr.LTR?{left:r,right:s}:{right:r,left:s}})});function tK(t){return Array.isArray(t)?t:[t]}function ZR(t,e,n){for(;t.value&&t.from<=n;)t.from==n&&e.push(t.value),t.next()}class sVe{constructor(e,n,r){this.gutter=e,this.height=r,this.i=0,this.cursor=Bn.iter(e.markers,n.from)}addElement(e,n,r){let{gutter:s}=this,i=(n.top-this.height)/e.scaleY,a=n.height/e.scaleY;if(this.i==s.elements.length){let l=new Rce(e,a,i,r);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,a,i,r);this.height=n.bottom,this.i++}line(e,n,r){let s=[];ZR(this.cursor,s,n.from),r.length&&(s=s.concat(r));let i=this.gutter.config.lineMarker(e,n,s);i&&s.unshift(i);let a=this.gutter;s.length==0&&!a.config.renderEmptyElements||this.addElement(e,n,s)}widget(e,n){let r=this.gutter.config.widgetMarker(e,n.widget,n),s=r?[r]:null;for(let i of e.state.facet(eVe)){let a=i(e,n.widget,n);a&&(s||(s=[])).push(a)}s&&this.addElement(e,n,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let n=e.elements.pop();e.dom.removeChild(n.dom),n.destroy()}}}class nK{constructor(e,n){this.view=e,this.config=n,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let r in n.domEventHandlers)this.dom.addEventListener(r,s=>{let i=s.target,a;if(i!=this.dom&&this.dom.contains(i)){for(;i.parentNode!=this.dom;)i=i.parentNode;let c=i.getBoundingClientRect();a=(c.top+c.bottom)/2}else a=s.clientY;let l=e.lineBlockAtHeight(a-e.documentTop);n.domEventHandlers[r](e,l,s)&&s.preventDefault()});this.markers=tK(n.markers(e)),n.initialSpacer&&(this.spacer=new Rce(e,0,0,[n.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let n=this.markers;if(this.markers=tK(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let r=e.view.viewport;return!Bn.eq(this.markers,n,r.from,r.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class Rce{constructor(e,n,r,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,n,r,s)}update(e,n,r,s){this.height!=n&&(this.height=n,this.dom.style.height=n+"px"),this.above!=r&&(this.dom.style.marginTop=(this.above=r)?r+"px":""),iVe(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,n){let r="cm-gutterElement",s=this.dom.firstChild;for(let i=0,a=0;;){let l=a,c=i<n.length?n[i++]:null,u=!1;if(c){let f=c.elementClass;f&&(r+=" "+f);for(let h=a;h<this.markers.length;h++)if(this.markers[h].compare(c)){l=h,u=!0;break}}else l=this.markers.length;for(;a<l;){let f=this.markers[a++];if(f.toDOM){f.destroy(s);let h=s.nextSibling;s.remove(),s=h}}if(!c)break;c.toDOM&&(u?s=s.nextSibling:this.dom.insertBefore(c.toDOM(e),s)),u&&a++}this.dom.className=r,this.markers=n}destroy(){this.setMarkers(null,[])}}function iVe(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].compare(e[n]))return!1;return!0}const oVe=_t.define(),aVe=_t.define(),Ex=_t.define({combine(t){return Cu(t,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,n){let r=Object.assign({},e);for(let s in n){let i=r[s],a=n[s];r[s]=i?(l,c,u)=>i(l,c,u)||a(l,c,u):a}return r}})}});class $3 extends Vd{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function F3(t,e){return t.state.facet(Ex).formatNumber(e,t.state)}const lVe=Mv.compute([Ex],t=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(oVe)},lineMarker(e,n,r){return r.some(s=>s.toDOM)?null:new $3(F3(e,e.state.doc.lineAt(n.from).number))},widgetMarker:(e,n,r)=>{for(let s of e.state.facet(aVe)){let i=s(e,n,r);if(i)return i}return null},lineMarkerChange:e=>e.startState.facet(Ex)!=e.state.facet(Ex),initialSpacer(e){return new $3(F3(e,rK(e.state.doc.lines)))},updateSpacer(e,n){let r=F3(n.view,rK(n.view.state.doc.lines));return r==e.number?e:new $3(r)},domEventHandlers:t.facet(Ex).domEventHandlers,side:"before"}));function Oce(t={}){return[Ex.of(t),Ice(),lVe]}function rK(t){let e=9;for(;e<t;)e=e*10+9;return e}const cVe=new class extends Vd{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},uVe=cj.compute(["selection"],t=>{let e=[],n=-1;for(let r of t.selection.ranges){let s=t.doc.lineAt(r.head).from;s>n&&(n=s,e.push(cVe.range(s)))}return Bn.of(e)});function dVe(){return uVe}const fVe=1024;let hVe=0,xl=class{constructor(e,n){this.from=e,this.to=n}};class Ln{constructor(e={}){this.id=hVe++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Lo.match(e)),n=>{let r=e(n);return r===void 0?null:[this,r]}}}Ln.closedBy=new Ln({deserialize:t=>t.split(" ")});Ln.openedBy=new Ln({deserialize:t=>t.split(" ")});Ln.group=new Ln({deserialize:t=>t.split(" ")});Ln.isolate=new Ln({deserialize:t=>{if(t&&t!="rtl"&&t!="ltr"&&t!="auto")throw new RangeError("Invalid value for isolate: "+t);return t||"auto"}});Ln.contextHash=new Ln({perNode:!0});Ln.lookAhead=new Ln({perNode:!0});Ln.mounted=new Ln({perNode:!0});class Gx{constructor(e,n,r,s=!1){this.tree=e,this.overlay=n,this.parser=r,this.bracketed=s}static get(e){return e&&e.props&&e.props[Ln.mounted.id]}}const mVe=Object.create(null);class Lo{constructor(e,n,r,s=0){this.name=e,this.props=n,this.id=r,this.flags=s}static define(e){let n=e.props&&e.props.length?Object.create(null):mVe,r=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new Lo(e.name||"",n,e.id,r);if(e.props){for(let i of e.props)if(Array.isArray(i)||(i=i(s)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");n[i[0].id]=i[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let n=this.prop(Ln.group);return n?n.indexOf(e)>-1:!1}return this.id==e}static match(e){let n=Object.create(null);for(let r in e)for(let s of r.split(" "))n[s]=e[r];return r=>{for(let s=r.prop(Ln.group),i=-1;i<(s?s.length:0);i++){let a=n[i<0?r.name:s[i]];if(a)return a}}}}Lo.none=new Lo("",Object.create(null),0,8);class XL{constructor(e){this.types=e;for(let n=0;n<e.length;n++)if(e[n].id!=n)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let n=[];for(let r of this.types){let s=null;for(let i of e){let a=i(r);if(a){s||(s=Object.assign({},r.props));let l=a[1],c=a[0];c.combine&&c.id in s&&(l=c.combine(s[c.id],l)),s[c.id]=l}}n.push(s?new Lo(r.name,s,r.id,r.flags):r)}return new XL(n)}}const o2=new WeakMap,sK=new WeakMap;var Hr;(function(t){t[t.ExcludeBuffers=1]="ExcludeBuffers",t[t.IncludeAnonymous=2]="IncludeAnonymous",t[t.IgnoreMounts=4]="IgnoreMounts",t[t.IgnoreOverlays=8]="IgnoreOverlays",t[t.EnterBracketed=16]="EnterBracketed"})(Hr||(Hr={}));class Wr{constructor(e,n,r,s,i){if(this.type=e,this.children=n,this.positions=r,this.length=s,this.props=null,i&&i.length){this.props=Object.create(null);for(let[a,l]of i)this.props[typeof a=="number"?a:a.id]=l}}toString(){let e=Gx.get(this);if(e&&!e.overlay)return e.tree.toString();let n="";for(let r of this.children){let s=r.toString();s&&(n&&(n+=","),n+=s)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(n.length?"("+n+")":""):n}cursor(e=0){return new QN(this.topNode,e)}cursorAt(e,n=0,r=0){let s=o2.get(this)||this.topNode,i=new QN(s);return i.moveTo(e,n),o2.set(this,i._tree),i}get topNode(){return new ho(this,0,0,null)}resolve(e,n=0){let r=S1(o2.get(this)||this.topNode,e,n,!1);return o2.set(this,r),r}resolveInner(e,n=0){let r=S1(sK.get(this)||this.topNode,e,n,!0);return sK.set(this,r),r}resolveStack(e,n=0){return xVe(this,e,n)}iterate(e){let{enter:n,leave:r,from:s=0,to:i=this.length}=e,a=e.mode||0,l=(a&Hr.IncludeAnonymous)>0;for(let c=this.cursor(a|Hr.IncludeAnonymous);;){let u=!1;if(c.from<=i&&c.to>=s&&(!l&&c.type.isAnonymous||n(c)!==!1)){if(c.firstChild())continue;u=!0}for(;u&&r&&(l||!c.type.isAnonymous)&&r(c),!c.nextSibling();){if(!c.parent())return;u=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let n in this.props)e.push([+n,this.props[n]]);return e}balance(e={}){return this.children.length<=8?this:n9(Lo.none,this.children,this.positions,0,this.children.length,0,this.length,(n,r,s)=>new Wr(this.type,n,r,s,this.propValues),e.makeTree||((n,r,s)=>new Wr(Lo.none,n,r,s)))}static build(e){return yVe(e)}}Wr.empty=new Wr(Lo.none,[],[],0);class e9{constructor(e,n){this.buffer=e,this.index=n}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new e9(this.buffer,this.index)}}class Hh{constructor(e,n,r){this.buffer=e,this.length=n,this.set=r}get type(){return Lo.none}toString(){let e=[];for(let n=0;n<this.buffer.length;)e.push(this.childString(n)),n=this.buffer[n+3];return e.join(",")}childString(e){let n=this.buffer[e],r=this.buffer[e+3],s=this.set.types[n],i=s.name;if(/\W/.test(i)&&!s.isError&&(i=JSON.stringify(i)),e+=4,r==e)return i;let a=[];for(;e<r;)a.push(this.childString(e)),e=this.buffer[e+3];return i+"("+a.join(",")+")"}findChild(e,n,r,s,i){let{buffer:a}=this,l=-1;for(let c=e;c!=n&&!(Dce(i,s,a[c+1],a[c+2])&&(l=c,r>0));c=a[c+3]);return l}slice(e,n,r){let s=this.buffer,i=new Uint16Array(n-e),a=0;for(let l=e,c=0;l<n;){i[c++]=s[l++],i[c++]=s[l++]-r;let u=i[c++]=s[l++]-r;i[c++]=s[l++]-e,a=Math.max(a,u)}return new Hh(i,a,this.set)}}function Dce(t,e,n,r){switch(t){case-2:return n<e;case-1:return r>=e&&n<e;case 0:return n<e&&r>e;case 1:return n<=e&&r>e;case 2:return r>e;case 4:return!0}}function S1(t,e,n,r){for(var s;t.from==t.to||(n<1?t.from>=e:t.from>e)||(n>-1?t.to<=e:t.to<e);){let a=!r&&t instanceof ho&&t.index<0?null:t.parent;if(!a)return t;t=a}let i=r?0:Hr.IgnoreOverlays;if(r)for(let a=t,l=a.parent;l;a=l,l=a.parent)a instanceof ho&&a.index<0&&((s=l.enter(e,n,i))===null||s===void 0?void 0:s.from)!=a.from&&(t=l);for(;;){let a=t.enter(e,n,i);if(!a)return t;t=a}}class Pce{cursor(e=0){return new QN(this,e)}getChild(e,n=null,r=null){let s=iK(this,e,n,r);return s.length?s[0]:null}getChildren(e,n=null,r=null){return iK(this,e,n,r)}resolve(e,n=0){return S1(this,e,n,!1)}resolveInner(e,n=0){return S1(this,e,n,!0)}matchContext(e){return XR(this.parent,e)}enterUnfinishedNodesBefore(e){let n=this.childBefore(e),r=this;for(;n;){let s=n.lastChild;if(!s||s.to!=n.to)break;s.type.isError&&s.from==s.to?(r=n,n=s.prevSibling):n=s}return r}get node(){return this}get next(){return this.parent}}class ho extends Pce{constructor(e,n,r,s){super(),this._tree=e,this.from=n,this.index=r,this._parent=s}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,n,r,s,i=0){for(let a=this;;){for(let{children:l,positions:c}=a._tree,u=n>0?l.length:-1;e!=u;e+=n){let f=l[e],h=c[e]+a.from,p;if(!(!(i&Hr.EnterBracketed&&f instanceof Wr&&(p=Gx.get(f))&&!p.overlay&&p.bracketed&&r>=h&&r<=h+f.length)&&!Dce(s,r,h,h+f.length))){if(f instanceof Hh){if(i&Hr.ExcludeBuffers)continue;let g=f.findChild(0,f.buffer.length,n,r-h,s);if(g>-1)return new Zc(new pVe(a,f,e,h),null,g)}else if(i&Hr.IncludeAnonymous||!f.type.isAnonymous||t9(f)){let g;if(!(i&Hr.IgnoreMounts)&&(g=Gx.get(f))&&!g.overlay)return new ho(g.tree,h,e,a);let b=new ho(f,h,e,a);return i&Hr.IncludeAnonymous||!b.type.isAnonymous?b:b.nextChild(n<0?f.children.length-1:0,n,r,s,i)}}}if(i&Hr.IncludeAnonymous||!a.type.isAnonymous||(a.index>=0?e=a.index+n:e=n<0?-1:a._parent._tree.children.length,a=a._parent,!a))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,n,r=0){let s;if(!(r&Hr.IgnoreOverlays)&&(s=Gx.get(this._tree))&&s.overlay){let i=e-this.from,a=r&Hr.EnterBracketed&&s.bracketed;for(let{from:l,to:c}of s.overlay)if((n>0||a?l<=i:l<i)&&(n<0||a?c>=i:c>i))return new ho(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,n,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function iK(t,e,n,r){let s=t.cursor(),i=[];if(!s.firstChild())return i;if(n!=null){for(let a=!1;!a;)if(a=s.type.is(n),!s.nextSibling())return i}for(;;){if(r!=null&&s.type.is(r))return i;if(s.type.is(e)&&i.push(s.node),!s.nextSibling())return r==null?i:[]}}function XR(t,e,n=e.length-1){for(let r=t;n>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(e[n]&&e[n]!=r.name)return!1;n--}}return!0}class pVe{constructor(e,n,r,s){this.parent=e,this.buffer=n,this.index=r,this.start=s}}class Zc extends Pce{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,n,r){super(),this.context=e,this._parent=n,this.index=r,this.type=e.buffer.set.types[e.buffer.buffer[r]]}child(e,n,r){let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],e,n-this.context.start,r);return i<0?null:new Zc(this.context,this,i)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,n,r=0){if(r&Hr.ExcludeBuffers)return null;let{buffer:s}=this.context,i=s.findChild(this.index+4,s.buffer[this.index+3],n>0?1:-1,e-this.context.start,n);return i<0?null:new Zc(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,n=e.buffer[this.index+3];return n<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Zc(this.context,this._parent,n):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,n=this._parent?this._parent.index+4:0;return this.index==n?this.externalSibling(-1):new Zc(this.context,this._parent,e.findChild(n,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],n=[],{buffer:r}=this.context,s=this.index+4,i=r.buffer[this.index+3];if(i>s){let a=r.buffer[this.index+1];e.push(r.slice(s,i,a)),n.push(0)}return new Wr(this.type,e,n,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function Lce(t){if(!t.length)return null;let e=0,n=t[0];for(let i=1;i<t.length;i++){let a=t[i];(a.from>n.from||a.to<n.to)&&(n=a,e=i)}let r=n instanceof ho&&n.index<0?null:n.parent,s=t.slice();return r?s[e]=r:s.splice(e,1),new gVe(s,n)}class gVe{constructor(e,n){this.heads=e,this.node=n}get next(){return Lce(this.heads)}}function xVe(t,e,n){let r=t.resolveInner(e,n),s=null;for(let i=r instanceof ho?r:r.context.parent;i;i=i.parent)if(i.index<0){let a=i.parent;(s||(s=[r])).push(a.resolve(e,n)),i=a}else{let a=Gx.get(i.tree);if(a&&a.overlay&&a.overlay[0].from<=e&&a.overlay[a.overlay.length-1].to>=e){let l=new ho(a.tree,a.overlay[0].from+i.from,-1,i);(s||(s=[r])).push(S1(l,e,n,!1))}}return s?Lce(s):r}class QN{get name(){return this.type.name}constructor(e,n=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=n&~Hr.EnterBracketed,e instanceof ho)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let r=e._parent;r;r=r._parent)this.stack.unshift(r.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,n){this.index=e;let{start:r,buffer:s}=this.buffer;return this.type=n||s.set.types[s.buffer[e]],this.from=r+s.buffer[e+1],this.to=r+s.buffer[e+2],!0}yield(e){return e?e instanceof ho?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,n,r){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,n,r,this.mode));let{buffer:s}=this.buffer,i=s.findChild(this.index+4,s.buffer[this.index+3],e,n-this.buffer.start,r);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,n,r=this.mode){return this.buffer?r&Hr.ExcludeBuffers?!1:this.enterChild(1,e,n):this.yield(this._tree.enter(e,n,r))}parent(){if(!this.buffer)return this.yieldNode(this.mode&Hr.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&Hr.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:n}=this.buffer,r=this.stack.length-1;if(e<0){let s=r<0?0:this.stack[r]+4;if(this.index!=s)return this.yieldBuf(n.findChild(s,this.index,-1,0,4))}else{let s=n.buffer[this.index+3];if(s<(r<0?n.buffer.length:n.buffer[this.stack[r]+3]))return this.yieldBuf(s)}return r<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let n,r,{buffer:s}=this;if(s){if(e>0){if(this.index<s.buffer.buffer.length)return!1}else for(let i=0;i<this.index;i++)if(s.buffer.buffer[i+3]<this.index)return!1;({index:n,parent:r}=s)}else({index:n,_parent:r}=this._tree);for(;r;{index:n,_parent:r}=r)if(n>-1)for(let i=n+e,a=e<0?-1:r._tree.children.length;i!=a;i+=e){let l=r._tree.children[i];if(this.mode&Hr.IncludeAnonymous||l instanceof Hh||!l.type.isAnonymous||t9(l))return!1}return!0}move(e,n){if(n&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,n=0){for(;(this.from==this.to||(n<1?this.from>=e:this.from>e)||(n>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,n););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,n=null,r=0;if(e&&e.context==this.buffer)e:for(let s=this.index,i=this.stack.length;i>=0;){for(let a=e;a;a=a._parent)if(a.index==s){if(s==this.index)return a;n=a,r=i+1;break e}s=this.stack[--i]}for(let s=r;s<this.stack.length;s++)n=new Zc(this.buffer,n,this.stack[s]);return this.bufferNode=new Zc(this.buffer,n,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,n){for(let r=0;;){let s=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){r++;continue}this.type.isAnonymous||(s=!0)}for(;;){if(s&&n&&n(this),s=this.type.isAnonymous,!r)return;if(this.nextSibling())break;this.parent(),r--,s=!0}}}matchContext(e){if(!this.buffer)return XR(this.node.parent,e);let{buffer:n}=this.buffer,{types:r}=n.set;for(let s=e.length-1,i=this.stack.length-1;s>=0;i--){if(i<0)return XR(this._tree,e,s);let a=r[n.buffer[this.stack[i]]];if(!a.isAnonymous){if(e[s]&&e[s]!=a.name)return!1;s--}}return!0}}function t9(t){return t.children.some(e=>e instanceof Hh||!e.type.isAnonymous||t9(e))}function yVe(t){var e;let{buffer:n,nodeSet:r,maxBufferLength:s=fVe,reused:i=[],minRepeatType:a=r.types.length}=t,l=Array.isArray(n)?new e9(n,n.length):n,c=r.types,u=0,f=0;function h(T,_,A,M,I,L){let{id:D,start:P,end:B,size:Z}=l,Q=f,q=u;if(Z<0)if(l.next(),Z==-1){let G=i[D];A.push(G),M.push(P-T);return}else if(Z==-3){u=D;return}else if(Z==-4){f=D;return}else throw new RangeError(`Unrecognized record size: ${Z}`);let O=c[D],z,V,$=P-T;if(B-P<=s&&(V=w(l.pos-_,I))){let G=new Uint16Array(V.size-V.skip),W=l.pos-V.size,F=G.length;for(;l.pos>W;)F=j(V.start,G,F);z=new Hh(G,B-V.start,r),$=V.start-T}else{let G=l.pos-Z;l.next();let W=[],F=[],le=D>=a?D:-1,ie=0,ne=B;for(;l.pos>G;)le>=0&&l.id==le&&l.size>=0?(l.end<=ne-s&&(b(W,F,P,ie,l.end,ne,le,Q,q),ie=W.length,ne=l.end),l.next()):L>2500?p(P,G,W,F):h(P,G,W,F,le,L+1);if(le>=0&&ie>0&&ie<W.length&&b(W,F,P,ie,P,ne,le,Q,q),W.reverse(),F.reverse(),le>-1&&ie>0){let X=g(O,q);z=n9(O,W,F,0,W.length,0,B-P,X,X)}else z=v(O,W,F,B-P,Q-B,q)}A.push(z),M.push($)}function p(T,_,A,M){let I=[],L=0,D=-1;for(;l.pos>_;){let{id:P,start:B,end:Z,size:Q}=l;if(Q>4)l.next();else{if(D>-1&&B<D)break;D<0&&(D=Z-s),I.push(P,B,Z),L++,l.next()}}if(L){let P=new Uint16Array(L*4),B=I[I.length-2];for(let Z=I.length-3,Q=0;Z>=0;Z-=3)P[Q++]=I[Z],P[Q++]=I[Z+1]-B,P[Q++]=I[Z+2]-B,P[Q++]=Q;A.push(new Hh(P,I[2]-B,r)),M.push(B-T)}}function g(T,_){return(A,M,I)=>{let L=0,D=A.length-1,P,B;if(D>=0&&(P=A[D])instanceof Wr){if(!D&&P.type==T&&P.length==I)return P;(B=P.prop(Ln.lookAhead))&&(L=M[D]+P.length+B)}return v(T,A,M,I,L,_)}}function b(T,_,A,M,I,L,D,P,B){let Z=[],Q=[];for(;T.length>M;)Z.push(T.pop()),Q.push(_.pop()+A-I);T.push(v(r.types[D],Z,Q,L-I,P-L,B)),_.push(I-A)}function v(T,_,A,M,I,L,D){if(L){let P=[Ln.contextHash,L];D=D?[P].concat(D):[P]}if(I>25){let P=[Ln.lookAhead,I];D=D?[P].concat(D):[P]}return new Wr(T,_,A,M,D)}function w(T,_){let A=l.fork(),M=0,I=0,L=0,D=A.end-s,P={size:0,start:0,skip:0};e:for(let B=A.pos-T;A.pos>B;){let Z=A.size;if(A.id==_&&Z>=0){P.size=M,P.start=I,P.skip=L,L+=4,M+=4,A.next();continue}let Q=A.pos-Z;if(Z<0||Q<B||A.start<D)break;let q=A.id>=a?4:0,O=A.start;for(A.next();A.pos>Q;){if(A.size<0)if(A.size==-3||A.size==-4)q+=4;else break e;else A.id>=a&&(q+=4);A.next()}I=O,M+=Z,L+=q}return(_<0||M==T)&&(P.size=M,P.start=I,P.skip=L),P.size>4?P:void 0}function j(T,_,A){let{id:M,start:I,end:L,size:D}=l;if(l.next(),D>=0&&M<a){let P=A;if(D>4){let B=l.pos-(D-4);for(;l.pos>B;)A=j(T,_,A)}_[--A]=P,_[--A]=L-T,_[--A]=I-T,_[--A]=M}else D==-3?u=M:D==-4&&(f=M);return A}let C=[],N=[];for(;l.pos>0;)h(t.start||0,t.bufferStart||0,C,N,-1,0);let S=(e=t.length)!==null&&e!==void 0?e:C.length?N[0]+C[0].length:0;return new Wr(c[t.topID],C.reverse(),N.reverse(),S)}const oK=new WeakMap;function uj(t,e){if(!t.isAnonymous||e instanceof Hh||e.type!=t)return 1;let n=oK.get(e);if(n==null){n=1;for(let r of e.children){if(r.type!=t||!(r instanceof Wr)){n=1;break}n+=uj(t,r)}oK.set(e,n)}return n}function n9(t,e,n,r,s,i,a,l,c){let u=0;for(let b=r;b<s;b++)u+=uj(t,e[b]);let f=Math.ceil(u*1.5/8),h=[],p=[];function g(b,v,w,j,C){for(let N=w;N<j;){let S=N,T=v[N],_=uj(t,b[N]);for(N++;N<j;N++){let A=uj(t,b[N]);if(_+A>=f)break;_+=A}if(N==S+1){if(_>f){let A=b[S];g(A.children,A.positions,0,A.children.length,v[S]+C);continue}h.push(b[S])}else{let A=v[N-1]+b[N-1].length-T;h.push(n9(t,b,v,S,N,T,A,null,c))}p.push(T+C-i)}}return g(e,n,r,s,0),(l||c)(h,p,a)}class hlt{constructor(){this.map=new WeakMap}setBuffer(e,n,r){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(n,r)}getBuffer(e,n){let r=this.map.get(e);return r&&r.get(n)}set(e,n){e instanceof Zc?this.setBuffer(e.context.buffer,e.index,n):e instanceof ho&&this.map.set(e.tree,n)}get(e){return e instanceof Zc?this.getBuffer(e.context.buffer,e.index):e instanceof ho?this.map.get(e.tree):void 0}cursorSet(e,n){e.buffer?this.setBuffer(e.buffer.buffer,e.index,n):this.map.set(e.tree,n)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Cd{constructor(e,n,r,s,i=!1,a=!1){this.from=e,this.to=n,this.tree=r,this.offset=s,this.open=(i?1:0)|(a?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,n=[],r=!1){let s=[new Cd(0,e.length,e,0,!1,r)];for(let i of n)i.to>e.length&&s.push(i);return s}static applyChanges(e,n,r=128){if(!n.length)return e;let s=[],i=1,a=e.length?e[0]:null;for(let l=0,c=0,u=0;;l++){let f=l<n.length?n[l]:null,h=f?f.fromA:1e9;if(h-c>=r)for(;a&&a.from<h;){let p=a;if(c>=p.from||h<=p.to||u){let g=Math.max(p.from,c)-u,b=Math.min(p.to,h)-u;p=g>=b?null:new Cd(g,b,p.tree,p.offset+u,l>0,!!f)}if(p&&s.push(p),a.to>h)break;a=i<e.length?e[i++]:null}if(!f)break;c=f.toA,u=f.toA-f.toB}return s}}class $ce{startParse(e,n,r){return typeof e=="string"&&(e=new bVe(e)),r=r?r.length?r.map(s=>new xl(s.from,s.to)):[new xl(0,0)]:[new xl(0,e.length)],this.createParse(e,n||[],r)}parse(e,n,r){let s=this.startParse(e,n,r);for(;;){let i=s.advance();if(i)return i}}}class bVe{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,n){return this.string.slice(e,n)}}function mlt(t){return(e,n,r,s)=>new wVe(e,t,n,r,s)}class aK{constructor(e,n,r,s,i,a){this.parser=e,this.parse=n,this.overlay=r,this.bracketed=s,this.target=i,this.from=a}}function lK(t){if(!t.length||t.some(e=>e.from>=e.to))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(t))}class vVe{constructor(e,n,r,s,i,a,l,c){this.parser=e,this.predicate=n,this.mounts=r,this.index=s,this.start=i,this.bracketed=a,this.target=l,this.prev=c,this.depth=0,this.ranges=[]}}const eO=new Ln({perNode:!0});class wVe{constructor(e,n,r,s,i){this.nest=n,this.input=r,this.fragments=s,this.ranges=i,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let r=this.baseParse.advance();if(!r)return null;if(this.baseParse=null,this.baseTree=r,this.startInner(),this.stoppedAt!=null)for(let s of this.inner)s.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let r=this.baseTree;return this.stoppedAt!=null&&(r=new Wr(r.type,r.children,r.positions,r.length,r.propValues.concat([[eO,this.stoppedAt]]))),r}let e=this.inner[this.innerDone],n=e.parse.advance();if(n){this.innerDone++;let r=Object.assign(Object.create(null),e.target.props);r[Ln.mounted.id]=new Gx(n,e.overlay,e.parser,e.bracketed),e.target.props=r}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let n=this.innerDone;n<this.inner.length;n++)this.inner[n].from<e&&(e=Math.min(e,this.inner[n].parse.parsedPos));return e}stopAt(e){if(this.stoppedAt=e,this.baseParse)this.baseParse.stopAt(e);else for(let n=this.innerDone;n<this.inner.length;n++)this.inner[n].parse.stopAt(e)}startInner(){let e=new jVe(this.fragments),n=null,r=null,s=new QN(new ho(this.baseTree,this.ranges[0].from,0,null),Hr.IncludeAnonymous|Hr.IgnoreMounts);e:for(let i,a;;){let l=!0,c;if(this.stoppedAt!=null&&s.from>=this.stoppedAt)l=!1;else if(e.hasNode(s)){if(n){let u=n.mounts.find(f=>f.frag.from<=s.from&&f.frag.to>=s.to&&f.mount.overlay);if(u)for(let f of u.mount.overlay){let h=f.from+u.pos,p=f.to+u.pos;h>=s.from&&p<=s.to&&!n.ranges.some(g=>g.from<p&&g.to>h)&&n.ranges.push({from:h,to:p})}}l=!1}else if(r&&(a=kVe(r.ranges,s.from,s.to)))l=a!=2;else if(!s.type.isAnonymous&&(i=this.nest(s,this.input))&&(s.from<s.to||!i.overlay)){s.tree||(CVe(s),n&&n.depth++,r&&r.depth++);let u=e.findMounts(s.from,i.parser);if(typeof i.overlay=="function")n=new vVe(i.parser,i.overlay,u,this.inner.length,s.from,!!i.bracketed,s.tree,n);else{let f=dK(this.ranges,i.overlay||(s.from<s.to?[new xl(s.from,s.to)]:[]));f.length&&lK(f),(f.length||!i.overlay)&&this.inner.push(new aK(i.parser,f.length?i.parser.startParse(this.input,fK(u,f),f):i.parser.startParse(""),i.overlay?i.overlay.map(h=>new xl(h.from-s.from,h.to-s.from)):null,!!i.bracketed,s.tree,f.length?f[0].from:s.from)),i.overlay?f.length&&(r={ranges:f,depth:0,prev:r}):l=!1}}else if(n&&(c=n.predicate(s))&&(c===!0&&(c=new xl(s.from,s.to)),c.from<c.to)){let u=n.ranges.length-1;u>=0&&n.ranges[u].to==c.from?n.ranges[u]={from:n.ranges[u].from,to:c.to}:n.ranges.push(c)}if(l&&s.firstChild())n&&n.depth++,r&&r.depth++;else for(;!s.nextSibling();){if(!s.parent())break e;if(n&&!--n.depth){let u=dK(this.ranges,n.ranges);u.length&&(lK(u),this.inner.splice(n.index,0,new aK(n.parser,n.parser.startParse(this.input,fK(n.mounts,u),u),n.ranges.map(f=>new xl(f.from-n.start,f.to-n.start)),n.bracketed,n.target,u[0].from))),n=n.prev}r&&!--r.depth&&(r=r.prev)}}}}function kVe(t,e,n){for(let r of t){if(r.from>=n)break;if(r.to>e)return r.from<=e&&r.to>=n?2:1}return 0}function cK(t,e,n,r,s,i){if(e<n){let a=t.buffer[e+1];r.push(t.slice(e,n,a)),s.push(a-i)}}function CVe(t){let{node:e}=t,n=[],r=e.context.buffer;do n.push(t.index),t.parent();while(!t.tree);let s=t.tree,i=s.children.indexOf(r),a=s.children[i],l=a.buffer,c=[i];function u(f,h,p,g,b,v){let w=n[v],j=[],C=[];cK(a,f,w,j,C,g);let N=l[w+1],S=l[w+2];c.push(j.length);let T=v?u(w+4,l[w+3],a.set.types[l[w]],N,S-N,v-1):e.toTree();return j.push(T),C.push(N-g),cK(a,l[w+3],h,j,C,g),new Wr(p,j,C,b)}s.children[i]=u(0,l.length,Lo.none,0,a.length,n.length-1);for(let f of c){let h=t.tree.children[f],p=t.tree.positions[f];t.yield(new ho(h,p+t.from,f,t._tree))}}class uK{constructor(e,n){this.offset=n,this.done=!1,this.cursor=e.cursor(Hr.IncludeAnonymous|Hr.IgnoreMounts)}moveTo(e){let{cursor:n}=this,r=e-this.offset;for(;!this.done&&n.from<r;)n.to>=e&&n.enter(r,1,Hr.IgnoreOverlays|Hr.ExcludeBuffers)||n.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let n=this.cursor.tree;;){if(n==e.tree)return!0;if(n.children.length&&n.positions[0]==0&&n.children[0]instanceof Wr)n=n.children[0];else break}return!1}}class jVe{constructor(e){var n;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let r=this.curFrag=e[0];this.curTo=(n=r.tree.prop(eO))!==null&&n!==void 0?n:r.to,this.inner=new uK(r.tree,-r.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let n=this.curFrag=this.fragments[this.fragI];this.curTo=(e=n.tree.prop(eO))!==null&&e!==void 0?e:n.to,this.inner=new uK(n.tree,-n.offset)}}findMounts(e,n){var r;let s=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let i=this.inner.cursor.node;i;i=i.parent){let a=(r=i.tree)===null||r===void 0?void 0:r.prop(Ln.mounted);if(a&&a.parser==n)for(let l=this.fragI;l<this.fragments.length;l++){let c=this.fragments[l];if(c.from>=i.to)break;c.tree==this.curFrag.tree&&s.push({frag:c,pos:i.from-c.offset,mount:a})}}}return s}}function dK(t,e){let n=null,r=e;for(let s=1,i=0;s<t.length;s++){let a=t[s-1].to,l=t[s].from;for(;i<r.length;i++){let c=r[i];if(c.from>=l)break;c.to<=a||(n||(r=n=e.slice()),c.from<a?(n[i]=new xl(c.from,a),c.to>l&&n.splice(i+1,0,new xl(l,c.to))):c.to>l?n[i--]=new xl(l,c.to):n.splice(i--,1))}}return r}function NVe(t,e,n,r){let s=0,i=0,a=!1,l=!1,c=-1e9,u=[];for(;;){let f=s==t.length?1e9:a?t[s].to:t[s].from,h=i==e.length?1e9:l?e[i].to:e[i].from;if(a!=l){let p=Math.max(c,n),g=Math.min(f,h,r);p<g&&u.push(new xl(p,g))}if(c=Math.min(f,h),c==1e9)break;f==c&&(a?(a=!1,s++):a=!0),h==c&&(l?(l=!1,i++):l=!0)}return u}function fK(t,e){let n=[];for(let{pos:r,mount:s,frag:i}of t){let a=r+(s.overlay?s.overlay[0].from:0),l=a+s.tree.length,c=Math.max(i.from,a),u=Math.min(i.to,l);if(s.overlay){let f=s.overlay.map(p=>new xl(p.from+r,p.to+r)),h=NVe(e,f,c,u);for(let p=0,g=c;;p++){let b=p==h.length,v=b?u:h[p].from;if(v>g&&n.push(new Cd(g,v,s.tree,-a,i.from>=g||i.openStart,i.to<=v||i.openEnd)),b)break;g=h[p].to}}else n.push(new Cd(c,u,s.tree,-a,i.from>=a||i.openStart,i.to<=l||i.openEnd))}return n}let SVe=0;class ml{constructor(e,n,r,s){this.name=e,this.set=n,this.base=r,this.modified=s,this.id=SVe++}toString(){let{name:e}=this;for(let n of this.modified)n.name&&(e=`${n.name}(${e})`);return e}static define(e,n){let r=typeof e=="string"?e:"?";if(e instanceof ml&&(n=e),n!=null&&n.base)throw new Error("Can not derive from a modified tag");let s=new ml(r,[],null,[]);if(s.set.push(s),n)for(let i of n.set)s.set.push(i);return s}static defineModifier(e){let n=new ZN(e);return r=>r.modified.indexOf(n)>-1?r:ZN.get(r.base||r,r.modified.concat(n).sort((s,i)=>s.id-i.id))}}let _Ve=0;class ZN{constructor(e){this.name=e,this.instances=[],this.id=_Ve++}static get(e,n){if(!n.length)return e;let r=n[0].instances.find(l=>l.base==e&&EVe(n,l.modified));if(r)return r;let s=[],i=new ml(e.name,s,e,n);for(let l of n)l.instances.push(i);let a=AVe(n);for(let l of e.set)if(!l.modified.length)for(let c of a)s.push(ZN.get(l,c));return i}}function EVe(t,e){return t.length==e.length&&t.every((n,r)=>n==e[r])}function AVe(t){let e=[[]];for(let n=0;n<t.length;n++)for(let r=0,s=e.length;r<s;r++)e.push(e[r].concat(t[n]));return e.sort((n,r)=>r.length-n.length)}function TVe(t){let e=Object.create(null);for(let n in t){let r=t[n];Array.isArray(r)||(r=[r]);for(let s of n.split(" "))if(s){let i=[],a=2,l=s;for(let h=0;;){if(l=="..."&&h>0&&h+3==s.length){a=1;break}let p=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!p)throw new RangeError("Invalid path: "+s);if(i.push(p[0]=="*"?"":p[0][0]=='"'?JSON.parse(p[0]):p[0]),h+=p[0].length,h==s.length)break;let g=s[h++];if(h==s.length&&g=="!"){a=0;break}if(g!="/")throw new RangeError("Invalid path: "+s);l=s.slice(h)}let c=i.length-1,u=i[c];if(!u)throw new RangeError("Invalid path: "+s);let f=new _1(r,a,c>0?i.slice(0,c):null);e[u]=f.sort(e[u])}}return Fce.add(e)}const Fce=new Ln({combine(t,e){let n,r,s;for(;t||e;){if(!t||e&&t.depth>=e.depth?(s=e,e=e.next):(s=t,t=t.next),n&&n.mode==s.mode&&!s.context&&!n.context)continue;let i=new _1(s.tags,s.mode,s.context);n?n.next=i:r=i,n=i}return r}});class _1{constructor(e,n,r,s){this.tags=e,this.mode=n,this.context=r,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}}_1.empty=new _1([],2,null);function Bce(t,e){let n=Object.create(null);for(let i of t)if(!Array.isArray(i.tag))n[i.tag.id]=i.class;else for(let a of i.tag)n[a.id]=i.class;let{scope:r,all:s=null}=e||{};return{style:i=>{let a=s;for(let l of i)for(let c of l.set){let u=n[c.id];if(u){a=a?a+" "+u:u;break}}return a},scope:r}}function MVe(t,e){let n=null;for(let r of t){let s=r.style(e);s&&(n=n?n+" "+s:s)}return n}function IVe(t,e,n,r=0,s=t.length){let i=new RVe(r,Array.isArray(e)?e:[e],n);i.highlightRange(t.cursor(),r,s,"",i.highlighters),i.flush(s)}class RVe{constructor(e,n,r){this.at=e,this.highlighters=n,this.span=r,this.class=""}startSpan(e,n){n!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=n)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,n,r,s,i){let{type:a,from:l,to:c}=e;if(l>=r||c<=n)return;a.isTop&&(i=this.highlighters.filter(g=>!g.scope||g.scope(a)));let u=s,f=OVe(e)||_1.empty,h=MVe(i,f.tags);if(h&&(u&&(u+=" "),u+=h,f.mode==1&&(s+=(s?" ":"")+h)),this.startSpan(Math.max(n,l),u),f.opaque)return;let p=e.tree&&e.tree.prop(Ln.mounted);if(p&&p.overlay){let g=e.node.enter(p.overlay[0].from+l,1),b=this.highlighters.filter(w=>!w.scope||w.scope(p.tree.type)),v=e.firstChild();for(let w=0,j=l;;w++){let C=w<p.overlay.length?p.overlay[w]:null,N=C?C.from+l:c,S=Math.max(n,j),T=Math.min(r,N);if(S<T&&v)for(;e.from<T&&(this.highlightRange(e,S,T,s,i),this.startSpan(Math.min(T,e.to),u),!(e.to>=N||!e.nextSibling())););if(!C||N>r)break;j=C.to+l,j>n&&(this.highlightRange(g.cursor(),Math.max(n,C.from+l),Math.min(r,j),"",b),this.startSpan(Math.min(r,j),u))}v&&e.parent()}else if(e.firstChild()){p&&(s="");do if(!(e.to<=n)){if(e.from>=r)break;this.highlightRange(e,n,r,s,i),this.startSpan(Math.min(r,e.to),u)}while(e.nextSibling());e.parent()}}}function OVe(t){let e=t.type.prop(Fce);for(;e&&e.context&&!t.matchContext(e.context);)e=e.next;return e||null}const vt=ml.define,a2=vt(),Vf=vt(),hK=vt(Vf),mK=vt(Vf),Hf=vt(),l2=vt(Hf),B3=vt(Hf),Oc=vt(),Rm=vt(Oc),Tc=vt(),Mc=vt(),tO=vt(),Pb=vt(tO),c2=vt(),Be={comment:a2,lineComment:vt(a2),blockComment:vt(a2),docComment:vt(a2),name:Vf,variableName:vt(Vf),typeName:hK,tagName:vt(hK),propertyName:mK,attributeName:vt(mK),className:vt(Vf),labelName:vt(Vf),namespace:vt(Vf),macroName:vt(Vf),literal:Hf,string:l2,docString:vt(l2),character:vt(l2),attributeValue:vt(l2),number:B3,integer:vt(B3),float:vt(B3),bool:vt(Hf),regexp:vt(Hf),escape:vt(Hf),color:vt(Hf),url:vt(Hf),keyword:Tc,self:vt(Tc),null:vt(Tc),atom:vt(Tc),unit:vt(Tc),modifier:vt(Tc),operatorKeyword:vt(Tc),controlKeyword:vt(Tc),definitionKeyword:vt(Tc),moduleKeyword:vt(Tc),operator:Mc,derefOperator:vt(Mc),arithmeticOperator:vt(Mc),logicOperator:vt(Mc),bitwiseOperator:vt(Mc),compareOperator:vt(Mc),updateOperator:vt(Mc),definitionOperator:vt(Mc),typeOperator:vt(Mc),controlOperator:vt(Mc),punctuation:tO,separator:vt(tO),bracket:Pb,angleBracket:vt(Pb),squareBracket:vt(Pb),paren:vt(Pb),brace:vt(Pb),content:Oc,heading:Rm,heading1:vt(Rm),heading2:vt(Rm),heading3:vt(Rm),heading4:vt(Rm),heading5:vt(Rm),heading6:vt(Rm),contentSeparator:vt(Oc),list:vt(Oc),quote:vt(Oc),emphasis:vt(Oc),strong:vt(Oc),link:vt(Oc),monospace:vt(Oc),strikethrough:vt(Oc),inserted:vt(),deleted:vt(),changed:vt(),invalid:vt(),meta:c2,documentMeta:vt(c2),annotation:vt(c2),processingInstruction:vt(c2),definition:ml.defineModifier("definition"),constant:ml.defineModifier("constant"),function:ml.defineModifier("function"),standard:ml.defineModifier("standard"),local:ml.defineModifier("local"),special:ml.defineModifier("special")};for(let t in Be){let e=Be[t];e instanceof ml&&(e.name=t)}Bce([{tag:Be.link,class:"tok-link"},{tag:Be.heading,class:"tok-heading"},{tag:Be.emphasis,class:"tok-emphasis"},{tag:Be.strong,class:"tok-strong"},{tag:Be.keyword,class:"tok-keyword"},{tag:Be.atom,class:"tok-atom"},{tag:Be.bool,class:"tok-bool"},{tag:Be.url,class:"tok-url"},{tag:Be.labelName,class:"tok-labelName"},{tag:Be.inserted,class:"tok-inserted"},{tag:Be.deleted,class:"tok-deleted"},{tag:Be.literal,class:"tok-literal"},{tag:Be.string,class:"tok-string"},{tag:Be.number,class:"tok-number"},{tag:[Be.regexp,Be.escape,Be.special(Be.string)],class:"tok-string2"},{tag:Be.variableName,class:"tok-variableName"},{tag:Be.local(Be.variableName),class:"tok-variableName tok-local"},{tag:Be.definition(Be.variableName),class:"tok-variableName tok-definition"},{tag:Be.special(Be.variableName),class:"tok-variableName2"},{tag:Be.definition(Be.propertyName),class:"tok-propertyName tok-definition"},{tag:Be.typeName,class:"tok-typeName"},{tag:Be.namespace,class:"tok-namespace"},{tag:Be.className,class:"tok-className"},{tag:Be.macroName,class:"tok-macroName"},{tag:Be.propertyName,class:"tok-propertyName"},{tag:Be.operator,class:"tok-operator"},{tag:Be.comment,class:"tok-comment"},{tag:Be.meta,class:"tok-meta"},{tag:Be.invalid,class:"tok-invalid"},{tag:Be.punctuation,class:"tok-punctuation"}]);var z3;const Jm=new Ln;function zce(t){return _t.define({combine:t?e=>e.concat(t):void 0})}const DVe=new Ln;class yl{constructor(e,n,r=[],s=""){this.data=e,this.name=s,Zn.prototype.hasOwnProperty("tree")||Object.defineProperty(Zn.prototype,"tree",{get(){return Ji(this)}}),this.parser=n,this.extension=[qh.of(this),Zn.languageData.of((i,a,l)=>{let c=pK(i,a,l),u=c.type.prop(Jm);if(!u)return[];let f=i.facet(u),h=c.type.prop(DVe);if(h){let p=c.resolve(a-c.from,l);for(let g of h)if(g.test(p,i)){let b=i.facet(g.facet);return g.type=="replace"?b:b.concat(f)}}return f})].concat(r)}isActiveAt(e,n,r=-1){return pK(e,n,r).type.prop(Jm)==this.data}findRegions(e){let n=e.facet(qh);if((n==null?void 0:n.data)==this.data)return[{from:0,to:e.doc.length}];if(!n||!n.allowsNesting)return[];let r=[],s=(i,a)=>{if(i.prop(Jm)==this.data){r.push({from:a,to:a+i.length});return}let l=i.prop(Ln.mounted);if(l){if(l.tree.prop(Jm)==this.data){if(l.overlay)for(let c of l.overlay)r.push({from:c.from+a,to:c.to+a});else r.push({from:a,to:a+i.length});return}else if(l.overlay){let c=r.length;if(s(l.tree,l.overlay[0].from+a),r.length>c)return}}for(let c=0;c<i.children.length;c++){let u=i.children[c];u instanceof Wr&&s(u,i.positions[c]+a)}};return s(Ji(e),0),r}get allowsNesting(){return!0}}yl.setState=pn.define();function pK(t,e,n){let r=t.facet(qh),s=Ji(t).topNode;if(!r||r.allowsNesting)for(let i=s;i;i=i.enter(e,n,Hr.ExcludeBuffers|Hr.EnterBracketed))i.type.isTop&&(s=i);return s}class nO extends yl{constructor(e,n,r){super(e,n,[],r),this.parser=n}static define(e){let n=zce(e.languageData);return new nO(n,e.parser.configure({props:[Jm.add(r=>r.isTop?n:void 0)]}),e.name)}configure(e,n){return new nO(this.data,this.parser.configure(e),n||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ji(t){let e=t.field(yl.state,!1);return e?e.tree:Wr.empty}class PVe{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,n){let r=this.cursorPos-this.string.length;return e<r||n>=this.cursorPos?this.doc.sliceString(e,n):this.string.slice(e-r,n-r)}}let Lb=null;class Ly{constructor(e,n,r=[],s,i,a,l,c){this.parser=e,this.state=n,this.fragments=r,this.tree=s,this.treeLen=i,this.viewport=a,this.skipped=l,this.scheduleOn=c,this.parse=null,this.tempSkipped=[]}static create(e,n,r){return new Ly(e,n,[],Wr.empty,0,r,[],null)}startParse(){return this.parser.startParse(new PVe(this.state.doc),this.fragments)}work(e,n){return n!=null&&n>=this.state.doc.length&&(n=void 0),this.tree!=Wr.empty&&this.isDone(n??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var r;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),n!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>n)&&n<this.state.doc.length&&this.parse.stopAt(n);;){let s=this.parse.advance();if(s)if(this.fragments=this.withoutTempSkipped(Cd.addTree(s,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(r=this.parse.stoppedAt)!==null&&r!==void 0?r:this.state.doc.length,this.tree=s,this.parse=null,this.treeLen<(n??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,n;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(n=this.parse.advance()););}),this.treeLen=e,this.tree=n,this.fragments=this.withoutTempSkipped(Cd.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let n=Lb;Lb=this;try{return e()}finally{Lb=n}}withoutTempSkipped(e){for(let n;n=this.tempSkipped.pop();)e=gK(e,n.from,n.to);return e}changes(e,n){let{fragments:r,tree:s,treeLen:i,viewport:a,skipped:l}=this;if(this.takeTree(),!e.empty){let c=[];if(e.iterChangedRanges((u,f,h,p)=>c.push({fromA:u,toA:f,fromB:h,toB:p})),r=Cd.applyChanges(r,c),s=Wr.empty,i=0,a={from:e.mapPos(a.from,-1),to:e.mapPos(a.to,1)},this.skipped.length){l=[];for(let u of this.skipped){let f=e.mapPos(u.from,1),h=e.mapPos(u.to,-1);f<h&&l.push({from:f,to:h})}}}return new Ly(this.parser,n,r,s,i,a,l,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let n=this.skipped.length;for(let r=0;r<this.skipped.length;r++){let{from:s,to:i}=this.skipped[r];s<e.to&&i>e.from&&(this.fragments=gK(this.fragments,s,i),this.skipped.splice(r--,1))}return this.skipped.length>=n?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,n){this.skipped.push({from:e,to:n})}static getSkippingParser(e){return new class extends $ce{createParse(n,r,s){let i=s[0].from,a=s[s.length-1].to;return{parsedPos:i,advance(){let c=Lb;if(c){for(let u of s)c.tempSkipped.push(u);e&&(c.scheduleOn=c.scheduleOn?Promise.all([c.scheduleOn,e]):e)}return this.parsedPos=a,new Wr(Lo.none,[],[],a-i)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let n=this.fragments;return this.treeLen>=e&&n.length&&n[0].from==0&&n[0].to>=e}static get(){return Lb}}function gK(t,e,n){return Cd.applyChanges(t,[{fromA:e,toA:n,fromB:e,toB:n}])}class $y{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let n=this.context.changes(e.changes,e.state),r=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),n.viewport.to);return n.work(20,r)||n.takeTree(),new $y(n)}static init(e){let n=Math.min(3e3,e.doc.length),r=Ly.create(e.facet(qh).parser,e,{from:0,to:n});return r.work(20,n)||r.takeTree(),new $y(r)}}yl.state=Oi.define({create:$y.init,update(t,e){for(let n of e.effects)if(n.is(yl.setState))return n.value;return e.startState.facet(qh)!=e.state.facet(qh)?$y.init(e.state):t.apply(e)}});let Uce=t=>{let e=setTimeout(()=>t(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Uce=t=>{let e=-1,n=setTimeout(()=>{e=requestIdleCallback(t,{timeout:400})},100);return()=>e<0?clearTimeout(n):cancelIdleCallback(e)});const U3=typeof navigator<"u"&&(!((z3=navigator.scheduling)===null||z3===void 0)&&z3.isInputPending)?()=>navigator.scheduling.isInputPending():null,LVe=ti.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let n=this.view.state.field(yl.state).context;(n.updateViewport(e.view.viewport)||this.view.viewport.to>n.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(n)}scheduleWork(){if(this.working)return;let{state:e}=this.view,n=e.field(yl.state);(n.tree!=n.context.tree||!n.context.isDone(e.doc.length))&&(this.working=Uce(this.work))}work(e){this.working=null;let n=Date.now();if(this.chunkEnd<n&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=n+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:r,viewport:{to:s}}=this.view,i=r.field(yl.state);if(i.tree==i.context.tree&&i.context.isDone(s+1e5))return;let a=Date.now()+Math.min(this.chunkBudget,100,e&&!U3?Math.max(25,e.timeRemaining()-5):1e9),l=i.context.treeLen<s&&r.doc.length>s+1e3,c=i.context.work(()=>U3&&U3()||Date.now()>a,s+(l?0:1e5));this.chunkBudget-=Date.now()-n,(c||this.chunkBudget<=0)&&(i.context.takeTree(),this.view.dispatch({effects:yl.setState.of(new $y(i.context))})),this.chunkBudget>0&&!(c&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(i.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(n=>aa(this.view.state,n)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),qh=_t.define({combine(t){return t.length?t[0]:null},enables:t=>[yl.state,LVe,Nt.contentAttributes.compute([t],e=>{let n=e.facet(t);return n&&n.name?{"data-language":n.name}:{}})]});class $Ve{constructor(e,n=[]){this.language=e,this.support=n,this.extension=[e,n]}}class Pe{constructor(e,n,r,s,i,a=void 0){this.name=e,this.alias=n,this.extensions=r,this.filename=s,this.loadFunc=i,this.support=a,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(e=>this.support=e,e=>{throw this.loading=null,e}))}static of(e){let{load:n,support:r}=e;if(!n){if(!r)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");n=()=>Promise.resolve(r)}return new Pe(e.name,(e.alias||[]).concat(e.name).map(s=>s.toLowerCase()),e.extensions||[],e.filename,n,r)}static matchFilename(e,n){for(let s of e)if(s.filename&&s.filename.test(n))return s;let r=/\.([^.]+)$/.exec(n);if(r){for(let s of e)if(s.extensions.indexOf(r[1])>-1)return s}return null}static matchLanguageName(e,n,r=!0){n=n.toLowerCase();for(let s of e)if(s.alias.some(i=>i==n))return s;if(r)for(let s of e)for(let i of s.alias){let a=n.indexOf(i);if(a>-1&&(i.length>2||!/\w/.test(n[a-1])&&!/\w/.test(n[a+i.length])))return s}return null}}const FVe=_t.define(),j5=_t.define({combine:t=>{if(!t.length)return" ";let e=t[0];if(!e||/\S/.test(e)||Array.from(e).some(n=>n!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(t[0]));return e}});function Yp(t){let e=t.facet(j5);return e.charCodeAt(0)==9?t.tabSize*e.length:e.length}function E1(t,e){let n="",r=t.tabSize,s=t.facet(j5)[0];if(s==" "){for(;e>=r;)n+=" ",e-=r;s=" "}for(let i=0;i<e;i++)n+=s;return n}function r9(t,e){t instanceof Zn&&(t=new N5(t));for(let r of t.state.facet(FVe)){let s=r(t,e);if(s!==void 0)return s}let n=Ji(t.state);return n.length>=e?BVe(t,n,e):null}class N5{constructor(e,n={}){this.state=e,this.options=n,this.unit=Yp(e)}lineAt(e,n=1){let r=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:i}=this.options;return s!=null&&s>=r.from&&s<=r.to?i&&s==e?{text:"",from:e}:(n<0?s<e:s<=e)?{text:r.text.slice(s-r.from),from:s}:{text:r.text.slice(0,s-r.from),from:r.from}:r}textAfterPos(e,n=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:r,from:s}=this.lineAt(e,n);return r.slice(e-s,Math.min(r.length,e+100-s))}column(e,n=1){let{text:r,from:s}=this.lineAt(e,n),i=this.countColumn(r,e-s),a=this.options.overrideIndentation?this.options.overrideIndentation(s):-1;return a>-1&&(i+=a-this.countColumn(r,r.search(/\S|$/))),i}countColumn(e,n=e.length){return N0(e,this.state.tabSize,n)}lineIndent(e,n=1){let{text:r,from:s}=this.lineAt(e,n),i=this.options.overrideIndentation;if(i){let a=i(s);if(a>-1)return a}return this.countColumn(r,r.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const Vce=new Ln;function BVe(t,e,n){let r=e.resolveStack(n),s=e.resolveInner(n,-1).resolve(n,0).enterUnfinishedNodesBefore(n);if(s!=r.node){let i=[];for(let a=s;a&&!(a.from<r.node.from||a.to>r.node.to||a.from==r.node.from&&a.type==r.node.type);a=a.parent)i.push(a);for(let a=i.length-1;a>=0;a--)r={node:i[a],next:r}}return Hce(r,t,n)}function Hce(t,e,n){for(let r=t;r;r=r.next){let s=UVe(r.node);if(s)return s(s9.create(e,n,r))}return 0}function zVe(t){return t.pos==t.options.simulateBreak&&t.options.simulateDoubleBreak}function UVe(t){let e=t.type.prop(Vce);if(e)return e;let n=t.firstChild,r;if(n&&(r=n.type.prop(Ln.closedBy))){let s=t.lastChild,i=s&&r.indexOf(s.name)>-1;return a=>qce(a,!0,1,void 0,i&&!zVe(a)?s.from:void 0)}return t.parent==null?VVe:null}function VVe(){return 0}class s9 extends N5{constructor(e,n,r){super(e.state,e.options),this.base=e,this.pos=n,this.context=r}get node(){return this.context.node}static create(e,n,r){return new s9(e,n,r)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let n=this.state.doc.lineAt(e.from);for(;;){let r=e.resolve(n.from);for(;r.parent&&r.parent.from==r.from;)r=r.parent;if(HVe(r,e))break;n=this.state.doc.lineAt(r.from)}return this.lineIndent(n.from)}continue(){return Hce(this.context.next,this.base,this.pos)}}function HVe(t,e){for(let n=e;n;n=n.parent)if(t==n)return!0;return!1}function qVe(t){let e=t.node,n=e.childAfter(e.from),r=e.lastChild;if(!n)return null;let s=t.options.simulateBreak,i=t.state.doc.lineAt(n.from),a=s==null||s<=i.from?i.to:Math.min(i.to,s);for(let l=n.to;;){let c=e.childAfter(l);if(!c||c==r)return null;if(!c.type.isSkipped){if(c.from>=a)return null;let u=/^ */.exec(i.text.slice(n.to-i.from))[0].length;return{from:n.from,to:n.to+u}}l=c.to}}function glt({closing:t,align:e=!0,units:n=1}){return r=>qce(r,e,n,t)}function qce(t,e,n,r,s){let i=t.textAfter,a=i.match(/^\s*/)[0].length,l=r&&i.slice(a,a+r.length)==r||s==t.pos+a,c=e?qVe(t):null;return c?l?t.column(c.from):t.column(c.to):t.baseIndent+(l?0:t.unit*n)}const xlt=t=>t.baseIndent;function ylt({except:t,units:e=1}={}){return n=>{let r=t&&t.test(n.textAfter);return n.baseIndent+(r?0:e*n.unit)}}const KVe=200;function WVe(){return Zn.transactionFilter.of(t=>{if(!t.docChanged||!t.isUserEvent("input.type")&&!t.isUserEvent("input.complete"))return t;let e=t.startState.languageDataAt("indentOnInput",t.startState.selection.main.head);if(!e.length)return t;let n=t.newDoc,{head:r}=t.newSelection.main,s=n.lineAt(r);if(r>s.from+KVe)return t;let i=n.sliceString(s.from,r);if(!e.some(u=>u.test(i)))return t;let{state:a}=t,l=-1,c=[];for(let{head:u}of a.selection.ranges){let f=a.doc.lineAt(u);if(f.from==l)continue;l=f.from;let h=r9(a,f.from);if(h==null)continue;let p=/^\s*/.exec(f.text)[0],g=E1(a,h);p!=g&&c.push({from:f.from,to:f.from+p.length,insert:g})}return c.length?[t,{changes:c,sequential:!0}]:t})}const GVe=_t.define(),YVe=new Ln;function blt(t){let e=t.firstChild,n=t.lastChild;return e&&e.to<n.from?{from:e.to,to:n.type.isError?t.to:n.from}:null}function JVe(t,e,n){let r=Ji(t);if(r.length<n)return null;let s=r.resolveStack(n,1),i=null;for(let a=s;a;a=a.next){let l=a.node;if(l.to<=n||l.from>n)continue;if(i&&l.from<e)break;let c=l.type.prop(YVe);if(c&&(l.to<r.length-50||r.length==t.doc.length||!QVe(l))){let u=c(l,t);u&&u.from<=n&&u.from>=e&&u.to>n&&(i=u)}}return i}function QVe(t){let e=t.lastChild;return e&&e.to==t.to&&e.type.isError}function XN(t,e,n){for(let r of t.facet(GVe)){let s=r(t,e,n);if(s)return s}return JVe(t,e,n)}function Kce(t,e){let n=e.mapPos(t.from,1),r=e.mapPos(t.to,-1);return n>=r?void 0:{from:n,to:r}}const S5=pn.define({map:Kce}),qw=pn.define({map:Kce});function Wce(t){let e=[];for(let{head:n}of t.state.selection.ranges)e.some(r=>r.from<=n&&r.to>=n)||e.push(t.lineBlockAt(n));return e}const Jp=Oi.define({create(){return Qt.none},update(t,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((n,r)=>t=xK(t,n,r)),t=t.map(e.changes);for(let n of e.effects)if(n.is(S5)&&!ZVe(t,n.value.from,n.value.to)){let{preparePlaceholder:r}=e.state.facet(Jce),s=r?Qt.replace({widget:new iHe(r(e.state,n.value))}):yK;t=t.update({add:[s.range(n.value.from,n.value.to)]})}else n.is(qw)&&(t=t.update({filter:(r,s)=>n.value.from!=r||n.value.to!=s,filterFrom:n.value.from,filterTo:n.value.to}));return e.selection&&(t=xK(t,e.selection.main.head)),t},provide:t=>Nt.decorations.from(t),toJSON(t,e){let n=[];return t.between(0,e.doc.length,(r,s)=>{n.push(r,s)}),n},fromJSON(t){if(!Array.isArray(t)||t.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let n=0;n<t.length;){let r=t[n++],s=t[n++];if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid JSON for fold state");e.push(yK.range(r,s))}return Qt.set(e,!0)}});function xK(t,e,n=e){let r=!1;return t.between(e,n,(s,i)=>{s<n&&i>e&&(r=!0)}),r?t.update({filterFrom:e,filterTo:n,filter:(s,i)=>s>=n||i<=e}):t}function eS(t,e,n){var r;let s=null;return(r=t.field(Jp,!1))===null||r===void 0||r.between(e,n,(i,a)=>{(!s||s.from>i)&&(s={from:i,to:a})}),s}function ZVe(t,e,n){let r=!1;return t.between(e,e,(s,i)=>{s==e&&i==n&&(r=!0)}),r}function Gce(t,e){return t.field(Jp,!1)?e:e.concat(pn.appendConfig.of(Qce()))}const XVe=t=>{for(let e of Wce(t)){let n=XN(t.state,e.from,e.to);if(n)return t.dispatch({effects:Gce(t.state,[S5.of(n),Yce(t,n)])}),!0}return!1},eHe=t=>{if(!t.state.field(Jp,!1))return!1;let e=[];for(let n of Wce(t)){let r=eS(t.state,n.from,n.to);r&&e.push(qw.of(r),Yce(t,r,!1))}return e.length&&t.dispatch({effects:e}),e.length>0};function Yce(t,e,n=!0){let r=t.state.doc.lineAt(e.from).number,s=t.state.doc.lineAt(e.to).number;return Nt.announce.of(`${t.state.phrase(n?"Folded lines":"Unfolded lines")} ${r} ${t.state.phrase("to")} ${s}.`)}const tHe=t=>{let{state:e}=t,n=[];for(let r=0;r<e.doc.length;){let s=t.lineBlockAt(r),i=XN(e,s.from,s.to);i&&n.push(S5.of(i)),r=(i?t.lineBlockAt(i.to):s).to+1}return n.length&&t.dispatch({effects:Gce(t.state,n)}),!!n.length},nHe=t=>{let e=t.state.field(Jp,!1);if(!e||!e.size)return!1;let n=[];return e.between(0,t.state.doc.length,(r,s)=>{n.push(qw.of({from:r,to:s}))}),t.dispatch({effects:n}),!0},rHe=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:XVe},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:eHe},{key:"Ctrl-Alt-[",run:tHe},{key:"Ctrl-Alt-]",run:nHe}],sHe={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},Jce=_t.define({combine(t){return Cu(t,sHe)}});function Qce(t){return[Jp,lHe]}function Zce(t,e){let{state:n}=t,r=n.facet(Jce),s=a=>{let l=t.lineBlockAt(t.posAtDOM(a.target)),c=eS(t.state,l.from,l.to);c&&t.dispatch({effects:qw.of(c)}),a.preventDefault()};if(r.placeholderDOM)return r.placeholderDOM(t,s,e);let i=document.createElement("span");return i.textContent=r.placeholderText,i.setAttribute("aria-label",n.phrase("folded code")),i.title=n.phrase("unfold"),i.className="cm-foldPlaceholder",i.onclick=s,i}const yK=Qt.replace({widget:new class extends ju{toDOM(t){return Zce(t,null)}}});class iHe extends ju{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return Zce(e,this.value)}}const oHe={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class V3 extends Vd{constructor(e,n){super(),this.config=e,this.open=n}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let n=document.createElement("span");return n.textContent=this.open?this.config.openText:this.config.closedText,n.title=e.state.phrase(this.open?"Fold line":"Unfold line"),n}}function aHe(t={}){let e={...oHe,...t},n=new V3(e,!0),r=new V3(e,!1),s=ti.fromClass(class{constructor(a){this.from=a.viewport.from,this.markers=this.buildMarkers(a)}update(a){(a.docChanged||a.viewportChanged||a.startState.facet(qh)!=a.state.facet(qh)||a.startState.field(Jp,!1)!=a.state.field(Jp,!1)||Ji(a.startState)!=Ji(a.state)||e.foldingChanged(a))&&(this.markers=this.buildMarkers(a.view))}buildMarkers(a){let l=new zd;for(let c of a.viewportLineBlocks){let u=eS(a.state,c.from,c.to)?r:XN(a.state,c.from,c.to)?n:null;u&&l.add(c.from,c.from,u)}return l.finish()}}),{domEventHandlers:i}=e;return[s,nVe({class:"cm-foldGutter",markers(a){var l;return((l=a.plugin(s))===null||l===void 0?void 0:l.markers)||Bn.empty},initialSpacer(){return new V3(e,!1)},domEventHandlers:{...i,click:(a,l,c)=>{if(i.click&&i.click(a,l,c))return!0;let u=eS(a.state,l.from,l.to);if(u)return a.dispatch({effects:qw.of(u)}),!0;let f=XN(a.state,l.from,l.to);return f?(a.dispatch({effects:S5.of(f)}),!0):!1}}}),Qce()]}const lHe=Nt.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Kw{constructor(e,n){this.specs=e;let r;function s(l){let c=zh.newName();return(r||(r=Object.create(null)))["."+c]=l,c}const i=typeof n.all=="string"?n.all:n.all?s(n.all):void 0,a=n.scope;this.scope=a instanceof yl?l=>l.prop(Jm)==a.data:a?l=>l==a:void 0,this.style=Bce(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:i}).style,this.module=r?new zh(r):null,this.themeType=n.themeType}static define(e,n){return new Kw(e,n||{})}}const rO=_t.define(),Xce=_t.define({combine(t){return t.length?[t[0]]:null}});function H3(t){let e=t.facet(rO);return e.length?e:t.facet(Xce)}function eue(t,e){let n=[uHe],r;return t instanceof Kw&&(t.module&&n.push(Nt.styleModule.of(t.module)),r=t.themeType),e!=null&&e.fallback?n.push(Xce.of(t)):r?n.push(rO.computeN([Nt.darkTheme],s=>s.facet(Nt.darkTheme)==(r=="dark")?[t]:[])):n.push(rO.of(t)),n}class cHe{constructor(e){this.markCache=Object.create(null),this.tree=Ji(e.state),this.decorations=this.buildDeco(e,H3(e.state)),this.decoratedTo=e.viewport.to}update(e){let n=Ji(e.state),r=H3(e.state),s=r!=H3(e.startState),{viewport:i}=e.view,a=e.changes.mapPos(this.decoratedTo,1);n.length<i.to&&!s&&n.type==this.tree.type&&a>=i.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=a):(n!=this.tree||e.viewportChanged||s)&&(this.tree=n,this.decorations=this.buildDeco(e.view,r),this.decoratedTo=i.to)}buildDeco(e,n){if(!n||!this.tree.length)return Qt.none;let r=new zd;for(let{from:s,to:i}of e.visibleRanges)IVe(this.tree,n,(a,l,c)=>{r.add(a,l,this.markCache[c]||(this.markCache[c]=Qt.mark({class:c})))},s,i);return r.finish()}}const uHe=um.high(ti.fromClass(cHe,{decorations:t=>t.decorations})),dHe=Kw.define([{tag:Be.meta,color:"#404740"},{tag:Be.link,textDecoration:"underline"},{tag:Be.heading,textDecoration:"underline",fontWeight:"bold"},{tag:Be.emphasis,fontStyle:"italic"},{tag:Be.strong,fontWeight:"bold"},{tag:Be.strikethrough,textDecoration:"line-through"},{tag:Be.keyword,color:"#708"},{tag:[Be.atom,Be.bool,Be.url,Be.contentSeparator,Be.labelName],color:"#219"},{tag:[Be.literal,Be.inserted],color:"#164"},{tag:[Be.string,Be.deleted],color:"#a11"},{tag:[Be.regexp,Be.escape,Be.special(Be.string)],color:"#e40"},{tag:Be.definition(Be.variableName),color:"#00f"},{tag:Be.local(Be.variableName),color:"#30a"},{tag:[Be.typeName,Be.namespace],color:"#085"},{tag:Be.className,color:"#167"},{tag:[Be.special(Be.variableName),Be.macroName],color:"#256"},{tag:Be.definition(Be.propertyName),color:"#00c"},{tag:Be.comment,color:"#940"},{tag:Be.invalid,color:"#f00"}]),fHe=Nt.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),tue=1e4,nue="()[]{}",rue=_t.define({combine(t){return Cu(t,{afterCursor:!0,brackets:nue,maxScanDistance:tue,renderMatch:pHe})}}),hHe=Qt.mark({class:"cm-matchingBracket"}),mHe=Qt.mark({class:"cm-nonmatchingBracket"});function pHe(t){let e=[],n=t.matched?hHe:mHe;return e.push(n.range(t.start.from,t.start.to)),t.end&&e.push(n.range(t.end.from,t.end.to)),e}const gHe=Oi.define({create(){return Qt.none},update(t,e){if(!e.docChanged&&!e.selection)return t;let n=[],r=e.state.facet(rue);for(let s of e.state.selection.ranges){if(!s.empty)continue;let i=Xc(e.state,s.head,-1,r)||s.head>0&&Xc(e.state,s.head-1,1,r)||r.afterCursor&&(Xc(e.state,s.head,1,r)||s.head<e.state.doc.length&&Xc(e.state,s.head+1,-1,r));i&&(n=n.concat(r.renderMatch(i,e.state)))}return Qt.set(n,!0)},provide:t=>Nt.decorations.from(t)}),xHe=[gHe,fHe];function yHe(t={}){return[rue.of(t),xHe]}const bHe=new Ln;function sO(t,e,n){let r=t.prop(e<0?Ln.openedBy:Ln.closedBy);if(r)return r;if(t.name.length==1){let s=n.indexOf(t.name);if(s>-1&&s%2==(e<0?1:0))return[n[s+e]]}return null}function iO(t){let e=t.type.prop(bHe);return e?e(t.node):t}function Xc(t,e,n,r={}){let s=r.maxScanDistance||tue,i=r.brackets||nue,a=Ji(t),l=a.resolveInner(e,n);for(let c=l;c;c=c.parent){let u=sO(c.type,n,i);if(u&&c.from<c.to){let f=iO(c);if(f&&(n>0?e>=f.from&&e<f.to:e>f.from&&e<=f.to))return vHe(t,e,n,c,f,u,i)}}return wHe(t,e,n,a,l.type,s,i)}function vHe(t,e,n,r,s,i,a){let l=r.parent,c={from:s.from,to:s.to},u=0,f=l==null?void 0:l.cursor();if(f&&(n<0?f.childBefore(r.from):f.childAfter(r.to)))do if(n<0?f.to<=r.from:f.from>=r.to){if(u==0&&i.indexOf(f.type.name)>-1&&f.from<f.to){let h=iO(f);return{start:c,end:h?{from:h.from,to:h.to}:void 0,matched:!0}}else if(sO(f.type,n,a))u++;else if(sO(f.type,-n,a)){if(u==0){let h=iO(f);return{start:c,end:h&&h.from<h.to?{from:h.from,to:h.to}:void 0,matched:!1}}u--}}while(n<0?f.prevSibling():f.nextSibling());return{start:c,matched:!1}}function wHe(t,e,n,r,s,i,a){let l=n<0?t.sliceDoc(e-1,e):t.sliceDoc(e,e+1),c=a.indexOf(l);if(c<0||c%2==0!=n>0)return null;let u={from:n<0?e-1:e,to:n>0?e+1:e},f=t.doc.iterRange(e,n>0?t.doc.length:0),h=0;for(let p=0;!f.next().done&&p<=i;){let g=f.value;n<0&&(p+=g.length);let b=e+p*n;for(let v=n>0?0:g.length-1,w=n>0?g.length:-1;v!=w;v+=n){let j=a.indexOf(g[v]);if(!(j<0||r.resolveInner(b+v,1).type!=s))if(j%2==0==n>0)h++;else{if(h==1)return{start:u,end:{from:b+v,to:b+v+1},matched:j>>1==c>>1};h--}}n>0&&(p+=g.length)}return f.done?{start:u,matched:!1}:null}function bK(t,e,n,r=0,s=0){e==null&&(e=t.search(/[^\s\u00a0]/),e==-1&&(e=t.length));let i=s;for(let a=r;a<e;a++)t.charCodeAt(a)==9?i+=n-i%n:i++;return i}class sue{constructor(e,n,r,s){this.string=e,this.tabSize=n,this.indentUnit=r,this.overrideIndent=s,this.pos=0,this.start=0,this.lastColumnPos=0,this.lastColumnValue=0}eol(){return this.pos>=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)}eat(e){let n=this.string.charAt(this.pos),r;if(typeof e=="string"?r=n==e:r=n&&(e instanceof RegExp?e.test(n):e(n)),r)return++this.pos,n}eatWhile(e){let n=this.pos;for(;this.eat(e););return this.pos>n}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let n=this.string.indexOf(e,this.pos);if(n>-1)return this.pos=n,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPos<this.start&&(this.lastColumnValue=bK(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue}indentation(){var e;return(e=this.overrideIndent)!==null&&e!==void 0?e:bK(this.string,null,this.tabSize)}match(e,n,r){if(typeof e=="string"){let s=a=>r?a.toLowerCase():a,i=this.string.substr(this.pos,e.length);return s(i)==s(e)?(n!==!1&&(this.pos+=e.length),!0):null}else{let s=this.string.slice(this.pos).match(e);return s&&s.index>0?null:(s&&n!==!1&&(this.pos+=s[0].length),s)}}current(){return this.string.slice(this.start,this.pos)}}function kHe(t){return{name:t.name||"",token:t.token,blankLine:t.blankLine||(()=>{}),startState:t.startState||(()=>!0),copyState:t.copyState||CHe,indent:t.indent||(()=>null),languageData:t.languageData||{},tokenTable:t.tokenTable||a9,mergeTokens:t.mergeTokens!==!1}}function CHe(t){if(typeof t!="object")return t;let e={};for(let n in t){let r=t[n];e[n]=r instanceof Array?r.slice():r}return e}const vK=new WeakMap;class i9 extends yl{constructor(e){let n=zce(e.languageData),r=kHe(e),s,i=new class extends $ce{createParse(a,l,c){return new NHe(s,a,l,c)}};super(n,i,[],e.name),this.topNode=EHe(n,this),s=this,this.streamParser=r,this.stateAfter=new Ln({perNode:!0}),this.tokenTable=e.tokenTable?new lue(r.tokenTable):_He}static define(e){return new i9(e)}getIndent(e){let n,{overrideIndentation:r}=e.options;r&&(n=vK.get(e.state),n!=null&&n<e.pos-1e4&&(n=void 0));let s=o9(this,e.node.tree,e.node.from,e.node.from,n??e.pos),i,a;if(s?(a=s.state,i=s.pos+1):(a=this.streamParser.startState(e.unit),i=e.node.from),e.pos-i>1e4)return null;for(;i<e.pos;){let c=e.state.doc.lineAt(i),u=Math.min(e.pos,c.to);if(c.length){let f=r?r(c.from):-1,h=new sue(c.text,e.state.tabSize,e.unit,f<0?void 0:f);for(;h.pos<u-c.from;)oue(this.streamParser.token,h,a)}else this.streamParser.blankLine(a,e.unit);if(u==e.pos)break;i=c.to+1}let l=e.lineAt(e.pos);return r&&n==null&&vK.set(e.state,l.from),this.streamParser.indent(a,/^\s*(.*)/.exec(l.text)[1],e)}get allowsNesting(){return!1}}function o9(t,e,n,r,s){let i=n>=r&&n+e.length<=s&&e.prop(t.stateAfter);if(i)return{state:t.streamParser.copyState(i),pos:n+e.length};for(let a=e.children.length-1;a>=0;a--){let l=e.children[a],c=n+e.positions[a],u=l instanceof Wr&&c<s&&o9(t,l,c,r,s);if(u)return u}return null}function iue(t,e,n,r,s){if(s&&n<=0&&r>=e.length)return e;!s&&n==0&&e.type==t.topNode&&(s=!0);for(let i=e.children.length-1;i>=0;i--){let a=e.positions[i],l=e.children[i],c;if(a<r&&l instanceof Wr){if(!(c=iue(t,l,n-a,r-a,s)))break;return s?new Wr(e.type,e.children.slice(0,i).concat(c),e.positions.slice(0,i+1),a+c.length):c}}return null}function jHe(t,e,n,r,s){for(let i of e){let a=i.from+(i.openStart?25:0),l=i.to-(i.openEnd?25:0),c=a<=n&&l>n&&o9(t,i.tree,0-i.offset,n,l),u;if(c&&c.pos<=r&&(u=iue(t,i.tree,n+i.offset,c.pos+i.offset,!1)))return{state:c.state,tree:u}}return{state:t.streamParser.startState(s?Yp(s):4),tree:Wr.empty}}class NHe{constructor(e,n,r,s){this.lang=e,this.input=n,this.fragments=r,this.ranges=s,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=s[s.length-1].to;let i=Ly.get(),a=s[0].from,{state:l,tree:c}=jHe(e,r,a,this.to,i==null?void 0:i.state);this.state=l,this.parsedPos=this.chunkStart=a+c.length;for(let u=0;u<c.children.length;u++)this.chunks.push(c.children[u]),this.chunkPos.push(c.positions[u]);i&&this.parsedPos<i.viewport.from-1e5&&s.some(u=>u.from<=i.viewport.from&&u.to>=i.viewport.from)&&(this.state=this.lang.streamParser.startState(Yp(i.state)),i.skipUntilInView(this.parsedPos,i.viewport.from),this.parsedPos=i.viewport.from),this.moveRangeIndex()}advance(){let e=Ly.get(),n=this.stoppedAt==null?this.to:Math.min(this.to,this.stoppedAt),r=Math.min(n,this.chunkStart+512);for(e&&(r=Math.min(r,e.viewport.to));this.parsedPos<r;)this.parseLine(e);return this.chunkStart<this.parsedPos&&this.finishChunk(),this.parsedPos>=n?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,n),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let n=this.input.chunk(e);if(this.input.lineChunks)n==`
1007
1007
  `&&(n="");else{let r=n.indexOf(`
1008
- `);r>-1&&(n=n.slice(0,r))}return e+n.length<=this.to?n:n.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,n=this.lineAfter(e),r=e+n.length;for(let s=this.rangeIndex;;){let i=this.ranges[s].to;if(i>=r||(n=n.slice(0,i-(r-n.length)),s++,s==this.ranges.length))break;let a=this.ranges[s].from,l=this.lineAfter(a);n+=l,r=a+l.length}return{line:n,end:r}}skipGapsTo(e,n,r){for(;;){let s=this.ranges[this.rangeIndex].to,i=e+n;if(r>0?s>i:s>=i)break;let a=this.ranges[++this.rangeIndex].from;n+=a-s}return n}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(e,n,r,s){let i=4;if(this.ranges.length>1){s=this.skipGapsTo(n,s,1),n+=s;let l=this.chunk.length;s=this.skipGapsTo(r,s,-1),r+=s,i+=this.chunk.length-l}let a=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&i==4&&a>=0&&this.chunk[a]==e&&this.chunk[a+2]==n?this.chunk[a+2]=r:this.chunk.push(e,n,r,i),s}parseLine(e){let{line:n,end:r}=this.nextLine(),s=0,{streamParser:i}=this.lang,a=new sue(n,e?e.state.tabSize:4,e?Yp(e.state):2);if(a.eol())i.blankLine(this.state,a.indentUnit);else for(;!a.eol();){let l=oue(i.token,a,this.state);if(l&&(s=this.emitToken(this.lang.tokenTable.resolve(l),this.parsedPos+a.start,this.parsedPos+a.pos,s)),a.start>1e4)break}this.parsedPos=r,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let e=Wr.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:SHe,topID:0,maxBufferLength:512,reused:this.chunkReused});e=new Wr(e.type,e.children,e.positions,e.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(e),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new Wr(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}}function oue(t,e,n){e.start=e.pos;for(let r=0;r<10;r++){let s=t(e,n);if(e.pos>e.start)return s}throw new Error("Stream parser failed to advance stream.")}const a9=Object.create(null),A1=[Lo.none],SHe=new XL(A1),wK=[],kK=Object.create(null),aue=Object.create(null);for(let[t,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])aue[t]=cue(a9,e);class lue{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),aue)}resolve(e){return e?this.table[e]||(this.table[e]=cue(this.extra,e)):0}}const _He=new lue(a9);function q3(t,e){wK.indexOf(t)>-1||(wK.push(t),console.warn(e))}function cue(t,e){let n=[];for(let l of e.split(" ")){let c=[];for(let u of l.split(".")){let f=t[u]||Be[u];f?typeof f=="function"?c.length?c=c.map(f):q3(u,`Modifier ${u} used at start of tag`):c.length?q3(u,`Tag ${u} used as modifier`):c=Array.isArray(f)?f:[f]:q3(u,`Unknown highlighting tag ${u}`)}for(let u of c)n.push(u)}if(!n.length)return 0;let r=e.replace(/ /g,"_"),s=r+" "+n.map(l=>l.id),i=kK[s];if(i)return i.id;let a=kK[s]=Lo.define({id:A1.length,name:r,props:[TVe({[r]:n})]});return A1.push(a),a.id}function EHe(t,e){let n=Lo.define({id:A1.length,name:"Document",props:[Jm.add(()=>t),Vce.add(()=>r=>e.getIndent(r))],top:!0});return A1.push(n),n}Kr.RTL,Kr.LTR;class uue{constructor(e,n,r,s){this.state=e,this.pos=n,this.explicit=r,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let n=Ji(this.state).resolveInner(this.pos,-1);for(;n&&e.indexOf(n.name)<0;)n=n.parent;return n?{from:n.from,to:this.pos,text:this.state.sliceDoc(n.from,this.pos),type:n.type}:null}matchBefore(e){let n=this.state.doc.lineAt(this.pos),r=Math.max(n.from,this.pos-250),s=n.text.slice(r-n.from,this.pos-n.from),i=s.search(due(e,!1));return i<0?null:{from:r+i,to:this.pos,text:s.slice(i)}}get aborted(){return this.abortListeners==null}addEventListener(e,n,r){e=="abort"&&this.abortListeners&&(this.abortListeners.push(n),r&&r.onDocChange&&(this.abortOnDocChange=!0))}}function CK(t){let e=Object.keys(t).join(""),n=/\w/.test(e);return n&&(e=e.replace(/\w/g,"")),`[${n?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function AHe(t){let e=Object.create(null),n=Object.create(null);for(let{label:s}of t){e[s[0]]=!0;for(let i=1;i<s.length;i++)n[s[i]]=!0}let r=CK(e)+CK(n)+"*$";return[new RegExp("^"+r),new RegExp(r)]}function THe(t){let e=t.map(s=>typeof s=="string"?{label:s}:s),[n,r]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:AHe(e);return s=>{let i=s.matchBefore(r);return i||s.explicit?{from:i?i.from:s.pos,options:e,validFor:n}:null}}function vlt(t,e){return n=>{for(let r=Ji(n.state).resolveInner(n.pos,-1);r;r=r.parent){if(t.indexOf(r.name)>-1)return null;if(r.type.isTop)break}return e(n)}}class jK{constructor(e,n,r,s){this.completion=e,this.source=n,this.match=r,this.score=s}}function hp(t){return t.selection.main.from}function due(t,e){var n;let{source:r}=t,s=e&&r[0]!="^",i=r[r.length-1]!="$";return!s&&!i?t:new RegExp(`${s?"^":""}(?:${r})${i?"$":""}`,(n=t.flags)!==null&&n!==void 0?n:t.ignoreCase?"i":"")}const l9=ef.define();function MHe(t,e,n,r){let{main:s}=t.selection,i=n-s.from,a=r-s.from;return{...t.changeByRange(l=>{if(l!=s&&n!=r&&t.sliceDoc(l.from+i,l.from+a)!=t.sliceDoc(n,r))return{range:l};let c=t.toText(e);return{changes:{from:l.from+i,to:r==s.from?l.to:l.from+a,insert:c},range:Qe.cursor(l.from+i+c.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const NK=new WeakMap;function IHe(t){if(!Array.isArray(t))return t;let e=NK.get(t);return e||NK.set(t,e=THe(t)),e}const tS=pn.define(),T1=pn.define();class RHe{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let n=0;n<e.length;){let r=na(e,n),s=qc(r);this.chars.push(r);let i=e.slice(n,n+s),a=i.toUpperCase();this.folded.push(na(a==i?i.toLowerCase():a,0)),n+=s}this.astral=e.length!=this.chars.length}ret(e,n){return this.score=e,this.matched=n,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:n,folded:r,any:s,precise:i,byWord:a}=this;if(n.length==1){let C=na(e,0),N=qc(C),S=N==e.length?0:-100;if(C!=n[0])if(C==r[0])S+=-200;else return null;return this.ret(S,[0,N])}let l=e.indexOf(this.pattern);if(l==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let c=n.length,u=0;if(l<0){for(let C=0,N=Math.min(e.length,200);C<N&&u<c;){let S=na(e,C);(S==n[u]||S==r[u])&&(s[u++]=C),C+=qc(S)}if(u<c)return null}let f=0,h=0,p=!1,g=0,b=-1,v=-1,w=/[a-z]/.test(e),j=!0;for(let C=0,N=Math.min(e.length,200),S=0;C<N&&h<c;){let T=na(e,C);l<0&&(f<c&&T==n[f]&&(i[f++]=C),g<c&&(T==n[g]||T==r[g]?(g==0&&(b=C),v=C+1,g++):g=0));let _,A=T<255?T>=48&&T<=57||T>=97&&T<=122?2:T>=65&&T<=90?1:0:(_=OL(T))!=_.toLowerCase()?1:_!=_.toUpperCase()?2:0;(!C||A==1&&w||S==0&&A!=0)&&(n[h]==T||r[h]==T&&(p=!0)?a[h++]=C:a.length&&(j=!1)),S=A,C+=qc(T)}return h==c&&a[0]==0&&j?this.result(-100+(p?-200:0),a,e):g==c&&b==0?this.ret(-200-e.length+(v==e.length?0:-100),[0,v]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):g==c?this.ret(-900-e.length,[b,v]):h==c?this.result(-100+(p?-200:0)+-700+(j?0:-1100),a,e):n.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,n,r){let s=[],i=0;for(let a of n){let l=a+(this.astral?qc(na(r,a)):1);i&&s[i-1]==a?s[i-1]=l:(s[i++]=a,s[i++]=l)}return this.ret(e-r.length,s)}}class OHe{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let n=e.slice(0,this.pattern.length),r=n==this.pattern?0:n.toLowerCase()==this.folded?-200:null;return r==null?null:(this.matched=[0,n.length],this.score=r+(e.length==this.pattern.length?0:-100),this)}}const ji=_t.define({combine(t){return Cu(t,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:DHe,filterStrict:!1,compareCompletions:(e,n)=>(e.sortText||e.label).localeCompare(n.sortText||n.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,n)=>e&&n,closeOnBlur:(e,n)=>e&&n,icons:(e,n)=>e&&n,tooltipClass:(e,n)=>r=>SK(e(r),n(r)),optionClass:(e,n)=>r=>SK(e(r),n(r)),addToOptions:(e,n)=>e.concat(n),filterStrict:(e,n)=>e||n})}});function SK(t,e){return t?e?t+" "+e:t:e}function DHe(t,e,n,r,s,i){let a=t.textDirection==Kr.RTL,l=a,c=!1,u="top",f,h,p=e.left-s.left,g=s.right-e.right,b=r.right-r.left,v=r.bottom-r.top;if(l&&p<Math.min(b,g)?l=!1:!l&&g<Math.min(b,p)&&(l=!0),b<=(l?p:g))f=Math.max(s.top,Math.min(n.top,s.bottom-v))-e.top,h=Math.min(400,l?p:g);else{c=!0,h=Math.min(400,(a?e.right:s.right-e.left)-30);let C=s.bottom-e.bottom;C>=v||C>e.top?f=n.bottom-e.top:(u="bottom",f=e.bottom-n.top)}let w=(e.bottom-e.top)/i.offsetHeight,j=(e.right-e.left)/i.offsetWidth;return{style:`${u}: ${f/w}px; max-width: ${h/j}px`,class:"cm-completionInfo-"+(c?a?"left-narrow":"right-narrow":l?"left":"right")}}function PHe(t){let e=t.addToOptions.slice();return t.icons&&e.push({render(n){let r=document.createElement("div");return r.classList.add("cm-completionIcon"),n.type&&r.classList.add(...n.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),r.setAttribute("aria-hidden","true"),r},position:20}),e.push({render(n,r,s,i){let a=document.createElement("span");a.className="cm-completionLabel";let l=n.displayLabel||n.label,c=0;for(let u=0;u<i.length;){let f=i[u++],h=i[u++];f>c&&a.appendChild(document.createTextNode(l.slice(c,f)));let p=a.appendChild(document.createElement("span"));p.appendChild(document.createTextNode(l.slice(f,h))),p.className="cm-completionMatchedText",c=h}return c<l.length&&a.appendChild(document.createTextNode(l.slice(c))),a},position:50},{render(n){if(!n.detail)return null;let r=document.createElement("span");return r.className="cm-completionDetail",r.textContent=n.detail,r},position:80}),e.sort((n,r)=>n.position-r.position).map(n=>n.render)}function K3(t,e,n){if(t<=n)return{from:0,to:t};if(e<0&&(e=0),e<=t>>1){let s=Math.floor(e/n);return{from:s*n,to:(s+1)*n}}let r=Math.floor((t-e)/n);return{from:t-(r+1)*n,to:t-r*n}}class LHe{constructor(e,n,r){this.view=e,this.stateField=n,this.applyCompletion=r,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:c=>this.placeInfo(c),key:this},this.space=null,this.currentClass="";let s=e.state.field(n),{options:i,selected:a}=s.open,l=e.state.facet(ji);this.optionContent=PHe(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=K3(i.length,a,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",c=>{let{options:u}=e.state.field(n).open;for(let f=c.target,h;f&&f!=this.dom;f=f.parentNode)if(f.nodeName=="LI"&&(h=/-(\d+)$/.exec(f.id))&&+h[1]<u.length){this.applyCompletion(e,u[+h[1]]),c.preventDefault();return}}),this.dom.addEventListener("focusout",c=>{let u=e.state.field(this.stateField,!1);u&&u.tooltip&&e.state.facet(ji).closeOnBlur&&c.relatedTarget!=e.contentDOM&&e.dispatch({effects:T1.of(null)})}),this.showOptions(i,s.id)}mount(){this.updateSel()}showOptions(e,n){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,n,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var n;let r=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),r!=s){let{options:i,selected:a,disabled:l}=r.open;(!s.open||s.open.options!=i)&&(this.range=K3(i.length,a,e.state.facet(ji).maxRenderedOptions),this.showOptions(i,r.id)),this.updateSel(),l!=((n=s.open)===null||n===void 0?void 0:n.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let n=this.tooltipClass(e);if(n!=this.currentClass){for(let r of this.currentClass.split(" "))r&&this.dom.classList.remove(r);for(let r of n.split(" "))r&&this.dom.classList.add(r);this.currentClass=n}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),n=e.open;(n.selected>-1&&n.selected<this.range.from||n.selected>=this.range.to)&&(this.range=K3(n.options.length,n.selected,this.view.state.facet(ji).maxRenderedOptions),this.showOptions(n.options,e.id));let r=this.updateSelectedOption(n.selected);if(r){this.destroyInfo();let{completion:s}=n.options[n.selected],{info:i}=s;if(!i)return;let a=typeof i=="string"?document.createTextNode(i):i(s);if(!a)return;"then"in a?a.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,s)}).catch(l=>aa(this.view.state,l,"completion info")):(this.addInfoPane(a,s),r.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,n){this.destroyInfo();let r=this.info=document.createElement("div");if(r.className="cm-tooltip cm-completionInfo",r.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)r.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:i}=e;r.appendChild(s),this.infoDestroy=i||null}this.dom.appendChild(r),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let n=null;for(let r=this.list.firstChild,s=this.range.from;r;r=r.nextSibling,s++)r.nodeName!="LI"||!r.id?s--:s==e?r.hasAttribute("aria-selected")||(r.setAttribute("aria-selected","true"),n=r):r.hasAttribute("aria-selected")&&(r.removeAttribute("aria-selected"),r.removeAttribute("aria-describedby"));return n&&FHe(this.list,n),n}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let n=this.dom.getBoundingClientRect(),r=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),i=this.space;if(!i){let a=this.dom.ownerDocument.documentElement;i={left:0,top:0,right:a.clientWidth,bottom:a.clientHeight}}return s.top>Math.min(i.bottom,n.bottom)-10||s.bottom<Math.max(i.top,n.top)+10?null:this.view.state.facet(ji).positionInfo(this.view,n,s,r,i,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,n,r){const s=document.createElement("ul");s.id=n,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions")),s.addEventListener("mousedown",a=>{a.target==s&&a.preventDefault()});let i=null;for(let a=r.from;a<r.to;a++){let{completion:l,match:c}=e[a],{section:u}=l;if(u){let p=typeof u=="string"?u:u.name;if(p!=i&&(a>r.from||r.from==0))if(i=p,typeof u!="string"&&u.header)s.appendChild(u.header(u));else{let g=s.appendChild(document.createElement("completion-section"));g.textContent=p}}const f=s.appendChild(document.createElement("li"));f.id=n+"-"+a,f.setAttribute("role","option");let h=this.optionClass(l);h&&(f.className=h);for(let p of this.optionContent){let g=p(l,this.view.state,this.view,c);g&&f.appendChild(g)}}return r.from&&s.classList.add("cm-completionListIncompleteTop"),r.to<e.length&&s.classList.add("cm-completionListIncompleteBottom"),s}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function $He(t,e){return n=>new LHe(n,t,e)}function FHe(t,e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),s=n.height/t.offsetHeight;r.top<n.top?t.scrollTop-=(n.top-r.top)/s:r.bottom>n.bottom&&(t.scrollTop+=(r.bottom-n.bottom)/s)}function _K(t){return(t.boost||0)*100+(t.apply?10:0)+(t.info?5:0)+(t.type?1:0)}function BHe(t,e){let n=[],r=null,s=null,i=f=>{n.push(f);let{section:h}=f.completion;if(h){r||(r=[]);let p=typeof h=="string"?h:h.name;r.some(g=>g.name==p)||r.push(typeof h=="string"?{name:p}:h)}},a=e.facet(ji);for(let f of t)if(f.hasResult()){let h=f.result.getMatch;if(f.result.filter===!1)for(let p of f.result.options)i(new jK(p,f.source,h?h(p):[],1e9-n.length));else{let p=e.sliceDoc(f.from,f.to),g,b=a.filterStrict?new OHe(p):new RHe(p);for(let v of f.result.options)if(g=b.match(v.label)){let w=v.displayLabel?h?h(v,g.matched):[]:g.matched,j=g.score+(v.boost||0);if(i(new jK(v,f.source,w,j)),typeof v.section=="object"&&v.section.rank==="dynamic"){let{name:C}=v.section;s||(s=Object.create(null)),s[C]=Math.max(j,s[C]||-1e9)}}}}if(r){let f=Object.create(null),h=0,p=(g,b)=>(g.rank==="dynamic"&&b.rank==="dynamic"?s[b.name]-s[g.name]:0)||(typeof g.rank=="number"?g.rank:1e9)-(typeof b.rank=="number"?b.rank:1e9)||(g.name<b.name?-1:1);for(let g of r.sort(p))h-=1e5,f[g.name]=h;for(let g of n){let{section:b}=g.completion;b&&(g.score+=f[typeof b=="string"?b:b.name])}}let l=[],c=null,u=a.compareCompletions;for(let f of n.sort((h,p)=>p.score-h.score||u(h.completion,p.completion))){let h=f.completion;!c||c.label!=h.label||c.detail!=h.detail||c.type!=null&&h.type!=null&&c.type!=h.type||c.apply!=h.apply||c.boost!=h.boost?l.push(f):_K(f.completion)>_K(c)&&(l[l.length-1]=f),c=f.completion}return l}class Ax{constructor(e,n,r,s,i,a){this.options=e,this.attrs=n,this.tooltip=r,this.timestamp=s,this.selected=i,this.disabled=a}setSelected(e,n){return e==this.selected||e>=this.options.length?this:new Ax(this.options,EK(n,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,n,r,s,i,a){if(s&&!a&&e.some(u=>u.isPending))return s.setDisabled();let l=BHe(e,n);if(!l.length)return s&&e.some(u=>u.isPending)?s.setDisabled():null;let c=n.facet(ji).selectOnOpen?0:-1;if(s&&s.selected!=c&&s.selected!=-1){let u=s.options[s.selected].completion;for(let f=0;f<l.length;f++)if(l[f].completion==u){c=f;break}}return new Ax(l,EK(r,c),{pos:e.reduce((u,f)=>f.hasResult()?Math.min(u,f.from):u,1e8),create:KHe,above:i.aboveCursor},s?s.timestamp:Date.now(),c,!1)}map(e){return new Ax(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ax(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class nS{constructor(e,n,r){this.active=e,this.id=n,this.open=r}static start(){return new nS(HHe,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:n}=e,r=n.facet(ji),i=(r.override||n.languageDataAt("autocomplete",hp(n)).map(IHe)).map(c=>(this.active.find(f=>f.source==c)||new bl(c,this.active.some(f=>f.state!=0)?1:0)).update(e,r));i.length==this.active.length&&i.every((c,u)=>c==this.active[u])&&(i=this.active);let a=this.open,l=e.effects.some(c=>c.is(c9));a&&e.docChanged&&(a=a.map(e.changes)),e.selection||i.some(c=>c.hasResult()&&e.changes.touchesRange(c.from,c.to))||!zHe(i,this.active)||l?a=Ax.build(i,n,this.id,a,r,l):a&&a.disabled&&!i.some(c=>c.isPending)&&(a=null),!a&&i.every(c=>!c.isPending)&&i.some(c=>c.hasResult())&&(i=i.map(c=>c.hasResult()?new bl(c.source,0):c));for(let c of e.effects)c.is(hue)&&(a=a&&a.setSelected(c.value,this.id));return i==this.active&&a==this.open?this:new nS(i,this.id,a)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?UHe:VHe}}function zHe(t,e){if(t==e)return!0;for(let n=0,r=0;;){for(;n<t.length&&!t[n].hasResult();)n++;for(;r<e.length&&!e[r].hasResult();)r++;let s=n==t.length,i=r==e.length;if(s||i)return s==i;if(t[n++].result!=e[r++].result)return!1}}const UHe={"aria-autocomplete":"list"},VHe={};function EK(t,e){let n={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":t};return e>-1&&(n["aria-activedescendant"]=t+"-"+e),n}const HHe=[];function fue(t,e){if(t.isUserEvent("input.complete")){let r=t.annotation(l9);if(r&&e.activateOnCompletion(r))return 12}let n=t.isUserEvent("input.type");return n&&e.activateOnTyping?5:n?1:t.isUserEvent("delete.backward")?2:t.selection?8:t.docChanged?16:0}class bl{constructor(e,n,r=!1){this.source=e,this.state=n,this.explicit=r}hasResult(){return!1}get isPending(){return this.state==1}update(e,n){let r=fue(e,n),s=this;(r&8||r&16&&this.touches(e))&&(s=new bl(s.source,0)),r&4&&s.state==0&&(s=new bl(this.source,1)),s=s.updateFor(e,r);for(let i of e.effects)if(i.is(tS))s=new bl(s.source,1,i.value);else if(i.is(T1))s=new bl(s.source,0);else if(i.is(c9))for(let a of i.value)a.source==s.source&&(s=a);return s}updateFor(e,n){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(hp(e.state))}}class Yx extends bl{constructor(e,n,r,s,i,a){super(e,3,n),this.limit=r,this.result=s,this.from=i,this.to=a}hasResult(){return!0}updateFor(e,n){var r;if(!(n&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let i=e.changes.mapPos(this.from),a=e.changes.mapPos(this.to,1),l=hp(e.state);if(l>a||!s||n&2&&(hp(e.startState)==this.from||l<this.limit))return new bl(this.source,n&4?1:0);let c=e.changes.mapPos(this.limit);return qHe(s.validFor,e.state,i,a)?new Yx(this.source,this.explicit,c,s,i,a):s.update&&(s=s.update(s,i,a,new uue(e.state,l,!1)))?new Yx(this.source,this.explicit,c,s,s.from,(r=s.to)!==null&&r!==void 0?r:hp(e.state)):new bl(this.source,1,this.explicit)}map(e){return e.empty?this:(this.result.map?this.result.map(this.result,e):this.result)?new Yx(this.source,this.explicit,e.mapPos(this.limit),this.result,e.mapPos(this.from),e.mapPos(this.to,1)):new bl(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}}function qHe(t,e,n,r){if(!t)return!1;let s=e.sliceDoc(n,r);return typeof t=="function"?t(s,n,r,e):due(t,!0).test(s)}const c9=pn.define({map(t,e){return t.map(n=>n.map(e))}}),hue=pn.define(),ra=Oi.define({create(){return nS.start()},update(t,e){return t.update(e)},provide:t=>[QL.from(t,e=>e.tooltip),Nt.contentAttributes.from(t,e=>e.attrs)]});function u9(t,e){const n=e.completion.apply||e.completion.label;let r=t.state.field(ra).active.find(s=>s.source==e.source);return r instanceof Yx?(typeof n=="string"?t.dispatch({...MHe(t.state,n,r.from,r.to),annotations:l9.of(e.completion)}):n(t,e.completion,r.from,r.to),!0):!1}const KHe=$He(ra,u9);function u2(t,e="option"){return n=>{let r=n.state.field(ra,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(ji).interactionDelay)return!1;let s=1,i;e=="page"&&(i=Ece(n,r.open.tooltip))&&(s=Math.max(2,Math.floor(i.dom.offsetHeight/i.dom.querySelector("li").offsetHeight)-1));let{length:a}=r.open.options,l=r.open.selected>-1?r.open.selected+s*(t?1:-1):t?0:a-1;return l<0?l=e=="page"?0:a-1:l>=a&&(l=e=="page"?a-1:0),n.dispatch({effects:hue.of(l)}),!0}}const WHe=t=>{let e=t.state.field(ra,!1);return t.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<t.state.facet(ji).interactionDelay?!1:u9(t,e.open.options[e.open.selected])},W3=t=>t.state.field(ra,!1)?(t.dispatch({effects:tS.of(!0)}),!0):!1,GHe=t=>{let e=t.state.field(ra,!1);return!e||!e.active.some(n=>n.state!=0)?!1:(t.dispatch({effects:T1.of(null)}),!0)};class YHe{constructor(e,n){this.active=e,this.context=n,this.time=Date.now(),this.updates=[],this.done=void 0}}const JHe=50,QHe=1e3,ZHe=ti.fromClass(class{constructor(t){this.view=t,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of t.state.field(ra).active)e.isPending&&this.startQuery(e)}update(t){let e=t.state.field(ra),n=t.state.facet(ji);if(!t.selectionSet&&!t.docChanged&&t.startState.field(ra)==e)return;let r=t.transactions.some(i=>{let a=fue(i,n);return a&8||(i.selection||i.docChanged)&&!(a&3)});for(let i=0;i<this.running.length;i++){let a=this.running[i];if(r||a.context.abortOnDocChange&&t.docChanged||a.updates.length+t.transactions.length>JHe&&Date.now()-a.time>QHe){for(let l of a.context.abortListeners)try{l()}catch(c){aa(this.view.state,c)}a.context.abortListeners=null,this.running.splice(i--,1)}else a.updates.push(...t.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),t.transactions.some(i=>i.effects.some(a=>a.is(tS)))&&(this.pendingStart=!0);let s=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(i=>i.isPending&&!this.running.some(a=>a.active.source==i.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let i of t.transactions)i.isUserEvent("input.type")?this.composing=2:this.composing==2&&i.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:t}=this.view,e=t.field(ra);for(let n of e.active)n.isPending&&!this.running.some(r=>r.active.source==n.source)&&this.startQuery(n);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ji).updateSyncTime))}startQuery(t){let{state:e}=this.view,n=hp(e),r=new uue(e,n,t.explicit,this.view),s=new YHe(t,r);this.running.push(s),Promise.resolve(t.source(r)).then(i=>{s.context.aborted||(s.done=i||null,this.scheduleAccept())},i=>{this.view.dispatch({effects:T1.of(null)}),aa(this.view.state,i)})}scheduleAccept(){this.running.every(t=>t.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ji).updateSyncTime))}accept(){var t;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],n=this.view.state.facet(ji),r=this.view.state.field(ra);for(let s=0;s<this.running.length;s++){let i=this.running[s];if(i.done===void 0)continue;if(this.running.splice(s--,1),i.done){let l=hp(i.updates.length?i.updates[0].startState:this.view.state),c=Math.min(l,i.done.from+(i.active.explicit?0:1)),u=new Yx(i.active.source,i.active.explicit,c,i.done,i.done.from,(t=i.done.to)!==null&&t!==void 0?t:l);for(let f of i.updates)u=u.update(f,n);if(u.hasResult()){e.push(u);continue}}let a=r.active.find(l=>l.source==i.active.source);if(a&&a.isPending)if(i.done==null){let l=new bl(i.active.source,0);for(let c of i.updates)l=l.update(c,n);l.isPending||e.push(l)}else this.startQuery(a)}(e.length||r.open&&r.open.disabled)&&this.view.dispatch({effects:c9.of(e)})}},{eventHandlers:{blur(t){let e=this.view.state.field(ra,!1);if(e&&e.tooltip&&this.view.state.facet(ji).closeOnBlur){let n=e.open&&Ece(this.view,e.open.tooltip);(!n||!n.dom.contains(t.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:T1.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:tS.of(!1)}),20),this.composing=0}}}),XHe=typeof navigator=="object"&&/Win/.test(navigator.platform),eqe=um.highest(Nt.domEventHandlers({keydown(t,e){let n=e.state.field(ra,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||t.key.length>1||t.ctrlKey&&!(XHe&&t.altKey)||t.metaKey)return!1;let r=n.open.options[n.open.selected],s=n.active.find(a=>a.source==r.source),i=r.completion.commitCharacters||s.result.commitCharacters;return i&&i.indexOf(t.key)>-1&&u9(e,r),!1}})),mue=Nt.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class tqe{constructor(e,n,r,s){this.field=e,this.line=n,this.from=r,this.to=s}}class d9{constructor(e,n,r){this.field=e,this.from=n,this.to=r}map(e){let n=e.mapPos(this.from,-1,qi.TrackDel),r=e.mapPos(this.to,1,qi.TrackDel);return n==null||r==null?null:new d9(this.field,n,r)}}class f9{constructor(e,n){this.lines=e,this.fieldPositions=n}instantiate(e,n){let r=[],s=[n],i=e.doc.lineAt(n),a=/^\s*/.exec(i.text)[0];for(let c of this.lines){if(r.length){let u=a,f=/^\t*/.exec(c)[0].length;for(let h=0;h<f;h++)u+=e.facet(j5);s.push(n+u.length-f),c=u+c.slice(f)}r.push(c),n+=c.length+1}let l=this.fieldPositions.map(c=>new d9(c.field,s[c.line]+c.from,s[c.line]+c.to));return{text:r,ranges:l}}static parse(e){let n=[],r=[],s=[],i;for(let a of e.split(/\r\n?|\n/)){for(;i=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(a);){let l=i[1]?+i[1]:null,c=i[2]||i[3]||"",u=-1,f=c.replace(/\\[{}]/g,h=>h[1]);for(let h=0;h<n.length;h++)(l!=null?n[h].seq==l:f&&n[h].name==f)&&(u=h);if(u<0){let h=0;for(;h<n.length&&(l==null||n[h].seq!=null&&n[h].seq<l);)h++;n.splice(h,0,{seq:l,name:f}),u=h;for(let p of s)p.field>=u&&p.field++}for(let h of s)if(h.line==r.length&&h.from>i.index){let p=i[2]?3+(i[1]||"").length:2;h.from-=p,h.to-=p}s.push(new tqe(u,r.length,i.index,i.index+f.length)),a=a.slice(0,i.index)+c+a.slice(i.index+i[0].length)}a=a.replace(/\\([{}])/g,(l,c,u)=>{for(let f of s)f.line==r.length&&f.from>u&&(f.from--,f.to--);return c}),r.push(a)}return new f9(r,s)}}let nqe=Qt.widget({widget:new class extends ju{toDOM(){let t=document.createElement("span");return t.className="cm-snippetFieldPosition",t}ignoreEvent(){return!1}}}),rqe=Qt.mark({class:"cm-snippetField"});class S0{constructor(e,n){this.ranges=e,this.active=n,this.deco=Qt.set(e.map(r=>(r.from==r.to?nqe:rqe).range(r.from,r.to)),!0)}map(e){let n=[];for(let r of this.ranges){let s=r.map(e);if(!s)return null;n.push(s)}return new S0(n,this.active)}selectionInsideField(e){return e.ranges.every(n=>this.ranges.some(r=>r.field==this.active&&r.from<=n.from&&r.to>=n.to))}}const Ww=pn.define({map(t,e){return t&&t.map(e)}}),sqe=pn.define(),M1=Oi.define({create(){return null},update(t,e){for(let n of e.effects){if(n.is(Ww))return n.value;if(n.is(sqe)&&t)return new S0(t.ranges,n.value)}return t&&e.docChanged&&(t=t.map(e.changes)),t&&e.selection&&!t.selectionInsideField(e.selection)&&(t=null),t},provide:t=>Nt.decorations.from(t,e=>e?e.deco:Qt.none)});function h9(t,e){return Qe.create(t.filter(n=>n.field==e).map(n=>Qe.range(n.from,n.to)))}function iqe(t){let e=f9.parse(t);return(n,r,s,i)=>{let{text:a,ranges:l}=e.instantiate(n.state,s),{main:c}=n.state.selection,u={changes:{from:s,to:i==c.from?c.to:i,insert:pr.of(a)},scrollIntoView:!0,annotations:r?[l9.of(r),Zs.userEvent.of("input.complete")]:void 0};if(l.length&&(u.selection=h9(l,0)),l.some(f=>f.field>0)){let f=new S0(l,0),h=u.effects=[Ww.of(f)];n.state.field(M1,!1)===void 0&&h.push(pn.appendConfig.of([M1,uqe,dqe,mue]))}n.dispatch(n.state.update(u))}}function pue(t){return({state:e,dispatch:n})=>{let r=e.field(M1,!1);if(!r||t<0&&r.active==0)return!1;let s=r.active+t,i=t>0&&!r.ranges.some(a=>a.field==s+t);return n(e.update({selection:h9(r.ranges,s),effects:Ww.of(i?null:new S0(r.ranges,s)),scrollIntoView:!0})),!0}}const oqe=({state:t,dispatch:e})=>t.field(M1,!1)?(e(t.update({effects:Ww.of(null)})),!0):!1,aqe=pue(1),lqe=pue(-1),cqe=[{key:"Tab",run:aqe,shift:lqe},{key:"Escape",run:oqe}],AK=_t.define({combine(t){return t.length?t[0]:cqe}}),uqe=um.highest(Vw.compute([AK],t=>t.facet(AK)));function wlt(t,e){return{...e,apply:iqe(t)}}const dqe=Nt.domEventHandlers({mousedown(t,e){let n=e.state.field(M1,!1),r;if(!n||(r=e.posAtCoords({x:t.clientX,y:t.clientY}))==null)return!1;let s=n.ranges.find(i=>i.from<=r&&i.to>=r);return!s||s.field==n.active?!1:(e.dispatch({selection:h9(n.ranges,s.field),effects:Ww.of(n.ranges.some(i=>i.field>s.field)?new S0(n.ranges,s.field):null),scrollIntoView:!0}),!0)}}),I1={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Qm=pn.define({map(t,e){let n=e.mapPos(t,-1,qi.TrackAfter);return n??void 0}}),m9=new class extends Bh{};m9.startSide=1;m9.endSide=-1;const gue=Oi.define({create(){return Bn.empty},update(t,e){if(t=t.map(e.changes),e.selection){let n=e.state.doc.lineAt(e.selection.main.head);t=t.update({filter:r=>r>=n.from&&r<=n.to})}for(let n of e.effects)n.is(Qm)&&(t=t.update({add:[m9.range(n.value,n.value+1)]}));return t}});function fqe(){return[mqe,gue]}const G3="()[]{}<>«»»«[]{}";function xue(t){for(let e=0;e<G3.length;e+=2)if(G3.charCodeAt(e)==t)return G3.charAt(e+1);return OL(t<128?t:t+1)}function yue(t,e){return t.languageDataAt("closeBrackets",e)[0]||I1}const hqe=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),mqe=Nt.inputHandler.of((t,e,n,r)=>{if((hqe?t.composing:t.compositionStarted)||t.state.readOnly)return!1;let s=t.state.selection.main;if(r.length>2||r.length==2&&qc(na(r,0))==1||e!=s.from||n!=s.to)return!1;let i=xqe(t.state,r);return i?(t.dispatch(i),!0):!1}),pqe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=yue(t,t.selection.main.head).brackets||I1.brackets,s=null,i=t.changeByRange(a=>{if(a.empty){let l=yqe(t.doc,a.head);for(let c of r)if(c==l&&_5(t.doc,a.head)==xue(na(c,0)))return{changes:{from:a.head-c.length,to:a.head+c.length},range:Qe.cursor(a.head-c.length)}}return{range:s=a}});return s||e(t.update(i,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},gqe=[{key:"Backspace",run:pqe}];function xqe(t,e){let n=yue(t,t.selection.main.head),r=n.brackets||I1.brackets;for(let s of r){let i=xue(na(s,0));if(e==s)return i==s?wqe(t,s,r.indexOf(s+s+s)>-1,n):bqe(t,s,i,n.before||I1.before);if(e==i&&bue(t,t.selection.main.from))return vqe(t,s,i)}return null}function bue(t,e){let n=!1;return t.field(gue).between(0,t.doc.length,r=>{r==e&&(n=!0)}),n}function _5(t,e){let n=t.sliceString(e,e+2);return n.slice(0,qc(na(n,0)))}function yqe(t,e){let n=t.sliceString(e-2,e);return qc(na(n,0))==n.length?n:n.slice(1)}function bqe(t,e,n,r){let s=null,i=t.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:n,from:a.to}],effects:Qm.of(a.to+e.length),range:Qe.range(a.anchor+e.length,a.head+e.length)};let l=_5(t.doc,a.head);return!l||/\s/.test(l)||r.indexOf(l)>-1?{changes:{insert:e+n,from:a.head},effects:Qm.of(a.head+e.length),range:Qe.cursor(a.head+e.length)}:{range:s=a}});return s?null:t.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function vqe(t,e,n){let r=null,s=t.changeByRange(i=>i.empty&&_5(t.doc,i.head)==n?{changes:{from:i.head,to:i.head+n.length,insert:n},range:Qe.cursor(i.head+n.length)}:r={range:i});return r?null:t.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function wqe(t,e,n,r){let s=r.stringPrefixes||I1.stringPrefixes,i=null,a=t.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Qm.of(l.to+e.length),range:Qe.range(l.anchor+e.length,l.head+e.length)};let c=l.head,u=_5(t.doc,c),f;if(u==e){if(TK(t,c))return{changes:{insert:e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)};if(bue(t,c)){let p=n&&t.sliceDoc(c,c+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:c,to:c+p.length,insert:p},range:Qe.cursor(c+p.length)}}}else{if(n&&t.sliceDoc(c-2*e.length,c)==e+e&&(f=MK(t,c-2*e.length,s))>-1&&TK(t,f))return{changes:{insert:e+e+e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)};if(t.charCategorizer(c)(u)!=hs.Word&&MK(t,c,s)>-1&&!kqe(t,c,e,s))return{changes:{insert:e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)}}return{range:i=l}});return i?null:t.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function TK(t,e){let n=Ji(t).resolveInner(e+1);return n.parent&&n.from==e}function kqe(t,e,n,r){let s=Ji(t).resolveInner(e,-1),i=r.reduce((a,l)=>Math.max(a,l.length),0);for(let a=0;a<5;a++){let l=t.sliceDoc(s.from,Math.min(s.to,s.from+n.length+i)),c=l.indexOf(n);if(!c||c>-1&&r.indexOf(l.slice(0,c))>-1){let f=s.firstChild;for(;f&&f.from==s.from&&f.to-f.from>n.length+c;){if(t.sliceDoc(f.to-n.length,f.to)==n)return!1;f=f.firstChild}return!0}let u=s.to==e&&s.parent;if(!u)break;s=u}return!1}function MK(t,e,n){let r=t.charCategorizer(e);if(r(t.sliceDoc(e-1,e))!=hs.Word)return e;for(let s of n){let i=e-s.length;if(t.sliceDoc(i,e)==s&&r(t.sliceDoc(i-1,i))!=hs.Word)return i}return-1}function Cqe(t={}){return[eqe,ra,ji.of(t),ZHe,jqe,mue]}const vue=[{key:"Ctrl-Space",run:W3},{mac:"Alt-`",run:W3},{mac:"Alt-i",run:W3},{key:"Escape",run:GHe},{key:"ArrowDown",run:u2(!0)},{key:"ArrowUp",run:u2(!1)},{key:"PageDown",run:u2(!0,"page")},{key:"PageUp",run:u2(!1,"page")},{key:"Enter",run:WHe}],jqe=um.highest(Vw.computeN([ji],t=>t.facet(ji).defaultKeymap?[vue]:[])),Nqe=t=>{let{state:e}=t,n=e.doc.lineAt(e.selection.main.from),r=g9(t.state,n.from);return r.line?Sqe(t):r.block?Eqe(t):!1};function p9(t,e){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=t(e,n);return s?(r(n.update(s)),!0):!1}}const Sqe=p9(Mqe,0),_qe=p9(wue,0),Eqe=p9((t,e)=>wue(t,e,Tqe(e)),0);function g9(t,e){let n=t.languageDataAt("commentTokens",e,1);return n.length?n[0]:{}}const $b=50;function Aqe(t,{open:e,close:n},r,s){let i=t.sliceDoc(r-$b,r),a=t.sliceDoc(s,s+$b),l=/\s*$/.exec(i)[0].length,c=/^\s*/.exec(a)[0].length,u=i.length-l;if(i.slice(u-e.length,u)==e&&a.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let f,h;s-r<=2*$b?f=h=t.sliceDoc(r,s):(f=t.sliceDoc(r,r+$b),h=t.sliceDoc(s-$b,s));let p=/^\s*/.exec(f)[0].length,g=/\s*$/.exec(h)[0].length,b=h.length-g-n.length;return f.slice(p,p+e.length)==e&&h.slice(b,b+n.length)==n?{open:{pos:r+p+e.length,margin:/\s/.test(f.charAt(p+e.length))?1:0},close:{pos:s-g-n.length,margin:/\s/.test(h.charAt(b-1))?1:0}}:null}function Tqe(t){let e=[];for(let n of t.selection.ranges){let r=t.doc.lineAt(n.from),s=n.to<=r.to?r:t.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:t.doc.lineAt(n.to-1));let i=e.length-1;i>=0&&e[i].to>r.from?e[i].to=s.to:e.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return e}function wue(t,e,n=e.selection.ranges){let r=n.map(i=>g9(e,i.from).block);if(!r.every(i=>i))return null;let s=n.map((i,a)=>Aqe(e,r[a],i.from,i.to));if(t!=2&&!s.every(i=>i))return{changes:e.changes(n.map((i,a)=>s[a]?[]:[{from:i.from,insert:r[a].open+" "},{from:i.to,insert:" "+r[a].close}]))};if(t!=1&&s.some(i=>i)){let i=[];for(let a=0,l;a<s.length;a++)if(l=s[a]){let c=r[a],{open:u,close:f}=l;i.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:f.pos-f.margin,to:f.pos+c.close.length})}return{changes:i}}return null}function Mqe(t,e,n=e.selection.ranges){let r=[],s=-1;e:for(let{from:i,to:a}of n){let l=r.length,c=1e9,u;for(let f=i;f<=a;){let h=e.doc.lineAt(f);if(u==null&&(u=g9(e,h.from).line,!u))continue e;if(h.from>s&&(i==a||a>h.from)){s=h.from;let p=/^\s*/.exec(h.text)[0].length,g=p==h.length,b=h.text.slice(p,p+u.length)==u?p:-1;p<h.text.length&&p<c&&(c=p),r.push({line:h,comment:b,token:u,indent:p,empty:g,single:!1})}f=h.to+1}if(c<1e9)for(let f=l;f<r.length;f++)r[f].indent<r[f].line.text.length&&(r[f].indent=c);r.length==l+1&&(r[l].single=!0)}if(t!=2&&r.some(i=>i.comment<0&&(!i.empty||i.single))){let i=[];for(let{line:l,token:c,indent:u,empty:f,single:h}of r)(h||!f)&&i.push({from:l.from+u,insert:c+" "});let a=e.changes(i);return{changes:a,selection:e.selection.map(a,1)}}else if(t!=1&&r.some(i=>i.comment>=0)){let i=[];for(let{line:a,comment:l,token:c}of r)if(l>=0){let u=a.from+l,f=u+c.length;a.text[f-a.from]==" "&&f++,i.push({from:u,to:f})}return{changes:i}}return null}const oO=ef.define(),Iqe=ef.define(),Rqe=_t.define(),kue=_t.define({combine(t){return Cu(t,{minDepth:100,newGroupDelay:500,joinToEvent:(e,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,n)=>(r,s)=>e(r,s)||n(r,s)})}}),Cue=Oi.define({create(){return eu.empty},update(t,e){let n=e.state.facet(kue),r=e.annotation(oO);if(r){let c=la.fromTransaction(e,r.selection),u=r.side,f=u==0?t.undone:t.done;return c?f=rS(f,f.length,n.minDepth,c):f=Sue(f,e.startState.selection),new eu(u==0?r.rest:f,u==0?f:r.rest)}let s=e.annotation(Iqe);if((s=="full"||s=="before")&&(t=t.isolate()),e.annotation(Zs.addToHistory)===!1)return e.changes.empty?t:t.addMapping(e.changes.desc);let i=la.fromTransaction(e),a=e.annotation(Zs.time),l=e.annotation(Zs.userEvent);return i?t=t.addChanges(i,a,l,n,e):e.selection&&(t=t.addSelection(e.startState.selection,a,l,n.newGroupDelay)),(s=="full"||s=="after")&&(t=t.isolate()),t},toJSON(t){return{done:t.done.map(e=>e.toJSON()),undone:t.undone.map(e=>e.toJSON())}},fromJSON(t){return new eu(t.done.map(la.fromJSON),t.undone.map(la.fromJSON))}});function Oqe(t={}){return[Cue,kue.of(t),Nt.domEventHandlers({beforeinput(e,n){let r=e.inputType=="historyUndo"?jue:e.inputType=="historyRedo"?aO:null;return r?(e.preventDefault(),r(n)):!1}})]}function E5(t,e){return function({state:n,dispatch:r}){if(!e&&n.readOnly)return!1;let s=n.field(Cue,!1);if(!s)return!1;let i=s.pop(t,n,e);return i?(r(i),!0):!1}}const jue=E5(0,!1),aO=E5(1,!1),Dqe=E5(0,!0),Pqe=E5(1,!0);class la{constructor(e,n,r,s,i){this.changes=e,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=i}setSelAfter(e){return new la(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,n,r;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new la(e.changes&&oi.fromJSON(e.changes),[],e.mapped&&iu.fromJSON(e.mapped),e.startSelection&&Qe.fromJSON(e.startSelection),e.selectionsAfter.map(Qe.fromJSON))}static fromTransaction(e,n){let r=vl;for(let s of e.startState.facet(Rqe)){let i=s(e);i.length&&(r=r.concat(i))}return!r.length&&e.changes.empty?null:new la(e.changes.invert(e.startState.doc),r,void 0,n||e.startState.selection,vl)}static selection(e){return new la(void 0,vl,void 0,void 0,e)}}function rS(t,e,n,r){let s=e+1>n+20?e-n-1:0,i=t.slice(s,e);return i.push(r),i}function Lqe(t,e){let n=[],r=!1;return t.iterChangedRanges((s,i)=>n.push(s,i)),e.iterChangedRanges((s,i,a,l)=>{for(let c=0;c<n.length;){let u=n[c++],f=n[c++];l>=u&&a<=f&&(r=!0)}}),r}function $qe(t,e){return t.ranges.length==e.ranges.length&&t.ranges.filter((n,r)=>n.empty!=e.ranges[r].empty).length===0}function Nue(t,e){return t.length?e.length?t.concat(e):t:e}const vl=[],Fqe=200;function Sue(t,e){if(t.length){let n=t[t.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-Fqe));return r.length&&r[r.length-1].eq(e)?t:(r.push(e),rS(t,t.length-1,1e9,n.setSelAfter(r)))}else return[la.selection([e])]}function Bqe(t){let e=t[t.length-1],n=t.slice();return n[t.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),n}function Y3(t,e){if(!t.length)return t;let n=t.length,r=vl;for(;n;){let s=zqe(t[n-1],e,r);if(s.changes&&!s.changes.empty||s.effects.length){let i=t.slice(0,n);return i[n-1]=s,i}else e=s.mapped,n--,r=s.selectionsAfter}return r.length?[la.selection(r)]:vl}function zqe(t,e,n){let r=Nue(t.selectionsAfter.length?t.selectionsAfter.map(l=>l.map(e)):vl,n);if(!t.changes)return la.selection(r);let s=t.changes.map(e),i=e.mapDesc(t.changes,!0),a=t.mapped?t.mapped.composeDesc(i):i;return new la(s,pn.mapEffects(t.effects,e),a,t.startSelection.map(i),r)}const Uqe=/^(input\.type|delete)($|\.)/;class eu{constructor(e,n,r=0,s=void 0){this.done=e,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new eu(this.done,this.undone):this}addChanges(e,n,r,s,i){let a=this.done,l=a[a.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!r||Uqe.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(i,Lqe(l.changes,e.changes))||r=="input.type.compose")?a=rS(a,a.length-1,s.minDepth,new la(e.changes.compose(l.changes),Nue(pn.mapEffects(e.effects,l.changes),l.effects),l.mapped,l.startSelection,vl)):a=rS(a,a.length,s.minDepth,e),new eu(a,vl,n,r)}addSelection(e,n,r,s){let i=this.done.length?this.done[this.done.length-1].selectionsAfter:vl;return i.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&$qe(i[i.length-1],e)?this:new eu(Sue(this.done,e),this.undone,n,r)}addMapping(e){return new eu(Y3(this.done,e),Y3(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,n,r){let s=e==0?this.done:this.undone;if(s.length==0)return null;let i=s[s.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):n.selection);if(r&&i.selectionsAfter.length)return n.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:oO.of({side:e,rest:Bqe(s),selection:a}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(i.changes){let l=s.length==1?vl:s.slice(0,s.length-1);return i.mapped&&(l=Y3(l,i.mapped)),n.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:oO.of({side:e,rest:l,selection:a}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}}eu.empty=new eu(vl,vl);const Vqe=[{key:"Mod-z",run:jue,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:aO,preventDefault:!0},{linux:"Ctrl-Shift-z",run:aO,preventDefault:!0},{key:"Mod-u",run:Dqe,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Pqe,preventDefault:!0}];function _0(t,e){return Qe.create(t.ranges.map(e),t.mainIndex)}function kc(t,e){return t.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function Cc({state:t,dispatch:e},n){let r=_0(t.selection,n);return r.eq(t.selection,!0)?!1:(e(kc(t,r)),!0)}function A5(t,e){return Qe.cursor(e?t.to:t.from)}function _ue(t,e){return Cc(t,n=>n.empty?t.moveByChar(n,e):A5(n,e))}function yo(t){return t.textDirectionAt(t.state.selection.main.head)==Kr.LTR}const Eue=t=>_ue(t,!yo(t)),Aue=t=>_ue(t,yo(t));function Tue(t,e){return Cc(t,n=>n.empty?t.moveByGroup(n,e):A5(n,e))}const Hqe=t=>Tue(t,!yo(t)),qqe=t=>Tue(t,yo(t));function Kqe(t,e,n){if(e.type.prop(n))return!0;let r=e.to-e.from;return r&&(r>2||/[^\s,.;:]/.test(t.sliceDoc(e.from,e.to)))||e.firstChild}function T5(t,e,n){let r=Ji(t).resolveInner(e.head),s=n?Ln.closedBy:Ln.openedBy;for(let c=e.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Kqe(t,u,s)?r=u:c=n?u.to:u.from}let i=r.type.prop(s),a,l;return i&&(a=n?Xc(t,r.from,1):Xc(t,r.to,-1))&&a.matched?l=n?a.end.to:a.end.from:l=n?r.to:r.from,Qe.cursor(l,n?-1:1)}const Wqe=t=>Cc(t,e=>T5(t.state,e,!yo(t))),Gqe=t=>Cc(t,e=>T5(t.state,e,yo(t)));function Mue(t,e){return Cc(t,n=>{if(!n.empty)return A5(n,e);let r=t.moveVertically(n,e);return r.head!=n.head?r:t.moveToLineBoundary(n,e)})}const Iue=t=>Mue(t,!1),Rue=t=>Mue(t,!0);function Oue(t){let e=t.scrollDOM.clientHeight<t.scrollDOM.scrollHeight-2,n=0,r=0,s;if(e){for(let i of t.state.facet(Nt.scrollMargins)){let a=i(t);a!=null&&a.top&&(n=Math.max(a==null?void 0:a.top,n)),a!=null&&a.bottom&&(r=Math.max(a==null?void 0:a.bottom,r))}s=t.scrollDOM.clientHeight-n-r}else s=(t.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:e,height:Math.max(t.defaultLineHeight,s-5)}}function Due(t,e){let n=Oue(t),{state:r}=t,s=_0(r.selection,a=>a.empty?t.moveVertically(a,e,n.height):A5(a,e));if(s.eq(r.selection))return!1;let i;if(n.selfScroll){let a=t.coordsAtPos(r.selection.main.head),l=t.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;a&&a.top>c&&a.bottom<u&&(i=Nt.scrollIntoView(s.main.head,{y:"start",yMargin:a.top-c}))}return t.dispatch(kc(r,s),{effects:i}),!0}const IK=t=>Due(t,!1),lO=t=>Due(t,!0);function dm(t,e,n){let r=t.lineBlockAt(e.head),s=t.moveToLineBoundary(e,n);if(s.head==e.head&&s.head!=(n?r.to:r.from)&&(s=t.moveToLineBoundary(e,n,!1)),!n&&s.head==r.from&&r.length){let i=/^\s*/.exec(t.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;i&&e.head!=r.from+i&&(s=Qe.cursor(r.from+i))}return s}const Yqe=t=>Cc(t,e=>dm(t,e,!0)),Jqe=t=>Cc(t,e=>dm(t,e,!1)),Qqe=t=>Cc(t,e=>dm(t,e,!yo(t))),Zqe=t=>Cc(t,e=>dm(t,e,yo(t))),Xqe=t=>Cc(t,e=>Qe.cursor(t.lineBlockAt(e.head).from,1)),eKe=t=>Cc(t,e=>Qe.cursor(t.lineBlockAt(e.head).to,-1));function tKe(t,e,n){let r=!1,s=_0(t.selection,i=>{let a=Xc(t,i.head,-1)||Xc(t,i.head,1)||i.head>0&&Xc(t,i.head-1,1)||i.head<t.doc.length&&Xc(t,i.head+1,-1);if(!a||!a.end)return i;r=!0;let l=a.start.from==i.head?a.end.to:a.end.from;return Qe.cursor(l)});return r?(e(kc(t,s)),!0):!1}const nKe=({state:t,dispatch:e})=>tKe(t,e);function Rl(t,e){let n=_0(t.state.selection,r=>{let s=e(r);return Qe.range(r.anchor,s.head,s.goalColumn,s.bidiLevel||void 0)});return n.eq(t.state.selection)?!1:(t.dispatch(kc(t.state,n)),!0)}function Pue(t,e){return Rl(t,n=>t.moveByChar(n,e))}const Lue=t=>Pue(t,!yo(t)),$ue=t=>Pue(t,yo(t));function Fue(t,e){return Rl(t,n=>t.moveByGroup(n,e))}const rKe=t=>Fue(t,!yo(t)),sKe=t=>Fue(t,yo(t)),iKe=t=>Rl(t,e=>T5(t.state,e,!yo(t))),oKe=t=>Rl(t,e=>T5(t.state,e,yo(t)));function Bue(t,e){return Rl(t,n=>t.moveVertically(n,e))}const zue=t=>Bue(t,!1),Uue=t=>Bue(t,!0);function Vue(t,e){return Rl(t,n=>t.moveVertically(n,e,Oue(t).height))}const RK=t=>Vue(t,!1),OK=t=>Vue(t,!0),aKe=t=>Rl(t,e=>dm(t,e,!0)),lKe=t=>Rl(t,e=>dm(t,e,!1)),cKe=t=>Rl(t,e=>dm(t,e,!yo(t))),uKe=t=>Rl(t,e=>dm(t,e,yo(t))),dKe=t=>Rl(t,e=>Qe.cursor(t.lineBlockAt(e.head).from)),fKe=t=>Rl(t,e=>Qe.cursor(t.lineBlockAt(e.head).to)),DK=({state:t,dispatch:e})=>(e(kc(t,{anchor:0})),!0),PK=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.doc.length})),!0),LK=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.selection.main.anchor,head:0})),!0),$K=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.selection.main.anchor,head:t.doc.length})),!0),hKe=({state:t,dispatch:e})=>(e(t.update({selection:{anchor:0,head:t.doc.length},userEvent:"select"})),!0),mKe=({state:t,dispatch:e})=>{let n=M5(t).map(({from:r,to:s})=>Qe.range(r,Math.min(s+1,t.doc.length)));return e(t.update({selection:Qe.create(n),userEvent:"select"})),!0},pKe=({state:t,dispatch:e})=>{let n=_0(t.selection,r=>{let s=Ji(t),i=s.resolveStack(r.from,1);if(r.empty){let a=s.resolveStack(r.from,-1);a.node.from>=i.node.from&&a.node.to<=i.node.to&&(i=a)}for(let a=i;a;a=a.next){let{node:l}=a;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&a.next)return Qe.range(l.to,l.from)}return r});return n.eq(t.selection)?!1:(e(kc(t,n)),!0)};function Hue(t,e){let{state:n}=t,r=n.selection,s=n.selection.ranges.slice();for(let i of n.selection.ranges){let a=n.doc.lineAt(i.head);if(e?a.to<t.state.doc.length:a.from>0)for(let l=i;;){let c=t.moveVertically(l,e);if(c.head<a.from||c.head>a.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(t.dispatch(kc(n,Qe.create(s,s.length-1))),!0)}const gKe=t=>Hue(t,!1),xKe=t=>Hue(t,!0),yKe=({state:t,dispatch:e})=>{let n=t.selection,r=null;return n.ranges.length>1?r=Qe.create([n.main]):n.main.empty||(r=Qe.create([Qe.cursor(n.main.head)])),r?(e(kc(t,r)),!0):!1};function Gw(t,e){if(t.state.readOnly)return!1;let n="delete.selection",{state:r}=t,s=r.changeByRange(i=>{let{from:a,to:l}=i;if(a==l){let c=e(i);c<a?(n="delete.backward",c=d2(t,c,!1)):c>a&&(n="delete.forward",c=d2(t,c,!0)),a=Math.min(a,c),l=Math.max(l,c)}else a=d2(t,a,!1),l=d2(t,l,!0);return a==l?{range:i}:{changes:{from:a,to:l},range:Qe.cursor(a,a<i.head?-1:1)}});return s.changes.empty?!1:(t.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Nt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function d2(t,e,n){if(t instanceof Nt)for(let r of t.state.facet(Nt.atomicRanges).map(s=>s(t)))r.between(e,e,(s,i)=>{s<e&&i>e&&(e=n?i:s)});return e}const que=(t,e,n)=>Gw(t,r=>{let s=r.from,{state:i}=t,a=i.doc.lineAt(s),l,c;if(n&&!e&&s>a.from&&s<a.from+200&&!/[^ \t]/.test(l=a.text.slice(0,s-a.from))){if(l[l.length-1]==" ")return s-1;let u=N0(l,i.tabSize),f=u%Yp(i)||Yp(i);for(let h=0;h<f&&l[l.length-1-h]==" ";h++)s--;c=s}else c=Ii(a.text,s-a.from,e,e)+a.from,c==s&&a.number!=(e?i.doc.lines:1)?c+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(a.text.slice(c-a.from,s-a.from))&&(c=Ii(a.text,c-a.from,!1,!1)+a.from);return c}),cO=t=>que(t,!1,!0),Kue=t=>que(t,!0,!1),Wue=(t,e)=>Gw(t,n=>{let r=n.head,{state:s}=t,i=s.doc.lineAt(r),a=s.charCategorizer(r);for(let l=null;;){if(r==(e?i.to:i.from)){r==n.head&&i.number!=(e?s.doc.lines:1)&&(r+=e?1:-1);break}let c=Ii(i.text,r-i.from,e)+i.from,u=i.text.slice(Math.min(r,c)-i.from,Math.max(r,c)-i.from),f=a(u);if(l!=null&&f!=l)break;(u!=" "||r!=n.head)&&(l=f),r=c}return r}),Gue=t=>Wue(t,!1),bKe=t=>Wue(t,!0),vKe=t=>Gw(t,e=>{let n=t.lineBlockAt(e.head).to;return e.head<n?n:Math.min(t.state.doc.length,e.head+1)}),wKe=t=>Gw(t,e=>{let n=t.moveToLineBoundary(e,!1).head;return e.head>n?n:Math.max(0,e.head-1)}),kKe=t=>Gw(t,e=>{let n=t.moveToLineBoundary(e,!0).head;return e.head<n?n:Math.min(t.state.doc.length,e.head+1)}),CKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=t.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:pr.of(["",""])},range:Qe.cursor(r.from)}));return e(t.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},jKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=t.changeByRange(r=>{if(!r.empty||r.from==0||r.from==t.doc.length)return{range:r};let s=r.from,i=t.doc.lineAt(s),a=s==i.from?s-1:Ii(i.text,s-i.from,!1)+i.from,l=s==i.to?s+1:Ii(i.text,s-i.from,!0)+i.from;return{changes:{from:a,to:l,insert:t.doc.slice(s,l).append(t.doc.slice(a,s))},range:Qe.cursor(l)}});return n.changes.empty?!1:(e(t.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function M5(t){let e=[],n=-1;for(let r of t.selection.ranges){let s=t.doc.lineAt(r.from),i=t.doc.lineAt(r.to);if(!r.empty&&r.to==i.from&&(i=t.doc.lineAt(r.to-1)),n>=s.number){let a=e[e.length-1];a.to=i.to,a.ranges.push(r)}else e.push({from:s.from,to:i.to,ranges:[r]});n=i.number+1}return e}function Yue(t,e,n){if(t.readOnly)return!1;let r=[],s=[];for(let i of M5(t)){if(n?i.to==t.doc.length:i.from==0)continue;let a=t.doc.lineAt(n?i.to+1:i.from-1),l=a.length+1;if(n){r.push({from:i.to,to:a.to},{from:i.from,insert:a.text+t.lineBreak});for(let c of i.ranges)s.push(Qe.range(Math.min(t.doc.length,c.anchor+l),Math.min(t.doc.length,c.head+l)))}else{r.push({from:a.from,to:i.from},{from:i.to,insert:t.lineBreak+a.text});for(let c of i.ranges)s.push(Qe.range(c.anchor-l,c.head-l))}}return r.length?(e(t.update({changes:r,scrollIntoView:!0,selection:Qe.create(s,t.selection.mainIndex),userEvent:"move.line"})),!0):!1}const NKe=({state:t,dispatch:e})=>Yue(t,e,!1),SKe=({state:t,dispatch:e})=>Yue(t,e,!0);function Jue(t,e,n){if(t.readOnly)return!1;let r=[];for(let i of M5(t))n?r.push({from:i.from,insert:t.doc.slice(i.from,i.to)+t.lineBreak}):r.push({from:i.to,insert:t.lineBreak+t.doc.slice(i.from,i.to)});let s=t.changes(r);return e(t.update({changes:s,selection:t.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const _Ke=({state:t,dispatch:e})=>Jue(t,e,!1),EKe=({state:t,dispatch:e})=>Jue(t,e,!0),AKe=t=>{if(t.state.readOnly)return!1;let{state:e}=t,n=e.changes(M5(e).map(({from:s,to:i})=>(s>0?s--:i<e.doc.length&&i++,{from:s,to:i}))),r=_0(e.selection,s=>{let i;if(t.lineWrapping){let a=t.lineBlockAt(s.head),l=t.coordsAtPos(s.head,s.assoc||1);l&&(i=a.bottom+t.documentTop-l.bottom+t.defaultLineHeight/2)}return t.moveVertically(s,!0,i)}).map(n);return t.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function TKe(t,e){if(/\(\)|\[\]|\{\}/.test(t.sliceDoc(e-1,e+1)))return{from:e,to:e};let n=Ji(t).resolveInner(e),r=n.childBefore(e),s=n.childAfter(e),i;return r&&s&&r.to<=e&&s.from>=e&&(i=r.type.prop(Ln.closedBy))&&i.indexOf(s.name)>-1&&t.doc.lineAt(r.to).from==t.doc.lineAt(s.from).from&&!/\S/.test(t.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const FK=Que(!1),MKe=Que(!0);function Que(t){return({state:e,dispatch:n})=>{if(e.readOnly)return!1;let r=e.changeByRange(s=>{let{from:i,to:a}=s,l=e.doc.lineAt(i),c=!t&&i==a&&TKe(e,i);t&&(i=a=(a<=l.to?l:e.doc.lineAt(a)).to);let u=new N5(e,{simulateBreak:i,simulateDoubleBreak:!!c}),f=r9(u,i);for(f==null&&(f=N0(/^\s*/.exec(e.doc.lineAt(i).text)[0],e.tabSize));a<l.to&&/\s/.test(l.text[a-l.from]);)a++;c?{from:i,to:a}=c:i>l.from&&i<l.from+100&&!/\S/.test(l.text.slice(0,i))&&(i=l.from);let h=["",E1(e,f)];return c&&h.push(E1(e,u.lineIndent(l.from,-1))),{changes:{from:i,to:a,insert:pr.of(h)},range:Qe.cursor(i+1+h[1].length)}});return n(e.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function x9(t,e){let n=-1;return t.changeByRange(r=>{let s=[];for(let a=r.from;a<=r.to;){let l=t.doc.lineAt(a);l.number>n&&(r.empty||r.to>l.from)&&(e(l,s,r),n=l.number),a=l.to+1}let i=t.changes(s);return{changes:s,range:Qe.range(i.mapPos(r.anchor,1),i.mapPos(r.head,1))}})}const IKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=Object.create(null),r=new N5(t,{overrideIndentation:i=>{let a=n[i];return a??-1}}),s=x9(t,(i,a,l)=>{let c=r9(r,i.from);if(c==null)return;/\S/.test(i.text)||(c=0);let u=/^\s*/.exec(i.text)[0],f=E1(t,c);(u!=f||l.from<i.from+u.length)&&(n[i.from]=c,a.push({from:i.from,to:i.from+u.length,insert:f}))});return s.changes.empty||e(t.update(s,{userEvent:"indent"})),!0},Zue=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(x9(t,(n,r)=>{r.push({from:n.from,insert:t.facet(j5)})}),{userEvent:"input.indent"})),!0),Xue=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(x9(t,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let i=N0(s,t.tabSize),a=0,l=E1(t,Math.max(0,i-Yp(t)));for(;a<s.length&&a<l.length&&s.charCodeAt(a)==l.charCodeAt(a);)a++;r.push({from:n.from+a,to:n.from+s.length,insert:l.slice(a)})}),{userEvent:"delete.dedent"})),!0),RKe=t=>(t.setTabFocusMode(),!0),OKe=[{key:"Ctrl-b",run:Eue,shift:Lue,preventDefault:!0},{key:"Ctrl-f",run:Aue,shift:$ue},{key:"Ctrl-p",run:Iue,shift:zue},{key:"Ctrl-n",run:Rue,shift:Uue},{key:"Ctrl-a",run:Xqe,shift:dKe},{key:"Ctrl-e",run:eKe,shift:fKe},{key:"Ctrl-d",run:Kue},{key:"Ctrl-h",run:cO},{key:"Ctrl-k",run:vKe},{key:"Ctrl-Alt-h",run:Gue},{key:"Ctrl-o",run:CKe},{key:"Ctrl-t",run:jKe},{key:"Ctrl-v",run:lO}],DKe=[{key:"ArrowLeft",run:Eue,shift:Lue,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Hqe,shift:rKe,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Qqe,shift:cKe,preventDefault:!0},{key:"ArrowRight",run:Aue,shift:$ue,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:qqe,shift:sKe,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Zqe,shift:uKe,preventDefault:!0},{key:"ArrowUp",run:Iue,shift:zue,preventDefault:!0},{mac:"Cmd-ArrowUp",run:DK,shift:LK},{mac:"Ctrl-ArrowUp",run:IK,shift:RK},{key:"ArrowDown",run:Rue,shift:Uue,preventDefault:!0},{mac:"Cmd-ArrowDown",run:PK,shift:$K},{mac:"Ctrl-ArrowDown",run:lO,shift:OK},{key:"PageUp",run:IK,shift:RK},{key:"PageDown",run:lO,shift:OK},{key:"Home",run:Jqe,shift:lKe,preventDefault:!0},{key:"Mod-Home",run:DK,shift:LK},{key:"End",run:Yqe,shift:aKe,preventDefault:!0},{key:"Mod-End",run:PK,shift:$K},{key:"Enter",run:FK,shift:FK},{key:"Mod-a",run:hKe},{key:"Backspace",run:cO,shift:cO,preventDefault:!0},{key:"Delete",run:Kue,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Gue,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:bKe,preventDefault:!0},{mac:"Mod-Backspace",run:wKe,preventDefault:!0},{mac:"Mod-Delete",run:kKe,preventDefault:!0}].concat(OKe.map(t=>({mac:t.key,run:t.run,shift:t.shift}))),PKe=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Wqe,shift:iKe},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Gqe,shift:oKe},{key:"Alt-ArrowUp",run:NKe},{key:"Shift-Alt-ArrowUp",run:_Ke},{key:"Alt-ArrowDown",run:SKe},{key:"Shift-Alt-ArrowDown",run:EKe},{key:"Mod-Alt-ArrowUp",run:gKe},{key:"Mod-Alt-ArrowDown",run:xKe},{key:"Escape",run:yKe},{key:"Mod-Enter",run:MKe},{key:"Alt-l",mac:"Ctrl-l",run:mKe},{key:"Mod-i",run:pKe,preventDefault:!0},{key:"Mod-[",run:Xue},{key:"Mod-]",run:Zue},{key:"Mod-Alt-\\",run:IKe},{key:"Shift-Mod-k",run:AKe},{key:"Shift-Mod-\\",run:nKe},{key:"Mod-/",run:Nqe},{key:"Alt-A",run:_qe},{key:"Ctrl-m",mac:"Shift-Alt-m",run:RKe}].concat(DKe),LKe={key:"Tab",run:Zue,shift:Xue};function $Ke(t,e,n,r){const s=fu(fs),i=Oa(Poe),a=Y.useRef(null),{lexicalNode:l}=xR(),c=Y.useRef(!1),u=Y.useRef(!1),f=Y.useCallback(()=>{i({editorType:e,rootNode:l,editorRef:a.current})},[e,l,i]),h=Y.useCallback(p=>{var g,b,v,w,j,C;if(p.key==="ArrowDown"){const N=(b=(g=a.current)==null?void 0:g.getCodemirror())==null?void 0:b.state;if(N){const S=N.doc.length,T=N.selection.ranges[0].to;S===T&&(c.current?(s==null||s.update(()=>{var _,A;const M=su(t);M.getNextSibling()?((A=(_=a.current)==null?void 0:_.getCodemirror())==null||A.contentDOM.blur(),M.selectNext()):M.insertAfter(gs())}),c.current=!1):c.current=!0)}}else if(p.key==="ArrowUp"){const N=(w=(v=a.current)==null?void 0:v.getCodemirror())==null?void 0:w.state;N&&N.selection.ranges[0].from===0&&(u.current?(s==null||s.update(()=>{var T,_;const A=su(t);A.getPreviousSibling()&&((_=(T=a.current)==null?void 0:T.getCodemirror())==null||_.contentDOM.blur(),A.selectPrevious())}),u.current=!1):u.current=!0)}else if(p.key==="Enter")p.stopPropagation();else if(p.key==="Backspace"||p.key==="Delete"){const N=(C=(j=a.current)==null?void 0:j.getCodemirror())==null?void 0:C.state;(N==null?void 0:N.doc.length)===0&&(s==null||s.update(()=>{su(t).remove()}))}},[s,t]);return Y.useEffect(()=>{const p=a.current;return setTimeout(()=>{var g,b;(g=p==null?void 0:p.getCodemirror())==null||g.contentDOM.addEventListener("focus",f),(b=p==null?void 0:p.getCodemirror())==null||b.contentDOM.addEventListener("keydown",h)},300),()=>{var g,b;(g=p==null?void 0:p.getCodemirror())==null||g.contentDOM.removeEventListener("focus",f),(b=p==null?void 0:p.getCodemirror())==null||b.contentDOM.removeEventListener("keydown",h)}},[a,f,h,n]),Y.useEffect(()=>{r.subscribe(()=>{var p,g;(g=(p=a.current)==null?void 0:p.getCodemirror())==null||g.focus(),f()})},[r,a,t,f]),a}function et(t){return new $Ve(i9.define(t))}function If(t){return ze(()=>import("./index-C0eJUuhF.js"),__vite__mapDeps([0,1])).then(e=>e.sql({dialect:e[t]}))}const FKe=[Pe.of({name:"C",extensions:["c","h","ino"],load(){return ze(()=>import("./index-Bw34OrlI.js"),__vite__mapDeps([2,1])).then(t=>t.cpp())}}),Pe.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return ze(()=>import("./index-Bw34OrlI.js"),__vite__mapDeps([2,1])).then(t=>t.cpp())}}),Pe.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return If("Cassandra")}}),Pe.of({name:"CSS",extensions:["css"],load(){return ze(()=>import("./index-samEGEZm.js"),__vite__mapDeps([3,1])).then(t=>t.css())}}),Pe.of({name:"Go",extensions:["go"],load(){return ze(()=>import("./index-IWMCpuKI.js"),__vite__mapDeps([4,1])).then(t=>t.go())}}),Pe.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return ze(()=>import("./index-D2T0iIrx.js"),__vite__mapDeps([5,1,3,6])).then(t=>t.html())}}),Pe.of({name:"Java",extensions:["java"],load(){return ze(()=>import("./index-CE0NQXcf.js"),__vite__mapDeps([7,1])).then(t=>t.java())}}),Pe.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return ze(()=>import("./index-ChbF-4_t.js"),__vite__mapDeps([6,1])).then(t=>t.javascript())}}),Pe.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return ze(()=>import("./index-lCZF_3wT.js"),__vite__mapDeps([8,5,1,3,6])).then(t=>t.jinja())}}),Pe.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return ze(()=>import("./index-CDX_vTiv.js"),__vite__mapDeps([9,1])).then(t=>t.json())}}),Pe.of({name:"JSX",extensions:["jsx"],load(){return ze(()=>import("./index-ChbF-4_t.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({jsx:!0}))}}),Pe.of({name:"LESS",extensions:["less"],load(){return ze(()=>import("./index-DErU01-2.js"),__vite__mapDeps([10,3,1])).then(t=>t.less())}}),Pe.of({name:"Liquid",extensions:["liquid"],load(){return ze(()=>import("./index-CoA6TNOP.js"),__vite__mapDeps([11,5,1,3,6])).then(t=>t.liquid())}}),Pe.of({name:"MariaDB SQL",load(){return If("MariaSQL")}}),Pe.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return ze(()=>import("./index-BYNiNvTL.js"),__vite__mapDeps([12,5,1,3,6])).then(t=>t.markdown())}}),Pe.of({name:"MS SQL",load(){return If("MSSQL")}}),Pe.of({name:"MySQL",load(){return If("MySQL")}}),Pe.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return ze(()=>import("./index-DM_ccx3O.js"),__vite__mapDeps([13,1,5,3,6])).then(t=>t.php())}}),Pe.of({name:"PLSQL",extensions:["pls"],load(){return If("PLSQL")}}),Pe.of({name:"PostgreSQL",load(){return If("PostgreSQL")}}),Pe.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return ze(()=>import("./index-0wF5nWs7.js"),__vite__mapDeps([14,1])).then(t=>t.python())}}),Pe.of({name:"Rust",extensions:["rs"],load(){return ze(()=>import("./index-DnxtFtFx.js"),__vite__mapDeps([15,1])).then(t=>t.rust())}}),Pe.of({name:"Sass",extensions:["sass"],load(){return ze(()=>import("./index-T3Zr4GMI.js"),__vite__mapDeps([16,1,3])).then(t=>t.sass({indented:!0}))}}),Pe.of({name:"SCSS",extensions:["scss"],load(){return ze(()=>import("./index-T3Zr4GMI.js"),__vite__mapDeps([16,1,3])).then(t=>t.sass())}}),Pe.of({name:"SQL",extensions:["sql"],load(){return If("StandardSQL")}}),Pe.of({name:"SQLite",load(){return If("SQLite")}}),Pe.of({name:"TSX",extensions:["tsx"],load(){return ze(()=>import("./index-ChbF-4_t.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({jsx:!0,typescript:!0}))}}),Pe.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return ze(()=>import("./index-ChbF-4_t.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({typescript:!0}))}}),Pe.of({name:"WebAssembly",extensions:["wat","wast"],load(){return ze(()=>import("./index-CPbbQZoC.js"),__vite__mapDeps([17,1])).then(t=>t.wast())}}),Pe.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return ze(()=>import("./index-BYLf-CL8.js"),__vite__mapDeps([18,1])).then(t=>t.xml())}}),Pe.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return ze(()=>import("./index-BpI5gD12.js"),__vite__mapDeps([19,1])).then(t=>t.yaml())}}),Pe.of({name:"APL",extensions:["dyalog","apl"],load(){return ze(()=>import("./apl-B4CMkyY2.js"),[]).then(t=>et(t.apl))}}),Pe.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return ze(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(t=>et(t.asciiArmor))}}),Pe.of({name:"ASN.1",extensions:["asn","asn1"],load(){return ze(()=>import("./asn1-EdZsLKOL.js"),[]).then(t=>et(t.asn1({})))}}),Pe.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return ze(()=>import("./asterisk-B-8jnY81.js"),[]).then(t=>et(t.asterisk))}}),Pe.of({name:"Brainfuck",extensions:["b","bf"],load(){return ze(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(t=>et(t.brainfuck))}}),Pe.of({name:"Cobol",extensions:["cob","cpy"],load(){return ze(()=>import("./cobol-CWcv1MsR.js"),[]).then(t=>et(t.cobol))}}),Pe.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.csharp))}}),Pe.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"ClojureScript",extensions:["cljs"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return ze(()=>import("./css-BnMrqG3P.js"),[]).then(t=>et(t.gss))}}),Pe.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return ze(()=>import("./cmake-BQqOBYOt.js"),[]).then(t=>et(t.cmake))}}),Pe.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return ze(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(t=>et(t.coffeeScript))}}),Pe.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return ze(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(t=>et(t.commonLisp))}}),Pe.of({name:"Cypher",extensions:["cyp","cypher"],load(){return ze(()=>import("./cypher-C_CwsFkJ.js"),[]).then(t=>et(t.cypher))}}),Pe.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return ze(()=>import("./python-BuPzkPfP.js"),[]).then(t=>et(t.cython))}}),Pe.of({name:"Crystal",extensions:["cr"],load(){return ze(()=>import("./crystal-SjHAIU92.js"),[]).then(t=>et(t.crystal))}}),Pe.of({name:"D",extensions:["d"],load(){return ze(()=>import("./d-pRatUO7H.js"),[]).then(t=>et(t.d))}}),Pe.of({name:"Dart",extensions:["dart"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.dart))}}),Pe.of({name:"diff",extensions:["diff","patch"],load(){return ze(()=>import("./diff-DbItnlRl.js"),[]).then(t=>et(t.diff))}}),Pe.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return ze(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([20,21])).then(t=>et(t.dockerFile))}}),Pe.of({name:"DTD",extensions:["dtd"],load(){return ze(()=>import("./dtd-DF_7sFjM.js"),[]).then(t=>et(t.dtd))}}),Pe.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return ze(()=>import("./dylan-DwRh75JA.js"),[]).then(t=>et(t.dylan))}}),Pe.of({name:"EBNF",load(){return ze(()=>import("./ebnf-CDyGwa7X.js"),[]).then(t=>et(t.ebnf))}}),Pe.of({name:"ECL",extensions:["ecl"],load(){return ze(()=>import("./ecl-Cabwm37j.js"),[]).then(t=>et(t.ecl))}}),Pe.of({name:"edn",extensions:["edn"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"Eiffel",extensions:["e"],load(){return ze(()=>import("./eiffel-CnydiIhH.js"),[]).then(t=>et(t.eiffel))}}),Pe.of({name:"Elm",extensions:["elm"],load(){return ze(()=>import("./elm-vLlmbW-K.js"),[]).then(t=>et(t.elm))}}),Pe.of({name:"Erlang",extensions:["erl"],load(){return ze(()=>import("./erlang-BNw1qcRV.js"),[]).then(t=>et(t.erlang))}}),Pe.of({name:"Esper",load(){return ze(()=>import("./sql-D0XecflT.js"),[]).then(t=>et(t.esper))}}),Pe.of({name:"Factor",extensions:["factor"],load(){return ze(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([22,21])).then(t=>et(t.factor))}}),Pe.of({name:"FCL",load(){return ze(()=>import("./fcl-Kvtd6kyn.js"),[]).then(t=>et(t.fcl))}}),Pe.of({name:"Forth",extensions:["forth","fth","4th"],load(){return ze(()=>import("./forth-Ffai-XNe.js"),[]).then(t=>et(t.forth))}}),Pe.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return ze(()=>import("./fortran-DYz_wnZ1.js"),[]).then(t=>et(t.fortran))}}),Pe.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.fSharp))}}),Pe.of({name:"Gas",extensions:["s"],load(){return ze(()=>import("./gas-Bneqetm1.js"),[]).then(t=>et(t.gas))}}),Pe.of({name:"Gherkin",extensions:["feature"],load(){return ze(()=>import("./gherkin-heZmZLOM.js"),[]).then(t=>et(t.gherkin))}}),Pe.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return ze(()=>import("./groovy-D9Dt4D0W.js"),[]).then(t=>et(t.groovy))}}),Pe.of({name:"Haskell",extensions:["hs"],load(){return ze(()=>import("./haskell-Cw1EW3IL.js"),[]).then(t=>et(t.haskell))}}),Pe.of({name:"Haxe",extensions:["hx"],load(){return ze(()=>import("./haxe-H-WmDvRZ.js"),[]).then(t=>et(t.haxe))}}),Pe.of({name:"HXML",extensions:["hxml"],load(){return ze(()=>import("./haxe-H-WmDvRZ.js"),[]).then(t=>et(t.hxml))}}),Pe.of({name:"HTTP",load(){return ze(()=>import("./http-DBlCnlav.js"),[]).then(t=>et(t.http))}}),Pe.of({name:"IDL",extensions:["pro"],load(){return ze(()=>import("./idl-BEugSyMb.js"),[]).then(t=>et(t.idl))}}),Pe.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return ze(()=>import("./javascript-iXu5QeM3.js"),[]).then(t=>et(t.jsonld))}}),Pe.of({name:"Julia",extensions:["jl"],load(){return ze(()=>import("./julia-DuME0IfC.js"),[]).then(t=>et(t.julia))}}),Pe.of({name:"Kotlin",extensions:["kt","kts"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.kotlin))}}),Pe.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return ze(()=>import("./livescript-BwQOo05w.js"),[]).then(t=>et(t.liveScript))}}),Pe.of({name:"Lua",extensions:["lua"],load(){return ze(()=>import("./lua-BgMRiT3U.js"),[]).then(t=>et(t.lua))}}),Pe.of({name:"mIRC",extensions:["mrc"],load(){return ze(()=>import("./mirc-CjQqDB4T.js"),[]).then(t=>et(t.mirc))}}),Pe.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return ze(()=>import("./mathematica-DTrFuWx2.js"),[]).then(t=>et(t.mathematica))}}),Pe.of({name:"Modelica",extensions:["mo"],load(){return ze(()=>import("./modelica-Dc1JOy9r.js"),[]).then(t=>et(t.modelica))}}),Pe.of({name:"MUMPS",extensions:["mps"],load(){return ze(()=>import("./mumps-BT43cFF4.js"),[]).then(t=>et(t.mumps))}}),Pe.of({name:"Mbox",extensions:["mbox"],load(){return ze(()=>import("./mbox-CNhZ1qSd.js"),[]).then(t=>et(t.mbox))}}),Pe.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return ze(()=>import("./nginx-DdIZxoE0.js"),[]).then(t=>et(t.nginx))}}),Pe.of({name:"NSIS",extensions:["nsh","nsi"],load(){return ze(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([23,21])).then(t=>et(t.nsis))}}),Pe.of({name:"NTriples",extensions:["nt","nq"],load(){return ze(()=>import("./ntriples-BfvgReVJ.js"),[]).then(t=>et(t.ntriples))}}),Pe.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.objectiveC))}}),Pe.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.objectiveCpp))}}),Pe.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.oCaml))}}),Pe.of({name:"Octave",extensions:["m"],load(){return ze(()=>import("./octave-Ck1zUtKM.js"),[]).then(t=>et(t.octave))}}),Pe.of({name:"Oz",extensions:["oz"],load(){return ze(()=>import("./oz-BzwKVEFT.js"),[]).then(t=>et(t.oz))}}),Pe.of({name:"Pascal",extensions:["p","pas"],load(){return ze(()=>import("./pascal--L3eBynH.js"),[]).then(t=>et(t.pascal))}}),Pe.of({name:"Perl",extensions:["pl","pm"],load(){return ze(()=>import("./perl-CdXCOZ3F.js"),[]).then(t=>et(t.perl))}}),Pe.of({name:"Pig",extensions:["pig"],load(){return ze(()=>import("./pig-CevX1Tat.js"),[]).then(t=>et(t.pig))}}),Pe.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return ze(()=>import("./powershell-CFHJl5sT.js"),[]).then(t=>et(t.powerShell))}}),Pe.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return ze(()=>import("./properties-C78fOPTZ.js"),[]).then(t=>et(t.properties))}}),Pe.of({name:"ProtoBuf",extensions:["proto"],load(){return ze(()=>import("./protobuf-ChK-085T.js"),[]).then(t=>et(t.protobuf))}}),Pe.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return ze(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([24,25])).then(t=>et(t.pug))}}),Pe.of({name:"Puppet",extensions:["pp"],load(){return ze(()=>import("./puppet-DMA9R1ak.js"),[]).then(t=>et(t.puppet))}}),Pe.of({name:"Q",extensions:["q"],load(){return ze(()=>import("./q-pXgVlZs6.js"),[]).then(t=>et(t.q))}}),Pe.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return ze(()=>import("./r-B6wPVr8A.js"),[]).then(t=>et(t.r))}}),Pe.of({name:"RPM Changes",load(){return ze(()=>import("./rpm-CTu-6PCP.js"),[]).then(t=>et(t.rpmChanges))}}),Pe.of({name:"RPM Spec",extensions:["spec"],load(){return ze(()=>import("./rpm-CTu-6PCP.js"),[]).then(t=>et(t.rpmSpec))}}),Pe.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return ze(()=>import("./ruby-B2Rjki9n.js"),[]).then(t=>et(t.ruby))}}),Pe.of({name:"SAS",extensions:["sas"],load(){return ze(()=>import("./sas-B4kiWyti.js"),[]).then(t=>et(t.sas))}}),Pe.of({name:"Scala",extensions:["scala"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.scala))}}),Pe.of({name:"Scheme",extensions:["scm","ss"],load(){return ze(()=>import("./scheme-C41bIUwD.js"),[]).then(t=>et(t.scheme))}}),Pe.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return ze(()=>import("./shell-CjFT_Tl9.js"),[]).then(t=>et(t.shell))}}),Pe.of({name:"Sieve",extensions:["siv","sieve"],load(){return ze(()=>import("./sieve-C3Gn_uJK.js"),[]).then(t=>et(t.sieve))}}),Pe.of({name:"Smalltalk",extensions:["st"],load(){return ze(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(t=>et(t.smalltalk))}}),Pe.of({name:"Solr",load(){return ze(()=>import("./solr-DehyRSwq.js"),[]).then(t=>et(t.solr))}}),Pe.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.sml))}}),Pe.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return ze(()=>import("./sparql-DkYu6x3z.js"),[]).then(t=>et(t.sparql))}}),Pe.of({name:"Spreadsheet",alias:["excel","formula"],load(){return ze(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(t=>et(t.spreadsheet))}}),Pe.of({name:"Squirrel",extensions:["nut"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.squirrel))}}),Pe.of({name:"Stylus",extensions:["styl"],load(){return ze(()=>import("./stylus-B533Al4x.js"),[]).then(t=>et(t.stylus))}}),Pe.of({name:"Swift",extensions:["swift"],load(){return ze(()=>import("./swift-BzpIVaGY.js"),[]).then(t=>et(t.swift))}}),Pe.of({name:"sTeX",load(){return ze(()=>import("./stex-C3f8Ysf7.js"),[]).then(t=>et(t.stex))}}),Pe.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return ze(()=>import("./stex-C3f8Ysf7.js"),[]).then(t=>et(t.stex))}}),Pe.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return ze(()=>import("./verilog-C6RDOZhf.js"),[]).then(t=>et(t.verilog))}}),Pe.of({name:"Tcl",extensions:["tcl"],load(){return ze(()=>import("./tcl-DVfN8rqt.js"),[]).then(t=>et(t.tcl))}}),Pe.of({name:"Textile",extensions:["textile"],load(){return ze(()=>import("./textile-CnDTJFAw.js"),[]).then(t=>et(t.textile))}}),Pe.of({name:"TiddlyWiki",load(){return ze(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(t=>et(t.tiddlyWiki))}}),Pe.of({name:"Tiki wiki",load(){return ze(()=>import("./tiki-DGYXhP31.js"),[]).then(t=>et(t.tiki))}}),Pe.of({name:"TOML",extensions:["toml"],load(){return ze(()=>import("./toml-Bm5Em-hy.js"),[]).then(t=>et(t.toml))}}),Pe.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return ze(()=>import("./troff-wAsdV37c.js"),[]).then(t=>et(t.troff))}}),Pe.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return ze(()=>import("./ttcn-CfJYG6tj.js"),[]).then(t=>et(t.ttcn))}}),Pe.of({name:"TTCN_CFG",extensions:["cfg"],load(){return ze(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(t=>et(t.ttcnCfg))}}),Pe.of({name:"Turtle",extensions:["ttl"],load(){return ze(()=>import("./turtle-B1tBg_DP.js"),[]).then(t=>et(t.turtle))}}),Pe.of({name:"Web IDL",extensions:["webidl"],load(){return ze(()=>import("./webidl-ZXfAyPTL.js"),[]).then(t=>et(t.webIDL))}}),Pe.of({name:"VB.NET",extensions:["vb"],load(){return ze(()=>import("./vb-CmGdzxic.js"),[]).then(t=>et(t.vb))}}),Pe.of({name:"VBScript",extensions:["vbs"],load(){return ze(()=>import("./vbscript-BuJXcnF6.js"),[]).then(t=>et(t.vbScript))}}),Pe.of({name:"Velocity",extensions:["vtl"],load(){return ze(()=>import("./velocity-D8B20fx6.js"),[]).then(t=>et(t.velocity))}}),Pe.of({name:"Verilog",extensions:["v"],load(){return ze(()=>import("./verilog-C6RDOZhf.js"),[]).then(t=>et(t.verilog))}}),Pe.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return ze(()=>import("./vhdl-lSbBsy5d.js"),[]).then(t=>et(t.vhdl))}}),Pe.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return ze(()=>import("./xquery-DzFWVndE.js"),[]).then(t=>et(t.xQuery))}}),Pe.of({name:"Yacas",extensions:["ys"],load(){return ze(()=>import("./yacas-BJ4BC0dw.js"),[]).then(t=>et(t.yacas))}}),Pe.of({name:"Z80",extensions:["z80"],load(){return ze(()=>import("./z80-Hz9HOZM7.js"),[]).then(t=>et(t.z80))}}),Pe.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.mscgen))}}),Pe.of({name:"Xù",extensions:["xu"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.xu))}}),Pe.of({name:"MsGenny",extensions:["msgenny"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.msgenny))}}),Pe.of({name:"Vue",extensions:["vue"],load(){return ze(()=>import("./index-BA22JOVS.js"),__vite__mapDeps([26,5,1,3,6])).then(t=>t.vue())}}),Pe.of({name:"Angular Template",load(){return ze(()=>import("./index-DOD72BH5.js"),__vite__mapDeps([27,5,1,3,6])).then(t=>t.angular())}})],BK="#2e3440",y9="#3b4252",zK="#434c5e",f2="#4c566a",UK="#e5e9f0",uO="#eceff4",J3="#8fbcbb",VK="#88c0d0",BKe="#81a1c1",$l="#5e81ac",zKe="#bf616a",sx="#d08770",Q3="#ebcb8b",HK="#a3be8c",UKe="#b48ead",qK="#d30102",b9=uO,Z3=b9,VKe="#ffffff",X3=y9,HKe=b9,KK=y9,qKe=Nt.theme({"&":{color:BK,backgroundColor:VKe},".cm-content":{caretColor:KK},".cm-cursor, .cm-dropCursor":{borderLeftColor:KK},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:HKe},".cm-panels":{backgroundColor:b9,color:f2},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${f2}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:UK},".cm-activeLine":{backgroundColor:Z3},".cm-selectionMatch":{backgroundColor:UK},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${f2}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:uO},".cm-gutters":{backgroundColor:uO,color:BK,border:"none"},".cm-activeLineGutter":{backgroundColor:Z3},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:X3},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:X3,borderBottomColor:X3},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Z3,color:f2}}},{dark:!1}),KKe=Kw.define([{tag:Be.keyword,color:$l},{tag:[Be.name,Be.deleted,Be.character,Be.propertyName,Be.macroName],color:sx},{tag:[Be.variableName],color:sx},{tag:[Be.function(Be.variableName)],color:$l},{tag:[Be.labelName],color:BKe},{tag:[Be.color,Be.constant(Be.name),Be.standard(Be.name)],color:$l},{tag:[Be.definition(Be.name),Be.separator],color:HK},{tag:[Be.brace],color:J3},{tag:[Be.annotation],color:qK},{tag:[Be.number,Be.changed,Be.annotation,Be.modifier,Be.self,Be.namespace],color:VK},{tag:[Be.typeName,Be.className],color:Q3},{tag:[Be.operator,Be.operatorKeyword],color:HK},{tag:[Be.tagName],color:UKe},{tag:[Be.squareBracket],color:zKe},{tag:[Be.angleBracket],color:sx},{tag:[Be.attributeName],color:Q3},{tag:[Be.regexp],color:$l},{tag:[Be.quote],color:y9},{tag:[Be.string],color:sx},{tag:Be.link,color:J3,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Be.url,Be.escape,Be.special(Be.string)],color:sx},{tag:[Be.meta],color:VK},{tag:[Be.comment],color:zK,fontStyle:"italic"},{tag:Be.strong,fontWeight:"bold",color:$l},{tag:Be.emphasis,fontStyle:"italic",color:$l},{tag:Be.strikethrough,textDecoration:"line-through"},{tag:Be.heading,fontWeight:"bold",color:$l},{tag:Be.special(Be.heading1),fontWeight:"bold",color:$l},{tag:Be.heading1,fontWeight:"bold",color:$l},{tag:[Be.heading2,Be.heading3,Be.heading4],fontWeight:"bold",color:$l},{tag:[Be.heading5,Be.heading6],color:$l},{tag:[Be.atom,Be.bool,Be.special(Be.variableName)],color:sx},{tag:[Be.processingInstruction,Be.inserted],color:J3},{tag:[Be.contentSeparator],color:Q3},{tag:Be.invalid,color:zK,borderBottom:`1px dotted ${qK}`}]),WKe=[qKe,eue(KKe)],WK=typeof String.prototype.normalize=="function"?t=>t.normalize("NFKD"):t=>t;class Fy{constructor(e,n,r=0,s=e.length,i,a){this.test=a,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(r,s),this.bufferStart=r,this.normalize=i?l=>i(WK(l)):WK,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return na(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let n=OL(e),r=this.bufferStart+this.bufferPos;this.bufferPos+=qc(e);let s=this.normalize(n);if(s.length)for(let i=0,a=r;;i++){let l=s.charCodeAt(i),c=this.match(l,a,this.bufferPos+this.bufferStart);if(i==s.length-1){if(c)return this.value=c,this;break}a==r&&i<n.length&&n.charCodeAt(i)==l&&a++}}}match(e,n,r){let s=null;for(let i=0;i<this.matches.length;i+=2){let a=this.matches[i],l=!1;this.query.charCodeAt(a)==e&&(a==this.query.length-1?s={from:this.matches[i+1],to:r}:(this.matches[i]++,l=!0)),l||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==e&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(Fy.prototype[Symbol.iterator]=function(){return this});const ede={from:-1,to:-1,match:/.*/.exec("")},v9="gm"+(/x/.unicode==null?"":"u");class tde{constructor(e,n,r,s=0,i=e.length){if(this.text=e,this.to=i,this.curLine="",this.done=!1,this.value=ede,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new nde(e,n,r,s,i);this.re=new RegExp(n,v9+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=e.iter();let a=e.lineAt(s);this.curLineStart=a.from,this.matchPos=sS(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=sS(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}}const eM=new WeakMap;class Jx{constructor(e,n){this.from=e,this.text=n}get to(){return this.from+this.text.length}static get(e,n,r){let s=eM.get(e);if(!s||s.from>=r||s.to<=n){let l=new Jx(n,e.sliceString(n,r));return eM.set(e,l),l}if(s.from==n&&s.to==r)return s;let{text:i,from:a}=s;return a>n&&(i=e.sliceString(n,a)+i,a=n),s.to<r&&(i+=e.sliceString(s.to,r)),eM.set(e,new Jx(a,i)),new Jx(n,i.slice(n-a,r-a))}}class nde{constructor(e,n,r,s,i){this.text=e,this.to=i,this.done=!1,this.value=ede,this.matchPos=sS(e,s),this.re=new RegExp(n,v9+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Jx.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==e&&(this.re.lastIndex=e+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=sS(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Jx.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(tde.prototype[Symbol.iterator]=nde.prototype[Symbol.iterator]=function(){return this});function GKe(t){try{return new RegExp(t,v9),!0}catch{return!1}}function sS(t,e){if(e>=t.length)return e;let n=t.lineAt(e),r;for(;e<n.to&&(r=n.text.charCodeAt(e-n.from))>=56320&&r<57344;)e++;return e}const YKe=t=>{let{state:e}=t,n=String(e.doc.lineAt(t.state.selection.main.head).number),{close:r,result:s}=ZUe(t,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:e.phrase("go")});return s.then(i=>{let a=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!a){t.dispatch({effects:r});return}let l=e.doc.lineAt(e.selection.main.head),[,c,u,f,h]=a,p=f?+f.slice(1):0,g=u?+u:l.number;if(u&&h){let w=g/100;c&&(w=w*(c=="-"?-1:1)+l.number/e.doc.lines),g=Math.round(e.doc.lines*w)}else u&&c&&(g=g*(c=="-"?-1:1)+l.number);let b=e.doc.line(Math.max(1,Math.min(e.doc.lines,g))),v=Qe.cursor(b.from+Math.max(0,Math.min(p,b.length)));t.dispatch({effects:[r,Nt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},JKe={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},QKe=_t.define({combine(t){return Cu(t,JKe,{highlightWordAroundCursor:(e,n)=>e||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function ZKe(t){return[rWe,nWe]}const XKe=Qt.mark({class:"cm-selectionMatch"}),eWe=Qt.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function GK(t,e,n,r){return(n==0||t(e.sliceDoc(n-1,n))!=hs.Word)&&(r==e.doc.length||t(e.sliceDoc(r,r+1))!=hs.Word)}function tWe(t,e,n,r){return t(e.sliceDoc(n,n+1))==hs.Word&&t(e.sliceDoc(r-1,r))==hs.Word}const nWe=ti.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.selectionSet||t.docChanged||t.viewportChanged)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=t.state.facet(QKe),{state:n}=t,r=n.selection;if(r.ranges.length>1)return Qt.none;let s=r.main,i,a=null;if(s.empty){if(!e.highlightWordAroundCursor)return Qt.none;let c=n.wordAt(s.head);if(!c)return Qt.none;a=n.charCategorizer(s.head),i=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<e.minSelectionLength||c>200)return Qt.none;if(e.wholeWords){if(i=n.sliceDoc(s.from,s.to),a=n.charCategorizer(s.head),!(GK(a,n,s.from,s.to)&&tWe(a,n,s.from,s.to)))return Qt.none}else if(i=n.sliceDoc(s.from,s.to),!i)return Qt.none}let l=[];for(let c of t.visibleRanges){let u=new Fy(n.doc,i,c.from,c.to);for(;!u.next().done;){let{from:f,to:h}=u.value;if((!a||GK(a,n,f,h))&&(s.empty&&f<=s.from&&h>=s.to?l.push(eWe.range(f,h)):(f>=s.to||h<=s.from)&&l.push(XKe.range(f,h)),l.length>e.maxMatches))return Qt.none}}return Qt.set(l)}},{decorations:t=>t.decorations}),rWe=Nt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),sWe=({state:t,dispatch:e})=>{let{selection:n}=t,r=Qe.create(n.ranges.map(s=>t.wordAt(s.head)||Qe.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(e(t.update({selection:r})),!0)};function iWe(t,e){let{main:n,ranges:r}=t.selection,s=t.wordAt(n.head),i=s&&s.from==n.from&&s.to==n.to;for(let a=!1,l=new Fy(t.doc,e,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new Fy(t.doc,e,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(c=>c.from==l.value.from))continue;if(i){let c=t.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const oWe=({state:t,dispatch:e})=>{let{ranges:n}=t.selection;if(n.some(i=>i.from===i.to))return sWe({state:t,dispatch:e});let r=t.sliceDoc(n[0].from,n[0].to);if(t.selection.ranges.some(i=>t.sliceDoc(i.from,i.to)!=r))return!1;let s=iWe(t,r);return s?(e(t.update({selection:t.selection.addRange(Qe.range(s.from,s.to),!1),effects:Nt.scrollIntoView(s.to)})),!0):!1},E0=_t.define({combine(t){return Cu(t,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new vWe(e),scrollToMatch:e=>Nt.scrollIntoView(e)})}});class rde{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||GKe(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1008
+ `);r>-1&&(n=n.slice(0,r))}return e+n.length<=this.to?n:n.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,n=this.lineAfter(e),r=e+n.length;for(let s=this.rangeIndex;;){let i=this.ranges[s].to;if(i>=r||(n=n.slice(0,i-(r-n.length)),s++,s==this.ranges.length))break;let a=this.ranges[s].from,l=this.lineAfter(a);n+=l,r=a+l.length}return{line:n,end:r}}skipGapsTo(e,n,r){for(;;){let s=this.ranges[this.rangeIndex].to,i=e+n;if(r>0?s>i:s>=i)break;let a=this.ranges[++this.rangeIndex].from;n+=a-s}return n}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(e,n,r,s){let i=4;if(this.ranges.length>1){s=this.skipGapsTo(n,s,1),n+=s;let l=this.chunk.length;s=this.skipGapsTo(r,s,-1),r+=s,i+=this.chunk.length-l}let a=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&i==4&&a>=0&&this.chunk[a]==e&&this.chunk[a+2]==n?this.chunk[a+2]=r:this.chunk.push(e,n,r,i),s}parseLine(e){let{line:n,end:r}=this.nextLine(),s=0,{streamParser:i}=this.lang,a=new sue(n,e?e.state.tabSize:4,e?Yp(e.state):2);if(a.eol())i.blankLine(this.state,a.indentUnit);else for(;!a.eol();){let l=oue(i.token,a,this.state);if(l&&(s=this.emitToken(this.lang.tokenTable.resolve(l),this.parsedPos+a.start,this.parsedPos+a.pos,s)),a.start>1e4)break}this.parsedPos=r,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let e=Wr.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:SHe,topID:0,maxBufferLength:512,reused:this.chunkReused});e=new Wr(e.type,e.children,e.positions,e.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(e),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new Wr(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}}function oue(t,e,n){e.start=e.pos;for(let r=0;r<10;r++){let s=t(e,n);if(e.pos>e.start)return s}throw new Error("Stream parser failed to advance stream.")}const a9=Object.create(null),A1=[Lo.none],SHe=new XL(A1),wK=[],kK=Object.create(null),aue=Object.create(null);for(let[t,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])aue[t]=cue(a9,e);class lue{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),aue)}resolve(e){return e?this.table[e]||(this.table[e]=cue(this.extra,e)):0}}const _He=new lue(a9);function q3(t,e){wK.indexOf(t)>-1||(wK.push(t),console.warn(e))}function cue(t,e){let n=[];for(let l of e.split(" ")){let c=[];for(let u of l.split(".")){let f=t[u]||Be[u];f?typeof f=="function"?c.length?c=c.map(f):q3(u,`Modifier ${u} used at start of tag`):c.length?q3(u,`Tag ${u} used as modifier`):c=Array.isArray(f)?f:[f]:q3(u,`Unknown highlighting tag ${u}`)}for(let u of c)n.push(u)}if(!n.length)return 0;let r=e.replace(/ /g,"_"),s=r+" "+n.map(l=>l.id),i=kK[s];if(i)return i.id;let a=kK[s]=Lo.define({id:A1.length,name:r,props:[TVe({[r]:n})]});return A1.push(a),a.id}function EHe(t,e){let n=Lo.define({id:A1.length,name:"Document",props:[Jm.add(()=>t),Vce.add(()=>r=>e.getIndent(r))],top:!0});return A1.push(n),n}Kr.RTL,Kr.LTR;class uue{constructor(e,n,r,s){this.state=e,this.pos=n,this.explicit=r,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let n=Ji(this.state).resolveInner(this.pos,-1);for(;n&&e.indexOf(n.name)<0;)n=n.parent;return n?{from:n.from,to:this.pos,text:this.state.sliceDoc(n.from,this.pos),type:n.type}:null}matchBefore(e){let n=this.state.doc.lineAt(this.pos),r=Math.max(n.from,this.pos-250),s=n.text.slice(r-n.from,this.pos-n.from),i=s.search(due(e,!1));return i<0?null:{from:r+i,to:this.pos,text:s.slice(i)}}get aborted(){return this.abortListeners==null}addEventListener(e,n,r){e=="abort"&&this.abortListeners&&(this.abortListeners.push(n),r&&r.onDocChange&&(this.abortOnDocChange=!0))}}function CK(t){let e=Object.keys(t).join(""),n=/\w/.test(e);return n&&(e=e.replace(/\w/g,"")),`[${n?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function AHe(t){let e=Object.create(null),n=Object.create(null);for(let{label:s}of t){e[s[0]]=!0;for(let i=1;i<s.length;i++)n[s[i]]=!0}let r=CK(e)+CK(n)+"*$";return[new RegExp("^"+r),new RegExp(r)]}function THe(t){let e=t.map(s=>typeof s=="string"?{label:s}:s),[n,r]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:AHe(e);return s=>{let i=s.matchBefore(r);return i||s.explicit?{from:i?i.from:s.pos,options:e,validFor:n}:null}}function vlt(t,e){return n=>{for(let r=Ji(n.state).resolveInner(n.pos,-1);r;r=r.parent){if(t.indexOf(r.name)>-1)return null;if(r.type.isTop)break}return e(n)}}class jK{constructor(e,n,r,s){this.completion=e,this.source=n,this.match=r,this.score=s}}function hp(t){return t.selection.main.from}function due(t,e){var n;let{source:r}=t,s=e&&r[0]!="^",i=r[r.length-1]!="$";return!s&&!i?t:new RegExp(`${s?"^":""}(?:${r})${i?"$":""}`,(n=t.flags)!==null&&n!==void 0?n:t.ignoreCase?"i":"")}const l9=ef.define();function MHe(t,e,n,r){let{main:s}=t.selection,i=n-s.from,a=r-s.from;return{...t.changeByRange(l=>{if(l!=s&&n!=r&&t.sliceDoc(l.from+i,l.from+a)!=t.sliceDoc(n,r))return{range:l};let c=t.toText(e);return{changes:{from:l.from+i,to:r==s.from?l.to:l.from+a,insert:c},range:Qe.cursor(l.from+i+c.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const NK=new WeakMap;function IHe(t){if(!Array.isArray(t))return t;let e=NK.get(t);return e||NK.set(t,e=THe(t)),e}const tS=pn.define(),T1=pn.define();class RHe{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let n=0;n<e.length;){let r=na(e,n),s=qc(r);this.chars.push(r);let i=e.slice(n,n+s),a=i.toUpperCase();this.folded.push(na(a==i?i.toLowerCase():a,0)),n+=s}this.astral=e.length!=this.chars.length}ret(e,n){return this.score=e,this.matched=n,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:n,folded:r,any:s,precise:i,byWord:a}=this;if(n.length==1){let C=na(e,0),N=qc(C),S=N==e.length?0:-100;if(C!=n[0])if(C==r[0])S+=-200;else return null;return this.ret(S,[0,N])}let l=e.indexOf(this.pattern);if(l==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let c=n.length,u=0;if(l<0){for(let C=0,N=Math.min(e.length,200);C<N&&u<c;){let S=na(e,C);(S==n[u]||S==r[u])&&(s[u++]=C),C+=qc(S)}if(u<c)return null}let f=0,h=0,p=!1,g=0,b=-1,v=-1,w=/[a-z]/.test(e),j=!0;for(let C=0,N=Math.min(e.length,200),S=0;C<N&&h<c;){let T=na(e,C);l<0&&(f<c&&T==n[f]&&(i[f++]=C),g<c&&(T==n[g]||T==r[g]?(g==0&&(b=C),v=C+1,g++):g=0));let _,A=T<255?T>=48&&T<=57||T>=97&&T<=122?2:T>=65&&T<=90?1:0:(_=OL(T))!=_.toLowerCase()?1:_!=_.toUpperCase()?2:0;(!C||A==1&&w||S==0&&A!=0)&&(n[h]==T||r[h]==T&&(p=!0)?a[h++]=C:a.length&&(j=!1)),S=A,C+=qc(T)}return h==c&&a[0]==0&&j?this.result(-100+(p?-200:0),a,e):g==c&&b==0?this.ret(-200-e.length+(v==e.length?0:-100),[0,v]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):g==c?this.ret(-900-e.length,[b,v]):h==c?this.result(-100+(p?-200:0)+-700+(j?0:-1100),a,e):n.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,n,r){let s=[],i=0;for(let a of n){let l=a+(this.astral?qc(na(r,a)):1);i&&s[i-1]==a?s[i-1]=l:(s[i++]=a,s[i++]=l)}return this.ret(e-r.length,s)}}class OHe{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let n=e.slice(0,this.pattern.length),r=n==this.pattern?0:n.toLowerCase()==this.folded?-200:null;return r==null?null:(this.matched=[0,n.length],this.score=r+(e.length==this.pattern.length?0:-100),this)}}const ji=_t.define({combine(t){return Cu(t,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:DHe,filterStrict:!1,compareCompletions:(e,n)=>(e.sortText||e.label).localeCompare(n.sortText||n.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,n)=>e&&n,closeOnBlur:(e,n)=>e&&n,icons:(e,n)=>e&&n,tooltipClass:(e,n)=>r=>SK(e(r),n(r)),optionClass:(e,n)=>r=>SK(e(r),n(r)),addToOptions:(e,n)=>e.concat(n),filterStrict:(e,n)=>e||n})}});function SK(t,e){return t?e?t+" "+e:t:e}function DHe(t,e,n,r,s,i){let a=t.textDirection==Kr.RTL,l=a,c=!1,u="top",f,h,p=e.left-s.left,g=s.right-e.right,b=r.right-r.left,v=r.bottom-r.top;if(l&&p<Math.min(b,g)?l=!1:!l&&g<Math.min(b,p)&&(l=!0),b<=(l?p:g))f=Math.max(s.top,Math.min(n.top,s.bottom-v))-e.top,h=Math.min(400,l?p:g);else{c=!0,h=Math.min(400,(a?e.right:s.right-e.left)-30);let C=s.bottom-e.bottom;C>=v||C>e.top?f=n.bottom-e.top:(u="bottom",f=e.bottom-n.top)}let w=(e.bottom-e.top)/i.offsetHeight,j=(e.right-e.left)/i.offsetWidth;return{style:`${u}: ${f/w}px; max-width: ${h/j}px`,class:"cm-completionInfo-"+(c?a?"left-narrow":"right-narrow":l?"left":"right")}}function PHe(t){let e=t.addToOptions.slice();return t.icons&&e.push({render(n){let r=document.createElement("div");return r.classList.add("cm-completionIcon"),n.type&&r.classList.add(...n.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),r.setAttribute("aria-hidden","true"),r},position:20}),e.push({render(n,r,s,i){let a=document.createElement("span");a.className="cm-completionLabel";let l=n.displayLabel||n.label,c=0;for(let u=0;u<i.length;){let f=i[u++],h=i[u++];f>c&&a.appendChild(document.createTextNode(l.slice(c,f)));let p=a.appendChild(document.createElement("span"));p.appendChild(document.createTextNode(l.slice(f,h))),p.className="cm-completionMatchedText",c=h}return c<l.length&&a.appendChild(document.createTextNode(l.slice(c))),a},position:50},{render(n){if(!n.detail)return null;let r=document.createElement("span");return r.className="cm-completionDetail",r.textContent=n.detail,r},position:80}),e.sort((n,r)=>n.position-r.position).map(n=>n.render)}function K3(t,e,n){if(t<=n)return{from:0,to:t};if(e<0&&(e=0),e<=t>>1){let s=Math.floor(e/n);return{from:s*n,to:(s+1)*n}}let r=Math.floor((t-e)/n);return{from:t-(r+1)*n,to:t-r*n}}class LHe{constructor(e,n,r){this.view=e,this.stateField=n,this.applyCompletion=r,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:c=>this.placeInfo(c),key:this},this.space=null,this.currentClass="";let s=e.state.field(n),{options:i,selected:a}=s.open,l=e.state.facet(ji);this.optionContent=PHe(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=K3(i.length,a,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",c=>{let{options:u}=e.state.field(n).open;for(let f=c.target,h;f&&f!=this.dom;f=f.parentNode)if(f.nodeName=="LI"&&(h=/-(\d+)$/.exec(f.id))&&+h[1]<u.length){this.applyCompletion(e,u[+h[1]]),c.preventDefault();return}}),this.dom.addEventListener("focusout",c=>{let u=e.state.field(this.stateField,!1);u&&u.tooltip&&e.state.facet(ji).closeOnBlur&&c.relatedTarget!=e.contentDOM&&e.dispatch({effects:T1.of(null)})}),this.showOptions(i,s.id)}mount(){this.updateSel()}showOptions(e,n){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,n,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var n;let r=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),r!=s){let{options:i,selected:a,disabled:l}=r.open;(!s.open||s.open.options!=i)&&(this.range=K3(i.length,a,e.state.facet(ji).maxRenderedOptions),this.showOptions(i,r.id)),this.updateSel(),l!=((n=s.open)===null||n===void 0?void 0:n.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let n=this.tooltipClass(e);if(n!=this.currentClass){for(let r of this.currentClass.split(" "))r&&this.dom.classList.remove(r);for(let r of n.split(" "))r&&this.dom.classList.add(r);this.currentClass=n}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),n=e.open;(n.selected>-1&&n.selected<this.range.from||n.selected>=this.range.to)&&(this.range=K3(n.options.length,n.selected,this.view.state.facet(ji).maxRenderedOptions),this.showOptions(n.options,e.id));let r=this.updateSelectedOption(n.selected);if(r){this.destroyInfo();let{completion:s}=n.options[n.selected],{info:i}=s;if(!i)return;let a=typeof i=="string"?document.createTextNode(i):i(s);if(!a)return;"then"in a?a.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,s)}).catch(l=>aa(this.view.state,l,"completion info")):(this.addInfoPane(a,s),r.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,n){this.destroyInfo();let r=this.info=document.createElement("div");if(r.className="cm-tooltip cm-completionInfo",r.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)r.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:i}=e;r.appendChild(s),this.infoDestroy=i||null}this.dom.appendChild(r),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let n=null;for(let r=this.list.firstChild,s=this.range.from;r;r=r.nextSibling,s++)r.nodeName!="LI"||!r.id?s--:s==e?r.hasAttribute("aria-selected")||(r.setAttribute("aria-selected","true"),n=r):r.hasAttribute("aria-selected")&&(r.removeAttribute("aria-selected"),r.removeAttribute("aria-describedby"));return n&&FHe(this.list,n),n}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let n=this.dom.getBoundingClientRect(),r=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),i=this.space;if(!i){let a=this.dom.ownerDocument.documentElement;i={left:0,top:0,right:a.clientWidth,bottom:a.clientHeight}}return s.top>Math.min(i.bottom,n.bottom)-10||s.bottom<Math.max(i.top,n.top)+10?null:this.view.state.facet(ji).positionInfo(this.view,n,s,r,i,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,n,r){const s=document.createElement("ul");s.id=n,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions")),s.addEventListener("mousedown",a=>{a.target==s&&a.preventDefault()});let i=null;for(let a=r.from;a<r.to;a++){let{completion:l,match:c}=e[a],{section:u}=l;if(u){let p=typeof u=="string"?u:u.name;if(p!=i&&(a>r.from||r.from==0))if(i=p,typeof u!="string"&&u.header)s.appendChild(u.header(u));else{let g=s.appendChild(document.createElement("completion-section"));g.textContent=p}}const f=s.appendChild(document.createElement("li"));f.id=n+"-"+a,f.setAttribute("role","option");let h=this.optionClass(l);h&&(f.className=h);for(let p of this.optionContent){let g=p(l,this.view.state,this.view,c);g&&f.appendChild(g)}}return r.from&&s.classList.add("cm-completionListIncompleteTop"),r.to<e.length&&s.classList.add("cm-completionListIncompleteBottom"),s}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function $He(t,e){return n=>new LHe(n,t,e)}function FHe(t,e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),s=n.height/t.offsetHeight;r.top<n.top?t.scrollTop-=(n.top-r.top)/s:r.bottom>n.bottom&&(t.scrollTop+=(r.bottom-n.bottom)/s)}function _K(t){return(t.boost||0)*100+(t.apply?10:0)+(t.info?5:0)+(t.type?1:0)}function BHe(t,e){let n=[],r=null,s=null,i=f=>{n.push(f);let{section:h}=f.completion;if(h){r||(r=[]);let p=typeof h=="string"?h:h.name;r.some(g=>g.name==p)||r.push(typeof h=="string"?{name:p}:h)}},a=e.facet(ji);for(let f of t)if(f.hasResult()){let h=f.result.getMatch;if(f.result.filter===!1)for(let p of f.result.options)i(new jK(p,f.source,h?h(p):[],1e9-n.length));else{let p=e.sliceDoc(f.from,f.to),g,b=a.filterStrict?new OHe(p):new RHe(p);for(let v of f.result.options)if(g=b.match(v.label)){let w=v.displayLabel?h?h(v,g.matched):[]:g.matched,j=g.score+(v.boost||0);if(i(new jK(v,f.source,w,j)),typeof v.section=="object"&&v.section.rank==="dynamic"){let{name:C}=v.section;s||(s=Object.create(null)),s[C]=Math.max(j,s[C]||-1e9)}}}}if(r){let f=Object.create(null),h=0,p=(g,b)=>(g.rank==="dynamic"&&b.rank==="dynamic"?s[b.name]-s[g.name]:0)||(typeof g.rank=="number"?g.rank:1e9)-(typeof b.rank=="number"?b.rank:1e9)||(g.name<b.name?-1:1);for(let g of r.sort(p))h-=1e5,f[g.name]=h;for(let g of n){let{section:b}=g.completion;b&&(g.score+=f[typeof b=="string"?b:b.name])}}let l=[],c=null,u=a.compareCompletions;for(let f of n.sort((h,p)=>p.score-h.score||u(h.completion,p.completion))){let h=f.completion;!c||c.label!=h.label||c.detail!=h.detail||c.type!=null&&h.type!=null&&c.type!=h.type||c.apply!=h.apply||c.boost!=h.boost?l.push(f):_K(f.completion)>_K(c)&&(l[l.length-1]=f),c=f.completion}return l}class Ax{constructor(e,n,r,s,i,a){this.options=e,this.attrs=n,this.tooltip=r,this.timestamp=s,this.selected=i,this.disabled=a}setSelected(e,n){return e==this.selected||e>=this.options.length?this:new Ax(this.options,EK(n,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,n,r,s,i,a){if(s&&!a&&e.some(u=>u.isPending))return s.setDisabled();let l=BHe(e,n);if(!l.length)return s&&e.some(u=>u.isPending)?s.setDisabled():null;let c=n.facet(ji).selectOnOpen?0:-1;if(s&&s.selected!=c&&s.selected!=-1){let u=s.options[s.selected].completion;for(let f=0;f<l.length;f++)if(l[f].completion==u){c=f;break}}return new Ax(l,EK(r,c),{pos:e.reduce((u,f)=>f.hasResult()?Math.min(u,f.from):u,1e8),create:KHe,above:i.aboveCursor},s?s.timestamp:Date.now(),c,!1)}map(e){return new Ax(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ax(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class nS{constructor(e,n,r){this.active=e,this.id=n,this.open=r}static start(){return new nS(HHe,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:n}=e,r=n.facet(ji),i=(r.override||n.languageDataAt("autocomplete",hp(n)).map(IHe)).map(c=>(this.active.find(f=>f.source==c)||new bl(c,this.active.some(f=>f.state!=0)?1:0)).update(e,r));i.length==this.active.length&&i.every((c,u)=>c==this.active[u])&&(i=this.active);let a=this.open,l=e.effects.some(c=>c.is(c9));a&&e.docChanged&&(a=a.map(e.changes)),e.selection||i.some(c=>c.hasResult()&&e.changes.touchesRange(c.from,c.to))||!zHe(i,this.active)||l?a=Ax.build(i,n,this.id,a,r,l):a&&a.disabled&&!i.some(c=>c.isPending)&&(a=null),!a&&i.every(c=>!c.isPending)&&i.some(c=>c.hasResult())&&(i=i.map(c=>c.hasResult()?new bl(c.source,0):c));for(let c of e.effects)c.is(hue)&&(a=a&&a.setSelected(c.value,this.id));return i==this.active&&a==this.open?this:new nS(i,this.id,a)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?UHe:VHe}}function zHe(t,e){if(t==e)return!0;for(let n=0,r=0;;){for(;n<t.length&&!t[n].hasResult();)n++;for(;r<e.length&&!e[r].hasResult();)r++;let s=n==t.length,i=r==e.length;if(s||i)return s==i;if(t[n++].result!=e[r++].result)return!1}}const UHe={"aria-autocomplete":"list"},VHe={};function EK(t,e){let n={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":t};return e>-1&&(n["aria-activedescendant"]=t+"-"+e),n}const HHe=[];function fue(t,e){if(t.isUserEvent("input.complete")){let r=t.annotation(l9);if(r&&e.activateOnCompletion(r))return 12}let n=t.isUserEvent("input.type");return n&&e.activateOnTyping?5:n?1:t.isUserEvent("delete.backward")?2:t.selection?8:t.docChanged?16:0}class bl{constructor(e,n,r=!1){this.source=e,this.state=n,this.explicit=r}hasResult(){return!1}get isPending(){return this.state==1}update(e,n){let r=fue(e,n),s=this;(r&8||r&16&&this.touches(e))&&(s=new bl(s.source,0)),r&4&&s.state==0&&(s=new bl(this.source,1)),s=s.updateFor(e,r);for(let i of e.effects)if(i.is(tS))s=new bl(s.source,1,i.value);else if(i.is(T1))s=new bl(s.source,0);else if(i.is(c9))for(let a of i.value)a.source==s.source&&(s=a);return s}updateFor(e,n){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(hp(e.state))}}class Yx extends bl{constructor(e,n,r,s,i,a){super(e,3,n),this.limit=r,this.result=s,this.from=i,this.to=a}hasResult(){return!0}updateFor(e,n){var r;if(!(n&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let i=e.changes.mapPos(this.from),a=e.changes.mapPos(this.to,1),l=hp(e.state);if(l>a||!s||n&2&&(hp(e.startState)==this.from||l<this.limit))return new bl(this.source,n&4?1:0);let c=e.changes.mapPos(this.limit);return qHe(s.validFor,e.state,i,a)?new Yx(this.source,this.explicit,c,s,i,a):s.update&&(s=s.update(s,i,a,new uue(e.state,l,!1)))?new Yx(this.source,this.explicit,c,s,s.from,(r=s.to)!==null&&r!==void 0?r:hp(e.state)):new bl(this.source,1,this.explicit)}map(e){return e.empty?this:(this.result.map?this.result.map(this.result,e):this.result)?new Yx(this.source,this.explicit,e.mapPos(this.limit),this.result,e.mapPos(this.from),e.mapPos(this.to,1)):new bl(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}}function qHe(t,e,n,r){if(!t)return!1;let s=e.sliceDoc(n,r);return typeof t=="function"?t(s,n,r,e):due(t,!0).test(s)}const c9=pn.define({map(t,e){return t.map(n=>n.map(e))}}),hue=pn.define(),ra=Oi.define({create(){return nS.start()},update(t,e){return t.update(e)},provide:t=>[QL.from(t,e=>e.tooltip),Nt.contentAttributes.from(t,e=>e.attrs)]});function u9(t,e){const n=e.completion.apply||e.completion.label;let r=t.state.field(ra).active.find(s=>s.source==e.source);return r instanceof Yx?(typeof n=="string"?t.dispatch({...MHe(t.state,n,r.from,r.to),annotations:l9.of(e.completion)}):n(t,e.completion,r.from,r.to),!0):!1}const KHe=$He(ra,u9);function u2(t,e="option"){return n=>{let r=n.state.field(ra,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(ji).interactionDelay)return!1;let s=1,i;e=="page"&&(i=Ece(n,r.open.tooltip))&&(s=Math.max(2,Math.floor(i.dom.offsetHeight/i.dom.querySelector("li").offsetHeight)-1));let{length:a}=r.open.options,l=r.open.selected>-1?r.open.selected+s*(t?1:-1):t?0:a-1;return l<0?l=e=="page"?0:a-1:l>=a&&(l=e=="page"?a-1:0),n.dispatch({effects:hue.of(l)}),!0}}const WHe=t=>{let e=t.state.field(ra,!1);return t.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<t.state.facet(ji).interactionDelay?!1:u9(t,e.open.options[e.open.selected])},W3=t=>t.state.field(ra,!1)?(t.dispatch({effects:tS.of(!0)}),!0):!1,GHe=t=>{let e=t.state.field(ra,!1);return!e||!e.active.some(n=>n.state!=0)?!1:(t.dispatch({effects:T1.of(null)}),!0)};class YHe{constructor(e,n){this.active=e,this.context=n,this.time=Date.now(),this.updates=[],this.done=void 0}}const JHe=50,QHe=1e3,ZHe=ti.fromClass(class{constructor(t){this.view=t,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of t.state.field(ra).active)e.isPending&&this.startQuery(e)}update(t){let e=t.state.field(ra),n=t.state.facet(ji);if(!t.selectionSet&&!t.docChanged&&t.startState.field(ra)==e)return;let r=t.transactions.some(i=>{let a=fue(i,n);return a&8||(i.selection||i.docChanged)&&!(a&3)});for(let i=0;i<this.running.length;i++){let a=this.running[i];if(r||a.context.abortOnDocChange&&t.docChanged||a.updates.length+t.transactions.length>JHe&&Date.now()-a.time>QHe){for(let l of a.context.abortListeners)try{l()}catch(c){aa(this.view.state,c)}a.context.abortListeners=null,this.running.splice(i--,1)}else a.updates.push(...t.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),t.transactions.some(i=>i.effects.some(a=>a.is(tS)))&&(this.pendingStart=!0);let s=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(i=>i.isPending&&!this.running.some(a=>a.active.source==i.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let i of t.transactions)i.isUserEvent("input.type")?this.composing=2:this.composing==2&&i.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:t}=this.view,e=t.field(ra);for(let n of e.active)n.isPending&&!this.running.some(r=>r.active.source==n.source)&&this.startQuery(n);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ji).updateSyncTime))}startQuery(t){let{state:e}=this.view,n=hp(e),r=new uue(e,n,t.explicit,this.view),s=new YHe(t,r);this.running.push(s),Promise.resolve(t.source(r)).then(i=>{s.context.aborted||(s.done=i||null,this.scheduleAccept())},i=>{this.view.dispatch({effects:T1.of(null)}),aa(this.view.state,i)})}scheduleAccept(){this.running.every(t=>t.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ji).updateSyncTime))}accept(){var t;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],n=this.view.state.facet(ji),r=this.view.state.field(ra);for(let s=0;s<this.running.length;s++){let i=this.running[s];if(i.done===void 0)continue;if(this.running.splice(s--,1),i.done){let l=hp(i.updates.length?i.updates[0].startState:this.view.state),c=Math.min(l,i.done.from+(i.active.explicit?0:1)),u=new Yx(i.active.source,i.active.explicit,c,i.done,i.done.from,(t=i.done.to)!==null&&t!==void 0?t:l);for(let f of i.updates)u=u.update(f,n);if(u.hasResult()){e.push(u);continue}}let a=r.active.find(l=>l.source==i.active.source);if(a&&a.isPending)if(i.done==null){let l=new bl(i.active.source,0);for(let c of i.updates)l=l.update(c,n);l.isPending||e.push(l)}else this.startQuery(a)}(e.length||r.open&&r.open.disabled)&&this.view.dispatch({effects:c9.of(e)})}},{eventHandlers:{blur(t){let e=this.view.state.field(ra,!1);if(e&&e.tooltip&&this.view.state.facet(ji).closeOnBlur){let n=e.open&&Ece(this.view,e.open.tooltip);(!n||!n.dom.contains(t.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:T1.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:tS.of(!1)}),20),this.composing=0}}}),XHe=typeof navigator=="object"&&/Win/.test(navigator.platform),eqe=um.highest(Nt.domEventHandlers({keydown(t,e){let n=e.state.field(ra,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||t.key.length>1||t.ctrlKey&&!(XHe&&t.altKey)||t.metaKey)return!1;let r=n.open.options[n.open.selected],s=n.active.find(a=>a.source==r.source),i=r.completion.commitCharacters||s.result.commitCharacters;return i&&i.indexOf(t.key)>-1&&u9(e,r),!1}})),mue=Nt.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class tqe{constructor(e,n,r,s){this.field=e,this.line=n,this.from=r,this.to=s}}class d9{constructor(e,n,r){this.field=e,this.from=n,this.to=r}map(e){let n=e.mapPos(this.from,-1,qi.TrackDel),r=e.mapPos(this.to,1,qi.TrackDel);return n==null||r==null?null:new d9(this.field,n,r)}}class f9{constructor(e,n){this.lines=e,this.fieldPositions=n}instantiate(e,n){let r=[],s=[n],i=e.doc.lineAt(n),a=/^\s*/.exec(i.text)[0];for(let c of this.lines){if(r.length){let u=a,f=/^\t*/.exec(c)[0].length;for(let h=0;h<f;h++)u+=e.facet(j5);s.push(n+u.length-f),c=u+c.slice(f)}r.push(c),n+=c.length+1}let l=this.fieldPositions.map(c=>new d9(c.field,s[c.line]+c.from,s[c.line]+c.to));return{text:r,ranges:l}}static parse(e){let n=[],r=[],s=[],i;for(let a of e.split(/\r\n?|\n/)){for(;i=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(a);){let l=i[1]?+i[1]:null,c=i[2]||i[3]||"",u=-1,f=c.replace(/\\[{}]/g,h=>h[1]);for(let h=0;h<n.length;h++)(l!=null?n[h].seq==l:f&&n[h].name==f)&&(u=h);if(u<0){let h=0;for(;h<n.length&&(l==null||n[h].seq!=null&&n[h].seq<l);)h++;n.splice(h,0,{seq:l,name:f}),u=h;for(let p of s)p.field>=u&&p.field++}for(let h of s)if(h.line==r.length&&h.from>i.index){let p=i[2]?3+(i[1]||"").length:2;h.from-=p,h.to-=p}s.push(new tqe(u,r.length,i.index,i.index+f.length)),a=a.slice(0,i.index)+c+a.slice(i.index+i[0].length)}a=a.replace(/\\([{}])/g,(l,c,u)=>{for(let f of s)f.line==r.length&&f.from>u&&(f.from--,f.to--);return c}),r.push(a)}return new f9(r,s)}}let nqe=Qt.widget({widget:new class extends ju{toDOM(){let t=document.createElement("span");return t.className="cm-snippetFieldPosition",t}ignoreEvent(){return!1}}}),rqe=Qt.mark({class:"cm-snippetField"});class S0{constructor(e,n){this.ranges=e,this.active=n,this.deco=Qt.set(e.map(r=>(r.from==r.to?nqe:rqe).range(r.from,r.to)),!0)}map(e){let n=[];for(let r of this.ranges){let s=r.map(e);if(!s)return null;n.push(s)}return new S0(n,this.active)}selectionInsideField(e){return e.ranges.every(n=>this.ranges.some(r=>r.field==this.active&&r.from<=n.from&&r.to>=n.to))}}const Ww=pn.define({map(t,e){return t&&t.map(e)}}),sqe=pn.define(),M1=Oi.define({create(){return null},update(t,e){for(let n of e.effects){if(n.is(Ww))return n.value;if(n.is(sqe)&&t)return new S0(t.ranges,n.value)}return t&&e.docChanged&&(t=t.map(e.changes)),t&&e.selection&&!t.selectionInsideField(e.selection)&&(t=null),t},provide:t=>Nt.decorations.from(t,e=>e?e.deco:Qt.none)});function h9(t,e){return Qe.create(t.filter(n=>n.field==e).map(n=>Qe.range(n.from,n.to)))}function iqe(t){let e=f9.parse(t);return(n,r,s,i)=>{let{text:a,ranges:l}=e.instantiate(n.state,s),{main:c}=n.state.selection,u={changes:{from:s,to:i==c.from?c.to:i,insert:pr.of(a)},scrollIntoView:!0,annotations:r?[l9.of(r),Zs.userEvent.of("input.complete")]:void 0};if(l.length&&(u.selection=h9(l,0)),l.some(f=>f.field>0)){let f=new S0(l,0),h=u.effects=[Ww.of(f)];n.state.field(M1,!1)===void 0&&h.push(pn.appendConfig.of([M1,uqe,dqe,mue]))}n.dispatch(n.state.update(u))}}function pue(t){return({state:e,dispatch:n})=>{let r=e.field(M1,!1);if(!r||t<0&&r.active==0)return!1;let s=r.active+t,i=t>0&&!r.ranges.some(a=>a.field==s+t);return n(e.update({selection:h9(r.ranges,s),effects:Ww.of(i?null:new S0(r.ranges,s)),scrollIntoView:!0})),!0}}const oqe=({state:t,dispatch:e})=>t.field(M1,!1)?(e(t.update({effects:Ww.of(null)})),!0):!1,aqe=pue(1),lqe=pue(-1),cqe=[{key:"Tab",run:aqe,shift:lqe},{key:"Escape",run:oqe}],AK=_t.define({combine(t){return t.length?t[0]:cqe}}),uqe=um.highest(Vw.compute([AK],t=>t.facet(AK)));function wlt(t,e){return{...e,apply:iqe(t)}}const dqe=Nt.domEventHandlers({mousedown(t,e){let n=e.state.field(M1,!1),r;if(!n||(r=e.posAtCoords({x:t.clientX,y:t.clientY}))==null)return!1;let s=n.ranges.find(i=>i.from<=r&&i.to>=r);return!s||s.field==n.active?!1:(e.dispatch({selection:h9(n.ranges,s.field),effects:Ww.of(n.ranges.some(i=>i.field>s.field)?new S0(n.ranges,s.field):null),scrollIntoView:!0}),!0)}}),I1={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Qm=pn.define({map(t,e){let n=e.mapPos(t,-1,qi.TrackAfter);return n??void 0}}),m9=new class extends Bh{};m9.startSide=1;m9.endSide=-1;const gue=Oi.define({create(){return Bn.empty},update(t,e){if(t=t.map(e.changes),e.selection){let n=e.state.doc.lineAt(e.selection.main.head);t=t.update({filter:r=>r>=n.from&&r<=n.to})}for(let n of e.effects)n.is(Qm)&&(t=t.update({add:[m9.range(n.value,n.value+1)]}));return t}});function fqe(){return[mqe,gue]}const G3="()[]{}<>«»»«[]{}";function xue(t){for(let e=0;e<G3.length;e+=2)if(G3.charCodeAt(e)==t)return G3.charAt(e+1);return OL(t<128?t:t+1)}function yue(t,e){return t.languageDataAt("closeBrackets",e)[0]||I1}const hqe=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),mqe=Nt.inputHandler.of((t,e,n,r)=>{if((hqe?t.composing:t.compositionStarted)||t.state.readOnly)return!1;let s=t.state.selection.main;if(r.length>2||r.length==2&&qc(na(r,0))==1||e!=s.from||n!=s.to)return!1;let i=xqe(t.state,r);return i?(t.dispatch(i),!0):!1}),pqe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let r=yue(t,t.selection.main.head).brackets||I1.brackets,s=null,i=t.changeByRange(a=>{if(a.empty){let l=yqe(t.doc,a.head);for(let c of r)if(c==l&&_5(t.doc,a.head)==xue(na(c,0)))return{changes:{from:a.head-c.length,to:a.head+c.length},range:Qe.cursor(a.head-c.length)}}return{range:s=a}});return s||e(t.update(i,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},gqe=[{key:"Backspace",run:pqe}];function xqe(t,e){let n=yue(t,t.selection.main.head),r=n.brackets||I1.brackets;for(let s of r){let i=xue(na(s,0));if(e==s)return i==s?wqe(t,s,r.indexOf(s+s+s)>-1,n):bqe(t,s,i,n.before||I1.before);if(e==i&&bue(t,t.selection.main.from))return vqe(t,s,i)}return null}function bue(t,e){let n=!1;return t.field(gue).between(0,t.doc.length,r=>{r==e&&(n=!0)}),n}function _5(t,e){let n=t.sliceString(e,e+2);return n.slice(0,qc(na(n,0)))}function yqe(t,e){let n=t.sliceString(e-2,e);return qc(na(n,0))==n.length?n:n.slice(1)}function bqe(t,e,n,r){let s=null,i=t.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:n,from:a.to}],effects:Qm.of(a.to+e.length),range:Qe.range(a.anchor+e.length,a.head+e.length)};let l=_5(t.doc,a.head);return!l||/\s/.test(l)||r.indexOf(l)>-1?{changes:{insert:e+n,from:a.head},effects:Qm.of(a.head+e.length),range:Qe.cursor(a.head+e.length)}:{range:s=a}});return s?null:t.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function vqe(t,e,n){let r=null,s=t.changeByRange(i=>i.empty&&_5(t.doc,i.head)==n?{changes:{from:i.head,to:i.head+n.length,insert:n},range:Qe.cursor(i.head+n.length)}:r={range:i});return r?null:t.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function wqe(t,e,n,r){let s=r.stringPrefixes||I1.stringPrefixes,i=null,a=t.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Qm.of(l.to+e.length),range:Qe.range(l.anchor+e.length,l.head+e.length)};let c=l.head,u=_5(t.doc,c),f;if(u==e){if(TK(t,c))return{changes:{insert:e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)};if(bue(t,c)){let p=n&&t.sliceDoc(c,c+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:c,to:c+p.length,insert:p},range:Qe.cursor(c+p.length)}}}else{if(n&&t.sliceDoc(c-2*e.length,c)==e+e&&(f=MK(t,c-2*e.length,s))>-1&&TK(t,f))return{changes:{insert:e+e+e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)};if(t.charCategorizer(c)(u)!=hs.Word&&MK(t,c,s)>-1&&!kqe(t,c,e,s))return{changes:{insert:e+e,from:c},effects:Qm.of(c+e.length),range:Qe.cursor(c+e.length)}}return{range:i=l}});return i?null:t.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function TK(t,e){let n=Ji(t).resolveInner(e+1);return n.parent&&n.from==e}function kqe(t,e,n,r){let s=Ji(t).resolveInner(e,-1),i=r.reduce((a,l)=>Math.max(a,l.length),0);for(let a=0;a<5;a++){let l=t.sliceDoc(s.from,Math.min(s.to,s.from+n.length+i)),c=l.indexOf(n);if(!c||c>-1&&r.indexOf(l.slice(0,c))>-1){let f=s.firstChild;for(;f&&f.from==s.from&&f.to-f.from>n.length+c;){if(t.sliceDoc(f.to-n.length,f.to)==n)return!1;f=f.firstChild}return!0}let u=s.to==e&&s.parent;if(!u)break;s=u}return!1}function MK(t,e,n){let r=t.charCategorizer(e);if(r(t.sliceDoc(e-1,e))!=hs.Word)return e;for(let s of n){let i=e-s.length;if(t.sliceDoc(i,e)==s&&r(t.sliceDoc(i-1,i))!=hs.Word)return i}return-1}function Cqe(t={}){return[eqe,ra,ji.of(t),ZHe,jqe,mue]}const vue=[{key:"Ctrl-Space",run:W3},{mac:"Alt-`",run:W3},{mac:"Alt-i",run:W3},{key:"Escape",run:GHe},{key:"ArrowDown",run:u2(!0)},{key:"ArrowUp",run:u2(!1)},{key:"PageDown",run:u2(!0,"page")},{key:"PageUp",run:u2(!1,"page")},{key:"Enter",run:WHe}],jqe=um.highest(Vw.computeN([ji],t=>t.facet(ji).defaultKeymap?[vue]:[])),Nqe=t=>{let{state:e}=t,n=e.doc.lineAt(e.selection.main.from),r=g9(t.state,n.from);return r.line?Sqe(t):r.block?Eqe(t):!1};function p9(t,e){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=t(e,n);return s?(r(n.update(s)),!0):!1}}const Sqe=p9(Mqe,0),_qe=p9(wue,0),Eqe=p9((t,e)=>wue(t,e,Tqe(e)),0);function g9(t,e){let n=t.languageDataAt("commentTokens",e,1);return n.length?n[0]:{}}const $b=50;function Aqe(t,{open:e,close:n},r,s){let i=t.sliceDoc(r-$b,r),a=t.sliceDoc(s,s+$b),l=/\s*$/.exec(i)[0].length,c=/^\s*/.exec(a)[0].length,u=i.length-l;if(i.slice(u-e.length,u)==e&&a.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let f,h;s-r<=2*$b?f=h=t.sliceDoc(r,s):(f=t.sliceDoc(r,r+$b),h=t.sliceDoc(s-$b,s));let p=/^\s*/.exec(f)[0].length,g=/\s*$/.exec(h)[0].length,b=h.length-g-n.length;return f.slice(p,p+e.length)==e&&h.slice(b,b+n.length)==n?{open:{pos:r+p+e.length,margin:/\s/.test(f.charAt(p+e.length))?1:0},close:{pos:s-g-n.length,margin:/\s/.test(h.charAt(b-1))?1:0}}:null}function Tqe(t){let e=[];for(let n of t.selection.ranges){let r=t.doc.lineAt(n.from),s=n.to<=r.to?r:t.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:t.doc.lineAt(n.to-1));let i=e.length-1;i>=0&&e[i].to>r.from?e[i].to=s.to:e.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return e}function wue(t,e,n=e.selection.ranges){let r=n.map(i=>g9(e,i.from).block);if(!r.every(i=>i))return null;let s=n.map((i,a)=>Aqe(e,r[a],i.from,i.to));if(t!=2&&!s.every(i=>i))return{changes:e.changes(n.map((i,a)=>s[a]?[]:[{from:i.from,insert:r[a].open+" "},{from:i.to,insert:" "+r[a].close}]))};if(t!=1&&s.some(i=>i)){let i=[];for(let a=0,l;a<s.length;a++)if(l=s[a]){let c=r[a],{open:u,close:f}=l;i.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:f.pos-f.margin,to:f.pos+c.close.length})}return{changes:i}}return null}function Mqe(t,e,n=e.selection.ranges){let r=[],s=-1;e:for(let{from:i,to:a}of n){let l=r.length,c=1e9,u;for(let f=i;f<=a;){let h=e.doc.lineAt(f);if(u==null&&(u=g9(e,h.from).line,!u))continue e;if(h.from>s&&(i==a||a>h.from)){s=h.from;let p=/^\s*/.exec(h.text)[0].length,g=p==h.length,b=h.text.slice(p,p+u.length)==u?p:-1;p<h.text.length&&p<c&&(c=p),r.push({line:h,comment:b,token:u,indent:p,empty:g,single:!1})}f=h.to+1}if(c<1e9)for(let f=l;f<r.length;f++)r[f].indent<r[f].line.text.length&&(r[f].indent=c);r.length==l+1&&(r[l].single=!0)}if(t!=2&&r.some(i=>i.comment<0&&(!i.empty||i.single))){let i=[];for(let{line:l,token:c,indent:u,empty:f,single:h}of r)(h||!f)&&i.push({from:l.from+u,insert:c+" "});let a=e.changes(i);return{changes:a,selection:e.selection.map(a,1)}}else if(t!=1&&r.some(i=>i.comment>=0)){let i=[];for(let{line:a,comment:l,token:c}of r)if(l>=0){let u=a.from+l,f=u+c.length;a.text[f-a.from]==" "&&f++,i.push({from:u,to:f})}return{changes:i}}return null}const oO=ef.define(),Iqe=ef.define(),Rqe=_t.define(),kue=_t.define({combine(t){return Cu(t,{minDepth:100,newGroupDelay:500,joinToEvent:(e,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,n)=>(r,s)=>e(r,s)||n(r,s)})}}),Cue=Oi.define({create(){return eu.empty},update(t,e){let n=e.state.facet(kue),r=e.annotation(oO);if(r){let c=la.fromTransaction(e,r.selection),u=r.side,f=u==0?t.undone:t.done;return c?f=rS(f,f.length,n.minDepth,c):f=Sue(f,e.startState.selection),new eu(u==0?r.rest:f,u==0?f:r.rest)}let s=e.annotation(Iqe);if((s=="full"||s=="before")&&(t=t.isolate()),e.annotation(Zs.addToHistory)===!1)return e.changes.empty?t:t.addMapping(e.changes.desc);let i=la.fromTransaction(e),a=e.annotation(Zs.time),l=e.annotation(Zs.userEvent);return i?t=t.addChanges(i,a,l,n,e):e.selection&&(t=t.addSelection(e.startState.selection,a,l,n.newGroupDelay)),(s=="full"||s=="after")&&(t=t.isolate()),t},toJSON(t){return{done:t.done.map(e=>e.toJSON()),undone:t.undone.map(e=>e.toJSON())}},fromJSON(t){return new eu(t.done.map(la.fromJSON),t.undone.map(la.fromJSON))}});function Oqe(t={}){return[Cue,kue.of(t),Nt.domEventHandlers({beforeinput(e,n){let r=e.inputType=="historyUndo"?jue:e.inputType=="historyRedo"?aO:null;return r?(e.preventDefault(),r(n)):!1}})]}function E5(t,e){return function({state:n,dispatch:r}){if(!e&&n.readOnly)return!1;let s=n.field(Cue,!1);if(!s)return!1;let i=s.pop(t,n,e);return i?(r(i),!0):!1}}const jue=E5(0,!1),aO=E5(1,!1),Dqe=E5(0,!0),Pqe=E5(1,!0);class la{constructor(e,n,r,s,i){this.changes=e,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=i}setSelAfter(e){return new la(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,n,r;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new la(e.changes&&oi.fromJSON(e.changes),[],e.mapped&&iu.fromJSON(e.mapped),e.startSelection&&Qe.fromJSON(e.startSelection),e.selectionsAfter.map(Qe.fromJSON))}static fromTransaction(e,n){let r=vl;for(let s of e.startState.facet(Rqe)){let i=s(e);i.length&&(r=r.concat(i))}return!r.length&&e.changes.empty?null:new la(e.changes.invert(e.startState.doc),r,void 0,n||e.startState.selection,vl)}static selection(e){return new la(void 0,vl,void 0,void 0,e)}}function rS(t,e,n,r){let s=e+1>n+20?e-n-1:0,i=t.slice(s,e);return i.push(r),i}function Lqe(t,e){let n=[],r=!1;return t.iterChangedRanges((s,i)=>n.push(s,i)),e.iterChangedRanges((s,i,a,l)=>{for(let c=0;c<n.length;){let u=n[c++],f=n[c++];l>=u&&a<=f&&(r=!0)}}),r}function $qe(t,e){return t.ranges.length==e.ranges.length&&t.ranges.filter((n,r)=>n.empty!=e.ranges[r].empty).length===0}function Nue(t,e){return t.length?e.length?t.concat(e):t:e}const vl=[],Fqe=200;function Sue(t,e){if(t.length){let n=t[t.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-Fqe));return r.length&&r[r.length-1].eq(e)?t:(r.push(e),rS(t,t.length-1,1e9,n.setSelAfter(r)))}else return[la.selection([e])]}function Bqe(t){let e=t[t.length-1],n=t.slice();return n[t.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),n}function Y3(t,e){if(!t.length)return t;let n=t.length,r=vl;for(;n;){let s=zqe(t[n-1],e,r);if(s.changes&&!s.changes.empty||s.effects.length){let i=t.slice(0,n);return i[n-1]=s,i}else e=s.mapped,n--,r=s.selectionsAfter}return r.length?[la.selection(r)]:vl}function zqe(t,e,n){let r=Nue(t.selectionsAfter.length?t.selectionsAfter.map(l=>l.map(e)):vl,n);if(!t.changes)return la.selection(r);let s=t.changes.map(e),i=e.mapDesc(t.changes,!0),a=t.mapped?t.mapped.composeDesc(i):i;return new la(s,pn.mapEffects(t.effects,e),a,t.startSelection.map(i),r)}const Uqe=/^(input\.type|delete)($|\.)/;class eu{constructor(e,n,r=0,s=void 0){this.done=e,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new eu(this.done,this.undone):this}addChanges(e,n,r,s,i){let a=this.done,l=a[a.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!r||Uqe.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(i,Lqe(l.changes,e.changes))||r=="input.type.compose")?a=rS(a,a.length-1,s.minDepth,new la(e.changes.compose(l.changes),Nue(pn.mapEffects(e.effects,l.changes),l.effects),l.mapped,l.startSelection,vl)):a=rS(a,a.length,s.minDepth,e),new eu(a,vl,n,r)}addSelection(e,n,r,s){let i=this.done.length?this.done[this.done.length-1].selectionsAfter:vl;return i.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&$qe(i[i.length-1],e)?this:new eu(Sue(this.done,e),this.undone,n,r)}addMapping(e){return new eu(Y3(this.done,e),Y3(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,n,r){let s=e==0?this.done:this.undone;if(s.length==0)return null;let i=s[s.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):n.selection);if(r&&i.selectionsAfter.length)return n.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:oO.of({side:e,rest:Bqe(s),selection:a}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(i.changes){let l=s.length==1?vl:s.slice(0,s.length-1);return i.mapped&&(l=Y3(l,i.mapped)),n.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:oO.of({side:e,rest:l,selection:a}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}}eu.empty=new eu(vl,vl);const Vqe=[{key:"Mod-z",run:jue,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:aO,preventDefault:!0},{linux:"Ctrl-Shift-z",run:aO,preventDefault:!0},{key:"Mod-u",run:Dqe,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Pqe,preventDefault:!0}];function _0(t,e){return Qe.create(t.ranges.map(e),t.mainIndex)}function kc(t,e){return t.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function Cc({state:t,dispatch:e},n){let r=_0(t.selection,n);return r.eq(t.selection,!0)?!1:(e(kc(t,r)),!0)}function A5(t,e){return Qe.cursor(e?t.to:t.from)}function _ue(t,e){return Cc(t,n=>n.empty?t.moveByChar(n,e):A5(n,e))}function yo(t){return t.textDirectionAt(t.state.selection.main.head)==Kr.LTR}const Eue=t=>_ue(t,!yo(t)),Aue=t=>_ue(t,yo(t));function Tue(t,e){return Cc(t,n=>n.empty?t.moveByGroup(n,e):A5(n,e))}const Hqe=t=>Tue(t,!yo(t)),qqe=t=>Tue(t,yo(t));function Kqe(t,e,n){if(e.type.prop(n))return!0;let r=e.to-e.from;return r&&(r>2||/[^\s,.;:]/.test(t.sliceDoc(e.from,e.to)))||e.firstChild}function T5(t,e,n){let r=Ji(t).resolveInner(e.head),s=n?Ln.closedBy:Ln.openedBy;for(let c=e.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Kqe(t,u,s)?r=u:c=n?u.to:u.from}let i=r.type.prop(s),a,l;return i&&(a=n?Xc(t,r.from,1):Xc(t,r.to,-1))&&a.matched?l=n?a.end.to:a.end.from:l=n?r.to:r.from,Qe.cursor(l,n?-1:1)}const Wqe=t=>Cc(t,e=>T5(t.state,e,!yo(t))),Gqe=t=>Cc(t,e=>T5(t.state,e,yo(t)));function Mue(t,e){return Cc(t,n=>{if(!n.empty)return A5(n,e);let r=t.moveVertically(n,e);return r.head!=n.head?r:t.moveToLineBoundary(n,e)})}const Iue=t=>Mue(t,!1),Rue=t=>Mue(t,!0);function Oue(t){let e=t.scrollDOM.clientHeight<t.scrollDOM.scrollHeight-2,n=0,r=0,s;if(e){for(let i of t.state.facet(Nt.scrollMargins)){let a=i(t);a!=null&&a.top&&(n=Math.max(a==null?void 0:a.top,n)),a!=null&&a.bottom&&(r=Math.max(a==null?void 0:a.bottom,r))}s=t.scrollDOM.clientHeight-n-r}else s=(t.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:e,height:Math.max(t.defaultLineHeight,s-5)}}function Due(t,e){let n=Oue(t),{state:r}=t,s=_0(r.selection,a=>a.empty?t.moveVertically(a,e,n.height):A5(a,e));if(s.eq(r.selection))return!1;let i;if(n.selfScroll){let a=t.coordsAtPos(r.selection.main.head),l=t.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;a&&a.top>c&&a.bottom<u&&(i=Nt.scrollIntoView(s.main.head,{y:"start",yMargin:a.top-c}))}return t.dispatch(kc(r,s),{effects:i}),!0}const IK=t=>Due(t,!1),lO=t=>Due(t,!0);function dm(t,e,n){let r=t.lineBlockAt(e.head),s=t.moveToLineBoundary(e,n);if(s.head==e.head&&s.head!=(n?r.to:r.from)&&(s=t.moveToLineBoundary(e,n,!1)),!n&&s.head==r.from&&r.length){let i=/^\s*/.exec(t.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;i&&e.head!=r.from+i&&(s=Qe.cursor(r.from+i))}return s}const Yqe=t=>Cc(t,e=>dm(t,e,!0)),Jqe=t=>Cc(t,e=>dm(t,e,!1)),Qqe=t=>Cc(t,e=>dm(t,e,!yo(t))),Zqe=t=>Cc(t,e=>dm(t,e,yo(t))),Xqe=t=>Cc(t,e=>Qe.cursor(t.lineBlockAt(e.head).from,1)),eKe=t=>Cc(t,e=>Qe.cursor(t.lineBlockAt(e.head).to,-1));function tKe(t,e,n){let r=!1,s=_0(t.selection,i=>{let a=Xc(t,i.head,-1)||Xc(t,i.head,1)||i.head>0&&Xc(t,i.head-1,1)||i.head<t.doc.length&&Xc(t,i.head+1,-1);if(!a||!a.end)return i;r=!0;let l=a.start.from==i.head?a.end.to:a.end.from;return Qe.cursor(l)});return r?(e(kc(t,s)),!0):!1}const nKe=({state:t,dispatch:e})=>tKe(t,e);function Rl(t,e){let n=_0(t.state.selection,r=>{let s=e(r);return Qe.range(r.anchor,s.head,s.goalColumn,s.bidiLevel||void 0)});return n.eq(t.state.selection)?!1:(t.dispatch(kc(t.state,n)),!0)}function Pue(t,e){return Rl(t,n=>t.moveByChar(n,e))}const Lue=t=>Pue(t,!yo(t)),$ue=t=>Pue(t,yo(t));function Fue(t,e){return Rl(t,n=>t.moveByGroup(n,e))}const rKe=t=>Fue(t,!yo(t)),sKe=t=>Fue(t,yo(t)),iKe=t=>Rl(t,e=>T5(t.state,e,!yo(t))),oKe=t=>Rl(t,e=>T5(t.state,e,yo(t)));function Bue(t,e){return Rl(t,n=>t.moveVertically(n,e))}const zue=t=>Bue(t,!1),Uue=t=>Bue(t,!0);function Vue(t,e){return Rl(t,n=>t.moveVertically(n,e,Oue(t).height))}const RK=t=>Vue(t,!1),OK=t=>Vue(t,!0),aKe=t=>Rl(t,e=>dm(t,e,!0)),lKe=t=>Rl(t,e=>dm(t,e,!1)),cKe=t=>Rl(t,e=>dm(t,e,!yo(t))),uKe=t=>Rl(t,e=>dm(t,e,yo(t))),dKe=t=>Rl(t,e=>Qe.cursor(t.lineBlockAt(e.head).from)),fKe=t=>Rl(t,e=>Qe.cursor(t.lineBlockAt(e.head).to)),DK=({state:t,dispatch:e})=>(e(kc(t,{anchor:0})),!0),PK=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.doc.length})),!0),LK=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.selection.main.anchor,head:0})),!0),$K=({state:t,dispatch:e})=>(e(kc(t,{anchor:t.selection.main.anchor,head:t.doc.length})),!0),hKe=({state:t,dispatch:e})=>(e(t.update({selection:{anchor:0,head:t.doc.length},userEvent:"select"})),!0),mKe=({state:t,dispatch:e})=>{let n=M5(t).map(({from:r,to:s})=>Qe.range(r,Math.min(s+1,t.doc.length)));return e(t.update({selection:Qe.create(n),userEvent:"select"})),!0},pKe=({state:t,dispatch:e})=>{let n=_0(t.selection,r=>{let s=Ji(t),i=s.resolveStack(r.from,1);if(r.empty){let a=s.resolveStack(r.from,-1);a.node.from>=i.node.from&&a.node.to<=i.node.to&&(i=a)}for(let a=i;a;a=a.next){let{node:l}=a;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&a.next)return Qe.range(l.to,l.from)}return r});return n.eq(t.selection)?!1:(e(kc(t,n)),!0)};function Hue(t,e){let{state:n}=t,r=n.selection,s=n.selection.ranges.slice();for(let i of n.selection.ranges){let a=n.doc.lineAt(i.head);if(e?a.to<t.state.doc.length:a.from>0)for(let l=i;;){let c=t.moveVertically(l,e);if(c.head<a.from||c.head>a.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(t.dispatch(kc(n,Qe.create(s,s.length-1))),!0)}const gKe=t=>Hue(t,!1),xKe=t=>Hue(t,!0),yKe=({state:t,dispatch:e})=>{let n=t.selection,r=null;return n.ranges.length>1?r=Qe.create([n.main]):n.main.empty||(r=Qe.create([Qe.cursor(n.main.head)])),r?(e(kc(t,r)),!0):!1};function Gw(t,e){if(t.state.readOnly)return!1;let n="delete.selection",{state:r}=t,s=r.changeByRange(i=>{let{from:a,to:l}=i;if(a==l){let c=e(i);c<a?(n="delete.backward",c=d2(t,c,!1)):c>a&&(n="delete.forward",c=d2(t,c,!0)),a=Math.min(a,c),l=Math.max(l,c)}else a=d2(t,a,!1),l=d2(t,l,!0);return a==l?{range:i}:{changes:{from:a,to:l},range:Qe.cursor(a,a<i.head?-1:1)}});return s.changes.empty?!1:(t.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Nt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function d2(t,e,n){if(t instanceof Nt)for(let r of t.state.facet(Nt.atomicRanges).map(s=>s(t)))r.between(e,e,(s,i)=>{s<e&&i>e&&(e=n?i:s)});return e}const que=(t,e,n)=>Gw(t,r=>{let s=r.from,{state:i}=t,a=i.doc.lineAt(s),l,c;if(n&&!e&&s>a.from&&s<a.from+200&&!/[^ \t]/.test(l=a.text.slice(0,s-a.from))){if(l[l.length-1]==" ")return s-1;let u=N0(l,i.tabSize),f=u%Yp(i)||Yp(i);for(let h=0;h<f&&l[l.length-1-h]==" ";h++)s--;c=s}else c=Ii(a.text,s-a.from,e,e)+a.from,c==s&&a.number!=(e?i.doc.lines:1)?c+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(a.text.slice(c-a.from,s-a.from))&&(c=Ii(a.text,c-a.from,!1,!1)+a.from);return c}),cO=t=>que(t,!1,!0),Kue=t=>que(t,!0,!1),Wue=(t,e)=>Gw(t,n=>{let r=n.head,{state:s}=t,i=s.doc.lineAt(r),a=s.charCategorizer(r);for(let l=null;;){if(r==(e?i.to:i.from)){r==n.head&&i.number!=(e?s.doc.lines:1)&&(r+=e?1:-1);break}let c=Ii(i.text,r-i.from,e)+i.from,u=i.text.slice(Math.min(r,c)-i.from,Math.max(r,c)-i.from),f=a(u);if(l!=null&&f!=l)break;(u!=" "||r!=n.head)&&(l=f),r=c}return r}),Gue=t=>Wue(t,!1),bKe=t=>Wue(t,!0),vKe=t=>Gw(t,e=>{let n=t.lineBlockAt(e.head).to;return e.head<n?n:Math.min(t.state.doc.length,e.head+1)}),wKe=t=>Gw(t,e=>{let n=t.moveToLineBoundary(e,!1).head;return e.head>n?n:Math.max(0,e.head-1)}),kKe=t=>Gw(t,e=>{let n=t.moveToLineBoundary(e,!0).head;return e.head<n?n:Math.min(t.state.doc.length,e.head+1)}),CKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=t.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:pr.of(["",""])},range:Qe.cursor(r.from)}));return e(t.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},jKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=t.changeByRange(r=>{if(!r.empty||r.from==0||r.from==t.doc.length)return{range:r};let s=r.from,i=t.doc.lineAt(s),a=s==i.from?s-1:Ii(i.text,s-i.from,!1)+i.from,l=s==i.to?s+1:Ii(i.text,s-i.from,!0)+i.from;return{changes:{from:a,to:l,insert:t.doc.slice(s,l).append(t.doc.slice(a,s))},range:Qe.cursor(l)}});return n.changes.empty?!1:(e(t.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function M5(t){let e=[],n=-1;for(let r of t.selection.ranges){let s=t.doc.lineAt(r.from),i=t.doc.lineAt(r.to);if(!r.empty&&r.to==i.from&&(i=t.doc.lineAt(r.to-1)),n>=s.number){let a=e[e.length-1];a.to=i.to,a.ranges.push(r)}else e.push({from:s.from,to:i.to,ranges:[r]});n=i.number+1}return e}function Yue(t,e,n){if(t.readOnly)return!1;let r=[],s=[];for(let i of M5(t)){if(n?i.to==t.doc.length:i.from==0)continue;let a=t.doc.lineAt(n?i.to+1:i.from-1),l=a.length+1;if(n){r.push({from:i.to,to:a.to},{from:i.from,insert:a.text+t.lineBreak});for(let c of i.ranges)s.push(Qe.range(Math.min(t.doc.length,c.anchor+l),Math.min(t.doc.length,c.head+l)))}else{r.push({from:a.from,to:i.from},{from:i.to,insert:t.lineBreak+a.text});for(let c of i.ranges)s.push(Qe.range(c.anchor-l,c.head-l))}}return r.length?(e(t.update({changes:r,scrollIntoView:!0,selection:Qe.create(s,t.selection.mainIndex),userEvent:"move.line"})),!0):!1}const NKe=({state:t,dispatch:e})=>Yue(t,e,!1),SKe=({state:t,dispatch:e})=>Yue(t,e,!0);function Jue(t,e,n){if(t.readOnly)return!1;let r=[];for(let i of M5(t))n?r.push({from:i.from,insert:t.doc.slice(i.from,i.to)+t.lineBreak}):r.push({from:i.to,insert:t.lineBreak+t.doc.slice(i.from,i.to)});let s=t.changes(r);return e(t.update({changes:s,selection:t.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const _Ke=({state:t,dispatch:e})=>Jue(t,e,!1),EKe=({state:t,dispatch:e})=>Jue(t,e,!0),AKe=t=>{if(t.state.readOnly)return!1;let{state:e}=t,n=e.changes(M5(e).map(({from:s,to:i})=>(s>0?s--:i<e.doc.length&&i++,{from:s,to:i}))),r=_0(e.selection,s=>{let i;if(t.lineWrapping){let a=t.lineBlockAt(s.head),l=t.coordsAtPos(s.head,s.assoc||1);l&&(i=a.bottom+t.documentTop-l.bottom+t.defaultLineHeight/2)}return t.moveVertically(s,!0,i)}).map(n);return t.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function TKe(t,e){if(/\(\)|\[\]|\{\}/.test(t.sliceDoc(e-1,e+1)))return{from:e,to:e};let n=Ji(t).resolveInner(e),r=n.childBefore(e),s=n.childAfter(e),i;return r&&s&&r.to<=e&&s.from>=e&&(i=r.type.prop(Ln.closedBy))&&i.indexOf(s.name)>-1&&t.doc.lineAt(r.to).from==t.doc.lineAt(s.from).from&&!/\S/.test(t.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const FK=Que(!1),MKe=Que(!0);function Que(t){return({state:e,dispatch:n})=>{if(e.readOnly)return!1;let r=e.changeByRange(s=>{let{from:i,to:a}=s,l=e.doc.lineAt(i),c=!t&&i==a&&TKe(e,i);t&&(i=a=(a<=l.to?l:e.doc.lineAt(a)).to);let u=new N5(e,{simulateBreak:i,simulateDoubleBreak:!!c}),f=r9(u,i);for(f==null&&(f=N0(/^\s*/.exec(e.doc.lineAt(i).text)[0],e.tabSize));a<l.to&&/\s/.test(l.text[a-l.from]);)a++;c?{from:i,to:a}=c:i>l.from&&i<l.from+100&&!/\S/.test(l.text.slice(0,i))&&(i=l.from);let h=["",E1(e,f)];return c&&h.push(E1(e,u.lineIndent(l.from,-1))),{changes:{from:i,to:a,insert:pr.of(h)},range:Qe.cursor(i+1+h[1].length)}});return n(e.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function x9(t,e){let n=-1;return t.changeByRange(r=>{let s=[];for(let a=r.from;a<=r.to;){let l=t.doc.lineAt(a);l.number>n&&(r.empty||r.to>l.from)&&(e(l,s,r),n=l.number),a=l.to+1}let i=t.changes(s);return{changes:s,range:Qe.range(i.mapPos(r.anchor,1),i.mapPos(r.head,1))}})}const IKe=({state:t,dispatch:e})=>{if(t.readOnly)return!1;let n=Object.create(null),r=new N5(t,{overrideIndentation:i=>{let a=n[i];return a??-1}}),s=x9(t,(i,a,l)=>{let c=r9(r,i.from);if(c==null)return;/\S/.test(i.text)||(c=0);let u=/^\s*/.exec(i.text)[0],f=E1(t,c);(u!=f||l.from<i.from+u.length)&&(n[i.from]=c,a.push({from:i.from,to:i.from+u.length,insert:f}))});return s.changes.empty||e(t.update(s,{userEvent:"indent"})),!0},Zue=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(x9(t,(n,r)=>{r.push({from:n.from,insert:t.facet(j5)})}),{userEvent:"input.indent"})),!0),Xue=({state:t,dispatch:e})=>t.readOnly?!1:(e(t.update(x9(t,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let i=N0(s,t.tabSize),a=0,l=E1(t,Math.max(0,i-Yp(t)));for(;a<s.length&&a<l.length&&s.charCodeAt(a)==l.charCodeAt(a);)a++;r.push({from:n.from+a,to:n.from+s.length,insert:l.slice(a)})}),{userEvent:"delete.dedent"})),!0),RKe=t=>(t.setTabFocusMode(),!0),OKe=[{key:"Ctrl-b",run:Eue,shift:Lue,preventDefault:!0},{key:"Ctrl-f",run:Aue,shift:$ue},{key:"Ctrl-p",run:Iue,shift:zue},{key:"Ctrl-n",run:Rue,shift:Uue},{key:"Ctrl-a",run:Xqe,shift:dKe},{key:"Ctrl-e",run:eKe,shift:fKe},{key:"Ctrl-d",run:Kue},{key:"Ctrl-h",run:cO},{key:"Ctrl-k",run:vKe},{key:"Ctrl-Alt-h",run:Gue},{key:"Ctrl-o",run:CKe},{key:"Ctrl-t",run:jKe},{key:"Ctrl-v",run:lO}],DKe=[{key:"ArrowLeft",run:Eue,shift:Lue,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Hqe,shift:rKe,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Qqe,shift:cKe,preventDefault:!0},{key:"ArrowRight",run:Aue,shift:$ue,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:qqe,shift:sKe,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Zqe,shift:uKe,preventDefault:!0},{key:"ArrowUp",run:Iue,shift:zue,preventDefault:!0},{mac:"Cmd-ArrowUp",run:DK,shift:LK},{mac:"Ctrl-ArrowUp",run:IK,shift:RK},{key:"ArrowDown",run:Rue,shift:Uue,preventDefault:!0},{mac:"Cmd-ArrowDown",run:PK,shift:$K},{mac:"Ctrl-ArrowDown",run:lO,shift:OK},{key:"PageUp",run:IK,shift:RK},{key:"PageDown",run:lO,shift:OK},{key:"Home",run:Jqe,shift:lKe,preventDefault:!0},{key:"Mod-Home",run:DK,shift:LK},{key:"End",run:Yqe,shift:aKe,preventDefault:!0},{key:"Mod-End",run:PK,shift:$K},{key:"Enter",run:FK,shift:FK},{key:"Mod-a",run:hKe},{key:"Backspace",run:cO,shift:cO,preventDefault:!0},{key:"Delete",run:Kue,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Gue,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:bKe,preventDefault:!0},{mac:"Mod-Backspace",run:wKe,preventDefault:!0},{mac:"Mod-Delete",run:kKe,preventDefault:!0}].concat(OKe.map(t=>({mac:t.key,run:t.run,shift:t.shift}))),PKe=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Wqe,shift:iKe},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Gqe,shift:oKe},{key:"Alt-ArrowUp",run:NKe},{key:"Shift-Alt-ArrowUp",run:_Ke},{key:"Alt-ArrowDown",run:SKe},{key:"Shift-Alt-ArrowDown",run:EKe},{key:"Mod-Alt-ArrowUp",run:gKe},{key:"Mod-Alt-ArrowDown",run:xKe},{key:"Escape",run:yKe},{key:"Mod-Enter",run:MKe},{key:"Alt-l",mac:"Ctrl-l",run:mKe},{key:"Mod-i",run:pKe,preventDefault:!0},{key:"Mod-[",run:Xue},{key:"Mod-]",run:Zue},{key:"Mod-Alt-\\",run:IKe},{key:"Shift-Mod-k",run:AKe},{key:"Shift-Mod-\\",run:nKe},{key:"Mod-/",run:Nqe},{key:"Alt-A",run:_qe},{key:"Ctrl-m",mac:"Shift-Alt-m",run:RKe}].concat(DKe),LKe={key:"Tab",run:Zue,shift:Xue};function $Ke(t,e,n,r){const s=fu(fs),i=Oa(Poe),a=Y.useRef(null),{lexicalNode:l}=xR(),c=Y.useRef(!1),u=Y.useRef(!1),f=Y.useCallback(()=>{i({editorType:e,rootNode:l,editorRef:a.current})},[e,l,i]),h=Y.useCallback(p=>{var g,b,v,w,j,C;if(p.key==="ArrowDown"){const N=(b=(g=a.current)==null?void 0:g.getCodemirror())==null?void 0:b.state;if(N){const S=N.doc.length,T=N.selection.ranges[0].to;S===T&&(c.current?(s==null||s.update(()=>{var _,A;const M=su(t);M.getNextSibling()?((A=(_=a.current)==null?void 0:_.getCodemirror())==null||A.contentDOM.blur(),M.selectNext()):M.insertAfter(gs())}),c.current=!1):c.current=!0)}}else if(p.key==="ArrowUp"){const N=(w=(v=a.current)==null?void 0:v.getCodemirror())==null?void 0:w.state;N&&N.selection.ranges[0].from===0&&(u.current?(s==null||s.update(()=>{var T,_;const A=su(t);A.getPreviousSibling()&&((_=(T=a.current)==null?void 0:T.getCodemirror())==null||_.contentDOM.blur(),A.selectPrevious())}),u.current=!1):u.current=!0)}else if(p.key==="Enter")p.stopPropagation();else if(p.key==="Backspace"||p.key==="Delete"){const N=(C=(j=a.current)==null?void 0:j.getCodemirror())==null?void 0:C.state;(N==null?void 0:N.doc.length)===0&&(s==null||s.update(()=>{su(t).remove()}))}},[s,t]);return Y.useEffect(()=>{const p=a.current;return setTimeout(()=>{var g,b;(g=p==null?void 0:p.getCodemirror())==null||g.contentDOM.addEventListener("focus",f),(b=p==null?void 0:p.getCodemirror())==null||b.contentDOM.addEventListener("keydown",h)},300),()=>{var g,b;(g=p==null?void 0:p.getCodemirror())==null||g.contentDOM.removeEventListener("focus",f),(b=p==null?void 0:p.getCodemirror())==null||b.contentDOM.removeEventListener("keydown",h)}},[a,f,h,n]),Y.useEffect(()=>{r.subscribe(()=>{var p,g;(g=(p=a.current)==null?void 0:p.getCodemirror())==null||g.focus(),f()})},[r,a,t,f]),a}function et(t){return new $Ve(i9.define(t))}function If(t){return ze(()=>import("./index-BFpb1Uts.js"),__vite__mapDeps([0,1])).then(e=>e.sql({dialect:e[t]}))}const FKe=[Pe.of({name:"C",extensions:["c","h","ino"],load(){return ze(()=>import("./index-CgdLFP5M.js"),__vite__mapDeps([2,1])).then(t=>t.cpp())}}),Pe.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return ze(()=>import("./index-CgdLFP5M.js"),__vite__mapDeps([2,1])).then(t=>t.cpp())}}),Pe.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return If("Cassandra")}}),Pe.of({name:"CSS",extensions:["css"],load(){return ze(()=>import("./index-D323YpVi.js"),__vite__mapDeps([3,1])).then(t=>t.css())}}),Pe.of({name:"Go",extensions:["go"],load(){return ze(()=>import("./index-CE0HSzds.js"),__vite__mapDeps([4,1])).then(t=>t.go())}}),Pe.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return ze(()=>import("./index-Bwrg3TbX.js"),__vite__mapDeps([5,1,3,6])).then(t=>t.html())}}),Pe.of({name:"Java",extensions:["java"],load(){return ze(()=>import("./index-DC95VDCB.js"),__vite__mapDeps([7,1])).then(t=>t.java())}}),Pe.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return ze(()=>import("./index-D3U0l9Rd.js"),__vite__mapDeps([6,1])).then(t=>t.javascript())}}),Pe.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return ze(()=>import("./index-BtbG7lJJ.js"),__vite__mapDeps([8,5,1,3,6])).then(t=>t.jinja())}}),Pe.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return ze(()=>import("./index-BCiTpvW7.js"),__vite__mapDeps([9,1])).then(t=>t.json())}}),Pe.of({name:"JSX",extensions:["jsx"],load(){return ze(()=>import("./index-D3U0l9Rd.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({jsx:!0}))}}),Pe.of({name:"LESS",extensions:["less"],load(){return ze(()=>import("./index-BmLtaZGd.js"),__vite__mapDeps([10,3,1])).then(t=>t.less())}}),Pe.of({name:"Liquid",extensions:["liquid"],load(){return ze(()=>import("./index-BxRp1P-l.js"),__vite__mapDeps([11,5,1,3,6])).then(t=>t.liquid())}}),Pe.of({name:"MariaDB SQL",load(){return If("MariaSQL")}}),Pe.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return ze(()=>import("./index-MmSDJweg.js"),__vite__mapDeps([12,5,1,3,6])).then(t=>t.markdown())}}),Pe.of({name:"MS SQL",load(){return If("MSSQL")}}),Pe.of({name:"MySQL",load(){return If("MySQL")}}),Pe.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return ze(()=>import("./index-Ub77KksK.js"),__vite__mapDeps([13,1,5,3,6])).then(t=>t.php())}}),Pe.of({name:"PLSQL",extensions:["pls"],load(){return If("PLSQL")}}),Pe.of({name:"PostgreSQL",load(){return If("PostgreSQL")}}),Pe.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return ze(()=>import("./index-CDlfoOW4.js"),__vite__mapDeps([14,1])).then(t=>t.python())}}),Pe.of({name:"Rust",extensions:["rs"],load(){return ze(()=>import("./index-DxMMWvuC.js"),__vite__mapDeps([15,1])).then(t=>t.rust())}}),Pe.of({name:"Sass",extensions:["sass"],load(){return ze(()=>import("./index-wl4NFr0G.js"),__vite__mapDeps([16,1,3])).then(t=>t.sass({indented:!0}))}}),Pe.of({name:"SCSS",extensions:["scss"],load(){return ze(()=>import("./index-wl4NFr0G.js"),__vite__mapDeps([16,1,3])).then(t=>t.sass())}}),Pe.of({name:"SQL",extensions:["sql"],load(){return If("StandardSQL")}}),Pe.of({name:"SQLite",load(){return If("SQLite")}}),Pe.of({name:"TSX",extensions:["tsx"],load(){return ze(()=>import("./index-D3U0l9Rd.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({jsx:!0,typescript:!0}))}}),Pe.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return ze(()=>import("./index-D3U0l9Rd.js"),__vite__mapDeps([6,1])).then(t=>t.javascript({typescript:!0}))}}),Pe.of({name:"WebAssembly",extensions:["wat","wast"],load(){return ze(()=>import("./index-h3EfCr48.js"),__vite__mapDeps([17,1])).then(t=>t.wast())}}),Pe.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return ze(()=>import("./index-DeRNQk7z.js"),__vite__mapDeps([18,1])).then(t=>t.xml())}}),Pe.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return ze(()=>import("./index-DKLd1OBJ.js"),__vite__mapDeps([19,1])).then(t=>t.yaml())}}),Pe.of({name:"APL",extensions:["dyalog","apl"],load(){return ze(()=>import("./apl-B4CMkyY2.js"),[]).then(t=>et(t.apl))}}),Pe.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return ze(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(t=>et(t.asciiArmor))}}),Pe.of({name:"ASN.1",extensions:["asn","asn1"],load(){return ze(()=>import("./asn1-EdZsLKOL.js"),[]).then(t=>et(t.asn1({})))}}),Pe.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return ze(()=>import("./asterisk-B-8jnY81.js"),[]).then(t=>et(t.asterisk))}}),Pe.of({name:"Brainfuck",extensions:["b","bf"],load(){return ze(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(t=>et(t.brainfuck))}}),Pe.of({name:"Cobol",extensions:["cob","cpy"],load(){return ze(()=>import("./cobol-CWcv1MsR.js"),[]).then(t=>et(t.cobol))}}),Pe.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.csharp))}}),Pe.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"ClojureScript",extensions:["cljs"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return ze(()=>import("./css-BnMrqG3P.js"),[]).then(t=>et(t.gss))}}),Pe.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return ze(()=>import("./cmake-BQqOBYOt.js"),[]).then(t=>et(t.cmake))}}),Pe.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return ze(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(t=>et(t.coffeeScript))}}),Pe.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return ze(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(t=>et(t.commonLisp))}}),Pe.of({name:"Cypher",extensions:["cyp","cypher"],load(){return ze(()=>import("./cypher-C_CwsFkJ.js"),[]).then(t=>et(t.cypher))}}),Pe.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return ze(()=>import("./python-BuPzkPfP.js"),[]).then(t=>et(t.cython))}}),Pe.of({name:"Crystal",extensions:["cr"],load(){return ze(()=>import("./crystal-SjHAIU92.js"),[]).then(t=>et(t.crystal))}}),Pe.of({name:"D",extensions:["d"],load(){return ze(()=>import("./d-pRatUO7H.js"),[]).then(t=>et(t.d))}}),Pe.of({name:"Dart",extensions:["dart"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.dart))}}),Pe.of({name:"diff",extensions:["diff","patch"],load(){return ze(()=>import("./diff-DbItnlRl.js"),[]).then(t=>et(t.diff))}}),Pe.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return ze(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([20,21])).then(t=>et(t.dockerFile))}}),Pe.of({name:"DTD",extensions:["dtd"],load(){return ze(()=>import("./dtd-DF_7sFjM.js"),[]).then(t=>et(t.dtd))}}),Pe.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return ze(()=>import("./dylan-DwRh75JA.js"),[]).then(t=>et(t.dylan))}}),Pe.of({name:"EBNF",load(){return ze(()=>import("./ebnf-CDyGwa7X.js"),[]).then(t=>et(t.ebnf))}}),Pe.of({name:"ECL",extensions:["ecl"],load(){return ze(()=>import("./ecl-Cabwm37j.js"),[]).then(t=>et(t.ecl))}}),Pe.of({name:"edn",extensions:["edn"],load(){return ze(()=>import("./clojure-BMjYHr_A.js"),[]).then(t=>et(t.clojure))}}),Pe.of({name:"Eiffel",extensions:["e"],load(){return ze(()=>import("./eiffel-CnydiIhH.js"),[]).then(t=>et(t.eiffel))}}),Pe.of({name:"Elm",extensions:["elm"],load(){return ze(()=>import("./elm-vLlmbW-K.js"),[]).then(t=>et(t.elm))}}),Pe.of({name:"Erlang",extensions:["erl"],load(){return ze(()=>import("./erlang-BNw1qcRV.js"),[]).then(t=>et(t.erlang))}}),Pe.of({name:"Esper",load(){return ze(()=>import("./sql-D0XecflT.js"),[]).then(t=>et(t.esper))}}),Pe.of({name:"Factor",extensions:["factor"],load(){return ze(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([22,21])).then(t=>et(t.factor))}}),Pe.of({name:"FCL",load(){return ze(()=>import("./fcl-Kvtd6kyn.js"),[]).then(t=>et(t.fcl))}}),Pe.of({name:"Forth",extensions:["forth","fth","4th"],load(){return ze(()=>import("./forth-Ffai-XNe.js"),[]).then(t=>et(t.forth))}}),Pe.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return ze(()=>import("./fortran-DYz_wnZ1.js"),[]).then(t=>et(t.fortran))}}),Pe.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.fSharp))}}),Pe.of({name:"Gas",extensions:["s"],load(){return ze(()=>import("./gas-Bneqetm1.js"),[]).then(t=>et(t.gas))}}),Pe.of({name:"Gherkin",extensions:["feature"],load(){return ze(()=>import("./gherkin-heZmZLOM.js"),[]).then(t=>et(t.gherkin))}}),Pe.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return ze(()=>import("./groovy-D9Dt4D0W.js"),[]).then(t=>et(t.groovy))}}),Pe.of({name:"Haskell",extensions:["hs"],load(){return ze(()=>import("./haskell-Cw1EW3IL.js"),[]).then(t=>et(t.haskell))}}),Pe.of({name:"Haxe",extensions:["hx"],load(){return ze(()=>import("./haxe-H-WmDvRZ.js"),[]).then(t=>et(t.haxe))}}),Pe.of({name:"HXML",extensions:["hxml"],load(){return ze(()=>import("./haxe-H-WmDvRZ.js"),[]).then(t=>et(t.hxml))}}),Pe.of({name:"HTTP",load(){return ze(()=>import("./http-DBlCnlav.js"),[]).then(t=>et(t.http))}}),Pe.of({name:"IDL",extensions:["pro"],load(){return ze(()=>import("./idl-BEugSyMb.js"),[]).then(t=>et(t.idl))}}),Pe.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return ze(()=>import("./javascript-iXu5QeM3.js"),[]).then(t=>et(t.jsonld))}}),Pe.of({name:"Julia",extensions:["jl"],load(){return ze(()=>import("./julia-DuME0IfC.js"),[]).then(t=>et(t.julia))}}),Pe.of({name:"Kotlin",extensions:["kt","kts"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.kotlin))}}),Pe.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return ze(()=>import("./livescript-BwQOo05w.js"),[]).then(t=>et(t.liveScript))}}),Pe.of({name:"Lua",extensions:["lua"],load(){return ze(()=>import("./lua-BgMRiT3U.js"),[]).then(t=>et(t.lua))}}),Pe.of({name:"mIRC",extensions:["mrc"],load(){return ze(()=>import("./mirc-CjQqDB4T.js"),[]).then(t=>et(t.mirc))}}),Pe.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return ze(()=>import("./mathematica-DTrFuWx2.js"),[]).then(t=>et(t.mathematica))}}),Pe.of({name:"Modelica",extensions:["mo"],load(){return ze(()=>import("./modelica-Dc1JOy9r.js"),[]).then(t=>et(t.modelica))}}),Pe.of({name:"MUMPS",extensions:["mps"],load(){return ze(()=>import("./mumps-BT43cFF4.js"),[]).then(t=>et(t.mumps))}}),Pe.of({name:"Mbox",extensions:["mbox"],load(){return ze(()=>import("./mbox-CNhZ1qSd.js"),[]).then(t=>et(t.mbox))}}),Pe.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return ze(()=>import("./nginx-DdIZxoE0.js"),[]).then(t=>et(t.nginx))}}),Pe.of({name:"NSIS",extensions:["nsh","nsi"],load(){return ze(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([23,21])).then(t=>et(t.nsis))}}),Pe.of({name:"NTriples",extensions:["nt","nq"],load(){return ze(()=>import("./ntriples-BfvgReVJ.js"),[]).then(t=>et(t.ntriples))}}),Pe.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.objectiveC))}}),Pe.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.objectiveCpp))}}),Pe.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.oCaml))}}),Pe.of({name:"Octave",extensions:["m"],load(){return ze(()=>import("./octave-Ck1zUtKM.js"),[]).then(t=>et(t.octave))}}),Pe.of({name:"Oz",extensions:["oz"],load(){return ze(()=>import("./oz-BzwKVEFT.js"),[]).then(t=>et(t.oz))}}),Pe.of({name:"Pascal",extensions:["p","pas"],load(){return ze(()=>import("./pascal--L3eBynH.js"),[]).then(t=>et(t.pascal))}}),Pe.of({name:"Perl",extensions:["pl","pm"],load(){return ze(()=>import("./perl-CdXCOZ3F.js"),[]).then(t=>et(t.perl))}}),Pe.of({name:"Pig",extensions:["pig"],load(){return ze(()=>import("./pig-CevX1Tat.js"),[]).then(t=>et(t.pig))}}),Pe.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return ze(()=>import("./powershell-CFHJl5sT.js"),[]).then(t=>et(t.powerShell))}}),Pe.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return ze(()=>import("./properties-C78fOPTZ.js"),[]).then(t=>et(t.properties))}}),Pe.of({name:"ProtoBuf",extensions:["proto"],load(){return ze(()=>import("./protobuf-ChK-085T.js"),[]).then(t=>et(t.protobuf))}}),Pe.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return ze(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([24,25])).then(t=>et(t.pug))}}),Pe.of({name:"Puppet",extensions:["pp"],load(){return ze(()=>import("./puppet-DMA9R1ak.js"),[]).then(t=>et(t.puppet))}}),Pe.of({name:"Q",extensions:["q"],load(){return ze(()=>import("./q-pXgVlZs6.js"),[]).then(t=>et(t.q))}}),Pe.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return ze(()=>import("./r-B6wPVr8A.js"),[]).then(t=>et(t.r))}}),Pe.of({name:"RPM Changes",load(){return ze(()=>import("./rpm-CTu-6PCP.js"),[]).then(t=>et(t.rpmChanges))}}),Pe.of({name:"RPM Spec",extensions:["spec"],load(){return ze(()=>import("./rpm-CTu-6PCP.js"),[]).then(t=>et(t.rpmSpec))}}),Pe.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return ze(()=>import("./ruby-B2Rjki9n.js"),[]).then(t=>et(t.ruby))}}),Pe.of({name:"SAS",extensions:["sas"],load(){return ze(()=>import("./sas-B4kiWyti.js"),[]).then(t=>et(t.sas))}}),Pe.of({name:"Scala",extensions:["scala"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.scala))}}),Pe.of({name:"Scheme",extensions:["scm","ss"],load(){return ze(()=>import("./scheme-C41bIUwD.js"),[]).then(t=>et(t.scheme))}}),Pe.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return ze(()=>import("./shell-CjFT_Tl9.js"),[]).then(t=>et(t.shell))}}),Pe.of({name:"Sieve",extensions:["siv","sieve"],load(){return ze(()=>import("./sieve-C3Gn_uJK.js"),[]).then(t=>et(t.sieve))}}),Pe.of({name:"Smalltalk",extensions:["st"],load(){return ze(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(t=>et(t.smalltalk))}}),Pe.of({name:"Solr",load(){return ze(()=>import("./solr-DehyRSwq.js"),[]).then(t=>et(t.solr))}}),Pe.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return ze(()=>import("./mllike-CXdrOF99.js"),[]).then(t=>et(t.sml))}}),Pe.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return ze(()=>import("./sparql-DkYu6x3z.js"),[]).then(t=>et(t.sparql))}}),Pe.of({name:"Spreadsheet",alias:["excel","formula"],load(){return ze(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(t=>et(t.spreadsheet))}}),Pe.of({name:"Squirrel",extensions:["nut"],load(){return ze(()=>import("./clike-B9uivgTg.js"),[]).then(t=>et(t.squirrel))}}),Pe.of({name:"Stylus",extensions:["styl"],load(){return ze(()=>import("./stylus-B533Al4x.js"),[]).then(t=>et(t.stylus))}}),Pe.of({name:"Swift",extensions:["swift"],load(){return ze(()=>import("./swift-BzpIVaGY.js"),[]).then(t=>et(t.swift))}}),Pe.of({name:"sTeX",load(){return ze(()=>import("./stex-C3f8Ysf7.js"),[]).then(t=>et(t.stex))}}),Pe.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return ze(()=>import("./stex-C3f8Ysf7.js"),[]).then(t=>et(t.stex))}}),Pe.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return ze(()=>import("./verilog-C6RDOZhf.js"),[]).then(t=>et(t.verilog))}}),Pe.of({name:"Tcl",extensions:["tcl"],load(){return ze(()=>import("./tcl-DVfN8rqt.js"),[]).then(t=>et(t.tcl))}}),Pe.of({name:"Textile",extensions:["textile"],load(){return ze(()=>import("./textile-CnDTJFAw.js"),[]).then(t=>et(t.textile))}}),Pe.of({name:"TiddlyWiki",load(){return ze(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(t=>et(t.tiddlyWiki))}}),Pe.of({name:"Tiki wiki",load(){return ze(()=>import("./tiki-DGYXhP31.js"),[]).then(t=>et(t.tiki))}}),Pe.of({name:"TOML",extensions:["toml"],load(){return ze(()=>import("./toml-Bm5Em-hy.js"),[]).then(t=>et(t.toml))}}),Pe.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return ze(()=>import("./troff-wAsdV37c.js"),[]).then(t=>et(t.troff))}}),Pe.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return ze(()=>import("./ttcn-CfJYG6tj.js"),[]).then(t=>et(t.ttcn))}}),Pe.of({name:"TTCN_CFG",extensions:["cfg"],load(){return ze(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(t=>et(t.ttcnCfg))}}),Pe.of({name:"Turtle",extensions:["ttl"],load(){return ze(()=>import("./turtle-B1tBg_DP.js"),[]).then(t=>et(t.turtle))}}),Pe.of({name:"Web IDL",extensions:["webidl"],load(){return ze(()=>import("./webidl-ZXfAyPTL.js"),[]).then(t=>et(t.webIDL))}}),Pe.of({name:"VB.NET",extensions:["vb"],load(){return ze(()=>import("./vb-CmGdzxic.js"),[]).then(t=>et(t.vb))}}),Pe.of({name:"VBScript",extensions:["vbs"],load(){return ze(()=>import("./vbscript-BuJXcnF6.js"),[]).then(t=>et(t.vbScript))}}),Pe.of({name:"Velocity",extensions:["vtl"],load(){return ze(()=>import("./velocity-D8B20fx6.js"),[]).then(t=>et(t.velocity))}}),Pe.of({name:"Verilog",extensions:["v"],load(){return ze(()=>import("./verilog-C6RDOZhf.js"),[]).then(t=>et(t.verilog))}}),Pe.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return ze(()=>import("./vhdl-lSbBsy5d.js"),[]).then(t=>et(t.vhdl))}}),Pe.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return ze(()=>import("./xquery-DzFWVndE.js"),[]).then(t=>et(t.xQuery))}}),Pe.of({name:"Yacas",extensions:["ys"],load(){return ze(()=>import("./yacas-BJ4BC0dw.js"),[]).then(t=>et(t.yacas))}}),Pe.of({name:"Z80",extensions:["z80"],load(){return ze(()=>import("./z80-Hz9HOZM7.js"),[]).then(t=>et(t.z80))}}),Pe.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.mscgen))}}),Pe.of({name:"Xù",extensions:["xu"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.xu))}}),Pe.of({name:"MsGenny",extensions:["msgenny"],load(){return ze(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(t=>et(t.msgenny))}}),Pe.of({name:"Vue",extensions:["vue"],load(){return ze(()=>import("./index-CuspQbA8.js"),__vite__mapDeps([26,5,1,3,6])).then(t=>t.vue())}}),Pe.of({name:"Angular Template",load(){return ze(()=>import("./index-CN2ALQ8u.js"),__vite__mapDeps([27,5,1,3,6])).then(t=>t.angular())}})],BK="#2e3440",y9="#3b4252",zK="#434c5e",f2="#4c566a",UK="#e5e9f0",uO="#eceff4",J3="#8fbcbb",VK="#88c0d0",BKe="#81a1c1",$l="#5e81ac",zKe="#bf616a",sx="#d08770",Q3="#ebcb8b",HK="#a3be8c",UKe="#b48ead",qK="#d30102",b9=uO,Z3=b9,VKe="#ffffff",X3=y9,HKe=b9,KK=y9,qKe=Nt.theme({"&":{color:BK,backgroundColor:VKe},".cm-content":{caretColor:KK},".cm-cursor, .cm-dropCursor":{borderLeftColor:KK},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:HKe},".cm-panels":{backgroundColor:b9,color:f2},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${f2}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:UK},".cm-activeLine":{backgroundColor:Z3},".cm-selectionMatch":{backgroundColor:UK},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${f2}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:uO},".cm-gutters":{backgroundColor:uO,color:BK,border:"none"},".cm-activeLineGutter":{backgroundColor:Z3},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:X3},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:X3,borderBottomColor:X3},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Z3,color:f2}}},{dark:!1}),KKe=Kw.define([{tag:Be.keyword,color:$l},{tag:[Be.name,Be.deleted,Be.character,Be.propertyName,Be.macroName],color:sx},{tag:[Be.variableName],color:sx},{tag:[Be.function(Be.variableName)],color:$l},{tag:[Be.labelName],color:BKe},{tag:[Be.color,Be.constant(Be.name),Be.standard(Be.name)],color:$l},{tag:[Be.definition(Be.name),Be.separator],color:HK},{tag:[Be.brace],color:J3},{tag:[Be.annotation],color:qK},{tag:[Be.number,Be.changed,Be.annotation,Be.modifier,Be.self,Be.namespace],color:VK},{tag:[Be.typeName,Be.className],color:Q3},{tag:[Be.operator,Be.operatorKeyword],color:HK},{tag:[Be.tagName],color:UKe},{tag:[Be.squareBracket],color:zKe},{tag:[Be.angleBracket],color:sx},{tag:[Be.attributeName],color:Q3},{tag:[Be.regexp],color:$l},{tag:[Be.quote],color:y9},{tag:[Be.string],color:sx},{tag:Be.link,color:J3,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Be.url,Be.escape,Be.special(Be.string)],color:sx},{tag:[Be.meta],color:VK},{tag:[Be.comment],color:zK,fontStyle:"italic"},{tag:Be.strong,fontWeight:"bold",color:$l},{tag:Be.emphasis,fontStyle:"italic",color:$l},{tag:Be.strikethrough,textDecoration:"line-through"},{tag:Be.heading,fontWeight:"bold",color:$l},{tag:Be.special(Be.heading1),fontWeight:"bold",color:$l},{tag:Be.heading1,fontWeight:"bold",color:$l},{tag:[Be.heading2,Be.heading3,Be.heading4],fontWeight:"bold",color:$l},{tag:[Be.heading5,Be.heading6],color:$l},{tag:[Be.atom,Be.bool,Be.special(Be.variableName)],color:sx},{tag:[Be.processingInstruction,Be.inserted],color:J3},{tag:[Be.contentSeparator],color:Q3},{tag:Be.invalid,color:zK,borderBottom:`1px dotted ${qK}`}]),WKe=[qKe,eue(KKe)],WK=typeof String.prototype.normalize=="function"?t=>t.normalize("NFKD"):t=>t;class Fy{constructor(e,n,r=0,s=e.length,i,a){this.test=a,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(r,s),this.bufferStart=r,this.normalize=i?l=>i(WK(l)):WK,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return na(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let n=OL(e),r=this.bufferStart+this.bufferPos;this.bufferPos+=qc(e);let s=this.normalize(n);if(s.length)for(let i=0,a=r;;i++){let l=s.charCodeAt(i),c=this.match(l,a,this.bufferPos+this.bufferStart);if(i==s.length-1){if(c)return this.value=c,this;break}a==r&&i<n.length&&n.charCodeAt(i)==l&&a++}}}match(e,n,r){let s=null;for(let i=0;i<this.matches.length;i+=2){let a=this.matches[i],l=!1;this.query.charCodeAt(a)==e&&(a==this.query.length-1?s={from:this.matches[i+1],to:r}:(this.matches[i]++,l=!0)),l||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==e&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(Fy.prototype[Symbol.iterator]=function(){return this});const ede={from:-1,to:-1,match:/.*/.exec("")},v9="gm"+(/x/.unicode==null?"":"u");class tde{constructor(e,n,r,s=0,i=e.length){if(this.text=e,this.to=i,this.curLine="",this.done=!1,this.value=ede,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new nde(e,n,r,s,i);this.re=new RegExp(n,v9+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=e.iter();let a=e.lineAt(s);this.curLineStart=a.from,this.matchPos=sS(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=sS(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}}const eM=new WeakMap;class Jx{constructor(e,n){this.from=e,this.text=n}get to(){return this.from+this.text.length}static get(e,n,r){let s=eM.get(e);if(!s||s.from>=r||s.to<=n){let l=new Jx(n,e.sliceString(n,r));return eM.set(e,l),l}if(s.from==n&&s.to==r)return s;let{text:i,from:a}=s;return a>n&&(i=e.sliceString(n,a)+i,a=n),s.to<r&&(i+=e.sliceString(s.to,r)),eM.set(e,new Jx(a,i)),new Jx(n,i.slice(n-a,r-a))}}class nde{constructor(e,n,r,s,i){this.text=e,this.to=i,this.done=!1,this.value=ede,this.matchPos=sS(e,s),this.re=new RegExp(n,v9+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Jx.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==e&&(this.re.lastIndex=e+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=sS(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Jx.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(tde.prototype[Symbol.iterator]=nde.prototype[Symbol.iterator]=function(){return this});function GKe(t){try{return new RegExp(t,v9),!0}catch{return!1}}function sS(t,e){if(e>=t.length)return e;let n=t.lineAt(e),r;for(;e<n.to&&(r=n.text.charCodeAt(e-n.from))>=56320&&r<57344;)e++;return e}const YKe=t=>{let{state:e}=t,n=String(e.doc.lineAt(t.state.selection.main.head).number),{close:r,result:s}=ZUe(t,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:e.phrase("go")});return s.then(i=>{let a=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!a){t.dispatch({effects:r});return}let l=e.doc.lineAt(e.selection.main.head),[,c,u,f,h]=a,p=f?+f.slice(1):0,g=u?+u:l.number;if(u&&h){let w=g/100;c&&(w=w*(c=="-"?-1:1)+l.number/e.doc.lines),g=Math.round(e.doc.lines*w)}else u&&c&&(g=g*(c=="-"?-1:1)+l.number);let b=e.doc.line(Math.max(1,Math.min(e.doc.lines,g))),v=Qe.cursor(b.from+Math.max(0,Math.min(p,b.length)));t.dispatch({effects:[r,Nt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},JKe={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},QKe=_t.define({combine(t){return Cu(t,JKe,{highlightWordAroundCursor:(e,n)=>e||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function ZKe(t){return[rWe,nWe]}const XKe=Qt.mark({class:"cm-selectionMatch"}),eWe=Qt.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function GK(t,e,n,r){return(n==0||t(e.sliceDoc(n-1,n))!=hs.Word)&&(r==e.doc.length||t(e.sliceDoc(r,r+1))!=hs.Word)}function tWe(t,e,n,r){return t(e.sliceDoc(n,n+1))==hs.Word&&t(e.sliceDoc(r-1,r))==hs.Word}const nWe=ti.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.selectionSet||t.docChanged||t.viewportChanged)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=t.state.facet(QKe),{state:n}=t,r=n.selection;if(r.ranges.length>1)return Qt.none;let s=r.main,i,a=null;if(s.empty){if(!e.highlightWordAroundCursor)return Qt.none;let c=n.wordAt(s.head);if(!c)return Qt.none;a=n.charCategorizer(s.head),i=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<e.minSelectionLength||c>200)return Qt.none;if(e.wholeWords){if(i=n.sliceDoc(s.from,s.to),a=n.charCategorizer(s.head),!(GK(a,n,s.from,s.to)&&tWe(a,n,s.from,s.to)))return Qt.none}else if(i=n.sliceDoc(s.from,s.to),!i)return Qt.none}let l=[];for(let c of t.visibleRanges){let u=new Fy(n.doc,i,c.from,c.to);for(;!u.next().done;){let{from:f,to:h}=u.value;if((!a||GK(a,n,f,h))&&(s.empty&&f<=s.from&&h>=s.to?l.push(eWe.range(f,h)):(f>=s.to||h<=s.from)&&l.push(XKe.range(f,h)),l.length>e.maxMatches))return Qt.none}}return Qt.set(l)}},{decorations:t=>t.decorations}),rWe=Nt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),sWe=({state:t,dispatch:e})=>{let{selection:n}=t,r=Qe.create(n.ranges.map(s=>t.wordAt(s.head)||Qe.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(e(t.update({selection:r})),!0)};function iWe(t,e){let{main:n,ranges:r}=t.selection,s=t.wordAt(n.head),i=s&&s.from==n.from&&s.to==n.to;for(let a=!1,l=new Fy(t.doc,e,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new Fy(t.doc,e,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(c=>c.from==l.value.from))continue;if(i){let c=t.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const oWe=({state:t,dispatch:e})=>{let{ranges:n}=t.selection;if(n.some(i=>i.from===i.to))return sWe({state:t,dispatch:e});let r=t.sliceDoc(n[0].from,n[0].to);if(t.selection.ranges.some(i=>t.sliceDoc(i.from,i.to)!=r))return!1;let s=iWe(t,r);return s?(e(t.update({selection:t.selection.addRange(Qe.range(s.from,s.to),!1),effects:Nt.scrollIntoView(s.to)})),!0):!1},E0=_t.define({combine(t){return Cu(t,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new vWe(e),scrollToMatch:e=>Nt.scrollIntoView(e)})}});class rde{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||GKe(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1009
1009
  `:r=="r"?"\r":r=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new fWe(this):new cWe(this)}getCursor(e,n=0,r){let s=e.doc?e:Zn.create({doc:e});return r==null&&(r=s.doc.length),this.regexp?kx(this,s,n,r):wx(this,s,n,r)}}class sde{constructor(e){this.spec=e}}function aWe(t,e,n){return(r,s,i,a)=>{if(n&&!n(r,s,i,a))return!1;let l=r>=a&&s<=a+i.length?i.slice(r-a,s-a):e.doc.sliceString(r,s);return t(l,e,r,s)}}function wx(t,e,n,r){let s;return t.wholeWord&&(s=lWe(e.doc,e.charCategorizer(e.selection.main.head))),t.test&&(s=aWe(t.test,e,s)),new Fy(e.doc,t.unquoted,n,r,t.caseSensitive?void 0:i=>i.toLowerCase(),s)}function lWe(t,e){return(n,r,s,i)=>((i>n||i+s.length<r)&&(i=Math.max(0,n-2),s=t.sliceString(i,Math.min(t.length,r+2))),(e(iS(s,n-i))!=hs.Word||e(oS(s,n-i))!=hs.Word)&&(e(oS(s,r-i))!=hs.Word||e(iS(s,r-i))!=hs.Word))}class cWe extends sde{constructor(e){super(e)}nextMatch(e,n,r){let s=wx(this.spec,e,r,e.doc.length).nextOverlapping();if(s.done){let i=Math.min(e.doc.length,n+this.spec.unquoted.length);s=wx(this.spec,e,0,i).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(e,n,r){for(let s=r;;){let i=Math.max(n,s-1e4-this.spec.unquoted.length),a=wx(this.spec,e,i,s),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(i==n)return null;s-=1e4}}prevMatch(e,n,r){let s=this.prevMatchInRange(e,0,n);return s||(s=this.prevMatchInRange(e,Math.max(0,r-this.spec.unquoted.length),e.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,n){let r=wx(this.spec,e,0,e.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(e,n,r,s){let i=wx(this.spec,e,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function uWe(t,e,n){return(r,s,i)=>(!n||n(r,s,i))&&t(i[0],e,r,s)}function kx(t,e,n,r){let s;return t.wholeWord&&(s=dWe(e.charCategorizer(e.selection.main.head))),t.test&&(s=uWe(t.test,e,s)),new tde(e.doc,t.search,{ignoreCase:!t.caseSensitive,test:s},n,r)}function iS(t,e){return t.slice(Ii(t,e,!1),e)}function oS(t,e){return t.slice(e,Ii(t,e))}function dWe(t){return(e,n,r)=>!r[0].length||(t(iS(r.input,r.index))!=hs.Word||t(oS(r.input,r.index))!=hs.Word)&&(t(oS(r.input,r.index+r[0].length))!=hs.Word||t(iS(r.input,r.index+r[0].length))!=hs.Word)}class fWe extends sde{nextMatch(e,n,r){let s=kx(this.spec,e,r,e.doc.length).next();return s.done&&(s=kx(this.spec,e,0,n).next()),s.done?null:s.value}prevMatchInRange(e,n,r){for(let s=1;;s++){let i=Math.max(n,r-s*1e4),a=kx(this.spec,e,i,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(i==n||l.from>i+10))return l;if(i==n)return null}}prevMatch(e,n,r){return this.prevMatchInRange(e,0,n)||this.prevMatchInRange(e,r,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return e.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let i=+r.slice(0,s);if(i>0&&i<e.match.length)return e.match[i]+r.slice(s)}return n})}matchAll(e,n){let r=kx(this.spec,e,0,e.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(e,n,r,s){let i=kx(this.spec,e,Math.max(0,n-250),Math.min(r+250,e.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const R1=pn.define(),w9=pn.define(),wh=Oi.define({create(t){return new tM(dO(t).create(),null)},update(t,e){for(let n of e.effects)n.is(R1)?t=new tM(n.value.create(),t.panel):n.is(w9)&&(t=new tM(t.query,n.value?k9:null));return t},provide:t=>N1.from(t,e=>e.panel)});class tM{constructor(e,n){this.query=e,this.panel=n}}const hWe=Qt.mark({class:"cm-searchMatch"}),mWe=Qt.mark({class:"cm-searchMatch cm-searchMatch-selected"}),pWe=ti.fromClass(class{constructor(t){this.view=t,this.decorations=this.highlight(t.state.field(wh))}update(t){let e=t.state.field(wh);(e!=t.startState.field(wh)||t.docChanged||t.selectionSet||t.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:t,panel:e}){if(!e||!t.spec.valid)return Qt.none;let{view:n}=this,r=new zd;for(let s=0,i=n.visibleRanges,a=i.length;s<a;s++){let{from:l,to:c}=i[s];for(;s<a-1&&c>i[s+1].from-500;)c=i[++s].to;t.highlight(n.state,l,c,(u,f)=>{let h=n.state.selection.ranges.some(p=>p.from==u&&p.to==f);r.add(u,f,h?mWe:hWe)})}return r.finish()}},{decorations:t=>t.decorations});function Yw(t){return e=>{let n=e.state.field(wh,!1);return n&&n.query.spec.valid?t(e,n):ade(e)}}const aS=Yw((t,{query:e})=>{let{to:n}=t.state.selection.main,r=e.nextMatch(t.state,n,n);if(!r)return!1;let s=Qe.single(r.from,r.to),i=t.state.facet(E0);return t.dispatch({selection:s,effects:[C9(t,r),i.scrollToMatch(s.main,t)],userEvent:"select.search"}),ode(t),!0}),lS=Yw((t,{query:e})=>{let{state:n}=t,{from:r}=n.selection.main,s=e.prevMatch(n,r,r);if(!s)return!1;let i=Qe.single(s.from,s.to),a=t.state.facet(E0);return t.dispatch({selection:i,effects:[C9(t,s),a.scrollToMatch(i.main,t)],userEvent:"select.search"}),ode(t),!0}),gWe=Yw((t,{query:e})=>{let n=e.matchAll(t.state,1e3);return!n||!n.length?!1:(t.dispatch({selection:Qe.create(n.map(r=>Qe.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),xWe=({state:t,dispatch:e})=>{let n=t.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,i=[],a=0;for(let l=new Fy(t.doc,t.sliceDoc(r,s));!l.next().done;){if(i.length>1e3)return!1;l.value.from==r&&(a=i.length),i.push(Qe.range(l.value.from,l.value.to))}return e(t.update({selection:Qe.create(i,a),userEvent:"select.search.matches"})),!0},YK=Yw((t,{query:e})=>{let{state:n}=t,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let i=e.nextMatch(n,r,r);if(!i)return!1;let a=i,l=[],c,u,f=[];a.from==r&&a.to==s&&(u=n.toText(e.getReplacement(a)),l.push({from:a.from,to:a.to,insert:u}),a=e.nextMatch(n,a.from,a.to),f.push(Nt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let h=t.state.changes(l);return a&&(c=Qe.single(a.from,a.to).map(h),f.push(C9(t,a)),f.push(n.facet(E0).scrollToMatch(c.main,t))),t.dispatch({changes:h,selection:c,effects:f,userEvent:"input.replace"}),!0}),yWe=Yw((t,{query:e})=>{if(t.state.readOnly)return!1;let n=e.matchAll(t.state,1e9).map(s=>{let{from:i,to:a}=s;return{from:i,to:a,insert:e.getReplacement(s)}});if(!n.length)return!1;let r=t.state.phrase("replaced $ matches",n.length)+".";return t.dispatch({changes:n,effects:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function k9(t){return t.state.facet(E0).createPanel(t)}function dO(t,e){var n,r,s,i,a;let l=t.selection.main,c=l.empty||l.to>l.from+100?"":t.sliceDoc(l.from,l.to);if(e&&!c)return e;let u=t.facet(E0);return new rde({search:((n=e==null?void 0:e.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=e==null?void 0:e.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=e==null?void 0:e.literal)!==null&&s!==void 0?s:u.literal,regexp:(i=e==null?void 0:e.regexp)!==null&&i!==void 0?i:u.regexp,wholeWord:(a=e==null?void 0:e.wholeWord)!==null&&a!==void 0?a:u.wholeWord})}function ide(t){let e=ZL(t,k9);return e&&e.dom.querySelector("[main-field]")}function ode(t){let e=ide(t);e&&e==t.root.activeElement&&e.select()}const ade=t=>{let e=t.state.field(wh,!1);if(e&&e.panel){let n=ide(t);if(n&&n!=t.root.activeElement){let r=dO(t.state,e.query.spec);r.valid&&t.dispatch({effects:R1.of(r)}),n.focus(),n.select()}}else t.dispatch({effects:[w9.of(!0),e?R1.of(dO(t.state,e.query.spec)):pn.appendConfig.of(kWe)]});return!0},lde=t=>{let e=t.state.field(wh,!1);if(!e||!e.panel)return!1;let n=ZL(t,k9);return n&&n.dom.contains(t.root.activeElement)&&t.focus(),t.dispatch({effects:w9.of(!1)}),!0},bWe=[{key:"Mod-f",run:ade,scope:"editor search-panel"},{key:"F3",run:aS,shift:lS,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:aS,shift:lS,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:lde,scope:"editor search-panel"},{key:"Mod-Shift-l",run:xWe},{key:"Mod-Alt-g",run:YKe},{key:"Mod-d",run:oWe,preventDefault:!0}];class vWe{constructor(e){this.view=e;let n=this.query=e.state.field(wh).query.spec;this.commit=this.commit.bind(this),this.searchField=Dr("input",{value:n.search,placeholder:Na(e,"Find"),"aria-label":Na(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Dr("input",{value:n.replace,placeholder:Na(e,"Replace"),"aria-label":Na(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Dr("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=Dr("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=Dr("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,i,a){return Dr("button",{class:"cm-button",name:s,onclick:i,type:"button"},a)}this.dom=Dr("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>aS(e),[Na(e,"next")]),r("prev",()=>lS(e),[Na(e,"previous")]),r("select",()=>gWe(e),[Na(e,"all")]),Dr("label",null,[this.caseField,Na(e,"match case")]),Dr("label",null,[this.reField,Na(e,"regexp")]),Dr("label",null,[this.wordField,Na(e,"by word")]),...e.state.readOnly?[]:[Dr("br"),this.replaceField,r("replace",()=>YK(e),[Na(e,"replace")]),r("replaceAll",()=>yWe(e),[Na(e,"replace all")])],Dr("button",{name:"close",onclick:()=>lde(e),"aria-label":Na(e,"close"),type:"button"},["×"])])}commit(){let e=new rde({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:R1.of(e)}))}keydown(e){uUe(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?lS:aS)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),YK(this.view))}update(e){for(let n of e.transactions)for(let r of n.effects)r.is(R1)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(E0).top}}function Na(t,e){return t.state.phrase(e)}const h2=30,m2=/[\s\.,:;?!]/;function C9(t,{from:e,to:n}){let r=t.state.doc.lineAt(e),s=t.state.doc.lineAt(n).to,i=Math.max(r.from,e-h2),a=Math.min(s,n+h2),l=t.state.sliceDoc(i,a);if(i!=r.from){for(let c=0;c<h2;c++)if(!m2.test(l[c+1])&&m2.test(l[c])){l=l.slice(c);break}}if(a!=s){for(let c=l.length-1;c>l.length-h2;c--)if(!m2.test(l[c-1])&&m2.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${t.state.phrase("current match")}. ${l} ${t.state.phrase("on line")} ${r.number}.`)}const wWe=Nt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),kWe=[wh,um.low(pWe),wWe];class JK{constructor(e,n,r){this.from=e,this.to=n,this.diagnostic=r}}class Vm{constructor(e,n,r){this.diagnostics=e,this.panel=n,this.selected=r}static init(e,n,r){let s=r.facet(O1).markerFilter;s&&(e=s(e,r));let i=e.slice().sort((g,b)=>g.from-b.from||g.to-b.to),a=new zd,l=[],c=0,u=r.doc.iter(),f=0,h=r.doc.length;for(let g=0;;){let b=g==i.length?null:i[g];if(!b&&!l.length)break;let v,w;if(l.length)v=c,w=l.reduce((N,S)=>Math.min(N,S.to),b&&b.from>v?b.from:1e8);else{if(v=b.from,v>h)break;w=b.to,l.push(b),g++}for(;g<i.length;){let N=i[g];if(N.from==v&&(N.to>N.from||N.to==v))l.push(N),g++,w=Math.min(N.to,w);else{w=Math.min(N.from,w);break}}w=Math.min(w,h);let j=!1;if(l.some(N=>N.from==v&&(N.to==w||w==h))&&(j=v==w,!j&&w-v<10)){let N=v-(f+u.value.length);N>0&&(u.next(N),f=v);for(let S=v;;){if(S>=w){j=!0;break}if(!u.lineBreak&&f+u.value.length>S)break;S=f+u.value.length,f+=u.value.length,u.next()}}let C=DWe(l);if(j)a.add(v,v,Qt.widget({widget:new MWe(C),diagnostics:l.slice()}));else{let N=l.reduce((S,T)=>T.markClass?S+" "+T.markClass:S,"");a.add(v,w,Qt.mark({class:"cm-lintRange cm-lintRange-"+C+N,diagnostics:l.slice(),inclusiveEnd:l.some(S=>S.to>w)}))}if(c=w,c==h)break;for(let N=0;N<l.length;N++)l[N].to<=c&&l.splice(N--,1)}let p=a.finish();return new Vm(p,n,Kh(p))}}function Kh(t,e=null,n=0){let r=null;return t.between(n,1e9,(s,i,{spec:a})=>{if(!(e&&a.diagnostics.indexOf(e)<0))if(!r)r=new JK(s,i,e||a.diagnostics[0]);else{if(a.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new JK(r.from,i,r.diagnostic)}}),r}function CWe(t,e){let n=e.pos,r=e.end||n,s=t.state.facet(O1).hideOn(t,n,r);if(s!=null)return s;let i=t.startState.doc.lineAt(e.pos);return!!(t.effects.some(a=>a.is(cde))||t.changes.touchesRange(i.from,Math.max(i.to,r)))}function jWe(t,e){return t.field(La,!1)?e:e.concat(pn.appendConfig.of(PWe))}const cde=pn.define(),j9=pn.define(),ude=pn.define(),La=Oi.define({create(){return new Vm(Qt.none,null,null)},update(t,e){if(e.docChanged&&t.diagnostics.size){let n=t.diagnostics.map(e.changes),r=null,s=t.panel;if(t.selected){let i=e.changes.mapPos(t.selected.from,1);r=Kh(n,t.selected.diagnostic,i)||Kh(n,null,i)}!n.size&&s&&e.state.facet(O1).autoPanel&&(s=null),t=new Vm(n,s,r)}for(let n of e.effects)if(n.is(cde)){let r=e.state.facet(O1).autoPanel?n.value.length?D1.open:null:t.panel;t=Vm.init(n.value,r,e.state)}else n.is(j9)?t=new Vm(t.diagnostics,n.value?D1.open:null,t.selected):n.is(ude)&&(t=new Vm(t.diagnostics,t.panel,n.value));return t},provide:t=>[N1.from(t,e=>e.panel),Nt.decorations.from(t,e=>e.diagnostics)]}),NWe=Qt.mark({class:"cm-lintRange cm-lintRange-active"});function SWe(t,e,n){let{diagnostics:r}=t.state.field(La),s,i=-1,a=-1;r.between(e-(n<0?1:0),e+(n>0?1:0),(c,u,{spec:f})=>{if(e>=c&&e<=u&&(c==u||(e>c||n>0)&&(e<u||n<0)))return s=f.diagnostics,i=c,a=u,!1});let l=t.state.facet(O1).tooltipFilter;return s&&l&&(s=l(s,t.state)),s?{pos:i,end:a,above:t.state.doc.lineAt(i).to<a,create(){return{dom:_We(t,s)}}}:null}function _We(t,e){return Dr("ul",{class:"cm-tooltip-lint"},e.map(n=>fde(t,n,!1)))}const EWe=t=>{let e=t.state.field(La,!1);(!e||!e.panel)&&t.dispatch({effects:jWe(t.state,[j9.of(!0)])});let n=ZL(t,D1.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},QK=t=>{let e=t.state.field(La,!1);return!e||!e.panel?!1:(t.dispatch({effects:j9.of(!1)}),!0)},AWe=t=>{let e=t.state.field(La,!1);if(!e)return!1;let n=t.state.selection.main,r=Kh(e.diagnostics,null,n.to+1);return!r&&(r=Kh(e.diagnostics,null,0),!r||r.from==n.from&&r.to==n.to)?!1:(t.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},TWe=[{key:"Mod-Shift-m",run:EWe,preventDefault:!0},{key:"F8",run:AWe}],O1=_t.define({combine(t){return{sources:t.map(e=>e.source).filter(e=>e!=null),...Cu(t.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:ZK,tooltipFilter:ZK,needsRefresh:(e,n)=>e?n?r=>e(r)||n(r):e:n,hideOn:(e,n)=>e?n?(r,s,i)=>e(r,s,i)||n(r,s,i):e:n,autoPanel:(e,n)=>e||n})}}});function ZK(t,e){return t?e?(n,r)=>e(t(n,r),r):t:e}function dde(t){let e=[];if(t)e:for(let{name:n}of t){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!e.some(i=>i.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function fde(t,e,n){var r;let s=n?dde(e.actions):[];return Dr("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},Dr("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(t):e.message),(r=e.actions)===null||r===void 0?void 0:r.map((i,a)=>{let l=!1,c=g=>{if(g.preventDefault(),l)return;l=!0;let b=Kh(t.state.field(La).diagnostics,e);b&&i.apply(t,b.from,b.to)},{name:u}=i,f=s[a]?u.indexOf(s[a]):-1,h=f<0?u:[u.slice(0,f),Dr("u",u.slice(f,f+1)),u.slice(f+1)],p=i.markClass?" "+i.markClass:"";return Dr("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${f<0?"":` (access key "${s[a]})"`}.`},h)}),e.source&&Dr("div",{class:"cm-diagnosticSource"},e.source))}class MWe extends ju{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return Dr("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class XK{constructor(e,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=fde(e,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class D1{constructor(e){this.view=e,this.items=[];let n=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)QK(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:i}=this.items[this.selectedIndex],a=dde(i.actions);for(let l=0;l<a.length;l++)if(a[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Kh(this.view.state.field(La).diagnostics,i);c&&i.actions[l].apply(e,c.from,c.to)}}else return;s.preventDefault()}},r=s=>{for(let i=0;i<this.items.length;i++)this.items[i].dom.contains(s.target)&&this.moveSelection(i)};this.list=Dr("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=Dr("div",{class:"cm-panel-lint"},this.list,Dr("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>QK(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(La).selected;if(!e)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==e.diagnostic)return n;return-1}update(){let{diagnostics:e,selected:n}=this.view.state.field(La),r=0,s=!1,i=null,a=new Set;for(e.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let f of u.diagnostics){if(a.has(f))continue;a.add(f);let h=-1,p;for(let g=r;g<this.items.length;g++)if(this.items[g].diagnostic==f){h=g;break}h<0?(p=new XK(this.view,f),this.items.splice(r,0,p),s=!0):(p=this.items[h],h>r&&(this.items.splice(r,h-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),i=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new XK(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),i?(this.list.setAttribute("aria-activedescendant",i.id),this.view.requestMeasure({key:this,read:()=>({sel:i.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function n(){let r=e;e=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;e!=r.dom;)n();e=r.dom.nextSibling}else this.list.insertBefore(r.dom,e);for(;e;)n()}moveSelection(e){if(this.selectedIndex<0)return;let n=this.view.state.field(La),r=Kh(n.diagnostics,this.items[e].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:ude.of(r)})}static open(e){return new D1(e)}}function IWe(t,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${e}>${encodeURIComponent(t)}</svg>')`}function p2(t){return IWe(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${t}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const RWe=Nt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:p2("#d11")},".cm-lintRange-warning":{backgroundImage:p2("orange")},".cm-lintRange-info":{backgroundImage:p2("#999")},".cm-lintRange-hint":{backgroundImage:p2("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function OWe(t){return t=="error"?4:t=="warning"?3:t=="info"?2:1}function DWe(t){let e="hint",n=1;for(let r of t){let s=OWe(r.severity);s>n&&(n=s,e=r.severity)}return e}const PWe=[La,Nt.decorations.compute([La],t=>{let{selected:e,panel:n}=t.field(La);return!e||!n||e.from==e.to?Qt.none:Qt.set([NWe.range(e.from,e.to)])}),JUe(SWe,{hideOn:CWe}),RWe],LWe=[Oce(),dVe(),_Ue(),Oqe(),aHe(),gUe(),wUe(),Zn.allowMultipleSelections.of(!0),WVe(),eue(dHe,{fallback:!0}),yHe(),fqe(),Cqe(),FUe(),UUe(),RUe(),ZKe(),Vw.of([...gqe,...PKe,...bWe,...Vqe,...rHe,...vue,...TWe])],$We=Y.forwardRef(({title:t,children:e},n)=>{const r=fu(fg);return Y.createElement(FD,{delayDuration:100},Y.createElement(BD,null,Y.createElement(zD,{ref:n,asChild:!0},Y.createElement("span",{className:ct.tooltipTrigger},e)),Y.createElement(UD,{container:r==null?void 0:r.current},Y.createElement(VD,{className:Pr(ct.tooltipContent),sideOffset:10},t))))}),FWe=Y.forwardRef(({children:t,className:e,...n},r)=>Y.createElement(EX,{...n,ref:r,className:Pr(e,ct.selectItem)},Y.createElement(AX,null,t))),BWe=({title:t,placeholder:e,className:n})=>{const[r,s]=bc(pc,Jd);return Y.createElement($We,{title:t},Y.createElement(kX,{"aria-label":e,className:Pr(ct.selectTrigger,n),"data-toolbar-item":!0,disabled:r},Y.createElement(CX,{placeholder:e}),Y.createElement(jX,{className:ct.selectDropdownArrow},s("arrow_drop_down"))))},zWe=({children:t,className:e=ct.selectContainer})=>{const n=fu(fg);return Y.createElement(NX,{container:n==null?void 0:n.current},Y.createElement(SX,{className:Pr(e,"mdxeditor-select-content"),onCloseAutoFocus:r=>{r.preventDefault()},position:"popper"},Y.createElement(_X,{"data-editor-dropdown":!0},t)))},UWe=t=>Y.createElement(wX,{value:t.value||"",onValueChange:t.onChange,disabled:t.disabled},Y.createElement(BWe,{title:t.triggerTitle,placeholder:t.placeholder}),Y.createElement(zWe,null,t.items.map((e,n)=>e==="separator"?Y.createElement(vke,{key:n}):Y.createElement(FWe,{key:n,value:e.value},e.label)))),eW="__EMPTY_VALUE__",hde=({language:t,nodeKey:e,code:n,focusEmitter:r})=>{const s=Qd(),{parentEditor:i,lexicalNode:a}=xR(),[l,c,u,f,h]=bc(pc,hO,mO,Jd,fO),p=$Ke(e,"codeblock",t,r),{setCode:g}=xR(),b=Y.useRef(null),v=Y.useRef(null),w=Y.useRef(g);return w.current=g,p.current={getCodemirror:()=>b.current},Y.useEffect(()=>{const j=v.current;return(async()=>{const C=[...c,LWe,WKe,Oce(),Vw.of([LKe]),Nt.lineWrapping,Nt.updateListener.of(({state:N})=>{w.current(N.doc.toString())}),Nt.domEventHandlers({focus:()=>{i.update(()=>{wu(null)})}})];if(l&&C.push(Zn.readOnly.of(!0)),t!==""&&u){const N=FKe.find(S=>S.name===t||S.alias.includes(t)||S.extensions.includes(t));if(N)try{const S=await N.load();C.push(S.extension)}catch{console.warn("failed to load language support for",t)}}j.innerHTML="",b.current=new Nt({parent:j,state:Zn.create({doc:n,extensions:C})}),j.addEventListener("keydown",tW)})(),()=>{var C;(C=b.current)==null||C.destroy(),b.current=null,j.removeEventListener("keydown",tW)}},[l,t,...c]),Y.createElement("div",{className:ct.codeMirrorWrapper},Y.createElement("div",{className:ct.codeMirrorToolbar},Y.createElement(UWe,{disabled:l,value:t,onChange:j=>{i.update(()=>{a.setLanguage(j===eW?"":j),setTimeout(()=>{i.update(()=>{a.getLatest().select()})})})},triggerTitle:s("codeBlock.selectLanguage","Select code block language"),placeholder:s("codeBlock.inlineLanguage","Language"),items:Object.entries(h).map(([j,C])=>({value:j||eW,label:C}))}),Y.createElement("button",{className:ct.iconButton,type:"button",disabled:l,title:s("codeblock.delete","Delete code block"),onClick:j=>{j.preventDefault(),i.update(()=>{a.remove()})}},f("delete_small"))),Y.createElement("div",{ref:v}))};function tW(t){t.stopPropagation()}const fO=It({js:"JavaScript",ts:"TypeScript",tsx:"TypeScript (React)",jsx:"JavaScript (React)",css:"CSS"}),VWe=Bs(t=>{t.link(t.pipe(VWe,Ih(({language:e,code:n})=>({code:n,language:e,meta:""}))),cle)}),hO=It([]),mO=It(!0),HWe=Va({update(t,e){t.pubIn({[fO]:e==null?void 0:e.codeBlockLanguages,[hO]:(e==null?void 0:e.codeMirrorExtensions)??[],[mO]:(e==null?void 0:e.autoLoadLanguageSupport)??!0})},init(t,e){t.pubIn({[fO]:e==null?void 0:e.codeBlockLanguages,[hO]:(e==null?void 0:e.codeMirrorExtensions)??[],[XFe]:qWe((e==null?void 0:e.codeBlockLanguages)??{}),[mO]:(e==null?void 0:e.autoLoadLanguageSupport)??!0})}});function qWe(t){return{match(e,n){return Object.hasOwn(t,e??"")&&!n},priority:1,Editor:hde}}function KWe({url:t,title:e,text:n,onSubmit:r,onCancel:s,linkAutocompleteSuggestions:i,showLinkTitleField:a,showAnchorTextField:l}){const{register:c,handleSubmit:u,control:f,setValue:h,reset:p}=$ae({values:{url:t,title:e,text:n}}),g=Qd();return Y.createElement("form",{onSubmit:b=>{u(r)(b),b.stopPropagation(),b.preventDefault()},onReset:b=>{b.stopPropagation(),s()},onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),s())},className:Pr(ct.multiFieldForm,ct.linkDialogEditForm)},Y.createElement("div",{className:ct.formField},Y.createElement("label",{htmlFor:"link-url"},g("createLink.url","URL")),Y.createElement(nle,{register:c,initialInputValue:t,inputName:"url",suggestions:i,setValue:h,control:f,placeholder:g("createLink.urlPlaceholder","Select or paste an URL"),autofocus:!0})),l?Y.createElement("div",{className:ct.formField},Y.createElement("label",{htmlFor:"link-text",title:g("createLink.textTooltip","The text to be displayed for the link")},g("createLink.text","Anchor text")),Y.createElement("input",{id:"link-text",className:ct.textInput,size:40,...c("text")})):null,a?Y.createElement("div",{className:ct.formField},Y.createElement("label",{htmlFor:"link-title",title:g("createLink.titleTooltip","The link's title attribute, shown on hover")},g("createLink.title","Link title")),Y.createElement("input",{id:"link-title",className:ct.textInput,size:40,...c("title")})):null,Y.createElement("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--spacing-2)"}},Y.createElement("button",{type:"submit",title:g("createLink.saveTooltip","Set URL"),"aria-label":g("createLink.saveTooltip","Set URL"),className:Pr(ct.primaryButton)},g("dialogControls.save","Save")),Y.createElement("button",{type:"reset",title:g("createLink.cancelTooltip","Cancel change"),"aria-label":g("createLink.cancelTooltip","Cancel change"),className:Pr(ct.secondaryButton)},g("dialogControls.cancel","Cancel"))))}const WWe=()=>{const[t,e,n,r,s,i,a]=bc(fg,fs,Jd,Yo,vde,wde,Cde),l=Oa(mde),c=Oa(pde),u=Oa(gde),f=Oa(xde),h=Oa(yde);Y.useEffect(()=>{const j=()=>{e==null||e.getEditorState().read(()=>{l(!0)})};return window.addEventListener("resize",j),window.addEventListener("scroll",j),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j)}},[e,l]);const[p,g]=Y.useState(!1),b=Qd();if(r.type==="inactive")return null;const v=r.rectangle,w=r.type==="preview"&&r.url.startsWith("http");return Y.createElement(a_,{open:!0},Y.createElement(Rwe,{"data-visible":r.type==="edit",className:ct.linkDialogAnchor,style:{top:`${v.top}px`,left:`${v.left}px`,width:`${v.width}px`,height:`${v.height}px`}}),Y.createElement(l_,{container:t==null?void 0:t.current},Y.createElement(OZ,{className:Pr(ct.linkDialogPopoverContent),sideOffset:5,onOpenAutoFocus:j=>{j.preventDefault()},key:r.linkNodeKey},r.type==="edit"&&Y.createElement(KWe,{url:r.url,title:r.title,text:r.text,onSubmit:c,onCancel:u.bind(null),linkAutocompleteSuggestions:s,showLinkTitleField:a,showAnchorTextField:r.withAnchorText}),r.type==="preview"&&Y.createElement(Y.Fragment,null,Y.createElement("a",{className:ct.linkDialogPreviewAnchor,href:r.url,...w?{target:"_blank",rel:"noreferrer"}:{},onClick:j=>{i!==null&&(j.preventDefault(),i(r.url))},title:w?b("linkPreview.open","Open {{url}} in new window",{url:r.url}):r.url},Y.createElement("span",null,r.url),w&&n("open_in_new")),Y.createElement(nM,{onClick:()=>{f()},title:b("linkPreview.edit","Edit link URL"),"aria-label":b("linkPreview.edit","Edit link URL")},n("edit")),Y.createElement(FD,null,Y.createElement(BD,{open:p},Y.createElement(zD,{asChild:!0},Y.createElement(nM,{title:b("linkPreview.copyToClipboard","Copy to clipboard"),"aria-label":b("linkPreview.copyToClipboard","Copy to clipboard"),onClick:()=>{window.navigator.clipboard.writeText(r.url).then(()=>{g(!0),setTimeout(()=>{g(!1)},1e3)})}},n(p?"check":"content_copy"))),Y.createElement(UD,{container:t==null?void 0:t.current},Y.createElement(VD,{className:Pr(ct.tooltipContent),sideOffset:5},b("linkPreview.copied","Copied!"),Y.createElement(pee,null))))),Y.createElement(nM,{title:b("linkPreview.remove","Remove link"),"aria-label":b("linkPreview.remove","Remove link"),onClick:()=>{h()}},n("link_off"))),Y.createElement(_D,{className:ct.popoverArrow}))))},nM=Y.forwardRef(({className:t,...e},n)=>Y.createElement("button",{className:Pr(ct.actionButton,t),ref:n,...e}));function pO(t){if(!t)return null;const e=N8e(t);if(e===null)return null;const n=e.getParent();return jo(n)?n:jo(e)?e:null}const mde=Bs(),Yo=It({type:"inactive"},t=>{t.pub(f1,e=>e.registerCommand(n5,()=>t.getValue(Yo).type==="preview"?(t.pub(Yo,{type:"inactive"}),!0):!1,es)),t.sub(t.pipe(h1),e=>{e!=="rich-text"&&t.pub(Yo,{type:"inactive"})}),t.pub(f1,e=>e.registerCommand(Zse,n=>{if(n.key==="k"&&(cae?n.metaKey:n.ctrlKey)&&!t.getValue(pc)){const r=Dt();return Bt(r)?(t.pub(bde),n.stopPropagation(),n.preventDefault(),!0):!1}return!1},a1)),t.sub(t.pipe(xde,ws(Yo,fs)),([,e,n])=>{if(e.type==="preview")setTimeout(()=>{n==null||n.getEditorState().read(()=>{const r=su(e.linkNodeKey),s=jo(r)?r.getTextContent().length>0&&r.getChildrenSize()<=1:!1,i=s&&r?r.getTextContent():"";t.pub(Yo,{type:"edit",initialUrl:e.url,url:e.url,title:e.title,text:i,withAnchorText:s,linkNodeKey:e.linkNodeKey,rectangle:e.rectangle})})});else throw new Error("Cannot switch to edit mode when not in preview mode")}),t.sub(t.pipe(pde,ws(fs,Yo,Ty)),([e,n,r,s])=>{var i,a,l;const c=((i=e.text)==null?void 0:i.trim())??"",u=((a=e.url)==null?void 0:a.trim())??"",f=((l=e.title)==null?void 0:l.trim())??"";if(u!==""){if(s!=null&&s.isCollapsed()){const h=c||f||u;n==null||n.update(()=>{const p=pO(s);if(p)if(Wl(p)){const g=Bd(u,{title:f});g.append(mu(c)),p.replace(g),g.select()}else p.setURL(u),p.setTitle(f),nW(p.getFirstChild(),c);else{const g=Bd(u,{title:f});g.append(mu(h)),y0([g]),g.select()}},{discrete:!0})}else n==null||n.update(()=>{nW(s==null?void 0:s.anchor.getNode(),c)}),n==null||n.dispatchCommand(My,{url:u,title:f});t.pub(Yo,{type:"preview",linkNodeKey:r.linkNodeKey,rectangle:r.rectangle,title:f,url:u})}else r.type==="edit"&&r.initialUrl!==""&&(n==null||n.dispatchCommand(My,null)),t.pub(Yo,{type:"inactive"})}),t.link(t.pipe(gde,ws(Yo,fs),Ih(([,e,n])=>{if(e.type==="edit")return n==null||n.focus(),e.initialUrl===""?{type:"inactive"}:{type:"preview",url:e.initialUrl,linkNodeKey:e.linkNodeKey,rectangle:e.rectangle};throw new Error("Cannot cancel edit when not in edit mode")})),Yo),t.link(t.pipe(t.combine(Ty,mde),ws(fs,Yo,pc),Ih(([[e],n,r,s])=>{if(Bt(e)&&n&&!s){const i=pO(e);if(!e.isCollapsed())return{type:"inactive"};if(i){const a=oae(n);return a?{type:"preview",url:i.getURL(),linkNodeKey:i.getKey(),title:i.getTitle(),rectangle:a}:{type:"inactive"}}else return{type:"inactive"}}else return{type:"inactive"}})),Yo)}),pde=Bs(),gde=im();im();const xde=im(),yde=im(t=>{t.sub(t.pipe(yde,ws(fs)),([,e])=>{e==null||e.dispatchCommand(My,null)})}),bde=im(t=>{t.sub(t.pipe(bde,ws(Ty,fs),Cw(([,e])=>Bt(e))),([,e,n])=>{n==null||n.focus(()=>{setTimeout(()=>{n.getEditorState().read(()=>{const r=pO(e),s=oae(n),i=(r==null?void 0:r.getURL())??"",a=(r==null?void 0:r.getURL())??"",l=(r==null?void 0:r.getTitle())??"",c=(r==null?void 0:r.getKey())??"",u=r?r.getTextContent().length>0&&r.getChildrenSize()<=1:!!(e!=null&&e.isCollapsed()),f=u&&r?r.getTextContent():"";t.pub(Yo,{type:"edit",initialUrl:i,url:a,title:l,text:f,withAnchorText:u,linkNodeKey:c,rectangle:s})})})})})}),vde=It([]),wde=It(null),kde=It(null,t=>{t.pub(f1,e=>{function n(r){const[s,i]=t.getValues([pc,kde]);!s||i===null||e.update(()=>{const a=Vp(r.target);if(a!==null){const l=ic(a,c=>c instanceof wc);l!==null&&i(r,l,l.getURL())}})}return e.registerRootListener((r,s)=>{r&&r.addEventListener("click",n),s&&s.removeEventListener("click",n)})})});function nW(t,e){xr(t)&&e&&(t.setTextContent(e),t.selectStart())}const Cde=It(!0),GWe=Va({init(t,e){t.pub(hg,(e==null?void 0:e.LinkDialog)??WWe),t.pub(wde,(e==null?void 0:e.onClickLinkCallback)??null),t.pub(kde,(e==null?void 0:e.onReadOnlyClickLinkCallback)??null),t.pub(Cde,(e==null?void 0:e.showLinkTitleField)??!0)},update(t,e={}){t.pub(vde,e.linkAutocompleteSuggestions??[])}});var rM={exports:{}},rW;function YWe(){return rW||(rW=1,(function(t){var e=typeof window<"u"?window:typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?self:{};/**
1010
1010
  * Prism: Lightweight, robust, elegant syntax highlighting
1011
1011
  *
@@ -1058,7 +1058,7 @@ ${c}`.trim();return[a,{kind:"tool_result",ts:e,toolUseId:Ui(n.callID)||Ui(n.id,r
1058
1058
  `}),n.push(t[r]);return e&&t.length>0&&n.push({type:"text",value:`
1059
1059
  `}),n}function XW(t){let e=0,n=t.charCodeAt(e);for(;n===9||n===32;)e++,n=t.charCodeAt(e);return t.slice(e)}function eG(t,e){const n=UXe(t,e),r=n.one(t,void 0),s=BXe(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:`
1060
1060
  `},s),i}function WXe(t,e){return t&&"run"in t?async function(n,r){const s=eG(n,{file:r,...e});await t.run(s,r)}:function(n,r){return eG(n,{file:r,...t||e})}}function tG(t){if(t)throw t}var gM,nG;function GXe(){if(nG)return gM;nG=1;var t=Object.prototype.hasOwnProperty,e=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=function(u){return typeof Array.isArray=="function"?Array.isArray(u):e.call(u)==="[object Array]"},i=function(u){if(!u||e.call(u)!=="[object Object]")return!1;var f=t.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&t.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!f&&!h)return!1;var p;for(p in u);return typeof p>"u"||t.call(u,p)},a=function(u,f){n&&f.name==="__proto__"?n(u,f.name,{enumerable:!0,configurable:!0,value:f.newValue,writable:!0}):u[f.name]=f.newValue},l=function(u,f){if(f==="__proto__")if(t.call(u,f)){if(r)return r(u,f).value}else return;return u[f]};return gM=function c(){var u,f,h,p,g,b,v=arguments[0],w=1,j=arguments.length,C=!1;for(typeof v=="boolean"&&(C=v,v=arguments[1]||{},w=2),(v==null||typeof v!="object"&&typeof v!="function")&&(v={});w<j;++w)if(u=arguments[w],u!=null)for(f in u)h=l(v,f),p=l(u,f),v!==p&&(C&&p&&(i(p)||(g=s(p)))?(g?(g=!1,b=h&&s(h)?h:[]):b=h&&i(h)?h:{},a(v,{name:f,newValue:c(C,b,p)})):typeof p<"u"&&a(v,{name:f,newValue:p}));return v},gM}var YXe=GXe();const xM=qy(YXe);function NO(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function JXe(){const t=[],e={run:n,use:r};return e;function n(...s){let i=-1;const a=s.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);l(null,...s);function l(c,...u){const f=t[++i];let h=-1;if(c){a(c);return}for(;++h<s.length;)(u[h]===null||u[h]===void 0)&&(u[h]=s[h]);s=u,f?QXe(f,l)(...u):a(null,...u)}}function r(s){if(typeof s!="function")throw new TypeError("Expected `middelware` to be a function, not "+s);return t.push(s),e}}function QXe(t,e){let n;return r;function r(...a){const l=t.length>a.length;let c;l&&a.push(s);try{c=t.apply(this,a)}catch(u){const f=u;if(l&&n)throw f;return s(f)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,s):c instanceof Error?s(c):i(c))}function s(a,...l){n||(n=!0,e(a,...l))}function i(a){s(null,a)}}const Lc={basename:ZXe,dirname:XXe,extname:eet,join:tet,sep:"/"};function ZXe(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');Zw(t);let n=0,r=-1,s=t.length,i;if(e===void 0||e.length===0||e.length>t.length){for(;s--;)if(t.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":t.slice(n,r)}if(e===t)return"";let a=-1,l=e.length-1;for(;s--;)if(t.codePointAt(s)===47){if(i){n=s+1;break}}else a<0&&(i=!0,a=s+1),l>-1&&(t.codePointAt(s)===e.codePointAt(l--)?l<0&&(r=s):(l=-1,r=a));return n===r?r=a:r<0&&(r=t.length),t.slice(n,r)}function XXe(t){if(Zw(t),t.length===0)return".";let e=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){e=n;break}}else r||(r=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function eet(t){Zw(t);let e=t.length,n=-1,r=0,s=-1,i=0,a;for(;e--;){const l=t.codePointAt(e);if(l===47){if(a){r=e+1;break}continue}n<0&&(a=!0,n=e+1),l===46?s<0?s=e:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":t.slice(s,n)}function tet(...t){let e=-1,n;for(;++e<t.length;)Zw(t[e]),t[e]&&(n=n===void 0?t[e]:n+"/"+t[e]);return n===void 0?".":net(n)}function net(t){Zw(t);const e=t.codePointAt(0)===47;let n=ret(t,!e);return n.length===0&&!e&&(n="."),n.length>0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function ret(t,e){let n="",r=0,s=-1,i=0,a=-1,l,c;for(;++a<=t.length;){if(a<t.length)l=t.codePointAt(a);else{if(l===47)break;l=47}if(l===47){if(!(s===a-1||i===1))if(s!==a-1&&i===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=a,i=0;continue}}else if(n.length>0){n="",r=0,s=a,i=0;continue}}e&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(s+1,a):n=t.slice(s+1,a),r=a-s-1;s=a,i=0}else l===46&&i>-1?i++:i=-1}return n}function Zw(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const set={cwd:iet};function iet(){return"/"}function SO(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function oet(t){if(typeof t=="string")t=new URL(t);else if(!SO(t)){const e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return aet(t)}function aet(t){if(t.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const e=t.pathname;let n=-1;for(;++n<e.length;)if(e.codePointAt(n)===37&&e.codePointAt(n+1)===50){const r=e.codePointAt(n+2);if(r===70||r===102){const s=new TypeError("File URL path must not include encoded / characters");throw s.code="ERR_INVALID_FILE_URL_PATH",s}}return decodeURIComponent(e)}const yM=["history","path","basename","stem","extname","dirname"];class Afe{constructor(e){let n;e?SO(e)?n={path:e}:typeof e=="string"||cet(e)?n={value:e}:n=e:n={},this.cwd="cwd"in n?"":set.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<yM.length;){const i=yM[r];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let s;for(s in n)yM.includes(s)||(this[s]=n[s])}get basename(){return typeof this.path=="string"?Lc.basename(this.path):void 0}set basename(e){vM(e,"basename"),bM(e,"basename"),this.path=Lc.join(this.dirname||"",e)}get dirname(){return typeof this.path=="string"?Lc.dirname(this.path):void 0}set dirname(e){rG(this.basename,"dirname"),this.path=Lc.join(e||"",this.basename)}get extname(){return typeof this.path=="string"?Lc.extname(this.path):void 0}set extname(e){if(bM(e,"extname"),rG(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Lc.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){SO(e)&&(e=oet(e)),vM(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path=="string"?Lc.basename(this.path,this.extname):void 0}set stem(e){vM(e,"stem"),bM(e,"stem"),this.path=Lc.join(this.dirname||"",e+(this.extname||""))}fail(e,n,r){const s=this.message(e,n,r);throw s.fatal=!0,s}info(e,n,r){const s=this.message(e,n,r);return s.fatal=void 0,s}message(e,n,r){const s=new mr(e,n,r);return this.path&&(s.name=this.path+":"+s.name,s.file=this.path),s.fatal=!1,this.messages.push(s),s}toString(e){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(e||void 0).decode(this.value)}}function bM(t,e){if(t&&t.includes(Lc.sep))throw new Error("`"+e+"` cannot be a path: did not expect `"+Lc.sep+"`")}function vM(t,e){if(!t)throw new Error("`"+e+"` cannot be empty")}function rG(t,e){if(!t)throw new Error("Setting `"+e+"` requires `path` to be set too")}function cet(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const uet=(function(t){const r=this.constructor.prototype,s=r[t],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),det={}.hasOwnProperty;class U9 extends uet{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=JXe()}copy(){const e=new U9;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];e.use(...r)}return e.data(xM(!0,{},this.namespace)),e}data(e,n){return typeof e=="string"?arguments.length===2?(CM("data",this.frozen),this.namespace[e]=n,this):det.call(this.namespace,e)&&this.namespace[e]||void 0:e?(CM("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;const e=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const s=n.call(e,...r);typeof s=="function"&&this.transformers.use(s)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();const n=j2(e),r=this.parser||this.Parser;return wM("parse",r),r(String(n),n)}process(e,n){const r=this;return this.freeze(),wM("process",this.parser||this.Parser),kM("process",this.compiler||this.Compiler),n?s(void 0,n):new Promise(s);function s(i,a){const l=j2(e),c=r.parse(l);r.run(c,l,function(f,h,p){if(f||!h||!p)return u(f);const g=h,b=r.stringify(g,p);met(b)?p.value=b:p.result=b,u(f,p)});function u(f,h){f||!h?a(f):i?i(h):n(void 0,h)}}}processSync(e){let n=!1,r;return this.freeze(),wM("processSync",this.parser||this.Parser),kM("processSync",this.compiler||this.Compiler),this.process(e,s),iG("processSync","process",n),r;function s(i,a){n=!0,tG(i),r=a}}run(e,n,r){sG(e),this.freeze();const s=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?i(void 0,r):new Promise(i);function i(a,l){const c=j2(n);s.run(e,c,u);function u(f,h,p){const g=h||e;f?l(f):a?a(g):r(void 0,g,p)}}}runSync(e,n){let r=!1,s;return this.run(e,n,i),iG("runSync","run",r),s;function i(a,l){tG(a),s=l,r=!0}}stringify(e,n){this.freeze();const r=j2(n),s=this.compiler||this.Compiler;return kM("stringify",s),sG(e),s(e,r)}use(e,...n){const r=this.attachers,s=this.namespace;if(CM("use",this.frozen),e!=null)if(typeof e=="function")c(e,n);else if(typeof e=="object")Array.isArray(e)?l(e):a(e);else throw new TypeError("Expected usable value, not `"+e+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[f,...h]=u;c(f,h)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(s.settings=xM(!0,s.settings,u.settings))}function l(u){let f=-1;if(u!=null)if(Array.isArray(u))for(;++f<u.length;){const h=u[f];i(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,f){let h=-1,p=-1;for(;++h<r.length;)if(r[h][0]===u){p=h;break}if(p===-1)r.push([u,...f]);else if(f.length>0){let[g,...b]=f;const v=r[p][1];NO(v)&&NO(g)&&(g=xM(!0,v,g)),r[p]=[u,g,...b]}}}}const fet=new U9().freeze();function wM(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function kM(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function CM(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sG(t){if(!NO(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function iG(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function j2(t){return het(t)?t:new Afe(t)}function het(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function met(t){return typeof t=="string"||pet(t)}function pet(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const get="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",oG=[],aG={allowDangerousHtml:!0},xet=/^(https?|ircs?|mailto|xmpp)$/i,yet=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function bet(t){const e=vet(t),n=wet(t);return ket(e.runSync(e.parse(n),n),t)}function vet(t){const e=t.rehypePlugins||oG,n=t.remarkPlugins||oG,r=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...aG}:aG;return fet().use(aXe).use(n).use(WXe,r).use(e)}function wet(t){const e=t.children||"",n=new Afe;return typeof e=="string"&&(n.value=e),n}function ket(t,e){const n=e.allowedElements,r=e.allowElement,s=e.components,i=e.disallowedElements,a=e.skipHtml,l=e.unwrapDisallowed,c=e.urlTransform||Cet;for(const f of yet)Object.hasOwn(e,f.from)&&(""+f.from+(f.to?"use `"+f.to+"` instead":"remove it")+get+f.id,void 0);return HP(t,u),qZe(t,{Fragment:o.Fragment,components:s,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(f,h,p){if(f.type==="raw"&&p&&typeof h=="number")return a?p.children.splice(h,1):p.children[h]={type:"text",value:f.value},h;if(f.type==="element"){let g;for(g in pM)if(Object.hasOwn(pM,g)&&Object.hasOwn(f.properties,g)){const b=f.properties[g],v=pM[g];(v===null||v.includes(f.tagName))&&(f.properties[g]=c(String(b||""),g,f))}}if(f.type==="element"){let g=n?!n.includes(f.tagName):i?i.includes(f.tagName):!1;if(!g&&r&&typeof h=="number"&&(g=!r(f,h,p)),g&&p&&typeof h=="number")return l&&f.children?p.children.splice(h,1,...f.children):p.children.splice(h,1),h}}}function Cet(t){const e=t.indexOf(":"),n=t.indexOf("?"),r=t.indexOf("#"),s=t.indexOf("/");return e===-1||s!==-1&&e>s||n!==-1&&e>n||r!==-1&&e>r||xet.test(t.slice(0,e))?t:""}function jet(t,e,n){const s=c5((n||{}).ignore||[]),i=Net(e);let a=-1;for(;++a<i.length;)Wie(t,"text",l);function l(u,f){let h=-1,p;for(;++h<f.length;){const g=f[h],b=p?p.children:void 0;if(s(g,b?b.indexOf(g):void 0,p))return;p=g}if(p)return c(u,f)}function c(u,f){const h=f[f.length-1],p=i[a][0],g=i[a][1];let b=0;const w=h.children.indexOf(u);let j=!1,C=[];p.lastIndex=0;let N=p.exec(u.value);for(;N;){const S=N.index,T={index:N.index,input:N.input,stack:[...f,u]};let _=g(...N,T);if(typeof _=="string"&&(_=_.length>0?{type:"text",value:_}:void 0),_===!1?p.lastIndex=S+1:(b!==S&&C.push({type:"text",value:u.value.slice(b,S)}),Array.isArray(_)?C.push(..._):_&&C.push(_),b=S+N[0].length,j=!0),!p.global)break;N=p.exec(u.value)}return j?(b<u.value.length&&C.push({type:"text",value:u.value.slice(b)}),h.children.splice(w,1,...C)):C=[u],w+C.length}}function Net(t){const e=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!t[0]||Array.isArray(t[0])?t:[t];let r=-1;for(;++r<n.length;){const s=n[r];e.push([_et(s[0]),Eet(s[1])])}return e}function _et(t){return typeof t=="string"?new RegExp(zFe(t),"g"):t}function Eet(t){return typeof t=="function"?t:function(){return t}}const jM="phrasing",NM=["autolink","link","image","label"];function Aet(){return{transforms:[Pet],enter:{literalAutolink:Met,literalAutolinkEmail:SM,literalAutolinkHttp:SM,literalAutolinkWww:SM},exit:{literalAutolink:Det,literalAutolinkEmail:Oet,literalAutolinkHttp:Iet,literalAutolinkWww:Ret}}}function Tet(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:jM,notInConstruct:NM},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:jM,notInConstruct:NM},{character:":",before:"[ps]",after:"\\/",inConstruct:jM,notInConstruct:NM}]}}function Met(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function SM(t){this.config.enter.autolinkProtocol.call(this,t)}function Iet(t){this.config.exit.autolinkProtocol.call(this,t)}function Ret(t){this.config.exit.data.call(this,t);const e=this.stack[this.stack.length-1];e.type,e.url="http://"+this.sliceSerialize(t)}function Oet(t){this.config.exit.autolinkEmail.call(this,t)}function Det(t){this.exit(t)}function Pet(t){jet(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Let],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),$et]],{ignore:["link","linkReference"]})}function Let(t,e,n,r,s){let i="";if(!Tfe(s)||(/^w/i.test(e)&&(n=e+n,e="",i="http://"),!Fet(n)))return!1;const a=Bet(n+r);if(!a[0])return!1;const l={type:"link",title:null,url:i+e+a[0],children:[{type:"text",value:e+a[0]}]};return a[1]?[l,{type:"text",value:a[1]}]:l}function $et(t,e,n,r){return!Tfe(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+e+"@"+n,children:[{type:"text",value:e+"@"+n}]}}function Fet(t){const e=t.split(".");return!(e.length<2||e[e.length-1]&&(/_/.test(e[e.length-1])||!/[a-zA-Z\d]/.test(e[e.length-1]))||e[e.length-2]&&(/_/.test(e[e.length-2])||!/[a-zA-Z\d]/.test(e[e.length-2])))}function Bet(t){const e=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!e)return[t,void 0];t=t.slice(0,e.index);let n=e[0],r=n.indexOf(")");const s=CN(t,"(");let i=CN(t,")");for(;r!==-1&&s>i;)t+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[t,n]}function Tfe(t,e){const n=t.input.charCodeAt(t.index-1);return(t.index===0||Co(n)||l5(n))&&(!e||n!==47)}Mfe.peek=Yet;function zet(){this.buffer()}function Uet(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function Vet(){this.buffer()}function Het(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function qet(t){const e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=oc(this.sliceSerialize(t)).toLowerCase(),n.label=e}function Ket(t){this.exit(t)}function Wet(t){const e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=oc(this.sliceSerialize(t)).toLowerCase(),n.label=e}function Get(t){this.exit(t)}function Yet(){return"["}function Mfe(t,e,n,r){const s=n.createTracker(r);let i=s.move("[^");const a=n.enter("footnoteReference"),l=n.enter("reference");return i+=s.move(n.safe(n.associationId(t),{after:"]",before:i})),l(),a(),i+=s.move("]"),i}function Jet(){return{enter:{gfmFootnoteCallString:zet,gfmFootnoteCall:Uet,gfmFootnoteDefinitionLabelString:Vet,gfmFootnoteDefinition:Het},exit:{gfmFootnoteCallString:qet,gfmFootnoteCall:Ket,gfmFootnoteDefinitionLabelString:Wet,gfmFootnoteDefinition:Get}}}function Qet(t){let e=!1;return t&&t.firstLineBlank&&(e=!0),{handlers:{footnoteDefinition:n,footnoteReference:Mfe},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,a){const l=i.createTracker(a);let c=l.move("[^");const u=i.enter("footnoteDefinition"),f=i.enter("label");return c+=l.move(i.safe(i.associationId(r),{before:c,after:"]"})),f(),c+=l.move("]:"),r.children&&r.children.length>0&&(l.shift(4),c+=l.move((e?`
1061
- `:" ")+i.indentLines(i.containerFlow(r,l.current()),e?Ife:Zet))),u(),c}}function Zet(t,e,n){return e===0?t:Ife(t,e,n)}function Ife(t,e,n){return(n?"":" ")+t}function Xet(){return[Aet(),Jet(),_ie(),xae(),pae()]}function ett(t){return{extensions:[Tet(),Qet(t),Eie(),yae(t),gae()]}}const ttt={tokenize:att,partial:!0},Rfe={tokenize:ltt,partial:!0},Ofe={tokenize:ctt,partial:!0},Dfe={tokenize:utt,partial:!0},ntt={tokenize:dtt,partial:!0},Pfe={name:"wwwAutolink",tokenize:itt,previous:$fe},Lfe={name:"protocolAutolink",tokenize:ott,previous:Ffe},tf={name:"emailAutolink",tokenize:stt,previous:Bfe},Su={};function rtt(){return{text:Su}}let Om=48;for(;Om<123;)Su[Om]=tf,Om++,Om===58?Om=65:Om===91&&(Om=97);Su[43]=tf;Su[45]=tf;Su[46]=tf;Su[95]=tf;Su[72]=[tf,Lfe];Su[104]=[tf,Lfe];Su[87]=[tf,Pfe];Su[119]=[tf,Pfe];function stt(t,e,n){const r=this;let s,i;return a;function a(h){return!_O(h)||!Bfe.call(r,r.previous)||V9(r.events)?n(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),l(h))}function l(h){return _O(h)?(t.consume(h),l):h===64?(t.consume(h),c):n(h)}function c(h){return h===46?t.check(ntt,f,u)(h):h===45||h===95||co(h)?(i=!0,t.consume(h),c):f(h)}function u(h){return t.consume(h),s=!0,c}function f(h){return i&&s&&So(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),e(h)):n(h)}}function itt(t,e,n){const r=this;return s;function s(a){return a!==87&&a!==119||!$fe.call(r,r.previous)||V9(r.events)?n(a):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(ttt,t.attempt(Rfe,t.attempt(Ofe,i),n),n)(a))}function i(a){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),e(a)}}function ott(t,e,n){const r=this;let s="",i=!1;return a;function a(h){return(h===72||h===104)&&Ffe.call(r,r.previous)&&!V9(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),s+=String.fromCodePoint(h),t.consume(h),l):n(h)}function l(h){if(So(h)&&s.length<5)return s+=String.fromCodePoint(h),t.consume(h),l;if(h===58){const p=s.toLowerCase();if(p==="http"||p==="https")return t.consume(h),c}return n(h)}function c(h){return h===47?(t.consume(h),i?u:(i=!0,c)):n(h)}function u(h){return h===null||kN(h)||Xn(h)||Co(h)||l5(h)?n(h):t.attempt(Rfe,t.attempt(Ofe,f),n)(h)}function f(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),e(h)}}function att(t,e,n){let r=0;return s;function s(a){return(a===87||a===119)&&r<3?(r++,t.consume(a),s):a===46&&r===3?(t.consume(a),i):n(a)}function i(a){return a===null?n(a):e(a)}}function ltt(t,e,n){let r,s,i;return a;function a(u){return u===46||u===95?t.check(Dfe,c,l)(u):u===null||Xn(u)||Co(u)||u!==45&&l5(u)?c(u):(i=!0,t.consume(u),a)}function l(u){return u===95?r=!0:(s=r,r=void 0),t.consume(u),a}function c(u){return s||r||!i?n(u):e(u)}}function ctt(t,e){let n=0,r=0;return s;function s(a){return a===40?(n++,t.consume(a),s):a===41&&r<n?i(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?t.check(Dfe,e,i)(a):a===null||Xn(a)||Co(a)?e(a):(t.consume(a),s)}function i(a){return a===41&&r++,t.consume(a),s}}function utt(t,e,n){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(t.consume(l),r):l===38?(t.consume(l),i):l===93?(t.consume(l),s):l===60||l===null||Xn(l)||Co(l)?e(l):n(l)}function s(l){return l===null||l===40||l===91||Xn(l)||Co(l)?e(l):r(l)}function i(l){return So(l)?a(l):n(l)}function a(l){return l===59?(t.consume(l),r):So(l)?(t.consume(l),a):n(l)}}function dtt(t,e,n){return r;function r(i){return t.consume(i),s}function s(i){return co(i)?n(i):e(i)}}function $fe(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Xn(t)}function Ffe(t){return!So(t)}function Bfe(t){return!(t===47||_O(t))}function _O(t){return t===43||t===45||t===46||t===95||co(t)}function V9(t){let e=t.length,n=!1;for(;e--;){const r=t[e][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return t.length>0&&!n&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const ftt={tokenize:vtt,partial:!0};function htt(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:xtt,continuation:{tokenize:ytt},exit:btt}},text:{91:{name:"gfmFootnoteCall",tokenize:gtt},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:mtt,resolveTo:ptt}}}}function mtt(t,e,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){a=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return l;function l(c){if(!a||!a._balanced)return n(c);const u=oc(r.sliceSerialize({start:a.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(c),t.exit("gfmFootnoteCallLabelMarker"),e(c))}}function ptt(t,e){let n=t.length;for(;n--;)if(t[n][1].type==="labelImage"&&t[n][0]==="enter"){t[n][1];break}t[n+1][1].type="data",t[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},t[n+3][1].start),end:Object.assign({},t[t.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},t[n+3][1].end),end:Object.assign({},t[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},t[t.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},l=[t[n+1],t[n+2],["enter",r,e],t[n+3],t[n+4],["enter",s,e],["exit",s,e],["enter",i,e],["enter",a,e],["exit",a,e],["exit",i,e],t[t.length-2],t[t.length-1],["exit",r,e]];return t.splice(n,t.length-n+1,...l),t}function gtt(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,a;return l;function l(h){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),c}function c(h){return h!==94?n(h):(t.enter("gfmFootnoteCallMarker"),t.consume(h),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",u)}function u(h){if(i>999||h===93&&!a||h===null||h===91||Xn(h))return n(h);if(h===93){t.exit("chunkString");const p=t.exit("gfmFootnoteCallString");return s.includes(oc(r.sliceSerialize(p)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),e):n(h)}return Xn(h)||(a=!0),i++,t.consume(h),h===92?f:u}function f(h){return h===91||h===92||h===93?(t.consume(h),i++,u):u(h)}}function xtt(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,a=0,l;return c;function c(b){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(b){return b===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",f):n(b)}function f(b){if(a>999||b===93&&!l||b===null||b===91||Xn(b))return n(b);if(b===93){t.exit("chunkString");const v=t.exit("gfmFootnoteDefinitionLabelString");return i=oc(r.sliceSerialize(v)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),p}return Xn(b)||(l=!0),a++,t.consume(b),b===92?h:f}function h(b){return b===91||b===92||b===93?(t.consume(b),a++,f):f(b)}function p(b){return b===58?(t.enter("definitionMarker"),t.consume(b),t.exit("definitionMarker"),s.includes(i)||s.push(i),zn(t,g,"gfmFootnoteDefinitionWhitespace")):n(b)}function g(b){return e(b)}}function ytt(t,e,n){return t.check(Rw,e,t.attempt(ftt,e,n))}function btt(t){t.exit("gfmFootnoteDefinition")}function vtt(t,e,n){const r=this;return zn(t,s,"gfmFootnoteDefinitionIndent",5);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?e(i):n(i)}}function wtt(t){return foe([rtt(),htt(),Sie(t),bae(),mae()])}const ktt={};function Ctt(t){const e=this,n=t||ktt,r=e.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(wtt(n)),i.push(Xet()),a.push(ett(n))}let _M=null;function jtt(){return _M||(_M=ze(()=>import("./mermaid.core-CpCDuAY2.js").then(t=>t.bC),[]).then(t=>t.default)),_M}function zfe(t){return t==null?"":typeof t=="string"||typeof t=="number"?String(t):Array.isArray(t)?t.map(e=>zfe(e)).join(""):""}function Ntt(t){if(!y.isValidElement(t))return null;const e=t.props;return typeof e.className!="string"||!/\blanguage-mermaid\b/i.test(e.className)?null:zfe(e.children).replace(/\n$/,"")}function Stt({source:t,darkMode:e}){const n=y.useId().replace(/[^a-zA-Z0-9_-]/g,""),[r,s]=y.useState(null),[i,a]=y.useState(null);return y.useEffect(()=>{let l=!0;return s(null),a(null),jtt().then(async c=>{c.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"dark":"default",fontFamily:"inherit",suppressErrorRendering:!0});const u=await c.render(`fidelios-mermaid-${n}`,t);l&&s(u.svg)}).catch(c=>{if(!l)return;const u=c instanceof Error&&c.message?c.message:"Failed to render Mermaid diagram.";a(u)}),()=>{l=!1}},[e,n,t]),o.jsx("div",{className:"fidelios-mermaid",children:r?o.jsx("div",{dangerouslySetInnerHTML:{__html:r}}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:se("fidelios-mermaid-status",i&&"fidelios-mermaid-status-error"),children:i?`Unable to render Mermaid diagram: ${i}`:"Rendering Mermaid diagram..."}),o.jsx("pre",{className:"fidelios-mermaid-source",children:o.jsx("code",{className:"language-mermaid",children:t})})]})})}function Al({children:t,className:e,resolveImageSrc:n}){const{theme:r}=Gde(),s={pre:({node:i,children:a,...l})=>{const c=Ntt(a);return c?o.jsx(Stt,{source:c,darkMode:r==="dark"}):o.jsx("pre",{...l,children:a})},a:({href:i,children:a})=>{const l=i?A9(i):null;if(l){const c=l.kind==="project"?`/projects/${l.projectId}`:`/agents/${l.agentId}`;return o.jsx("a",{href:c,className:se("fidelios-mention-chip",`fidelios-mention-chip--${l.kind}`,l.kind==="project"&&"fidelios-project-mention-chip"),"data-mention-kind":l.kind,style:Vde(l),children:a})}return o.jsx("a",{href:i,rel:"noreferrer",children:a})}};return n&&(s.img=({node:i,src:a,alt:l,...c})=>{const u=a?n(a):null;return o.jsx("img",{...c,src:u??a,alt:l??""})}),o.jsx("div",{className:se("fidelios-markdown prose prose-sm max-w-none break-words overflow-hidden",r==="dark"&&"prose-invert",e),children:o.jsx(bet,{remarkPlugins:[Ctt],components:s,urlTransform:i=>i,children:t})})}function H9(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function xu(t){return t.replace(/\s+/g," ").trim()}function Hl(t,e){return t.length>e?`${t.slice(0,Math.max(0,e-1))}…`:t}function xS(t){return t.replace(/[_-]+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase())}function lG(t){const e=xu(t),n=e.match(/^(?:(?:\/bin\/)?(?:zsh|bash|sh)|cmd(?:\.exe)?(?:\s+\/d)?(?:\s+\/s)?(?:\s+\/c)?)\s+(?:-lc|\/c)\s+(.+)$/i),r=(n==null?void 0:n[1])??e,s=r.match(/^(['"])([\s\S]*)\1$/);return xu((s==null?void 0:s[2])??r)}function Ufe(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function eg(t){if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return Ufe(t)}function _tt(t){const e=H9(t);if(!e)return;const n=[e.toolUseId,e.tool_use_id,e.callId,e.call_id,e.id];for(const r of n)if(typeof r=="string"&&r.trim())return r}function cG(t,e){for(const n of e){const r=t[n];if(typeof r=="string"&&r.trim())return Hl(xu(r),120)}return null}function yS(t,e,n){const r=n==="compact"?72:120;if(typeof e=="string"){const c=Hy(t,e)?lG(e):xu(e);return Hl(c,r)}const s=H9(e);if(!s){const c=xu(Ufe(e));return c?Hl(c,r):`Inspect ${t} input`}const i=typeof s.command=="string"?s.command:typeof s.cmd=="string"?s.cmd:null;if(i&&Hy(t,s))return Hl(lG(i),r);const a=cG(s,["command","cmd","path","filePath","file_path","query","url","prompt","message"])??cG(s,["pattern","name","title","target","tool"])??null;if(a)return Hl(a,r);if(Array.isArray(s.paths)&&s.paths.length>0){const c=s.paths.find(u=>typeof u=="string"&&u.trim().length>0);if(c)return Hl(`${s.paths.length} paths, starting with ${c}`,r)}const l=Object.keys(s);return l.length===0?`No ${t} input`:l.length===1?Hl(`${l[0]} payload`,r):Hl(`${l.length} fields: ${l.slice(0,3).join(", ")}`,r)}function Vfe(t){var i;if(!t)return null;const e=t.split(/\r?\n/),n=new Map;let r=e.findIndex(a=>a.trim()==="");r===-1&&(r=e.length);for(let a=0;a<r;a+=1){const l=(i=e[a])==null?void 0:i.match(/^([a-z_]+):\s*(.+)$/i);l&&n.set(l[1].toLowerCase(),xu(l[2]))}const s=e.slice(Math.min(r+1,e.length)).map(a=>xu(a)).filter(Boolean).join(`
1061
+ `:" ")+i.indentLines(i.containerFlow(r,l.current()),e?Ife:Zet))),u(),c}}function Zet(t,e,n){return e===0?t:Ife(t,e,n)}function Ife(t,e,n){return(n?"":" ")+t}function Xet(){return[Aet(),Jet(),_ie(),xae(),pae()]}function ett(t){return{extensions:[Tet(),Qet(t),Eie(),yae(t),gae()]}}const ttt={tokenize:att,partial:!0},Rfe={tokenize:ltt,partial:!0},Ofe={tokenize:ctt,partial:!0},Dfe={tokenize:utt,partial:!0},ntt={tokenize:dtt,partial:!0},Pfe={name:"wwwAutolink",tokenize:itt,previous:$fe},Lfe={name:"protocolAutolink",tokenize:ott,previous:Ffe},tf={name:"emailAutolink",tokenize:stt,previous:Bfe},Su={};function rtt(){return{text:Su}}let Om=48;for(;Om<123;)Su[Om]=tf,Om++,Om===58?Om=65:Om===91&&(Om=97);Su[43]=tf;Su[45]=tf;Su[46]=tf;Su[95]=tf;Su[72]=[tf,Lfe];Su[104]=[tf,Lfe];Su[87]=[tf,Pfe];Su[119]=[tf,Pfe];function stt(t,e,n){const r=this;let s,i;return a;function a(h){return!_O(h)||!Bfe.call(r,r.previous)||V9(r.events)?n(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),l(h))}function l(h){return _O(h)?(t.consume(h),l):h===64?(t.consume(h),c):n(h)}function c(h){return h===46?t.check(ntt,f,u)(h):h===45||h===95||co(h)?(i=!0,t.consume(h),c):f(h)}function u(h){return t.consume(h),s=!0,c}function f(h){return i&&s&&So(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),e(h)):n(h)}}function itt(t,e,n){const r=this;return s;function s(a){return a!==87&&a!==119||!$fe.call(r,r.previous)||V9(r.events)?n(a):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(ttt,t.attempt(Rfe,t.attempt(Ofe,i),n),n)(a))}function i(a){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),e(a)}}function ott(t,e,n){const r=this;let s="",i=!1;return a;function a(h){return(h===72||h===104)&&Ffe.call(r,r.previous)&&!V9(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),s+=String.fromCodePoint(h),t.consume(h),l):n(h)}function l(h){if(So(h)&&s.length<5)return s+=String.fromCodePoint(h),t.consume(h),l;if(h===58){const p=s.toLowerCase();if(p==="http"||p==="https")return t.consume(h),c}return n(h)}function c(h){return h===47?(t.consume(h),i?u:(i=!0,c)):n(h)}function u(h){return h===null||kN(h)||Xn(h)||Co(h)||l5(h)?n(h):t.attempt(Rfe,t.attempt(Ofe,f),n)(h)}function f(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),e(h)}}function att(t,e,n){let r=0;return s;function s(a){return(a===87||a===119)&&r<3?(r++,t.consume(a),s):a===46&&r===3?(t.consume(a),i):n(a)}function i(a){return a===null?n(a):e(a)}}function ltt(t,e,n){let r,s,i;return a;function a(u){return u===46||u===95?t.check(Dfe,c,l)(u):u===null||Xn(u)||Co(u)||u!==45&&l5(u)?c(u):(i=!0,t.consume(u),a)}function l(u){return u===95?r=!0:(s=r,r=void 0),t.consume(u),a}function c(u){return s||r||!i?n(u):e(u)}}function ctt(t,e){let n=0,r=0;return s;function s(a){return a===40?(n++,t.consume(a),s):a===41&&r<n?i(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?t.check(Dfe,e,i)(a):a===null||Xn(a)||Co(a)?e(a):(t.consume(a),s)}function i(a){return a===41&&r++,t.consume(a),s}}function utt(t,e,n){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(t.consume(l),r):l===38?(t.consume(l),i):l===93?(t.consume(l),s):l===60||l===null||Xn(l)||Co(l)?e(l):n(l)}function s(l){return l===null||l===40||l===91||Xn(l)||Co(l)?e(l):r(l)}function i(l){return So(l)?a(l):n(l)}function a(l){return l===59?(t.consume(l),r):So(l)?(t.consume(l),a):n(l)}}function dtt(t,e,n){return r;function r(i){return t.consume(i),s}function s(i){return co(i)?n(i):e(i)}}function $fe(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Xn(t)}function Ffe(t){return!So(t)}function Bfe(t){return!(t===47||_O(t))}function _O(t){return t===43||t===45||t===46||t===95||co(t)}function V9(t){let e=t.length,n=!1;for(;e--;){const r=t[e][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return t.length>0&&!n&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const ftt={tokenize:vtt,partial:!0};function htt(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:xtt,continuation:{tokenize:ytt},exit:btt}},text:{91:{name:"gfmFootnoteCall",tokenize:gtt},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:mtt,resolveTo:ptt}}}}function mtt(t,e,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){a=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return l;function l(c){if(!a||!a._balanced)return n(c);const u=oc(r.sliceSerialize({start:a.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(c),t.exit("gfmFootnoteCallLabelMarker"),e(c))}}function ptt(t,e){let n=t.length;for(;n--;)if(t[n][1].type==="labelImage"&&t[n][0]==="enter"){t[n][1];break}t[n+1][1].type="data",t[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},t[n+3][1].start),end:Object.assign({},t[t.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},t[n+3][1].end),end:Object.assign({},t[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},t[t.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},l=[t[n+1],t[n+2],["enter",r,e],t[n+3],t[n+4],["enter",s,e],["exit",s,e],["enter",i,e],["enter",a,e],["exit",a,e],["exit",i,e],t[t.length-2],t[t.length-1],["exit",r,e]];return t.splice(n,t.length-n+1,...l),t}function gtt(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,a;return l;function l(h){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),c}function c(h){return h!==94?n(h):(t.enter("gfmFootnoteCallMarker"),t.consume(h),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",u)}function u(h){if(i>999||h===93&&!a||h===null||h===91||Xn(h))return n(h);if(h===93){t.exit("chunkString");const p=t.exit("gfmFootnoteCallString");return s.includes(oc(r.sliceSerialize(p)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),e):n(h)}return Xn(h)||(a=!0),i++,t.consume(h),h===92?f:u}function f(h){return h===91||h===92||h===93?(t.consume(h),i++,u):u(h)}}function xtt(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,a=0,l;return c;function c(b){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(b){return b===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",f):n(b)}function f(b){if(a>999||b===93&&!l||b===null||b===91||Xn(b))return n(b);if(b===93){t.exit("chunkString");const v=t.exit("gfmFootnoteDefinitionLabelString");return i=oc(r.sliceSerialize(v)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(b),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),p}return Xn(b)||(l=!0),a++,t.consume(b),b===92?h:f}function h(b){return b===91||b===92||b===93?(t.consume(b),a++,f):f(b)}function p(b){return b===58?(t.enter("definitionMarker"),t.consume(b),t.exit("definitionMarker"),s.includes(i)||s.push(i),zn(t,g,"gfmFootnoteDefinitionWhitespace")):n(b)}function g(b){return e(b)}}function ytt(t,e,n){return t.check(Rw,e,t.attempt(ftt,e,n))}function btt(t){t.exit("gfmFootnoteDefinition")}function vtt(t,e,n){const r=this;return zn(t,s,"gfmFootnoteDefinitionIndent",5);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?e(i):n(i)}}function wtt(t){return foe([rtt(),htt(),Sie(t),bae(),mae()])}const ktt={};function Ctt(t){const e=this,n=t||ktt,r=e.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(wtt(n)),i.push(Xet()),a.push(ett(n))}let _M=null;function jtt(){return _M||(_M=ze(()=>import("./mermaid.core-DuMJwP7Z.js").then(t=>t.bC),[]).then(t=>t.default)),_M}function zfe(t){return t==null?"":typeof t=="string"||typeof t=="number"?String(t):Array.isArray(t)?t.map(e=>zfe(e)).join(""):""}function Ntt(t){if(!y.isValidElement(t))return null;const e=t.props;return typeof e.className!="string"||!/\blanguage-mermaid\b/i.test(e.className)?null:zfe(e.children).replace(/\n$/,"")}function Stt({source:t,darkMode:e}){const n=y.useId().replace(/[^a-zA-Z0-9_-]/g,""),[r,s]=y.useState(null),[i,a]=y.useState(null);return y.useEffect(()=>{let l=!0;return s(null),a(null),jtt().then(async c=>{c.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"dark":"default",fontFamily:"inherit",suppressErrorRendering:!0});const u=await c.render(`fidelios-mermaid-${n}`,t);l&&s(u.svg)}).catch(c=>{if(!l)return;const u=c instanceof Error&&c.message?c.message:"Failed to render Mermaid diagram.";a(u)}),()=>{l=!1}},[e,n,t]),o.jsx("div",{className:"fidelios-mermaid",children:r?o.jsx("div",{dangerouslySetInnerHTML:{__html:r}}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:se("fidelios-mermaid-status",i&&"fidelios-mermaid-status-error"),children:i?`Unable to render Mermaid diagram: ${i}`:"Rendering Mermaid diagram..."}),o.jsx("pre",{className:"fidelios-mermaid-source",children:o.jsx("code",{className:"language-mermaid",children:t})})]})})}function Al({children:t,className:e,resolveImageSrc:n}){const{theme:r}=Gde(),s={pre:({node:i,children:a,...l})=>{const c=Ntt(a);return c?o.jsx(Stt,{source:c,darkMode:r==="dark"}):o.jsx("pre",{...l,children:a})},a:({href:i,children:a})=>{const l=i?A9(i):null;if(l){const c=l.kind==="project"?`/projects/${l.projectId}`:`/agents/${l.agentId}`;return o.jsx("a",{href:c,className:se("fidelios-mention-chip",`fidelios-mention-chip--${l.kind}`,l.kind==="project"&&"fidelios-project-mention-chip"),"data-mention-kind":l.kind,style:Vde(l),children:a})}return o.jsx("a",{href:i,rel:"noreferrer",children:a})}};return n&&(s.img=({node:i,src:a,alt:l,...c})=>{const u=a?n(a):null;return o.jsx("img",{...c,src:u??a,alt:l??""})}),o.jsx("div",{className:se("fidelios-markdown prose prose-sm max-w-none break-words overflow-hidden",r==="dark"&&"prose-invert",e),children:o.jsx(bet,{remarkPlugins:[Ctt],components:s,urlTransform:i=>i,children:t})})}function H9(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function xu(t){return t.replace(/\s+/g," ").trim()}function Hl(t,e){return t.length>e?`${t.slice(0,Math.max(0,e-1))}…`:t}function xS(t){return t.replace(/[_-]+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase())}function lG(t){const e=xu(t),n=e.match(/^(?:(?:\/bin\/)?(?:zsh|bash|sh)|cmd(?:\.exe)?(?:\s+\/d)?(?:\s+\/s)?(?:\s+\/c)?)\s+(?:-lc|\/c)\s+(.+)$/i),r=(n==null?void 0:n[1])??e,s=r.match(/^(['"])([\s\S]*)\1$/);return xu((s==null?void 0:s[2])??r)}function Ufe(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function eg(t){if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return Ufe(t)}function _tt(t){const e=H9(t);if(!e)return;const n=[e.toolUseId,e.tool_use_id,e.callId,e.call_id,e.id];for(const r of n)if(typeof r=="string"&&r.trim())return r}function cG(t,e){for(const n of e){const r=t[n];if(typeof r=="string"&&r.trim())return Hl(xu(r),120)}return null}function yS(t,e,n){const r=n==="compact"?72:120;if(typeof e=="string"){const c=Hy(t,e)?lG(e):xu(e);return Hl(c,r)}const s=H9(e);if(!s){const c=xu(Ufe(e));return c?Hl(c,r):`Inspect ${t} input`}const i=typeof s.command=="string"?s.command:typeof s.cmd=="string"?s.cmd:null;if(i&&Hy(t,s))return Hl(lG(i),r);const a=cG(s,["command","cmd","path","filePath","file_path","query","url","prompt","message"])??cG(s,["pattern","name","title","target","tool"])??null;if(a)return Hl(a,r);if(Array.isArray(s.paths)&&s.paths.length>0){const c=s.paths.find(u=>typeof u=="string"&&u.trim().length>0);if(c)return Hl(`${s.paths.length} paths, starting with ${c}`,r)}const l=Object.keys(s);return l.length===0?`No ${t} input`:l.length===1?Hl(`${l[0]} payload`,r):Hl(`${l.length} fields: ${l.slice(0,3).join(", ")}`,r)}function Vfe(t){var i;if(!t)return null;const e=t.split(/\r?\n/),n=new Map;let r=e.findIndex(a=>a.trim()==="");r===-1&&(r=e.length);for(let a=0;a<r;a+=1){const l=(i=e[a])==null?void 0:i.match(/^([a-z_]+):\s*(.+)$/i);l&&n.set(l[1].toLowerCase(),xu(l[2]))}const s=e.slice(Math.min(r+1,e.length)).map(a=>xu(a)).filter(Boolean).join(`
1062
1062
  `);return{command:n.get("command")??null,status:n.get("status")??null,exitCode:n.get("exit_code")??null,body:s}}function Hy(t,e){if(t==="command_execution"||t==="shell"||t==="shellToolCall"||t==="bash")return!0;if(typeof e=="string")return/\b(?:bash|zsh|sh|cmd|powershell)\b/i.test(e);const n=H9(e);return!!(n&&(typeof n.command=="string"||typeof n.cmd=="string"))}function Ett(t,e){return Hy(t,e)?"Executing command":xS(t)}function Att(t,e,n){if(!t)return e?"Tool failed":"Waiting for result";const r=Vfe(t);if(r){if(r.body)return Hl(r.body.split(`
1063
1063
  `)[0]??r.body,n==="compact"?84:140);if(r.status==="completed")return"Completed";if(r.status==="failed"||r.status==="error")return r.exitCode?`Failed with exit code ${r.exitCode}`:"Failed"}const i=t.split(/\r?\n/).map(a=>xu(a)).filter(Boolean)[0]??t;return Hl(i,n==="compact"?84:140)}function Ttt(t){const e=t.match(/^item (started|completed):\s*([a-z0-9_-]+)(?:\s+\(id=([^)]+)\))?$/i);return e?{status:e[1].toLowerCase()==="started"?"running":"completed",name:xS(e[2]??"Activity"),activityId:e[3]||void 0}:null}function Mtt(t){return xu(t).toLowerCase().startsWith("[fidelios] skipping saved session resume")}function Itt(t){const e=[];let n=[],r=null,s;const i=()=>{n.length===0||!r||(e.push({type:"command_group",ts:r,endTs:s,items:n}),n=[],r=null,s=void 0)};for(const a of t){if(a.type==="tool"&&Hy(a.name,a.input)){r||(r=a.ts),s=a.endTs??a.ts,n.push({ts:a.ts,endTs:a.endTs,input:a.input,result:a.result,isError:a.isError,status:a.status});continue}i(),e.push(a)}return i(),e}function Rtt(t){const e=[];let n=[],r=null,s;const i=()=>{n.length===0||!r||(e.push({type:"tool_group",ts:r,endTs:s,items:n}),n=[],r=null,s=void 0)};for(const a of t){if(a.type==="tool"&&!Hy(a.name,a.input)){r||(r=a.ts),s=a.endTs??a.ts,n.push({ts:a.ts,endTs:a.endTs,name:a.name,input:a.input,result:a.result,isError:a.isError,status:a.status});continue}i(),e.push(a)}return i(),e}function Ott(t,e){const n=[],r=new Map,s=new Map;for(const i of t){const a=n[n.length-1];if(i.kind==="assistant"||i.kind==="user"){const c=e&&i.kind==="assistant"&&i.delta===!0;(a==null?void 0:a.type)==="message"&&a.role===i.kind?(a.text+=a.text.endsWith(`
1064
1064
  `)||i.text.startsWith(`
@@ -1084,7 +1084,7 @@ ${Kn(r.inputTokens)} / ${Kn(r.outputTokens)} / $${r.costUsd.toFixed(6)}`:r.kind=
1084
1084
  `).map(g=>g.trim()).filter(g=>g.length>0&&!g.startsWith("---")&&!g.startsWith("|")&&!g.startsWith("```")&&!/^[-*>]/.test(g)&&!/^\d+\./.test(g)),h=[];let p=0;for(const g of f){if(h.length>=3||p+g.length>280)break;h.push(g),p+=g.length}return h.join(" ")},[c]);return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex w-full items-center justify-between",children:[o.jsxs("h3",{className:"flex items-center gap-2 text-sm font-medium",children:[i&&o.jsxs("span",{className:"relative flex h-2 w-2",children:[o.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-cyan-400"})]}),i?"Live Run":"Latest Run"]}),o.jsx(jt,{to:`/agents/${e}/runs/${s.id}`,className:"shrink-0 text-xs text-muted-foreground hover:text-foreground transition-colors no-underline",children:"View details →"})]}),o.jsxs(jt,{to:`/agents/${e}/runs/${s.id}`,className:se("block border rounded-lg p-4 space-y-2 w-full no-underline transition-colors hover:bg-muted/50 cursor-pointer",i?"border-cyan-500/30 shadow-[0_0_12px_rgba(6,182,212,0.08)]":"border-border"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(l,{className:se("h-3.5 w-3.5",a.color,s.status==="running"&&"animate-spin")}),o.jsx(sr,{status:s.status}),o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:s.id.slice(0,8)}),o.jsx("span",{className:se("inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium",s.invocationSource==="timer"?"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300":s.invocationSource==="assignment"?"bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300":s.invocationSource==="on_demand"?"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300":"bg-muted text-muted-foreground"),children:lhe[s.invocationSource]??s.invocationSource}),o.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:mo(s.createdAt)})]}),u&&o.jsx("div",{className:"overflow-hidden max-h-16",children:o.jsx(Al,{className:"[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:u})})]})]})}function Jnt({agent:t,runs:e,assignedIssues:n,runtimeState:r,agentId:s,agentRouteId:i}){return o.jsxs("div",{className:"space-y-8",children:[o.jsx(Ynt,{runs:e,agentId:i}),o.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(dh,{title:"Run Activity",subtitle:"Last 14 days",children:o.jsx(Wfe,{runs:e})}),o.jsx(dh,{title:"Issues by Priority",subtitle:"Last 14 days",children:o.jsx(Gfe,{issues:n})}),o.jsx(dh,{title:"Issues by Status",subtitle:"Last 14 days",children:o.jsx(Yfe,{issues:n})}),o.jsx(dh,{title:"Success Rate",subtitle:"Last 14 days",children:o.jsx(Jfe,{runs:e})})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"text-sm font-medium",children:"Recent Issues"}),o.jsx(jt,{to:`/issues?participantAgentId=${s}`,className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:"See All →"})]}),n.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent issues."}):o.jsxs("div",{className:"border border-border rounded-lg",children:[n.slice(0,10).map(a=>o.jsx(Uc,{identifier:a.identifier??a.id.slice(0,8),title:a.title,to:`/issues/${a.identifier??a.id}`,trailing:o.jsx(sr,{status:a.status})},a.id)),n.length>10&&o.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground text-center border-t border-border",children:["+",n.length-10," more issues"]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium",children:"Costs"}),o.jsx(Qnt,{runtimeState:r,runs:e})]})]})}function Qnt({runtimeState:t,runs:e}){const n=e.filter(r=>{const s=wS(r);return s.cost>0||s.input>0||s.output>0||s.cached>0}).sort((r,s)=>new Date(s.createdAt).getTime()-new Date(r.createdAt).getTime());return o.jsxs("div",{className:"space-y-4",children:[t&&o.jsx("div",{className:"border border-border rounded-lg p-4",children:o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 tabular-nums",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-muted-foreground block",children:"Input tokens"}),o.jsx("span",{className:"text-lg font-semibold",children:Kn(t.totalInputTokens)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-muted-foreground block",children:"Output tokens"}),o.jsx("span",{className:"text-lg font-semibold",children:Kn(t.totalOutputTokens)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-muted-foreground block",children:"Cached tokens"}),o.jsx("span",{className:"text-lg font-semibold",children:Kn(t.totalCachedInputTokens)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-xs text-muted-foreground block",children:"Total cost"}),o.jsx("span",{className:"text-lg font-semibold",children:tn(t.totalCostCents)})]})]})}),n.length>0&&o.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:o.jsxs("table",{className:"w-full text-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-border bg-accent/20",children:[o.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Date"}),o.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Run"}),o.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Input"}),o.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Output"}),o.jsx("th",{className:"text-right px-3 py-2 font-medium text-muted-foreground",children:"Cost"})]})}),o.jsx("tbody",{children:n.slice(0,10).map(r=>{const s=wS(r);return o.jsxs("tr",{className:"border-b border-border last:border-b-0",children:[o.jsx("td",{className:"px-3 py-2",children:To(r.createdAt)}),o.jsx("td",{className:"px-3 py-2 font-mono",children:r.id.slice(0,8)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Kn(s.input)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Kn(s.output)}),o.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:s.cost>0?`$${s.cost.toFixed(4)}`:"-"})]},r.id)})})]})})]})}function Znt({agent:t,agentId:e,companyId:n,onDirtyChange:r,onSaveActionChange:s,onCancelActionChange:i,onSavingChange:a,updatePermissions:l}){const c=hn(),[u,f]=y.useState(!1),{data:h}=_e({queryKey:J.agents.configRevisions(t.id),queryFn:()=>Mt.listConfigRevisions(t.id,n)}),p=Xe({mutationFn:g=>Mt.rollbackConfigRevision(t.id,g,n),onSuccess:()=>{c.invalidateQueries({queryKey:J.agents.detail(t.id)}),c.invalidateQueries({queryKey:J.agents.detail(t.urlKey)}),c.invalidateQueries({queryKey:J.agents.configRevisions(t.id)})}});return o.jsxs("div",{className:"max-w-3xl space-y-6",children:[o.jsx(Xnt,{agent:t,onDirtyChange:r,onSaveActionChange:s,onCancelActionChange:i,onSavingChange:a,updatePermissions:l,companyId:n,hidePromptTemplate:!0,hideInstructionsFile:!0}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium mb-3",children:"API Keys"}),o.jsx(irt,{agentId:e,companyId:n})]}),o.jsxs("div",{children:[o.jsxs("button",{className:"flex items-center gap-2 text-sm font-medium hover:text-foreground transition-colors",onClick:()=>f(g=>!g),children:[u?o.jsx(ns,{className:"h-3.5 w-3.5 text-muted-foreground"}):o.jsx($r,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Configuration Revisions",o.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:(h==null?void 0:h.length)??0})]}),u&&o.jsx("div",{className:"mt-3",children:(h??[]).length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No configuration revisions yet."}):o.jsx("div",{className:"space-y-2",children:(h??[]).slice(0,10).map(g=>o.jsxs("div",{className:"border border-border/70 rounded-md p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"text-xs text-muted-foreground",children:[o.jsx("span",{className:"font-mono",children:g.id.slice(0,8)}),o.jsx("span",{className:"mx-1",children:"·"}),o.jsx("span",{children:To(g.createdAt)}),o.jsx("span",{className:"mx-1",children:"·"}),o.jsx("span",{children:g.source})]}),o.jsx(ue,{size:"sm",variant:"outline",className:"h-7 px-2.5 text-xs",onClick:()=>p.mutate(g.id),disabled:p.isPending,children:"Restore"})]}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Changed:"," ",g.changedKeys.length>0?g.changedKeys.join(", "):"no tracked changes"]})]},g.id))})})]})]})}function Xnt({agent:t,companyId:e,onDirtyChange:n,onSaveActionChange:r,onCancelActionChange:s,onSavingChange:i,updatePermissions:a,hidePromptTemplate:l,hideInstructionsFile:c}){var _,A,M;const u=hn(),{pushToast:f}=Bo(),[h,p]=y.useState(!1),g=y.useRef(t),{data:b}=_e({queryKey:e?J.agents.adapterModels(e,t.adapterType):["agents","none","adapter-models",t.adapterType],queryFn:()=>Mt.adapterModels(e,t.adapterType),enabled:!!e}),v=Xe({mutationFn:I=>Mt.update(t.id,I,e),onMutate:()=>{p(!0)},onSuccess:()=>{u.invalidateQueries({queryKey:J.agents.detail(t.id)}),u.invalidateQueries({queryKey:J.agents.detail(t.urlKey)}),u.invalidateQueries({queryKey:J.agents.configRevisions(t.id)}),u.invalidateQueries({queryKey:J.agents.list(t.companyId)})},onError:I=>{p(!1);const L=I instanceof Hd||I instanceof Error?I.message:"Could not save agent";f({title:"Save failed",body:L,tone:"error"})}});y.useEffect(()=>{h&&t!==g.current&&p(!1),g.current=t},[t,h]);const w=v.isPending||h;y.useEffect(()=>{i(w)},[i,w]);const j=!!((_=t.permissions)!=null&&_.canCreateAgents),C=!!((A=t.access)!=null&&A.canAssignTasks),N=((M=t.access)==null?void 0:M.taskAssignSource)??"none",S=t.role==="ceo"||j,T=N==="ceo_role"?"Enabled automatically for CEO agents.":N==="agent_creator"?"Enabled automatically while this agent can create new agents.":N==="explicit_grant"?"Enabled via explicit company permission grant.":"Disabled unless explicitly granted.";return o.jsxs("div",{className:"space-y-6",children:[o.jsx(q9,{mode:"edit",agent:t,onSave:I=>v.mutate(I),isSaving:w,adapterModels:b,onDirtyChange:n,onSaveActionChange:r,onCancelActionChange:s,hideInlineSave:!0,hidePromptTemplate:l,hideInstructionsFile:c,sectionLayout:"cards"}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium mb-3",children:"Permissions"}),o.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{children:"Can create new agents"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Lets this agent create or hire agents and implicitly assign tasks."})]}),o.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":j,className:se("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 disabled:cursor-not-allowed disabled:opacity-50",j?"bg-green-600":"bg-muted"),onClick:()=>a.mutate({canCreateAgents:!j,canAssignTasks:j?C:!0}),disabled:a.isPending,children:o.jsx("span",{className:se("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",j?"translate-x-4.5":"translate-x-0.5")})})]}),o.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{children:"Can assign tasks"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:T})]}),o.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":C,className:se("relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 disabled:cursor-not-allowed disabled:opacity-50",C?"bg-green-600":"bg-muted"),onClick:()=>a.mutate({canCreateAgents:j,canAssignTasks:!C}),disabled:a.isPending||S,children:o.jsx("span",{className:se("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",C?"translate-x-4.5":"translate-x-0.5")})})]})]})]})]})}function ert({agent:t,companyId:e,onDirtyChange:n,onSaveActionChange:r,onCancelActionChange:s,onSavingChange:i}){const a=hn(),{selectedCompanyId:l}=Xt(),{isMobile:c}=yc(),[u,f]=y.useState("AGENTS.md"),[h,p]=y.useState(!1),[g,b]=y.useState(null),[v,w]=y.useState(null),[j,C]=y.useState(""),[N,S]=y.useState(!1),[T,_]=y.useState([]),[A,M]=y.useState(new Set),[I,L]=y.useState(260),D=y.useRef(null),[P,B]=y.useState(!1),Z=y.useRef(null),Q=y.useRef(null);y.useEffect(()=>{f("AGENTS.md"),p(!1),b(null),w(null),C(""),S(!1),_([]),M(new Set),B(!1),Z.current=null,Q.current=null},[t.id]);const q=t.adapterType==="claude_local"||t.adapterType==="codex_local"||t.adapterType==="opencode_local"||t.adapterType==="pi_local"||t.adapterType==="hermes_local"||t.adapterType==="cursor",{data:O,isLoading:z}=_e({queryKey:J.agents.instructionsBundle(t.id),queryFn:()=>Mt.instructionsBundle(t.id,e),enabled:!!(e&&q)}),V=(O==null?void 0:O.mode)??"managed",$=V==="managed"?(O==null?void 0:O.managedRootPath)??(O==null?void 0:O.rootPath)??"":(O==null?void 0:O.rootPath)??"",G=(v==null?void 0:v.mode)??V,W=(v==null?void 0:v.entryFile)??(O==null?void 0:O.entryFile)??"AGENTS.md",F=(v==null?void 0:v.rootPath)??$,le=y.useMemo(()=>(O==null?void 0:O.files.map(fe=>fe.path))??[],[O]),ie=!!(O&&G===V&&W===O.entryFile&&F===$),ne=y.useMemo(()=>ie?[...new Set([W,...le,...T])]:[W,...T],[ie,W,le,T]),X=y.useMemo(()=>Zx(Object.fromEntries(ne.map(fe=>[fe,""]))),[ne]),ee=u||W,de=ie&&le.includes(ee),ve=(O==null?void 0:O.files.find(fe=>fe.path===ee))??null,{data:Te,isLoading:Fe}=_e({queryKey:J.agents.instructionsFile(t.id,ee),queryFn:()=>Mt.instructionsFile(t.id,ee,e),enabled:!!(e&&q&&de)}),Ee=Xe({mutationFn:fe=>Mt.updateInstructionsBundle(t.id,fe,e),onMutate:()=>B(!0),onSuccess:()=>{a.invalidateQueries({queryKey:J.agents.instructionsBundle(t.id)}),a.invalidateQueries({queryKey:J.agents.detail(t.id)}),a.invalidateQueries({queryKey:J.agents.detail(t.urlKey)})},onError:()=>B(!1)}),tt=Xe({mutationFn:fe=>Mt.saveInstructionsFile(t.id,fe,e),onMutate:()=>B(!0),onSuccess:(fe,ke)=>{_(ce=>ce.filter(ye=>ye!==ke.path)),a.invalidateQueries({queryKey:J.agents.instructionsBundle(t.id)}),a.invalidateQueries({queryKey:J.agents.instructionsFile(t.id,ke.path)}),a.invalidateQueries({queryKey:J.agents.detail(t.id)}),a.invalidateQueries({queryKey:J.agents.detail(t.urlKey)})},onError:()=>B(!1)}),ot=Xe({mutationFn:fe=>Mt.deleteInstructionsFile(t.id,fe,e),onMutate:()=>B(!0),onSuccess:(fe,ke)=>{a.invalidateQueries({queryKey:J.agents.instructionsBundle(t.id)}),a.removeQueries({queryKey:J.agents.instructionsFile(t.id,ke)}),a.invalidateQueries({queryKey:J.agents.detail(t.id)}),a.invalidateQueries({queryKey:J.agents.detail(t.urlKey)})},onError:()=>B(!1)}),Ie=Xe({mutationFn:async({file:fe,namespace:ke})=>{if(!l)throw new Error("Select a company to upload images");return sm.uploadImage(l,fe,ke)}});y.useEffect(()=>{if(!O)return;if(!ie){u!==W&&f(W);return}const fe=O.files.map(ke=>ke.path);if(fe.length===0){u!==O.entryFile&&f(O.entryFile);return}!fe.includes(u)&&u!==W&&!T.includes(u)&&f(fe.includes(O.entryFile)?O.entryFile:fe[0])},[O,ie,W,T,u]),y.useEffect(()=>{const fe=new Set;for(const ke of ne){const ce=ke.split("/");let ye="";for(let re=0;re<ce.length-1;re++)ye=ye?`${ye}/${ce[re]}`:ce[re],fe.add(ye)}M(ke=>Unt(ke,fe)?ke:fe)},[ne]),y.useEffect(()=>{const fe=de&&Te?`${Te.path}:${Te.content}`:`draft:${G}:${F}:${ee}`;if(P){B(!1),w(null),b(null),Z.current=fe;return}Z.current!==fe&&(b(null),Z.current=fe)},[P,G,F,Te,de,ee]),y.useEffect(()=>{O&&w(fe=>fe||{mode:V,rootPath:$,entryFile:O.entryFile})},[O,V,$]),y.useEffect(()=>{!O||G!=="external"||(Q.current={rootPath:F,entryFile:W,selectedFile:ee})},[O,W,G,F,ee]);const rt=de?(Te==null?void 0:Te.content)??"":"",H=g??rt,U=!!(v&&(v.mode!==V||v.rootPath!==$||v.entryFile!==((O==null?void 0:O.entryFile)??"AGENTS.md"))),me=g!==null&&g!==rt,oe=U||me,pe=Ee.isPending||tt.isPending||ot.isPending||P;y.useEffect(()=>{i(pe)},[i,pe]),y.useEffect(()=>{n(oe)},[n,oe]),y.useEffect(()=>{r(oe?()=>{(async()=>{const ke=!!(O!=null&&O.legacyPromptTemplateActive)||!!(O!=null&&O.legacyBootstrapPromptTemplateActive);U&&v&&await Ee.mutateAsync({mode:v.mode,rootPath:v.mode==="external"?v.rootPath:null,entryFile:v.entryFile}),me&&await tt.mutateAsync({path:ee,content:H,clearLegacyPromptTemplate:ke})})().catch(()=>{})}:null)},[O,U,v,H,me,oe,r,tt,ee,Ee]),y.useEffect(()=>{s(oe?()=>{b(null),O&&w({mode:V,rootPath:$,entryFile:O.entryFile})}:null)},[O,oe,s,V,$]);const Ne=y.useCallback(fe=>{fe.preventDefault();const ke=fe.clientX,ce=I,ye=Ye=>{const gt=Ye.clientX-ke,Et=Math.max(180,Math.min(500,ce+gt));L(Et)},re=()=>{document.removeEventListener("mousemove",ye),document.removeEventListener("mouseup",re),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",ye),document.addEventListener("mouseup",re),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[I]);return q?z&&!O?o.jsx(trt,{}):o.jsxs("div",{className:"max-w-6xl space-y-6",children:[((O==null?void 0:O.warnings)??[]).length>0&&o.jsx("div",{className:"space-y-2",children:((O==null?void 0:O.warnings)??[]).map(fe=>o.jsx("div",{className:"rounded-md border border-sky-500/25 bg-sky-500/10 px-3 py-2 text-xs text-sky-100",children:fe},fe))}),o.jsxs(tm,{defaultOpen:G==="external",children:[o.jsxs(nm,{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors group",children:[o.jsx($r,{className:"h-3 w-3 transition-transform group-data-[state=open]:rotate-90"}),"Advanced"]}),o.jsx(rm,{className:"pt-4 pb-6",children:o.jsx(Yte,{children:o.jsxs("div",{className:"grid gap-x-6 gap-y-4 sm:grid-cols-[auto_1fr_1fr]",children:[o.jsxs("label",{className:"space-y-1.5",children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Mode",o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx(Dx,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),o.jsx(Mi,{side:"right",sideOffset:4,children:"Managed: FideliOS stores and serves the instructions bundle. External: you provide a path on disk where the instructions live."})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ue,{type:"button",size:"sm",variant:G==="managed"?"default":"outline",onClick:()=>{G==="external"&&(Q.current={rootPath:F,entryFile:W,selectedFile:ee});const fe=W||"AGENTS.md";w({mode:"managed",rootPath:(O==null?void 0:O.managedRootPath)??F,entryFile:fe}),f(fe)},children:"Managed"}),o.jsx(ue,{type:"button",size:"sm",variant:G==="external"?"default":"outline",onClick:()=>{const fe=Q.current,ke=(fe==null?void 0:fe.entryFile)??W??"AGENTS.md";w({mode:"external",rootPath:(fe==null?void 0:fe.rootPath)??((O==null?void 0:O.mode)==="external"?O.rootPath??"":""),entryFile:ke}),f((fe==null?void 0:fe.selectedFile)??ke)},children:"External"})]})]}),o.jsxs("label",{className:"space-y-1.5 min-w-0",children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Root path",o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx(Dx,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),o.jsx(Mi,{side:"right",sideOffset:4,children:"The absolute directory on disk where the instructions bundle lives. In managed mode this is set by FideliOS automatically."})]})]}),G==="managed"?o.jsxs("div",{className:"flex items-center gap-1.5 font-mono text-xs text-muted-foreground pt-1.5",children:[o.jsx("span",{className:"min-w-0 truncate",title:F||void 0,children:F||"(managed)"}),F&&o.jsx(vS,{text:F,className:"shrink-0",children:o.jsx(uc,{className:"h-3.5 w-3.5"})})]}):o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(_r,{value:F,onChange:fe=>{const ke=fe.target.value;Q.current={rootPath:ke,entryFile:W,selectedFile:ee},w({mode:"external",rootPath:ke,entryFile:W})},className:"font-mono text-sm",placeholder:"/absolute/path/to/agent/prompts"}),F&&o.jsx(vS,{text:F,className:"shrink-0",children:o.jsx(uc,{className:"h-3.5 w-3.5"})})]})]}),o.jsxs("label",{className:"space-y-1.5",children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:["Entry file",o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx(Dx,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),o.jsx(Mi,{side:"right",sideOffset:4,children:"The main file the agent reads first when loading instructions. Defaults to AGENTS.md."})]})]}),o.jsx(_r,{value:W,onChange:fe=>{const ke=fe.target.value||"AGENTS.md",ce=ee===W?ke:ee;G==="external"&&(Q.current={rootPath:F,entryFile:ke,selectedFile:ce}),ee===W&&f(ke),w({mode:G,rootPath:F,entryFile:ke})},className:"font-mono text-sm"})]})]})})})]}),o.jsxs("div",{ref:D,className:se("flex gap-0",c&&"flex-col gap-3"),children:[o.jsxs("div",{className:se("border border-border rounded-lg p-3 space-y-3 shrink-0",c&&h&&"block",c&&!h&&"hidden"),style:c?void 0:{width:I},children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h4",{className:"text-sm font-medium",children:"Files"}),o.jsxs("div",{className:"flex items-center gap-1",children:[!N&&o.jsx(ue,{type:"button",size:"icon",variant:"outline",className:"h-7 w-7",onClick:()=>S(!0),children:"+"}),c&&o.jsx(ue,{type:"button",size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>p(!1),children:"✕"})]})]}),N&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(_r,{value:j,onChange:fe=>C(fe.target.value),placeholder:"TOOLS.md",className:"font-mono text-sm",autoFocus:!0,onKeyDown:fe=>{fe.key==="Escape"&&(S(!1),C(""))}}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ue,{type:"button",size:"sm",variant:"default",className:"flex-1",disabled:!j.trim()||j.includes(".."),onClick:()=>{const fe=j.trim();!fe||fe.includes("..")||(_(ke=>ke.includes(fe)?ke:[...ke,fe]),f(fe),b(""),C(""),S(!1))},children:"Create"}),o.jsx(ue,{type:"button",size:"sm",variant:"outline",className:"flex-1",onClick:()=>{S(!1),C("")},children:"Cancel"})]})]}),o.jsx(z5,{nodes:X,selectedFile:ee,expandedDirs:A,checkedFiles:new Set,onToggleDir:fe=>M(ke=>{const ce=new Set(ke);return ce.has(fe)?ce.delete(fe):ce.add(fe),ce}),onSelectFile:fe=>{f(fe),le.includes(fe)||b(""),c&&p(!1)},onToggleCheck:()=>{},showCheckboxes:!1,renderFileExtra:fe=>{const ke=O==null?void 0:O.files.find(ce=>ce.path===fe.path);return ke?ke.deprecated?o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx("span",{className:"ml-3 shrink-0 rounded border border-amber-500/40 bg-amber-500/10 text-amber-200 px-1.5 py-0.5 text-[10px] uppercase tracking-wide cursor-help",children:"virtual file"})}),o.jsx(Mi,{side:"right",sideOffset:4,children:"Legacy inline prompt — this deprecated virtual file preserves the old promptTemplate content"})]}):o.jsx("span",{className:"ml-3 shrink-0 rounded border border-border text-muted-foreground px-1.5 py-0.5 text-[10px] uppercase tracking-wide",children:ke.isEntryFile?"entry":`${ke.size}b`}):null}})]}),!c&&o.jsx("div",{className:"w-1 shrink-0 cursor-col-resize hover:bg-border active:bg-primary/50 rounded transition-colors mx-1",onMouseDown:Ne}),o.jsxs("div",{className:se("border border-border rounded-lg p-4 space-y-3 min-w-0 flex-1",c&&h&&"hidden"),children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[c&&o.jsx(ue,{type:"button",size:"icon",variant:"outline",className:"h-7 w-7 shrink-0",onClick:()=>p(!0),children:o.jsx(mw,{className:"h-3.5 w-3.5"})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:"text-sm font-medium font-mono truncate",children:ee}),o.jsx("p",{className:"text-xs text-muted-foreground",children:de?ve!=null&&ve.deprecated?"Deprecated virtual file":`${(Te==null?void 0:Te.language)??"text"} file`:"New file in this bundle"})]})]}),de&&!(ve!=null&&ve.deprecated)&&ee!==W&&o.jsx(ue,{type:"button",size:"sm",variant:"outline",onClick:()=>{confirm(`Delete ${ee}?`)&&ot.mutate(ee,{onSuccess:()=>{f(W),b(null)}})},disabled:ot.isPending,children:"Delete"})]}),de&&Fe&&!Te?o.jsx(uhe,{}):Lnt(ee)?o.jsx(Ao,{value:H,onChange:fe=>b(fe??""),placeholder:"# Agent instructions",contentClassName:"min-h-[420px] text-sm font-mono",imageUploadHandler:async fe=>{const ke=`agents/${t.id}/instructions/${ee.replaceAll("/","-")}`;return(await Ie.mutateAsync({file:fe,namespace:ke})).contentPath}},ee):o.jsx("textarea",{value:H,onChange:fe=>b(fe.target.value),className:"min-h-[420px] w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-sm outline-none",placeholder:"File contents"})]})]})]}):o.jsx("div",{className:"max-w-3xl",children:o.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions bundles are only available for local adapters."})})}function trt(){return o.jsxs("div",{className:"max-w-5xl space-y-4",children:[o.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{className:"h-4 w-40"}),o.jsx(zt,{className:"h-4 w-[30rem] max-w-full"})]}),o.jsx(zt,{className:"h-4 w-16"})]}),o.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:Array.from({length:3}).map((t,e)=>o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{className:"h-3 w-20"}),o.jsx(zt,{className:"h-10 w-full"})]},e))})]}),o.jsxs("div",{className:"grid gap-4 lg:grid-cols-[260px_minmax(0,1fr)]",children:[o.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(zt,{className:"h-4 w-12"}),o.jsx(zt,{className:"h-8 w-16"})]}),o.jsx(zt,{className:"h-10 w-full"}),o.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((t,e)=>o.jsx(zt,{className:"h-9 w-full rounded-none"},e))})]}),o.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{className:"h-4 w-48"}),o.jsx(zt,{className:"h-3 w-28"})]}),o.jsx(uhe,{})]})]})]})}function uhe(){return o.jsxs("div",{className:"space-y-3",children:[o.jsx(zt,{className:"h-10 w-full"}),o.jsx(zt,{className:"h-[420px] w-full"})]})}function nrt({agent:t,companyId:e}){const n=hn(),[r,s]=y.useState([]),[i,a]=y.useState([]),[l,c]=y.useState(!1),u=y.useRef([]),f=y.useRef(!1),h=y.useRef(!0),{data:p,isLoading:g}=_e({queryKey:J.agents.skills(t.id),queryFn:()=>Mt.skills(t.id,e),enabled:!!e}),{data:b}=_e({queryKey:J.companySkills.list(e??""),queryFn:()=>rl.list(e),enabled:!!e}),v=Xe({mutationFn:D=>Mt.syncSkills(t.id,D,e),onSuccess:async D=>{n.setQueryData(J.agents.skills(t.id),D),u.current=D.desiredSkills,a(D.desiredSkills),await Promise.all([n.invalidateQueries({queryKey:J.agents.detail(t.id)}),n.invalidateQueries({queryKey:J.agents.detail(t.urlKey)})])}});y.useEffect(()=>{s([]),a([]),u.current=[],f.current=!1,h.current=!0},[t.id]),y.useEffect(()=>{if(!p)return;const D=Tnt({draft:r,lastSaved:u.current,hasHydratedSnapshot:f.current},p.desiredSkills);h.current=D.shouldSkipAutosave,f.current=D.hasHydratedSnapshot,s(D.draft),u.current=D.lastSaved,a(D.lastSaved)},[r,p]),y.useEffect(()=>{if(!p)return;if(h.current){h.current=!1;return}if(v.isPending||fj(r,u.current))return;const D=window.setTimeout(()=>{fj(r,u.current)||v.mutate(r)},250);return()=>window.clearTimeout(D)},[r,p,v.isPending,v.mutate]);const w=y.useMemo(()=>new Map((b??[]).map(D=>[D.key,D])),[b]),j=y.useMemo(()=>new Set((b??[]).map(D=>D.key)),[b]),C=y.useMemo(()=>new Map(((p==null?void 0:p.entries)??[]).map(D=>[D.key,D])),[p]),N=y.useMemo(()=>(b??[]).filter(D=>{var P;return!((P=C.get(D.key))!=null&&P.required)}).map(D=>{var P,B,Z;return{id:D.id,key:D.key,name:D.name,description:D.description,detail:((P=C.get(D.key))==null?void 0:P.detail)??null,locationLabel:((B=C.get(D.key))==null?void 0:B.locationLabel)??null,originLabel:((Z=C.get(D.key))==null?void 0:Z.originLabel)??null,linkTo:`/skills/${D.id}`,readOnly:!1,adapterEntry:C.get(D.key)??null}}),[C,b]),S=y.useMemo(()=>((p==null?void 0:p.entries)??[]).filter(D=>D.required).map(D=>{const P=w.get(D.key);return{id:(P==null?void 0:P.id)??`required:${D.key}`,key:D.key,name:(P==null?void 0:P.name)??D.key,description:(P==null?void 0:P.description)??null,detail:D.detail??null,locationLabel:D.locationLabel??null,originLabel:D.originLabel??null,linkTo:P?`/skills/${P.id}`:null,readOnly:!1,adapterEntry:D}}),[w,p]),T=y.useMemo(()=>((p==null?void 0:p.entries)??[]).filter(D=>Mnt(D,j)).map(D=>({id:`external:${D.key}`,key:D.key,name:D.runtimeName??D.key,description:null,detail:D.detail??null,locationLabel:D.locationLabel??null,originLabel:D.originLabel??null,linkTo:null,readOnly:!0,adapterEntry:D})),[j,p]),_=y.useMemo(()=>r.filter(D=>!w.has(D)),[w,r]),A=y.useMemo(()=>{switch(p==null?void 0:p.mode){case"persistent":return"Kept in the workspace";case"ephemeral":return"Applied when the agent runs";case"unsupported":return"Tracked only";default:return"Unknown"}},[p==null?void 0:p.mode]),M=y.useMemo(()=>(p==null?void 0:p.mode)!=="unsupported"?null:t.adapterType==="openclaw_gateway"?"FideliOS cannot manage OpenClaw skills here. Visit your OpenClaw instance to manage this agent's skills.":"FideliOS cannot manage skills for this adapter yet. Manage them in the adapter directly.",[t.adapterType,p==null?void 0:p.mode]),I=!fj(r,i),L=v.isPending?"Saving changes...":I?"Saving soon...":null;return o.jsxs("div",{className:"max-w-4xl space-y-5",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[o.jsx(jt,{to:"/skills",className:"text-sm font-medium text-foreground underline-offset-4 no-underline transition-colors hover:text-foreground/70 hover:underline",children:"View company skills library"}),L?o.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[v.isPending?o.jsx(Pa,{className:"h-3.5 w-3.5 animate-spin"}):null,o.jsx("span",{children:L})]}):null]}),p!=null&&p.warnings.length?o.jsx("div",{className:"space-y-1 rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200",children:p.warnings.map(D=>o.jsx("div",{children:D},D))}):null,M?o.jsx("div",{className:"rounded-xl border border-border px-4 py-3 text-sm text-muted-foreground",children:M}):null,g?o.jsx(is,{variant:"list"}):o.jsxs(o.Fragment,{children:[(()=>{const D=P=>{const B=P.adapterEntry??C.get(P.key),Z=!!(B!=null&&B.required),Q=se("flex items-start gap-3 border-b border-border px-3 py-3 text-sm last:border-b-0",P.readOnly?"bg-muted/20":"hover:bg-accent/20"),q=o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("div",{className:"min-w-0",children:o.jsx("span",{className:"truncate font-medium",children:P.name})}),P.linkTo?o.jsx(jt,{to:P.linkTo,className:"shrink-0 text-xs text-muted-foreground no-underline hover:text-foreground",children:"View"}):null]}),P.description&&o.jsx(Al,{className:"mt-1 text-xs text-muted-foreground prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",children:P.description}),P.readOnly&&P.originLabel&&o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:P.originLabel}),P.readOnly&&P.locationLabel&&o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Location: ",P.locationLabel]}),P.detail&&o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:P.detail})]});if(P.readOnly)return o.jsxs("div",{className:Q,children:[o.jsx("span",{className:"mt-1 h-2 w-2 rounded-full bg-muted-foreground/40"}),q]},P.id);const O=Z||r.includes(P.key),z=Z||(p==null?void 0:p.mode)==="unsupported",V=o.jsx("input",{type:"checkbox",checked:O,disabled:z,onChange:$=>{const G=$.target.checked?Array.from(new Set([...r,P.key])):r.filter(W=>W!==P.key);s(G)},className:"mt-0.5 disabled:cursor-not-allowed disabled:opacity-60"});return o.jsxs("label",{className:Q,children:[Z&&(B!=null&&B.requiredReason)?o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx("span",{children:V})}),o.jsx(Mi,{side:"top",children:B.requiredReason})]}):(p==null?void 0:p.mode)==="unsupported"?o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx("span",{children:V})}),o.jsx(Mi,{side:"top",children:M??"Manage skills in the adapter directly."})]}):V,q]},P.id)};return N.length===0&&S.length===0&&T.length===0?o.jsx("section",{className:"border-y border-border",children:o.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground",children:"Import skills into the company library first, then attach them here."})}):o.jsxs(o.Fragment,{children:[N.length>0&&o.jsx("section",{className:"border-y border-border",children:N.map(D)}),S.length>0&&o.jsxs("section",{className:"border-y border-border",children:[o.jsx("div",{className:"border-b border-border bg-muted/40 px-3 py-2",children:o.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Required by FideliOS"})}),S.map(D)]}),T.length>0&&o.jsxs("section",{className:"border-y border-border",children:[o.jsxs("div",{role:"button",tabIndex:0,className:"flex cursor-pointer items-center gap-2 border-b border-border bg-muted/40 px-3 py-2 select-none",onClick:()=>c(P=>!P),onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),c(B=>!B))},children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["(",T.length,") User-installed skills, not managed by FideliOS"]}),l?o.jsx(ns,{className:"h-3.5 w-3.5 text-muted-foreground"}):o.jsx($r,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),l&&T.map(D)]})]})})(),_.length>0&&o.jsxs("div",{className:"rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200",children:[o.jsx("div",{className:"font-medium",children:"Requested skills missing from the company library"}),o.jsx("div",{className:"mt-1 text-xs",children:_.join(", ")})]}),o.jsxs("section",{className:"border-t border-border pt-4",children:[o.jsxs("div",{className:"grid gap-2 text-sm sm:grid-cols-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Adapter"}),o.jsx("span",{className:"font-medium",children:R5[t.adapterType]??t.adapterType})]}),o.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Skills applied"}),o.jsx("span",{children:A})]}),o.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/60 py-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Selected skills"}),o.jsx("span",{children:r.length})]})]}),v.isError&&o.jsx("p",{className:"mt-3 text-xs text-destructive",children:v.error instanceof Error?v.error.message:"Failed to update skills"})]})]})]})}function jG({run:t,isSelected:e,agentId:n}){const r=ahe[t.status]??{icon:ky,color:"text-neutral-400"},s=r.icon,i=wS(t),a=t.resultJson?String(t.resultJson.summary??t.resultJson.result??""):t.error??"";return o.jsxs(jt,{to:e?`/agents/${n}/runs`:`/agents/${n}/runs/${t.id}`,className:se("flex flex-col gap-1 w-full px-3 py-2.5 text-left border-b border-border last:border-b-0 transition-colors no-underline text-inherit",e?"bg-accent/40":"hover:bg-accent/20"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(s,{className:se("h-3.5 w-3.5 shrink-0",r.color,t.status==="running"&&"animate-spin")}),o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.id.slice(0,8)}),o.jsx("span",{className:se("inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium shrink-0",t.invocationSource==="timer"?"bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300":t.invocationSource==="assignment"?"bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300":t.invocationSource==="on_demand"?"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300":"bg-muted text-muted-foreground"),children:lhe[t.invocationSource]??t.invocationSource}),o.jsx("span",{className:"ml-auto text-[11px] text-muted-foreground shrink-0",children:mo(t.createdAt)})]}),a&&o.jsx("span",{className:"text-xs text-muted-foreground truncate pl-5.5",children:a.slice(0,60)}),(i.totalTokens>0||i.cost>0)&&o.jsxs("div",{className:"flex items-center gap-2 pl-5.5 text-[11px] text-muted-foreground tabular-nums",children:[i.totalTokens>0&&o.jsxs("span",{children:[Kn(i.totalTokens)," tok"]}),i.cost>0&&o.jsxs("span",{children:["$",i.cost.toFixed(3)]})]})]})}function rrt({runs:t,companyId:e,agentId:n,agentRouteId:r,selectedRunId:s,adapterType:i}){var f;const{isMobile:a}=yc();if(t.length===0)return o.jsx("p",{className:"text-sm text-muted-foreground",children:"No runs yet."});const l=[...t].sort((h,p)=>new Date(p.createdAt).getTime()-new Date(h.createdAt).getTime()),c=a?s:s??((f=l[0])==null?void 0:f.id)??null,u=l.find(h=>h.id===c)??null;return a?u?o.jsxs("div",{className:"space-y-3 min-w-0 overflow-x-hidden",children:[o.jsxs(jt,{to:`/agents/${r}/runs`,className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors no-underline",children:[o.jsx(fw,{className:"h-3.5 w-3.5"}),"Back to runs"]}),o.jsx(NG,{run:u,agentRouteId:r,adapterType:i},u.id)]}):o.jsx("div",{className:"border border-border rounded-lg overflow-x-hidden",children:l.map(h=>o.jsx(jG,{run:h,isSelected:!1,agentId:r},h.id))}):o.jsxs("div",{className:"flex gap-0",children:[o.jsx("div",{className:se("shrink-0 border border-border rounded-lg",u?"w-72":"w-full"),children:o.jsx("div",{className:"sticky top-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 2rem)"},children:l.map(h=>o.jsx(jG,{run:h,isSelected:h.id===c,agentId:r},h.id))})}),u&&o.jsx("div",{className:"flex-1 min-w-0 pl-4",children:o.jsx(NG,{run:u,agentRouteId:r,adapterType:i},u.id)})]})}function NG({run:t,agentRouteId:e,adapterType:n}){const r=hn(),s=As(),{data:i}=_e({queryKey:J.runDetail(t.id),queryFn:()=>qr.get(t.id),enabled:!!t.id}),a=i??t,l=wS(a),[c,u]=y.useState(!1),[f,h]=y.useState(null);y.useEffect(()=>{h(null)},[a.id]);const p=Xe({mutationFn:()=>qr.cancel(a.id),onSuccess:()=>{r.invalidateQueries({queryKey:J.heartbeats(a.companyId,a.agentId)})}}),g=a.errorCode==="process_lost"&&a.status==="failed",b=y.useMemo(()=>{const V={resumeFromRunId:a.id},$=gp(a.contextSnapshot);if(!$)return V;const G=Xr($.issueId),W=Xr($.taskId),F=Xr($.taskKey),le=Xr($.wakeCommentId)??Xr($.commentId);return G&&(V.issueId=G),W&&(V.taskId=W),F&&(V.taskKey=F),le&&(V.commentId=le),V},[a.contextSnapshot,a.id]),v=Xe({mutationFn:async()=>{const V=await Mt.wakeup(a.agentId,{source:"on_demand",triggerDetail:"manual",reason:"resume_process_lost_run",payload:b},a.companyId);if(!("id"in V))throw new Error("Resume request was skipped because the agent is not currently invokable.");return V},onSuccess:V=>{r.invalidateQueries({queryKey:J.heartbeats(a.companyId,a.agentId)}),s(`/agents/${e}/runs/${V.id}`)}}),w=a.status==="failed"||a.status==="timed_out",j=y.useMemo(()=>{const V={},$=gp(a.contextSnapshot);if(!$)return V;const G=Xr($.issueId),W=Xr($.taskId),F=Xr($.taskKey);return G&&(V.issueId=G),W&&(V.taskId=W),F&&(V.taskKey=F),V},[a.contextSnapshot]),C=Xe({mutationFn:async()=>{const V=await Mt.wakeup(a.agentId,{source:"on_demand",triggerDetail:"manual",reason:"retry_failed_run",payload:j},a.companyId);if(!("id"in V))throw new Error("Retry was skipped because the agent is not currently invokable.");return V},onSuccess:V=>{r.invalidateQueries({queryKey:J.heartbeats(a.companyId,a.agentId)}),s(`/agents/${e}/runs/${V.id}`)}}),{data:N}=_e({queryKey:J.runIssues(a.id),queryFn:()=>Ch.issuesForRun(a.id)}),S=y.useMemo(()=>Array.from(new Set((N??[]).map(V=>V.issueId))),[N]),T=Xe({mutationFn:async()=>S.length===0?0:(await Promise.all(S.map(V=>Mt.resetSession(a.agentId,V,a.companyId))),S.length),onSuccess:()=>{r.invalidateQueries({queryKey:J.agents.runtimeState(a.agentId)}),r.invalidateQueries({queryKey:J.agents.taskSessions(a.agentId)}),r.invalidateQueries({queryKey:J.runIssues(a.id)})}}),_=Xe({mutationFn:()=>Mt.loginWithClaude(a.agentId,a.companyId),onSuccess:V=>{h(V)}}),A=a.status==="running"&&!!a.startedAt&&!a.finishedAt,[M,I]=y.useState(()=>a.startedAt?Math.max(0,Math.round((Date.now()-new Date(a.startedAt).getTime())/1e3)):0);y.useEffect(()=>{if(!A||!a.startedAt)return;const V=new Date(a.startedAt).getTime();I(Math.max(0,Math.round((Date.now()-V)/1e3)));const $=setInterval(()=>{I(Math.max(0,Math.round((Date.now()-V)/1e3)))},1e3);return()=>clearInterval($)},[A,a.startedAt]);const L={hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1},D=a.startedAt?new Date(a.startedAt).toLocaleTimeString("en-US",L):null,P=a.finishedAt?new Date(a.finishedAt).toLocaleTimeString("en-US",L):null,Z=(a.startedAt&&a.finishedAt?Math.round((new Date(a.finishedAt).getTime()-new Date(a.startedAt).getTime())/1e3):null)??(A?M:null),Q=l.input>0||l.output>0||l.cached>0||l.cost>0,q=!!(a.sessionIdBefore||a.sessionIdAfter),O=a.sessionIdBefore&&a.sessionIdAfter&&a.sessionIdBefore!==a.sessionIdAfter;a.sessionIdAfter||a.sessionIdBefore;const z=a.exitCode!==null&&a.exitCode!==0;return o.jsxs("div",{className:"space-y-4 min-w-0",children:[o.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{className:"flex flex-col sm:flex-row",children:[o.jsxs("div",{className:"flex-1 p-4 space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(sr,{status:a.status}),(a.status==="running"||a.status==="queued")&&o.jsx(ue,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive text-xs h-6 px-2",onClick:()=>p.mutate(),disabled:p.isPending,children:p.isPending?"Cancelling…":"Cancel"}),g&&o.jsxs(ue,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2",onClick:()=>v.mutate(),disabled:v.isPending,children:[o.jsx(Ip,{className:"h-3.5 w-3.5 mr-1"}),v.isPending?"Resuming…":"Resume"]}),w&&!g&&o.jsxs(ue,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2",onClick:()=>C.mutate(),disabled:C.isPending,children:[o.jsx(Ip,{className:"h-3.5 w-3.5 mr-1"}),C.isPending?"Retrying…":"Retry"]})]}),v.isError&&o.jsx("div",{className:"text-xs text-destructive",children:v.error instanceof Error?v.error.message:"Failed to resume run"}),C.isError&&o.jsx("div",{className:"text-xs text-destructive",children:C.error instanceof Error?C.error.message:"Failed to retry run"}),D&&o.jsxs("div",{className:"space-y-0.5",children:[o.jsxs("div",{className:"text-sm font-mono",children:[D,P&&o.jsx("span",{className:"text-muted-foreground",children:" → "}),P]}),o.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[mo(a.startedAt),a.finishedAt&&o.jsxs(o.Fragment,{children:[" → ",mo(a.finishedAt)]})]}),Z!==null&&o.jsxs("div",{className:"text-xs text-muted-foreground",children:["Duration: ",Z>=60?`${Math.floor(Z/60)}m ${Z%60}s`:`${Z}s`]})]}),a.error&&o.jsxs("div",{className:"text-xs",children:[o.jsx("span",{className:"text-red-600 dark:text-red-400",children:a.error}),a.errorCode&&o.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",a.errorCode,")"]})]}),a.errorCode==="claude_auth_required"&&n==="claude_local"&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(ue,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>_.mutate(),disabled:_.isPending,children:_.isPending?"Running claude login...":"Login to Claude Code"}),_.isError&&o.jsx("p",{className:"text-xs text-destructive",children:_.error instanceof Error?_.error.message:"Failed to run Claude login"}),(f==null?void 0:f.loginUrl)&&o.jsxs("p",{className:"text-xs",children:["Login URL:",o.jsx("a",{href:f.loginUrl,className:"text-blue-600 underline underline-offset-2 ml-1 break-all dark:text-blue-400",target:"_blank",rel:"noreferrer",children:f.loginUrl})]}),f&&o.jsxs(o.Fragment,{children:[!!f.stdout&&o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap",children:f.stdout}),!!f.stderr&&o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap",children:f.stderr})]})]}),z&&o.jsxs("div",{className:"text-xs text-red-600 dark:text-red-400",children:["Exit code ",a.exitCode,a.signal&&o.jsxs("span",{className:"text-muted-foreground ml-1",children:["(signal: ",a.signal,")"]})]})]}),Q&&o.jsxs("div",{className:"border-t sm:border-t-0 sm:border-l border-border p-4 grid grid-cols-2 gap-x-4 sm:gap-x-8 gap-y-3 content-center tabular-nums",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Input"}),o.jsx("div",{className:"text-sm font-medium font-mono",children:Kn(l.input)})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Output"}),o.jsx("div",{className:"text-sm font-medium font-mono",children:Kn(l.output)})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Cached"}),o.jsx("div",{className:"text-sm font-medium font-mono",children:Kn(l.cached)})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Cost"}),o.jsx("div",{className:"text-sm font-medium font-mono",children:l.cost>0?`$${l.cost.toFixed(4)}`:"-"})]})]})]}),q&&o.jsxs("div",{className:"border-t border-border",children:[o.jsxs("button",{className:"flex items-center gap-1.5 w-full px-4 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>u(V=>!V),children:[o.jsx($r,{className:se("h-3 w-3 transition-transform",c&&"rotate-90")}),"Session",O&&o.jsx("span",{className:"text-yellow-400 ml-1",children:"(changed)"})]}),c&&o.jsxs("div",{className:"px-4 pb-3 space-y-1 text-xs",children:[a.sessionIdBefore&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-12",children:O?"Before":"ID"}),o.jsx(vS,{text:a.sessionIdBefore,className:"font-mono"})]}),O&&a.sessionIdAfter&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-12",children:"After"}),o.jsx(vS,{text:a.sessionIdAfter,className:"font-mono"})]}),S.length>0&&o.jsxs("div",{className:"pt-1",children:[o.jsx("button",{type:"button",className:"text-[11px] text-muted-foreground underline underline-offset-2 hover:text-foreground disabled:opacity-60",disabled:T.isPending,onClick:()=>{const V=S.length;window.confirm(`Clear session for ${V} issue${V===1?"":"s"} touched by this run?`)&&T.mutate()},children:T.isPending?"clearing session...":"clear session for these issues"}),T.isError&&o.jsx("p",{className:"text-[11px] text-destructive mt-1",children:T.error instanceof Error?T.error.message:"Failed to clear sessions"})]})]})]})]}),N&&N.length>0&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Issues Touched (",N.length,")"]}),o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:N.map(V=>o.jsxs(jt,{to:`/issues/${V.identifier??V.issueId}`,className:"flex items-center justify-between w-full px-3 py-2 text-xs hover:bg-accent/20 transition-colors text-left no-underline text-inherit",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(sr,{status:V.status}),o.jsx("span",{className:"truncate",children:V.title})]}),o.jsx("span",{className:"font-mono text-muted-foreground shrink-0 ml-2",children:V.identifier??V.issueId.slice(0,8)})]},V.issueId))})]}),a.stderrExcerpt&&o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs font-medium text-red-600 dark:text-red-400",children:"stderr"}),o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap",children:a.stderrExcerpt})]}),a.stdoutExcerpt&&!a.logRef&&o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"stdout"}),o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap",children:a.stdoutExcerpt})]}),o.jsx(srt,{run:a,adapterType:n}),o.jsx(ohe,{})]})}function srt({run:t,adapterType:e}){var W;const[n,r]=y.useState([]),[s,i]=y.useState([]),[a,l]=y.useState(!0),[c,u]=y.useState(!!t.logRef),[f,h]=y.useState(null),[p,g]=y.useState(0),[b,v]=y.useState(!1),[w,j]=y.useState(!1),[C,N]=y.useState("nice"),S=y.useRef(null),T=y.useRef(""),_=y.useRef(null),A=y.useRef(!1),M=y.useRef({scrollHeight:0,distanceFromBottom:Number.POSITIVE_INFINITY}),I=t.status==="running"||t.status==="queued",{data:L=[]}=_e({queryKey:J.runWorkspaceOperations(t.id),queryFn:()=>qr.workspaceOperations(t.id),refetchInterval:I?2e3:!1});function D(F){return F instanceof Hd&&F.status===404}function P(F,le=!1){if(!F&&!le)return;const ne=`${T.current}${F}`.split(`
1085
1085
  `);T.current=ne.pop()??"",le&&T.current&&(ne.push(T.current),T.current="");const X=[];for(const ee of ne){const de=ee.trim();if(de)try{const ve=JSON.parse(de),Te=ve.stream==="stderr"||ve.stream==="system"?ve.stream:"stdout",Fe=typeof ve.chunk=="string"?ve.chunk:"",Ee=typeof ve.ts=="string"?ve.ts:new Date().toISOString();if(!Fe)continue;X.push({ts:Ee,stream:Te,chunk:Fe})}catch{}}X.length>0&&i(ee=>[...ee,...X])}const{data:B}=_e({queryKey:["run-events",t.id],queryFn:()=>qr.events(t.id,0,200)});y.useEffect(()=>{B&&(r(B),l(!1))},[B]);const Z=y.useCallback(()=>{if(_.current)return _.current;const F=Bnt(S.current);return _.current=F,F},[]),Q=y.useCallback(()=>{const F=Z(),le=S2(F);M.current=le;const ie=le.distanceFromBottom<=kG;A.current=ie,v(ne=>ne===ie?ne:ie)},[Z]);y.useEffect(()=>{if(_.current=null,M.current={scrollHeight:0,distanceFromBottom:Number.POSITIVE_INFINITY},!I){A.current=!1,v(!1);return}Q()},[I,t.id,Q]),y.useEffect(()=>{if(!I)return;const F=Z();return Q(),F===window?window.addEventListener("scroll",Q,{passive:!0}):F.addEventListener("scroll",Q,{passive:!0}),window.addEventListener("resize",Q),()=>{F===window?window.removeEventListener("scroll",Q):F.removeEventListener("scroll",Q),window.removeEventListener("resize",Q)}},[I,t.id,Z,Q]),y.useEffect(()=>{if(!I||!A.current)return;const F=Z(),le=M.current,ie=S2(F),ne=Math.max(0,ie.scrollHeight-le.scrollHeight),X=le.distanceFromBottom+ne;if(ie.distanceFromBottom-X>kG){A.current=!1,v(!1),M.current=ie;return}CG(F,"auto");const de=S2(F);M.current=de,A.current||(A.current=!0),v(ve=>ve||!0)},[n.length,s.length,I,Z]),y.useEffect(()=>{let F=!1;if(T.current="",i([]),g(0),h(null),!t.logRef&&!I)return u(!1),()=>{F=!0};u(!0);const le=typeof t.logBytes=="number"&&t.logBytes>0?Math.min(Math.max(t.logBytes+1024,256e3),2e6):256e3;return(async()=>{try{let ne=0,X=!0;for(;!F;){const ee=await qr.log(t.id,ne,X?le:256e3);if(F)break;P(ee.content,ee.nextOffset===void 0);const de=ee.nextOffset??ne+ee.content.length;if(g(de),ne=de,X=!1,ee.nextOffset===void 0||I)break}}catch(ne){if(!F){if(I&&D(ne)){u(!1);return}h(ne instanceof Error?ne.message:"Failed to load run log")}}finally{F||u(!1)}})(),()=>{F=!0}},[t.id,t.logRef,t.logBytes,I]),y.useEffect(()=>{if(!I||w)return;const F=setInterval(async()=>{const le=n.length>0?Math.max(...n.map(ie=>ie.seq)):0;try{const ie=await qr.events(t.id,le,100);ie.length>0&&r(ne=>[...ne,...ie])}catch{}},2e3);return()=>clearInterval(F)},[t.id,I,w,n]),y.useEffect(()=>{if(!I||w)return;const F=setInterval(async()=>{try{const le=await qr.log(t.id,p,256e3);le.content&&P(le.content,le.nextOffset===void 0),le.nextOffset!==void 0?g(le.nextOffset):le.content.length>0&&g(ie=>ie+le.content.length)}catch(le){if(D(le))return}},2e3);return()=>clearInterval(F)},[t.id,I,w,p]),y.useEffect(()=>{if(!I)return;let F=!1,le=null,ie=null;const ne=()=>{F||(le=window.setTimeout(X,1500))},X=()=>{if(F)return;const de=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/companies/${encodeURIComponent(t.companyId)}/events/ws`;ie=new WebSocket(de),ie.onopen=()=>{j(!0)},ie.onmessage=ve=>{const Te=typeof ve.data=="string"?ve.data:"";if(!Te)return;let Fe;try{Fe=JSON.parse(Te)}catch{return}if(Fe.companyId!==t.companyId)return;const Ee=gp(Fe.payload),tt=Xr(Ee==null?void 0:Ee.runId);if(!Ee||tt!==t.id)return;if(Fe.type==="heartbeat.run.log"){const oe=typeof Ee.chunk=="string"?Ee.chunk:"";if(!oe)return;const pe=Xr(Ee.stream),Ne=pe==="stderr"||pe==="system"?pe:"stdout",fe=Xr(Ee.ts)??Fe.createdAt;i(ke=>[...ke,{ts:fe,stream:Ne,chunk:oe}]);return}if(Fe.type!=="heartbeat.run.event")return;const ot=typeof Ee.seq=="number"?Ee.seq:null;if(ot===null||!Number.isFinite(ot))return;const Ie=Xr(Ee.stream),rt=Ie==="stdout"||Ie==="stderr"||Ie==="system"?Ie:null,H=Xr(Ee.level),U=H==="info"||H==="warn"||H==="error"?H:null,me={id:ot,companyId:t.companyId,runId:t.id,agentId:t.agentId,seq:ot,eventType:Xr(Ee.eventType)??"event",stream:rt,level:U,color:Xr(Ee.color),message:Xr(Ee.message),payload:gp(Ee.payload),createdAt:new Date(Fe.createdAt)};r(oe=>oe.some(pe=>pe.seq===ot)?oe:[...oe,me])},ie.onerror=()=>{ie==null||ie.close()},ie.onclose=()=>{j(!1),ne()}};return X(),()=>{F=!0,j(!1),le!==null&&window.clearTimeout(le),ie&&(ie.onopen=null,ie.onmessage=null,ie.onerror=null,ie.onclose=null,ie.close(1e3,"run_detail_unmount"))}},[I,t.companyId,t.id,t.agentId]);const q=((W=_e({queryKey:J.instance.generalSettings,queryFn:()=>Od.getGeneral()}).data)==null?void 0:W.censorUsernameInLogs)===!0,O=y.useMemo(()=>{const F=n.find(le=>le.eventType==="adapter.invoke");return Cx(gp((F==null?void 0:F.payload)??null),q)},[q,n]),z=y.useMemo(()=>Zp(e),[e]),V=y.useMemo(()=>ofe(s,z.parseStdoutLine,{censorUsernameInLogs:q}),[z,q,s]);if(y.useEffect(()=>{N("nice")},[t.id]),a&&c)return o.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading run logs..."});if(n.length===0&&s.length===0&&!f)return o.jsx("p",{className:"text-xs text-muted-foreground",children:"No log events."});const $={info:"text-foreground",warn:"text-yellow-600 dark:text-yellow-400",error:"text-red-600 dark:text-red-400"},G={stdout:"text-foreground",stderr:"text-red-600 dark:text-red-300",system:"text-blue-600 dark:text-blue-300"};return o.jsxs("div",{className:"space-y-3",children:[o.jsx(Gnt,{operations:L,censorUsernameInLogs:q}),O&&o.jsxs("div",{className:"rounded-lg border border-border bg-background/60 p-3 space-y-2",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Invocation"}),typeof O.adapterType=="string"&&o.jsxs("div",{className:"text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:"Adapter: "}),O.adapterType]}),typeof O.cwd=="string"&&o.jsxs("div",{className:"text-xs break-all",children:[o.jsx("span",{className:"text-muted-foreground",children:"Working dir: "}),o.jsx("span",{className:"font-mono",children:O.cwd})]}),typeof O.command=="string"&&o.jsxs("div",{className:"text-xs break-all",children:[o.jsx("span",{className:"text-muted-foreground",children:"Command: "}),o.jsx("span",{className:"font-mono",children:[O.command,...Array.isArray(O.commandArgs)?O.commandArgs.filter(F=>typeof F=="string"):[]].join(" ")})]}),Array.isArray(O.commandNotes)&&O.commandNotes.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Command notes"}),o.jsx("ul",{className:"list-disc pl-5 space-y-1",children:O.commandNotes.filter(F=>typeof F=="string"&&F.trim().length>0).map((F,le)=>o.jsx("li",{className:"text-xs break-all font-mono",children:F},`${le}-${F}`))})]}),O.prompt!==void 0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Prompt"}),o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap",children:typeof O.prompt=="string"?Wc(O.prompt,q):JSON.stringify(Cx(O.prompt,q),null,2)})]}),O.context!==void 0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Context"}),o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(Cx(O.context,q),null,2)})]}),O.env!==void 0&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Environment"}),o.jsx("pre",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap font-mono",children:$nt(O.env,q)})]})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Transcript (",V.length,")"]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"inline-flex rounded-lg border border-border/70 bg-background/70 p-0.5",children:["nice","raw"].map(F=>o.jsx("button",{type:"button",className:se("rounded-md px-2.5 py-1 text-[11px] font-medium capitalize transition-colors",C===F?"bg-accent text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),onClick:()=>N(F),children:F},F))}),I&&!b&&o.jsx(ue,{variant:"ghost",size:"xs",onClick:()=>{const F=Z();A.current=!0,v(!0),CG(F,"auto"),M.current=S2(F)},children:"Jump to live"}),I&&o.jsxs("span",{className:"flex items-center gap-1 text-xs text-cyan-400",children:[o.jsxs("span",{className:"relative flex h-2 w-2",children:[o.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-cyan-400"})]}),"Live"]})]})]}),o.jsxs("div",{className:"max-h-[38rem] overflow-y-auto rounded-2xl border border-border/70 bg-background/40 p-3 sm:p-4",children:[o.jsx(T0,{entries:V,mode:C,streaming:I,emptyMessage:t.logRef?"Waiting for transcript...":"No persisted transcript for this run."}),f&&o.jsx("div",{className:"mt-3 rounded-xl border border-red-500/20 bg-red-500/[0.06] px-3 py-2 text-xs text-red-700 dark:text-red-300",children:f}),o.jsx("div",{ref:S})]}),(t.status==="failed"||t.status==="timed_out")&&o.jsxs("div",{className:"rounded-lg border border-red-300 dark:border-red-500/30 bg-red-50 dark:bg-red-950/20 p-3 space-y-2",children:[o.jsx("div",{className:"text-xs font-medium text-red-700 dark:text-red-300",children:"Failure details"}),t.error&&o.jsxs("div",{className:"text-xs text-red-600 dark:text-red-200",children:[o.jsx("span",{className:"text-red-700 dark:text-red-300",children:"Error: "}),Wc(t.error,q)]}),t.stderrExcerpt&&t.stderrExcerpt.trim()&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"stderr excerpt"}),o.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:Wc(t.stderrExcerpt,q)})]}),t.resultJson&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"adapter result JSON"}),o.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:JSON.stringify(Cx(t.resultJson,q),null,2)})]}),t.stdoutExcerpt&&t.stdoutExcerpt.trim()&&!t.resultJson&&o.jsxs("div",{children:[o.jsx("div",{className:"text-xs text-red-700 dark:text-red-300 mb-1",children:"stdout excerpt"}),o.jsx("pre",{className:"bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100",children:Wc(t.stdoutExcerpt,q)})]})]}),n.length>0&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Events (",n.length,")"]}),o.jsx("div",{className:"bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5",children:n.map(F=>{const le=F.color??(F.level?$[F.level]:null)??(F.stream?G[F.stream]:null)??"text-foreground";return o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"text-neutral-400 dark:text-neutral-600 shrink-0 select-none w-16",children:new Date(F.createdAt).toLocaleTimeString("en-US",{hour12:!1})}),o.jsx("span",{className:se("shrink-0 w-14",F.stream?G[F.stream]??"text-neutral-500":"text-neutral-500"),children:F.stream?`[${F.stream}]`:""}),o.jsx("span",{className:se("break-all",le),children:F.message?Wc(F.message,q):F.payload?JSON.stringify(Cx(F.payload,q)):""})]},F.id)})})]})]})}function irt({agentId:t,companyId:e}){const n=hn(),[r,s]=y.useState(""),[i,a]=y.useState(null),[l,c]=y.useState(!1),[u,f]=y.useState(!1),{data:h,isLoading:p}=_e({queryKey:J.agents.keys(t),queryFn:()=>Mt.listKeys(t,e)}),g=Xe({mutationFn:()=>Mt.createKey(t,r.trim()||"Default",e),onSuccess:C=>{a(C.token),c(!0),s(""),n.invalidateQueries({queryKey:J.agents.keys(t)})}}),b=Xe({mutationFn:C=>Mt.revokeKey(t,C,e),onSuccess:()=>{n.invalidateQueries({queryKey:J.agents.keys(t)})}});function v(){i&&(navigator.clipboard.writeText(i),f(!0),setTimeout(()=>f(!1),2e3))}const w=(h??[]).filter(C=>!C.revokedAt),j=(h??[]).filter(C=>C.revokedAt);return o.jsxs("div",{className:"space-y-6",children:[i&&o.jsxs("div",{className:"border border-yellow-300 dark:border-yellow-600/40 bg-yellow-50 dark:bg-yellow-500/5 rounded-lg p-4 space-y-2",children:[o.jsx("p",{className:"text-sm font-medium text-yellow-700 dark:text-yellow-400",children:"API key created — copy it now, it will not be shown again."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate",children:l?i:i.replace(/./g,"•")}),o.jsx(ue,{variant:"ghost",size:"icon-sm",onClick:()=>c(C=>!C),title:l?"Hide":"Show",children:l?o.jsx(Vv,{className:"h-3.5 w-3.5"}):o.jsx(hw,{className:"h-3.5 w-3.5"})}),o.jsx(ue,{variant:"ghost",size:"icon-sm",onClick:v,title:"Copy",children:o.jsx(uc,{className:"h-3.5 w-3.5"})}),u&&o.jsx("span",{className:"text-xs text-green-400",children:"Copied!"})]}),o.jsx(ue,{variant:"ghost",size:"sm",className:"text-muted-foreground text-xs",onClick:()=>a(null),children:"Dismiss"})]}),o.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[o.jsxs("h3",{className:"text-xs font-medium text-muted-foreground flex items-center gap-2",children:[o.jsx(E_e,{className:"h-3.5 w-3.5"}),"Create API Key"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"API keys allow this agent to authenticate calls to the FideliOS server."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_r,{placeholder:"Key name (e.g. production)",value:r,onChange:C=>s(C.target.value),className:"h-8 text-sm",onKeyDown:C=>{C.key==="Enter"&&g.mutate()}}),o.jsxs(ue,{size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,children:[o.jsx(Er,{className:"h-3.5 w-3.5 mr-1"}),"Create"]})]})]}),p&&o.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading keys..."}),!p&&w.length===0&&!i&&o.jsx("p",{className:"text-sm text-muted-foreground",children:"No active API keys."}),w.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Active Keys"}),o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:w.map(C=>o.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-sm font-medium",children:C.name}),o.jsxs("span",{className:"text-xs text-muted-foreground ml-3",children:["Created ",To(C.createdAt)]})]}),o.jsx(ue,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive text-xs",onClick:()=>b.mutate(C.id),disabled:b.isPending,children:"Revoke"})]},C.id))})]}),j.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Revoked Keys"}),o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border opacity-50",children:j.map(C=>o.jsx("div",{className:"flex items-center justify-between px-4 py-2.5",children:o.jsxs("div",{children:[o.jsx("span",{className:"text-sm line-through",children:C.name}),o.jsxs("span",{className:"text-xs text-muted-foreground ml-3",children:["Revoked ",C.revokedAt?To(C.revokedAt):""]})]})},C.id))})]})]})}function ort(){const{selectedCompanyId:t}=Xt(),{openNewProject:e}=Ts(),{setBreadcrumbs:n}=yr();y.useEffect(()=>{n([{label:"Projects"}])},[n]);const{data:r,isLoading:s,error:i}=_e({queryKey:J.projects.list(t),queryFn:()=>vs.list(t),enabled:!!t}),a=y.useMemo(()=>(r??[]).filter(l=>!l.archivedAt),[r]);return t?s?o.jsx(is,{variant:"list"}):o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"flex items-center justify-end",children:o.jsxs(ue,{size:"sm",variant:"outline",onClick:e,children:[o.jsx(Er,{className:"h-4 w-4 mr-1"}),"Add Project"]})}),i&&o.jsx("p",{className:"text-sm text-destructive",children:i.message}),!s&&a.length===0&&o.jsx(Ar,{icon:cu,message:"No projects yet.",action:"Add Project",onAction:e}),a.length>0&&o.jsx("div",{className:"border border-border",children:a.map(l=>o.jsx(Uc,{title:l.name,subtitle:l.description??void 0,to:y_(l),trailing:o.jsxs("div",{className:"flex items-center gap-3",children:[l.targetDate&&o.jsx("span",{className:"text-xs text-muted-foreground",children:To(l.targetDate)}),o.jsx(sr,{status:l.status})]})},l.id))})]}):o.jsx(Ar,{icon:cu,message:"Select a company to view projects."})}function Ro({className:t,orientation:e="horizontal",decorative:n=!0,...r}){return o.jsx(MX,{"data-slot":"separator",decorative:n,orientation:e,className:se("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}const art=250,lrt=1600;function dhe(){const[t,e]=y.useState("idle"),n=y.useRef(0),r=y.useRef(null),s=y.useRef(null),i=y.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null),s.current&&(clearTimeout(s.current),s.current=null)},[]);y.useEffect(()=>i,[i]);const a=y.useCallback(()=>{n.current+=1,i(),e("idle")},[i]),l=y.useCallback(()=>{i(),e("idle")},[i]),c=y.useCallback(async u=>{const f=n.current+1;n.current=f,i(),r.current=setTimeout(()=>{n.current===f&&e("saving")},art);try{if(await u(),n.current!==f)return;i(),e("saved"),s.current=setTimeout(()=>{n.current===f&&e("idle")},lrt)}catch(h){throw n.current!==f||(i(),e("error")),h}},[i]);return{state:t,markDirty:l,reset:a,runSave:c}}const SG="px-1 -mx-1",crt="px-1",urt=900;function ou({value:t,onSave:e,as:n="span",className:r,placeholder:s="Click to edit...",multiline:i=!1,imageUploadHandler:a,mentions:l}){const[c,u]=y.useState(!1),[f,h]=y.useState(!1),[p,g]=y.useState(t),b=y.useRef(null),v=y.useRef(null),w=y.useRef(null),{state:j,markDirty:C,reset:N,runSave:S}=dhe();y.useEffect(()=>{i&&f||g(t)},[t,i,f]),y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const T=y.useCallback(I=>{I&&(I.style.height="auto",I.style.height=`${I.scrollHeight}px`)},[]);y.useEffect(()=>{c&&b.current&&(b.current.focus(),b.current.select(),b.current instanceof HTMLTextAreaElement&&T(b.current))},[c,T]),y.useEffect(()=>{if(!c||!i)return;const I=requestAnimationFrame(()=>{var L;(L=v.current)==null||L.focus()});return()=>cancelAnimationFrame(I)},[c,i]);const _=y.useCallback(async(I=p)=>{const L=I.trim();L&&L!==t?await Promise.resolve(e(L)):g(t),i||u(!1)},[p,i,e,t]);function A(I){I.key==="Enter"&&!i&&(I.preventDefault(),_()),I.key==="Escape"&&(w.current&&clearTimeout(w.current),N(),g(t),i?(h(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):u(!1))}if(y.useEffect(()=>{if(!i||!f)return;const I=p.trim();if(!I||I===t){j!=="saved"&&N();return}return C(),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{S(()=>_(I))},urt),()=>{w.current&&clearTimeout(w.current)}},[j,_,p,C,i,f,N,S,t]),i)return o.jsxs("div",{className:se(crt,"rounded transition-colors",f?"bg-transparent":"hover:bg-accent/20"),onFocusCapture:()=>h(!0),onBlurCapture:I=>{if(I.currentTarget.contains(I.relatedTarget))return;w.current&&clearTimeout(w.current),h(!1);const L=p.trim();if(!L||L===t){N(),_();return}S(()=>_())},onKeyDown:A,children:[o.jsx(Ao,{ref:v,value:p,onChange:g,placeholder:s,bordered:!1,className:"bg-transparent",contentClassName:se("fidelios-edit-in-place-content",r),imageUploadHandler:a,mentions:l,onSubmit:()=>{const I=p.trim();if(!I||I===t){N(),_();return}S(()=>_())}}),o.jsx("div",{className:"flex min-h-4 items-center justify-end pr-1",children:o.jsx("span",{className:se("text-[11px] transition-opacity duration-150",j==="error"?"text-destructive":"text-muted-foreground",j==="idle"?"opacity-0":"opacity-100"),children:j==="saving"?"Autosaving...":j==="saved"?"Saved":j==="error"?"Could not save":"Idle"})})]});if(c)return o.jsx("textarea",{ref:b,value:p,rows:1,onChange:I=>{g(I.target.value),T(I.target)},onBlur:()=>{_()},onKeyDown:A,className:se("w-full bg-transparent rounded outline-none resize-none overflow-hidden",SG,r)});const M=t&&i?"div":n;return o.jsx(M,{className:se("cursor-pointer rounded hover:bg-accent/50 transition-colors overflow-hidden",SG,!t&&"text-muted-foreground italic",r),onClick:()=>u(!0),children:t||s})}const drt=[{value:"backlog",label:"Backlog"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"},{value:"cancelled",label:"Cancelled"}];function Bf({state:t}){return t==="saving"?o.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[o.jsx(Pa,{className:"h-3 w-3 animate-spin"}),"Saving"]}):t==="saved"?o.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-green-600 dark:text-green-400",children:[o.jsx($s,{className:"h-3 w-3"}),"Saved"]}):t==="error"?o.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-destructive",children:[o.jsx(o6,{className:"h-3 w-3"}),"Failed"]}):null}function Dm({label:t,state:e}){return o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:t}),o.jsx(Bf,{state:e})]})}function Rf({label:t,children:e,alignStart:n=!1,valueClassName:r=""}){return o.jsxs("div",{className:se("flex gap-3 py-1.5",n?"items-start":"items-center"),children:[o.jsx("div",{className:"shrink-0 w-20",children:t}),o.jsx("div",{className:se("min-w-0 flex-1",n?"pt-0.5":"flex items-center gap-1.5",r),children:e})]})}function frt({status:t,onChange:e}){const[n,r]=y.useState(!1),s=qne[t]??Kne;return o.jsxs(wr,{open:n,onOpenChange:r,children:[o.jsx(kr,{asChild:!0,children:o.jsx("button",{className:se("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0 cursor-pointer hover:opacity-80 transition-opacity",s),children:t.replace("_"," ")})}),o.jsx(Cr,{className:"w-40 p-1",align:"start",children:drt.map(i=>o.jsx(ue,{variant:"ghost",size:"sm",className:se("w-full justify-start gap-2 text-xs",i.value===t&&"bg-accent"),onClick:()=>{e(i.value),r(!1)},children:i.label},i.value))})]})}function hrt({project:t,onArchive:e,archivePending:n}){const[r,s]=y.useState(!1),i=!t.archivedAt,a=i?"Archive":"Unarchive";return o.jsxs("div",{className:"space-y-3 rounded-md border border-destructive/40 bg-destructive/5 px-4 py-4",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:i?"Archive this project to hide it from the sidebar and project selectors.":"Unarchive this project to restore it in the sidebar and project selectors."}),n?o.jsxs(ue,{size:"sm",variant:"destructive",disabled:!0,children:[o.jsx(Pa,{className:"h-3 w-3 animate-spin mr-1"}),i?"Archiving...":"Unarchiving..."]}):r?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm text-destructive font-medium",children:[a," “",t.name,"”?"]}),o.jsx(ue,{size:"sm",variant:"destructive",onClick:()=>{s(!1),e(i)},children:"Confirm"}),o.jsx(ue,{size:"sm",variant:"outline",onClick:()=>s(!1),children:"Cancel"})]}):o.jsx(ue,{size:"sm",variant:"destructive",onClick:()=>s(!0),children:i?o.jsxs(o.Fragment,{children:[o.jsx(ate,{className:"h-3 w-3 mr-1"}),a," project"]}):o.jsxs(o.Fragment,{children:[o.jsx(HNe,{className:"h-3 w-3 mr-1"}),a," project"]})})]})}function mrt({project:t,onUpdate:e,onFieldUpdate:n,getFieldSaveState:r,onArchive:s,archivePending:i}){var rt;const{selectedCompanyId:a}=Xt(),l=hn(),[c,u]=y.useState(!1),[f,h]=y.useState(!1),[p,g]=y.useState(null),[b,v]=y.useState(""),[w,j]=y.useState(""),[C,N]=y.useState(null),S=(H,U)=>{if(n){n(H,U);return}e==null||e(U)},T=H=>(r==null?void 0:r(H))??"idle",{data:_}=_e({queryKey:J.goals.list(a),queryFn:()=>jl.list(a),enabled:!!a}),{data:A}=_e({queryKey:J.instance.experimentalSettings,queryFn:()=>Od.getExperimental()}),M=t.goalIds.length>0?t.goalIds:t.goalId?[t.goalId]:[],I=t.goals.length>0?t.goals:M.map(H=>{var U;return{id:H,title:((U=_==null?void 0:_.find(me=>me.id===H))==null?void 0:U.title)??H.slice(0,8)}}),L=(_??[]).filter(H=>!M.includes(H.id)),D=t.workspaces??[],P=t.codebase,B=t.primaryWorkspace??null,Z=D.some(H=>H.id!==(B==null?void 0:B.id)),Q=t.executionWorkspacePolicy??null,q=(Q==null?void 0:Q.enabled)===!0,O=(A==null?void 0:A.enableIsolatedWorkspaces)===!0,z=(Q==null?void 0:Q.defaultMode)==="isolated_workspace"?"isolated_workspace":"shared_workspace",V=(Q==null?void 0:Q.workspaceStrategy)??{type:"git_worktree",baseRef:"",branchTemplate:"",worktreeParentDir:""},$=()=>{l.invalidateQueries({queryKey:J.projects.detail(t.id)}),t.urlKey!==t.id&&l.invalidateQueries({queryKey:J.projects.detail(t.urlKey)}),a&&l.invalidateQueries({queryKey:J.projects.list(a)})},G=Xe({mutationFn:H=>vs.createWorkspace(t.id,H),onSuccess:()=>{v(""),j(""),g(null),N(null),$()}}),W=Xe({mutationFn:H=>vs.removeWorkspace(t.id,H),onSuccess:()=>{v(""),j(""),g(null),N(null),$()}}),F=Xe({mutationFn:({workspaceId:H,data:U})=>vs.updateWorkspace(t.id,H,U),onSuccess:()=>{v(""),j(""),g(null),N(null),$()}}),le=H=>{!e&&!n||S("goals",{goalIds:M.filter(U=>U!==H)})},ie=H=>{!e&&!n||M.includes(H)||(S("goals",{goalIds:[...M,H]}),u(!1))},ne=H=>{if(!(!e&&!n))return{executionWorkspacePolicy:{enabled:q,defaultMode:z,allowIssueOverride:(Q==null?void 0:Q.allowIssueOverride)??!0,...Q,...H}}},X=H=>H.startsWith("/")||/^[A-Za-z]:[\\/]/.test(H),ee=H=>{try{const U=new URL(H),me=U.hostname.toLowerCase();return me!=="github.com"&&me!=="www.github.com"?!1:U.pathname.split("/").filter(Boolean).length>=2}catch{return!1}},de=H=>{if(!H)return!1;try{const U=new URL(H);return U.protocol==="http:"||U.protocol==="https:"}catch{return!1}},ve=H=>{var U;try{const me=new URL(H),oe=me.pathname.split("/").filter(Boolean);if(oe.length<2)return me.host;const pe=oe[0],Ne=(U=oe[1])==null?void 0:U.replace(/\.git$/i,"");return!pe||!Ne?me.host:`${me.host}/${pe}/${Ne}`}catch{return H}},Te=(H,U)=>{if(U)return"git_repo";if(H)return"local_path"},Fe=H=>{const U=H.cwd!==void 0?H.cwd:P.localFolder,me=H.repoUrl!==void 0?H.repoUrl:P.repoUrl;if(!U&&!me){B&&W.mutate(B.id);return}const oe={...H.cwd!==void 0?{cwd:H.cwd}:{},...H.repoUrl!==void 0?{repoUrl:H.repoUrl}:{},...Te(U,me)?{sourceType:Te(U,me)}:{},isPrimary:!0};if(B){F.mutate({workspaceId:B.id,data:oe});return}G.mutate(oe)},Ee=()=>{const H=b.trim();if(!H){N(null),Fe({cwd:null});return}if(!X(H)){N("Local folder must be a full absolute path.");return}N(null),Fe({cwd:H})},tt=()=>{const H=w.trim();if(!H){N(null),Fe({repoUrl:null});return}if(!ee(H)){N("Repo must use a valid GitHub repo URL.");return}N(null),Fe({repoUrl:H})},ot=()=>{window.confirm(P.repoUrl?"Clear local folder from this workspace?":"Delete this workspace local folder?")&&Fe({cwd:null})},Ie=()=>{const H=!!P.localFolder;if(window.confirm(H?"Clear repo from this workspace?":"Delete this workspace repo?")){if(B&&H){F.mutate({workspaceId:B.id,data:{repoUrl:null,repoRef:null,defaultRef:null,sourceType:Te(P.localFolder,null)}});return}Fe({repoUrl:null})}};return o.jsxs("div",{children:[o.jsxs("div",{className:"space-y-1 pb-4",children:[o.jsx(Rf,{label:o.jsx(Dm,{label:"Name",state:T("name")}),children:e||n?o.jsx(Lr,{value:t.name,onCommit:H=>S("name",{name:H}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-sm outline-none",placeholder:"Project name"}):o.jsx("span",{className:"text-sm",children:t.name})}),o.jsx(Rf,{label:o.jsx(Dm,{label:"Description",state:T("description")}),alignStart:!0,valueClassName:"space-y-0.5",children:e||n?o.jsx(ou,{value:t.description??"",onSave:H=>S("description",{description:H}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0}):o.jsx("p",{className:"text-sm text-muted-foreground",children:((rt=t.description)==null?void 0:rt.trim())||"No description"})}),o.jsx(Rf,{label:o.jsx(Dm,{label:"Status",state:T("status")}),children:e||n?o.jsx(frt,{status:t.status,onChange:H=>S("status",{status:H})}):o.jsx(sr,{status:t.status})}),t.leadAgentId&&o.jsx(Rf,{label:"Lead",children:o.jsx("span",{className:"text-sm font-mono",children:t.leadAgentId.slice(0,8)})}),o.jsxs(Rf,{label:o.jsx(Dm,{label:"Goals",state:T("goals")}),alignStart:!0,valueClassName:"space-y-2",children:[I.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(H=>o.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs",children:[o.jsx(jt,{to:`/goals/${H.id}`,className:"hover:underline max-w-[220px] truncate",children:H.title}),(e||n)&&o.jsx("button",{className:"text-muted-foreground hover:text-foreground",type:"button",onClick:()=>le(H.id),"aria-label":`Remove goal ${H.title}`,children:o.jsx(ps,{className:"h-3 w-3"})})]},H.id))}),(e||n)&&o.jsxs(wr,{open:c,onOpenChange:u,children:[o.jsx(kr,{asChild:!0,children:o.jsxs(ue,{variant:"outline",size:"xs",className:se("h-6 w-fit px-2",I.length>0&&"ml-1"),disabled:L.length===0,children:[o.jsx(Er,{className:"h-3 w-3 mr-1"}),"Goal"]})}),o.jsx(Cr,{className:"w-56 p-1",align:"start",children:L.length===0?o.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All goals linked."}):L.map(H=>o.jsx("button",{className:"flex items-center w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",onClick:()=>ie(H.id),children:H.title},H.id))})]})]}),o.jsx(Rf,{label:o.jsx(Dm,{label:"Created",state:"idle"}),children:o.jsx("span",{className:"text-sm",children:To(t.createdAt)})}),o.jsx(Rf,{label:o.jsx(Dm,{label:"Updated",state:"idle"}),children:o.jsx("span",{className:"text-sm",children:To(t.updatedAt)})}),t.targetDate&&o.jsx(Rf,{label:o.jsx(Dm,{label:"Target Date",state:"idle"}),children:o.jsx("span",{className:"text-sm",children:To(t.targetDate)})})]}),o.jsx(Ro,{className:"my-4"}),o.jsxs("div",{className:"space-y-1 py-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Codebase"}),o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-border text-[10px] text-muted-foreground hover:text-foreground","aria-label":"Codebase help",children:"?"})}),o.jsx(Mi,{side:"top",children:"Repo identifies the source of truth. Local folder is the default place agents write code."})]})]}),o.jsxs("div",{className:"space-y-2 rounded-md border border-border/70 p-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Repo"}),P.repoUrl?o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[de(P.repoUrl)?o.jsxs("a",{href:P.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground hover:underline",children:[o.jsx(zj,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:ve(P.repoUrl)}),o.jsx(Md,{className:"h-3 w-3 shrink-0"})]}):o.jsxs("div",{className:"inline-flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx(zj,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:P.repoUrl})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ue,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{g("repo"),j(P.repoUrl??""),N(null)},children:"Change repo"}),o.jsx(ue,{variant:"ghost",size:"icon-xs",onClick:Ie,"aria-label":"Clear repo",children:o.jsx(Fa,{className:"h-3 w-3"})})]})]}):o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Not set."}),o.jsx(ue,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{g("repo"),j(P.repoUrl??""),N(null)},children:"Set repo"})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Local folder"}),o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0 space-y-1",children:[o.jsx("div",{className:"min-w-0 truncate font-mono text-xs text-muted-foreground",children:P.effectiveLocalFolder}),P.origin==="managed_checkout"&&o.jsx("div",{className:"text-[11px] text-muted-foreground",children:"FideliOS-managed folder."})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ue,{variant:"outline",size:"xs",className:"h-6 px-2",onClick:()=>{g("local"),v(P.localFolder??""),N(null)},children:P.localFolder?"Change local folder":"Set local folder"}),P.localFolder?o.jsx(ue,{variant:"ghost",size:"icon-xs",onClick:ot,"aria-label":"Clear local folder",children:o.jsx(Fa,{className:"h-3 w-3"})}):null]})]})]}),Z&&o.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Additional legacy workspace records exist on this project. FideliOS is using the primary workspace as the codebase view."}),B!=null&&B.runtimeServices&&B.runtimeServices.length>0?o.jsx("div",{className:"space-y-1",children:B.runtimeServices.map(H=>o.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-border/60 px-2 py-1",children:[o.jsxs("div",{className:"min-w-0 space-y-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-[11px] font-medium",children:H.serviceName}),o.jsx("span",{className:se("rounded-full px-1.5 py-0.5 text-[10px] uppercase tracking-wide",H.status==="running"?"bg-green-500/15 text-green-700 dark:text-green-300":H.status==="failed"?"bg-red-500/15 text-red-700 dark:text-red-300":"bg-muted text-muted-foreground"),children:H.status})]}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:H.url?o.jsx("a",{href:H.url,target:"_blank",rel:"noreferrer",className:"hover:text-foreground hover:underline",children:H.url}):H.command??"No URL"})]}),o.jsx("div",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:H.lifecycle})]},H.id))}):null]}),p==="local"&&o.jsxs("div",{className:"space-y-1.5 rounded-md border border-border p-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",value:b,onChange:H=>v(H.target.value),placeholder:"/absolute/path/to/workspace"}),o.jsx(Nu,{})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ue,{variant:"outline",size:"xs",className:"h-6 px-2",disabled:!b.trim()&&!B||G.isPending||F.isPending,onClick:Ee,children:"Save"}),o.jsx(ue,{variant:"ghost",size:"xs",className:"h-6 px-2",onClick:()=>{g(null),v(""),N(null)},children:"Cancel"})]})]}),p==="repo"&&o.jsxs("div",{className:"space-y-1.5 rounded-md border border-border p-2",children:[o.jsx("input",{className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs outline-none",value:w,onChange:H=>j(H.target.value),placeholder:"https://github.com/org/repo"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ue,{variant:"outline",size:"xs",className:"h-6 px-2",disabled:!w.trim()&&!B||G.isPending||F.isPending,onClick:tt,children:"Save"}),o.jsx(ue,{variant:"ghost",size:"xs",className:"h-6 px-2",onClick:()=>{g(null),j(""),N(null)},children:"Cancel"})]})]}),C&&o.jsx("p",{className:"text-xs text-destructive",children:C}),G.isError&&o.jsx("p",{className:"text-xs text-destructive",children:"Failed to save workspace."}),W.isError&&o.jsx("p",{className:"text-xs text-destructive",children:"Failed to delete workspace."}),F.isError&&o.jsx("p",{className:"text-xs text-destructive",children:"Failed to update workspace."})]}),O?o.jsxs(o.Fragment,{children:[o.jsx(Ro,{className:"my-4"}),o.jsxs("div",{className:"py-1.5 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Execution Workspaces"}),o.jsxs(Ai,{children:[o.jsx(Ti,{asChild:!0,children:o.jsx("button",{type:"button",className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-border text-[10px] text-muted-foreground hover:text-foreground","aria-label":"Execution workspaces help",children:"?"})}),o.jsx(Mi,{side:"top",children:"Project-owned defaults for isolated issue checkouts and execution workspace behavior."})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[o.jsx("span",{children:"Enable isolated issue checkouts"}),o.jsx(Bf,{state:T("execution_workspace_enabled")})]}),o.jsx("div",{className:"text-xs text-muted-foreground",children:"Let issues choose between the project's primary checkout and an isolated execution workspace."})]}),e||n?o.jsx("button",{"data-slot":"toggle",className:se("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",q?"bg-green-600":"bg-muted"),type:"button",onClick:()=>S("execution_workspace_enabled",ne({enabled:!q})),children:o.jsx("span",{className:se("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",q?"translate-x-4.5":"translate-x-0.5")})}):o.jsx("span",{className:"text-xs text-muted-foreground",children:q?"Enabled":"Disabled"})]}),q?o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{children:"New issues default to isolated checkout"}),o.jsx(Bf,{state:T("execution_workspace_default_mode")})]}),o.jsx("div",{className:"text-[11px] text-muted-foreground",children:"If disabled, new issues stay on the project's primary checkout unless someone opts in."})]}),o.jsx("button",{"data-slot":"toggle",className:se("relative inline-flex h-5 w-9 items-center rounded-full transition-colors",z==="isolated_workspace"?"bg-green-600":"bg-muted"),type:"button",onClick:()=>S("execution_workspace_default_mode",ne({defaultMode:z==="isolated_workspace"?"shared_workspace":"isolated_workspace"})),children:o.jsx("span",{className:se("inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",z==="isolated_workspace"?"translate-x-4.5":"translate-x-0.5")})})]}),o.jsx("div",{className:"border-t border-border/60 pt-2",children:o.jsx("button",{type:"button",className:"flex w-full items-center gap-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground",onClick:()=>h(H=>!H),children:f?"Hide advanced checkout settings":"Show advanced checkout settings"})}),f?o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"text-xs text-muted-foreground",children:["Host-managed implementation: ",o.jsx("span",{className:"text-foreground",children:"Git worktree"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Base ref"}),o.jsx(Bf,{state:T("execution_workspace_base_ref")})]})}),o.jsx(Lr,{value:V.baseRef??"",onCommit:H=>S("execution_workspace_base_ref",{...ne({workspaceStrategy:{...V,type:"git_worktree",baseRef:H||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"origin/main"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Branch template"}),o.jsx(Bf,{state:T("execution_workspace_branch_template")})]})}),o.jsx(Lr,{value:V.branchTemplate??"",onCommit:H=>S("execution_workspace_branch_template",{...ne({workspaceStrategy:{...V,type:"git_worktree",branchTemplate:H||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"{{issue.identifier}}-{{slug}}"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Worktree parent dir"}),o.jsx(Bf,{state:T("execution_workspace_worktree_parent_dir")})]})}),o.jsx(Lr,{value:V.worktreeParentDir??"",onCommit:H=>S("execution_workspace_worktree_parent_dir",{...ne({workspaceStrategy:{...V,type:"git_worktree",worktreeParentDir:H||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:".fidelios/worktrees"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Provision command"}),o.jsx(Bf,{state:T("execution_workspace_provision_command")})]})}),o.jsx(Lr,{value:V.provisionCommand??"",onCommit:H=>S("execution_workspace_provision_command",{...ne({workspaceStrategy:{...V,type:"git_worktree",provisionCommand:H||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"bash ./scripts/provision-worktree.sh"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 flex items-center gap-1.5",children:o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx("span",{children:"Teardown command"}),o.jsx(Bf,{state:T("execution_workspace_teardown_command")})]})}),o.jsx(Lr,{value:V.teardownCommand??"",onCommit:H=>S("execution_workspace_teardown_command",{...ne({workspaceStrategy:{...V,type:"git_worktree",teardownCommand:H||null}})}),immediate:!0,className:"w-full rounded border border-border bg-transparent px-2 py-1 text-xs font-mono outline-none",placeholder:"bash ./scripts/teardown-worktree.sh"})]}),o.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Provision runs inside the derived worktree before agent execution. Teardown is stored here for future cleanup flows."})]}):null]}):null]})]})]}):null]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Ro,{className:"my-4"}),o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("div",{className:"text-xs font-medium text-destructive uppercase tracking-wide",children:"Danger Zone"}),o.jsx(hrt,{project:t,onArchive:s,archivePending:i})]})]})]})}function MM(t,e){const n={};for(const r of t){const s=e(r);n[s]||(n[s]=[]),n[s].push(r)}return n}const IM={critical:{icon:ec,color:rh.critical,label:"Critical"},high:{icon:lte,color:rh.high,label:"High"},medium:{icon:m6,color:rh.medium,label:"Medium"},low:{icon:i6,color:rh.low,label:"Low"}},prt=["critical","high","medium","low"];function ea({priority:t,onChange:e,className:n,showLabel:r}){const[s,i]=y.useState(!1),a=IM[t]??IM.medium,l=a.icon,c=o.jsx("span",{className:se("inline-flex items-center justify-center shrink-0",a.color,e&&!r&&"cursor-pointer",n),children:o.jsx(l,{className:"h-3.5 w-3.5"})});if(!e)return r?o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c,o.jsx("span",{className:"text-sm",children:a.label})]}):c;const u=r?o.jsxs("button",{className:"inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",children:[c,o.jsx("span",{className:"text-sm",children:a.label})]}):c;return o.jsxs(wr,{open:s,onOpenChange:i,children:[o.jsx(kr,{asChild:!0,children:u}),o.jsx(Cr,{className:"w-36 p-1",align:"start",children:prt.map(f=>{const h=IM[f],p=h.icon;return o.jsxs(ue,{variant:"ghost",size:"sm",className:se("w-full justify-start gap-2 text-xs",f===t&&"bg-accent"),onClick:()=>{e(f),i(!1)},children:[o.jsx(p,{className:se("h-3.5 w-3.5",h.color)}),h.label]},f)})})]})}function fhe({issue:t,issueLinkState:e,mobileLeading:n,desktopMetaLeading:r,desktopLeadingSpacer:s=!1,mobileMeta:i,desktopTrailing:a,trailingMeta:l,unreadState:c=null,onMarkRead:u,onArchive:f,archiveDisabled:h,className:p}){const g=t.identifier??t.id,b=t.identifier??t.id.slice(0,8),v=c!==null,w=c==="visible"||c==="fading";return o.jsxs(jt,{to:`/issues/${g}`,state:e,className:se("group flex items-start gap-2 border-b border-border py-2.5 pl-2 pr-3 text-sm no-underline text-inherit transition-colors hover:bg-accent/50 last:border-b-0 sm:items-center sm:py-2 sm:pl-1",p),children:[o.jsx("span",{className:"shrink-0 pt-px sm:hidden",children:n??o.jsx(Js,{status:t.status})}),o.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-1 sm:contents",children:[o.jsx("span",{className:"line-clamp-2 text-sm sm:order-2 sm:min-w-0 sm:flex-1 sm:truncate sm:line-clamp-none",children:t.title}),o.jsxs("span",{className:"flex items-center gap-2 sm:order-1 sm:shrink-0",children:[s?o.jsx("span",{className:"hidden w-3.5 shrink-0 sm:block"}):null,r??o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden shrink-0 sm:inline-flex",children:o.jsx(Js,{status:t.status})}),o.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:b})]}),i?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-xs text-muted-foreground sm:hidden","aria-hidden":"true",children:"·"}),o.jsx("span",{className:"text-xs text-muted-foreground sm:hidden",children:i})]}):null]})]}),a||l?o.jsxs("span",{className:"ml-auto hidden shrink-0 items-center gap-2 sm:order-3 sm:flex sm:gap-3",children:[a,l?o.jsx("span",{className:"text-xs text-muted-foreground",children:l}):null]}):null,v?o.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:w?o.jsx("button",{type:"button",onClick:j=>{j.preventDefault(),j.stopPropagation(),u==null||u()},onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),j.stopPropagation(),u==null||u())},className:"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors hover:bg-blue-500/20","aria-label":"Mark as read",children:o.jsx("span",{className:se("block h-2 w-2 rounded-full bg-blue-600 transition-opacity duration-300 dark:bg-blue-400",c==="fading"?"opacity-0":"opacity-100")})}):f?o.jsx("button",{type:"button",onClick:j=>{j.preventDefault(),j.stopPropagation(),f()},onKeyDown:j=>{j.key!=="Enter"&&j.key!==" "||(j.preventDefault(),j.stopPropagation(),f())},disabled:h,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:o.jsx(ps,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null]})}function fl({className:t,...e}){return o.jsx(dQ,{"data-slot":"checkbox",className:se("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:o.jsx(hQ,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:o.jsx($s,{className:"size-3.5"})})})}const RM=["backlog","todo","in_progress","in_review","blocked","done","cancelled"];function grt(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function xrt({status:t,issues:e,agents:n,liveIssueIds:r}){const{setNodeRef:s,isOver:i}=Vte({id:t});return o.jsxs("div",{className:"flex flex-col min-w-[260px] w-[260px] shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-2 px-2 py-2 mb-1",children:[o.jsx(Js,{status:t}),o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:grt(t)}),o.jsx("span",{className:"text-xs text-muted-foreground/60 ml-auto tabular-nums",children:e.length})]}),o.jsx("div",{ref:s,className:`flex-1 min-h-[120px] rounded-md p-1 space-y-1 transition-colors ${i?"bg-accent/40":"bg-muted/20"}`,children:o.jsx(T6,{items:e.map(a=>a.id),strategy:A6,children:e.map(a=>o.jsx(hhe,{issue:a,agents:n,isLive:r==null?void 0:r.has(a.id)},a.id))})})]})}function hhe({issue:t,agents:e,isLive:n,isOverlay:r}){const{attributes:s,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:u}=M6({id:t.id,data:{issue:t}}),f={transform:du.Transform.toString(l),transition:c},h=p=>{var g;return!p||!e?null:((g=e.find(b=>b.id===p))==null?void 0:g.name)??null};return o.jsx("div",{ref:a,style:f,...s,...i,className:`rounded-md border bg-card p-2.5 cursor-grab active:cursor-grabbing transition-shadow ${u&&!r?"opacity-30":""} ${r?"shadow-lg ring-1 ring-primary/20":"hover:shadow-sm"}`,children:o.jsxs(jt,{to:`/issues/${t.identifier??t.id}`,className:"block no-underline text-inherit",onClick:p=>{u&&p.preventDefault()},children:[o.jsxs("div",{className:"flex items-start gap-1.5 mb-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground font-mono shrink-0",children:t.identifier??t.id.slice(0,8)}),n&&o.jsxs("span",{className:"relative flex h-2 w-2 shrink-0 mt-0.5",children:[o.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]})]}),o.jsx("p",{className:"text-sm leading-snug line-clamp-2 mb-2",children:t.title}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ea,{priority:t.priority}),t.assigneeAgentId&&(()=>{const p=h(t.assigneeAgentId);return p?o.jsx(lr,{name:p,size:"xs"}):o.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:t.assigneeAgentId.slice(0,8)})})()]})]})})}function yrt({issues:t,agents:e,liveIssueIds:n,onUpdateIssue:r}){const[s,i]=y.useState(null),a=C6(k6(yw,{activationConstraint:{distance:5}})),l=y.useMemo(()=>{const p={};for(const g of RM)p[g]=[];for(const g of t)p[g.status]&&p[g.status].push(g);return p},[t]),c=y.useMemo(()=>s?t.find(p=>p.id===s):null,[s,t]);function u(p){i(p.active.id)}function f(p){i(null);const{active:g,over:b}=p;if(!b)return;const v=g.id,w=t.find(C=>C.id===v);if(!w)return;let j=null;if(RM.includes(b.id))j=b.id;else{const C=t.find(N=>N.id===b.id);C&&(j=C.status)}j&&j!==w.status&&r(v,{status:j})}function h(p){}return o.jsxs(E6,{sensors:a,onDragStart:u,onDragOver:h,onDragEnd:f,children:[o.jsx("div",{className:"flex gap-3 overflow-x-auto pb-4 -mx-2 px-2",children:RM.map(p=>o.jsx(xrt,{status:p,issues:l[p]??[],agents:e,liveIssueIds:n},p))}),o.jsx(YAe,{children:c?o.jsx(hhe,{issue:c,agents:e,isOverlay:!0}):null})]})}const kS=["in_progress","todo","backlog","in_review","blocked","done","cancelled"],CS=["critical","high","medium","low"];function _2(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}const jS={statuses:[],priorities:[],assignees:[],labels:[],projects:[],sortField:"updated",sortDir:"desc",groupBy:"none",viewMode:"list",collapsedGroups:[]},brt=[{label:"All",statuses:[]},{label:"Active",statuses:["todo","in_progress","in_review","blocked"]},{label:"Backlog",statuses:["backlog"]},{label:"Done",statuses:["done","cancelled"]}],vrt=150;function _G(t){try{const e=localStorage.getItem(t);if(e)return{...jS,...JSON.parse(e)}}catch{}return{...jS}}function wrt(t,e){localStorage.setItem(t,JSON.stringify(e))}function krt(t,e){if(t.length!==e.length)return!1;const n=[...t].sort(),r=[...e].sort();return n.every((s,i)=>s===r[i])}function Pm(t,e){return t.includes(e)?t.filter(n=>n!==e):[...t,e]}function Crt(t,e,n){let r=t;return e.statuses.length>0&&(r=r.filter(s=>e.statuses.includes(s.status))),e.priorities.length>0&&(r=r.filter(s=>e.priorities.includes(s.priority))),e.assignees.length>0&&(r=r.filter(s=>{for(const i of e.assignees)if(i==="__unassigned"&&!s.assigneeAgentId&&!s.assigneeUserId||i==="__me"&&n&&s.assigneeUserId===n||s.assigneeAgentId===i)return!0;return!1})),e.labels.length>0&&(r=r.filter(s=>(s.labelIds??[]).some(i=>e.labels.includes(i)))),e.projects.length>0&&(r=r.filter(s=>s.projectId!=null&&e.projects.includes(s.projectId))),r}function jrt(t,e){const n=[...t],r=e.sortDir==="asc"?1:-1;return n.sort((s,i)=>{switch(e.sortField){case"status":return r*(kS.indexOf(s.status)-kS.indexOf(i.status));case"priority":return r*(CS.indexOf(s.priority)-CS.indexOf(i.priority));case"title":return r*s.title.localeCompare(i.title);case"created":return r*(new Date(s.createdAt).getTime()-new Date(i.createdAt).getTime());case"updated":return r*(new Date(s.updatedAt).getTime()-new Date(i.updatedAt).getTime());default:return 0}}),n}function Nrt(t){let e=0;return t.statuses.length>0&&e++,t.priorities.length>0&&e++,t.assignees.length>0&&e++,t.labels.length>0&&e++,t.projects.length>0&&e++,e}function Srt({initialValue:t,onValueCommitted:e}){const[n,r]=y.useState(t),s=y.useRef(e);return y.useEffect(()=>{r(t)},[t]),y.useEffect(()=>{s.current=e},[e]),y.useEffect(()=>{const i=window.setTimeout(()=>{s.current(n)},vrt);return()=>window.clearTimeout(i)},[n]),o.jsxs("div",{className:"relative w-48 sm:w-64 md:w-80",children:[o.jsx(Kl,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),o.jsx(_r,{value:n,onChange:i=>r(i.target.value),placeholder:"Search issues...",className:"pl-7 text-xs sm:text-sm","aria-label":"Search issues"})]})}function mhe({issues:t,isLoading:e,error:n,agents:r,projects:s,liveIssueIds:i,projectId:a,viewStateKey:l,issueLinkState:c,initialAssignees:u,initialSearch:f,searchFilters:h,onSearchChange:p,onUpdateIssue:g}){var F,le;const{selectedCompanyId:b}=Xt(),{openNewIssue:v}=Ts(),{data:w}=_e({queryKey:J.auth.session,queryFn:()=>fi.getSession()}),j=((F=w==null?void 0:w.user)==null?void 0:F.id)??((le=w==null?void 0:w.session)==null?void 0:le.userId)??null,C=b?`${l}:${b}`:l,[N,S]=y.useState(()=>u?{...jS,assignees:u,statuses:[]}:_G(C)),[T,_]=y.useState(null),[A,M]=y.useState(""),[I,L]=y.useState(f??""),D=I.trim();y.useEffect(()=>{L(f??"")},[f]);const P=y.useRef(C);y.useEffect(()=>{P.current!==C&&(P.current=C,S(u?{...jS,assignees:u,statuses:[]}:_G(C)))},[C,u]);const B=y.useCallback(ie=>{y.startTransition(()=>{L(ie)}),p==null||p(ie)},[p]),Z=y.useCallback(ie=>{S(ne=>{const X={...ne,...ie};return wrt(C,X),X})},[C]),{data:Q=[]}=_e({queryKey:[...J.issues.search(b,D,a),h??{}],queryFn:()=>wn.list(b,{q:D,projectId:a,...h}),enabled:!!b&&D.length>0,placeholderData:ie=>ie}),q=y.useCallback(ie=>{var ne;return!ie||!r?null:((ne=r.find(X=>X.id===ie))==null?void 0:ne.name)??null},[r]),O=y.useMemo(()=>{const ie=D.length>0?Q:t,ne=Crt(ie,N,j);return jrt(ne,N)},[t,Q,N,D,j]),{data:z}=_e({queryKey:J.issues.labels(b),queryFn:()=>wn.listLabels(b),enabled:!!b}),V=Nrt(N),$=y.useMemo(()=>{if(N.groupBy==="none")return[{key:"__all",label:null,items:O}];if(N.groupBy==="status"){const ne=MM(O,X=>X.status);return kS.filter(X=>{var ee;return(ee=ne[X])==null?void 0:ee.length}).map(X=>({key:X,label:_2(X),items:ne[X]}))}if(N.groupBy==="priority"){const ne=MM(O,X=>X.priority);return CS.filter(X=>{var ee;return(ee=ne[X])==null?void 0:ee.length}).map(X=>({key:X,label:_2(X),items:ne[X]}))}const ie=MM(O,ne=>ne.assigneeAgentId??(ne.assigneeUserId?`__user:${ne.assigneeUserId}`:"__unassigned"));return Object.keys(ie).map(ne=>({key:ne,label:ne==="__unassigned"?"Unassigned":ne.startsWith("__user:")?sI(ne.slice(7),j)??"User":q(ne)??ne.slice(0,8),items:ie[ne]}))},[O,N.groupBy,r,q,j]),G=ie=>{const ne={};return a&&(ne.projectId=a),ie&&(N.groupBy==="status"?ne.status=ie:N.groupBy==="priority"?ne.priority=ie:N.groupBy==="assignee"&&ie!=="__unassigned"&&(ie.startsWith("__user:")?ne.assigneeUserId=ie.slice(7):ne.assigneeAgentId=ie)),ne},W=(ie,ne,X=null)=>{g(ie,{assigneeAgentId:ne,assigneeUserId:X}),_(null),M("")};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 sm:gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2 sm:gap-3",children:[o.jsxs(ue,{size:"sm",variant:"outline",onClick:()=>v(G()),children:[o.jsx(Er,{className:"h-4 w-4 sm:mr-1"}),o.jsx("span",{className:"hidden sm:inline",children:"New Issue"})]}),o.jsx(Srt,{initialValue:f??"",onValueCommitted:B})]}),o.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1 shrink-0",children:[o.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden mr-1",children:[o.jsx("button",{className:`p-1.5 transition-colors ${N.viewMode==="list"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>Z({viewMode:"list"}),title:"List view",children:o.jsx(fte,{className:"h-3.5 w-3.5"})}),o.jsx("button",{className:`p-1.5 transition-colors ${N.viewMode==="board"?"bg-accent text-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>Z({viewMode:"board"}),title:"Board view",children:o.jsx($Se,{className:"h-3.5 w-3.5"})})]}),o.jsxs(wr,{children:[o.jsx(kr,{asChild:!0,children:o.jsxs(ue,{variant:"ghost",size:"sm",className:`text-xs ${V>0?"text-blue-600 dark:text-blue-400":""}`,children:[o.jsx(h_e,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),o.jsx("span",{className:"hidden sm:inline",children:V>0?`Filters: ${V}`:"Filter"}),V>0&&o.jsx("span",{className:"sm:hidden text-[10px] font-medium ml-0.5",children:V}),V>0&&o.jsx(ps,{className:"h-3 w-3 ml-1 hidden sm:block",onClick:ie=>{ie.stopPropagation(),Z({statuses:[],priorities:[],assignees:[],labels:[],projects:[]})}})]})}),o.jsx(Cr,{align:"end",className:"w-[min(480px,calc(100vw-2rem))] p-0",children:o.jsxs("div",{className:"p-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-medium",children:"Filters"}),V>0&&o.jsx("button",{className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>Z({statuses:[],priorities:[],assignees:[],labels:[]}),children:"Clear"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Quick filters"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:brt.map(ie=>{const ne=krt(N.statuses,ie.statuses);return o.jsx("button",{className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${ne?"bg-primary text-primary-foreground border-primary":"border-border text-muted-foreground hover:text-foreground hover:border-foreground/30"}`,onClick:()=>Z({statuses:ne?[]:[...ie.statuses]}),children:ie.label},ie.label)})})]}),o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Status"}),o.jsx("div",{className:"space-y-0.5",children:kS.map(ie=>o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.statuses.includes(ie),onCheckedChange:()=>Z({statuses:Pm(N.statuses,ie)})}),o.jsx(Js,{status:ie}),o.jsx("span",{className:"text-sm",children:_2(ie)})]},ie))})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Priority"}),o.jsx("div",{className:"space-y-0.5",children:CS.map(ie=>o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.priorities.includes(ie),onCheckedChange:()=>Z({priorities:Pm(N.priorities,ie)})}),o.jsx(ea,{priority:ie}),o.jsx("span",{className:"text-sm",children:_2(ie)})]},ie))})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Assignee"}),o.jsxs("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:[o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.assignees.includes("__unassigned"),onCheckedChange:()=>Z({assignees:Pm(N.assignees,"__unassigned")})}),o.jsx("span",{className:"text-sm",children:"No assignee"})]}),j&&o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.assignees.includes("__me"),onCheckedChange:()=>Z({assignees:Pm(N.assignees,"__me")})}),o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm",children:"Me"})]}),(r??[]).map(ie=>o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.assignees.includes(ie.id),onCheckedChange:()=>Z({assignees:Pm(N.assignees,ie.id)})}),o.jsx("span",{className:"text-sm",children:ie.name})]},ie.id))]})]}),z&&z.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Labels"}),o.jsx("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:z.map(ie=>o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.labels.includes(ie.id),onCheckedChange:()=>Z({labels:Pm(N.labels,ie.id)})}),o.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:ie.color}}),o.jsx("span",{className:"text-sm",children:ie.name})]},ie.id))})]}),s&&s.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Project"}),o.jsx("div",{className:"space-y-0.5 max-h-32 overflow-y-auto",children:s.map(ie=>o.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-accent/50 cursor-pointer",children:[o.jsx(fl,{checked:N.projects.includes(ie.id),onCheckedChange:()=>Z({projects:Pm(N.projects,ie.id)})}),o.jsx("span",{className:"text-sm",children:ie.name})]},ie.id))})]})]})]})]})})]}),N.viewMode==="list"&&o.jsxs(wr,{children:[o.jsx(kr,{asChild:!0,children:o.jsxs(ue,{variant:"ghost",size:"sm",className:"text-xs",children:[o.jsx(ZNe,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),o.jsx("span",{className:"hidden sm:inline",children:"Sort"})]})}),o.jsx(Cr,{align:"end",className:"w-48 p-0",children:o.jsx("div",{className:"p-2 space-y-0.5",children:[["status","Status"],["priority","Priority"],["title","Title"],["created","Created"],["updated","Updated"]].map(([ie,ne])=>o.jsxs("button",{className:`flex items-center justify-between w-full px-2 py-1.5 text-sm rounded-sm ${N.sortField===ie?"bg-accent/50 text-foreground":"hover:bg-accent/50 text-muted-foreground"}`,onClick:()=>{N.sortField===ie?Z({sortDir:N.sortDir==="asc"?"desc":"asc"}):Z({sortField:ie,sortDir:"asc"})},children:[o.jsx("span",{children:ne}),N.sortField===ie&&o.jsx("span",{className:"text-xs text-muted-foreground",children:N.sortDir==="asc"?"↑":"↓"})]},ie))})})]}),N.viewMode==="list"&&o.jsxs(wr,{children:[o.jsx(kr,{asChild:!0,children:o.jsxs(ue,{variant:"ghost",size:"sm",className:"text-xs",children:[o.jsx(ute,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),o.jsx("span",{className:"hidden sm:inline",children:"Group"})]})}),o.jsx(Cr,{align:"end",className:"w-44 p-0",children:o.jsx("div",{className:"p-2 space-y-0.5",children:[["status","Status"],["priority","Priority"],["assignee","Assignee"],["none","None"]].map(([ie,ne])=>o.jsxs("button",{className:`flex items-center justify-between w-full px-2 py-1.5 text-sm rounded-sm ${N.groupBy===ie?"bg-accent/50 text-foreground":"hover:bg-accent/50 text-muted-foreground"}`,onClick:()=>Z({groupBy:ie}),children:[o.jsx("span",{children:ne}),N.groupBy===ie&&o.jsx($s,{className:"h-3.5 w-3.5"})]},ie))})})]})]})]}),e&&o.jsx(is,{variant:"issues-list"}),n&&o.jsx("p",{className:"text-sm text-destructive",children:n.message}),!e&&O.length===0&&N.viewMode==="list"&&o.jsx(Ar,{icon:oa,message:"No issues match the current filters or search.",action:"Create Issue",onAction:()=>v(G())}),N.viewMode==="board"?o.jsx(yrt,{issues:O,agents:r,liveIssueIds:i,onUpdateIssue:g}):$.map(ie=>o.jsxs(tm,{open:!N.collapsedGroups.includes(ie.key),onOpenChange:ne=>{Z({collapsedGroups:ne?N.collapsedGroups.filter(X=>X!==ie.key):[...N.collapsedGroups,ie.key]})},children:[ie.label&&o.jsxs("div",{className:"flex items-center py-1.5 pl-1 pr-3",children:[o.jsxs(nm,{className:"flex items-center gap-1.5",children:[o.jsx($r,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90"}),o.jsx("span",{className:"text-sm font-semibold uppercase tracking-wide",children:ie.label})]}),o.jsx(ue,{variant:"ghost",size:"icon-xs",className:"ml-auto text-muted-foreground",onClick:()=>v(G(ie.key)),children:o.jsx(Er,{className:"h-3 w-3"})})]}),o.jsx(rm,{children:ie.items.map(ne=>o.jsx(fhe,{issue:ne,issueLinkState:c,desktopLeadingSpacer:!0,mobileLeading:o.jsx("span",{onClick:X=>{X.preventDefault(),X.stopPropagation()},children:o.jsx(Js,{status:ne.status,onChange:X=>g(ne.id,{status:X})})}),desktopMetaLeading:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden shrink-0 sm:inline-flex",onClick:X=>{X.preventDefault(),X.stopPropagation()},children:o.jsx(Js,{status:ne.status,onChange:X=>g(ne.id,{status:X})})}),o.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:ne.identifier??ne.id.slice(0,8)}),(i==null?void 0:i.has(ne.id))&&o.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-blue-500/10 px-1.5 py-0.5 sm:gap-1.5 sm:px-2",children:[o.jsxs("span",{className:"relative flex h-2 w-2",children:[o.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-500"})]}),o.jsx("span",{className:"hidden text-[11px] font-medium text-blue-600 dark:text-blue-400 sm:inline",children:"Live"})]})]}),mobileMeta:ca(ne.updatedAt),desktopTrailing:o.jsxs(o.Fragment,{children:[(ne.labels??[]).length>0&&o.jsxs("span",{className:"hidden items-center gap-1 overflow-hidden md:flex md:max-w-[240px]",children:[(ne.labels??[]).slice(0,3).map(X=>o.jsx("span",{className:"inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-medium",style:{borderColor:X.color,color:D_(X.color,.12),backgroundColor:`${X.color}1f`},children:X.name},X.id)),(ne.labels??[]).length>3&&o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",(ne.labels??[]).length-3]})]}),o.jsxs(wr,{open:T===ne.id,onOpenChange:X=>{_(X?ne.id:null),X||M("")},children:[o.jsx(kr,{asChild:!0,children:o.jsx("button",{className:"flex w-[180px] shrink-0 items-center rounded-md px-2 py-1 transition-colors hover:bg-accent/50",onClick:X=>{X.preventDefault(),X.stopPropagation()},children:ne.assigneeAgentId&&q(ne.assigneeAgentId)?o.jsx(lr,{name:q(ne.assigneeAgentId),size:"sm"}):ne.assigneeUserId?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[o.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30",children:o.jsx(Ra,{className:"h-3 w-3"})}),sI(ne.assigneeUserId,j)??"User"]}):o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center rounded-full border border-dashed border-muted-foreground/35 bg-muted/30",children:o.jsx(Ra,{className:"h-3 w-3"})}),"Assignee"]})})}),o.jsxs(Cr,{className:"w-56 p-1",align:"end",onClick:X=>X.stopPropagation(),onPointerDownOutside:()=>M(""),children:[o.jsx("input",{className:"mb-1 w-full border-b border-border bg-transparent px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:A,onChange:X=>M(X.target.value),autoFocus:!0}),o.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[o.jsx("button",{className:se("flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/50",!ne.assigneeAgentId&&!ne.assigneeUserId&&"bg-accent"),onClick:X=>{X.preventDefault(),X.stopPropagation(),W(ne.id,null,null)},children:"No assignee"}),j&&o.jsxs("button",{className:se("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",ne.assigneeUserId===j&&"bg-accent"),onClick:X=>{X.preventDefault(),X.stopPropagation(),W(ne.id,null,j)},children:[o.jsx(Ra,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{children:"Me"})]}),(r??[]).filter(X=>A.trim()?X.name.toLowerCase().includes(A.toLowerCase()):!0).map(X=>o.jsx("button",{className:se("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",ne.assigneeAgentId===X.id&&"bg-accent"),onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),W(ne.id,X.id,null)},children:o.jsx(lr,{name:X.name,size:"sm",className:"min-w-0"})},X.id))]})]})]})]}),trailingMeta:To(ne.createdAt)},ne.id))})]},ie.key))]})}function E2(t){return typeof t=="string"&&t.startsWith("plugin:")}function _rt(t,e){const n=t.split("/").filter(Boolean),r=n.indexOf("projects");if(r===-1||n[r+1]!==e)return null;const s=n[r+2];return s==="overview"?"overview":s==="configuration"?"configuration":s==="budget"?"budget":s==="issues"?"list":null}function Ert({project:t,onUpdate:e,imageUploadHandler:n}){return o.jsxs("div",{className:"space-y-6",children:[o.jsx(ou,{value:t.description??"",onSave:r=>e({description:r}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0,imageUploadHandler:n}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Status"}),o.jsx("div",{className:"mt-1",children:o.jsx(sr,{status:t.status})})]}),t.targetDate&&o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Target Date"}),o.jsx("p",{children:t.targetDate})]})]})]})}function Art({currentColor:t,onSelect:e}){const[n,r]=y.useState(!1),s=y.useRef(null);return y.useEffect(()=>{if(!n)return;function i(a){s.current&&!s.current.contains(a.target)&&r(!1)}return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[n]),o.jsxs("div",{className:"relative",ref:s,children:[o.jsx("button",{onClick:()=>r(!n),className:"shrink-0 h-5 w-5 rounded-md cursor-pointer hover:ring-2 hover:ring-foreground/20 transition-[box-shadow]",style:{backgroundColor:t},"aria-label":"Change project color"}),n&&o.jsx("div",{className:"absolute top-full left-0 mt-2 p-2 bg-popover border border-border rounded-lg shadow-lg z-50 w-max",children:o.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:E4.map(i=>o.jsx("button",{onClick:()=>{e(i),r(!1)},className:`h-6 w-6 rounded-md cursor-pointer transition-[transform,box-shadow] duration-150 hover:scale-110 ${i===t?"ring-2 ring-foreground ring-offset-1 ring-offset-background":"hover:ring-2 hover:ring-foreground/30"}`,style:{backgroundColor:i},"aria-label":`Select color ${i}`},i))})})]})}function Trt({projectId:t,companyId:e}){const n=hn(),{data:r}=_e({queryKey:J.agents.list(e),queryFn:()=>Mt.list(e),enabled:!!e}),{data:s}=_e({queryKey:J.liveRuns(e),queryFn:()=>qr.liveRunsForCompany(e),enabled:!!e,refetchInterval:5e3}),i=y.useMemo(()=>{const f=new Set;for(const h of s??[])h.issueId&&f.add(h.issueId);return f},[s]),{data:a,isLoading:l,error:c}=_e({queryKey:J.issues.listByProject(e,t),queryFn:()=>wn.list(e,{projectId:t}),enabled:!!e}),u=Xe({mutationFn:({id:f,data:h})=>wn.update(f,h),onSuccess:()=>{n.invalidateQueries({queryKey:J.issues.listByProject(e,t)}),n.invalidateQueries({queryKey:J.issues.list(e)})}});return o.jsx(mhe,{issues:a??[],isLoading:l,error:c,agents:r,liveIssueIds:i,projectId:t,viewStateKey:`fidelios:project-view:${t}`,onUpdateIssue:(f,h)=>u.mutate({id:f,data:h})})}function dx(){const{companyPrefix:t,projectId:e,filter:n}=Zi(),{companies:r,selectedCompanyId:s,setSelectedCompanyId:i}=Xt(),{closePanel:a}=l0(),{setBreadcrumbs:l}=yr(),{pushToast:c}=Bo(),u=hn(),f=As(),h=er(),[p,g]=y.useState({}),b=y.useRef({}),v=y.useRef({}),w=e??"",C=y.useMemo(()=>{var de;if(!t)return null;const ee=t.toUpperCase();return((de=r.find(ve=>ve.issuePrefix.toUpperCase()===ee))==null?void 0:de.id)??null},[r,t])??s??void 0,N=w.length>0&&(e6(w)||!!C),S=w?_rt(h.pathname,w):null,T=y.useMemo(()=>{const ee=new URLSearchParams(h.search).get("tab");return E2(ee)?ee:null},[h.search]),_=S??T,{data:A,isLoading:M,error:I}=_e({queryKey:[...J.projects.detail(w),C??null],queryFn:()=>vs.get(w,C),enabled:N}),L=A?s6(A):w,D=(A==null?void 0:A.id)??w,P=(A==null?void 0:A.companyId)??s,{slots:B,isLoading:Z}=o0({slotTypes:["detailTab"],entityType:"project",enabled:!!P}),Q=y.useMemo(()=>B.map(ee=>({value:`plugin:${ee.pluginKey}:${ee.id}`,label:ee.displayName,slot:ee})),[B]),q=Q.find(ee=>ee.value===_)??null;y.useEffect(()=>{!(A!=null&&A.companyId)||A.companyId===s||i(A.companyId,{source:"route_sync"})},[A==null?void 0:A.companyId,s,i]);const O=()=>{u.invalidateQueries({queryKey:J.projects.detail(w)}),u.invalidateQueries({queryKey:J.projects.detail(D)}),P&&u.invalidateQueries({queryKey:J.projects.list(P)})},z=Xe({mutationFn:ee=>vs.update(D,ee,P??C),onSuccess:O}),V=Xe({mutationFn:ee=>vs.update(D,{archivedAt:ee?new Date().toISOString():null},P??C),onSuccess:(ee,de)=>{O();const ve=(ee==null?void 0:ee.name)??(A==null?void 0:A.name)??"Project";de?(c({title:`"${ve}" has been archived`,tone:"success"}),f("/dashboard")):c({title:`"${ve}" has been unarchived`,tone:"success"})},onError:(ee,de)=>{c({title:de?"Failed to archive project":"Failed to unarchive project",tone:"error"})}}),$=Xe({mutationFn:async ee=>{if(!P)throw new Error("No company selected");return sm.uploadImage(P,ee,`projects/${D||"draft"}`)}}),{data:G}=_e({queryKey:J.budgets.overview(P??"__none__"),queryFn:()=>pp.overview(P),enabled:!!P,refetchInterval:3e4,staleTime:5e3});y.useEffect(()=>{l([{label:"Projects",href:"/projects"},{label:(A==null?void 0:A.name)??w??"Project"}])},[l,A,w]),y.useEffect(()=>{if(A&&w!==L){if(E2(_)){f(`/projects/${L}?tab=${encodeURIComponent(_)}`,{replace:!0});return}if(_==="overview"){f(`/projects/${L}/overview`,{replace:!0});return}if(_==="configuration"){f(`/projects/${L}/configuration`,{replace:!0});return}if(_==="budget"){f(`/projects/${L}/budget`,{replace:!0});return}if(_==="list"){if(n){f(`/projects/${L}/issues/${n}`,{replace:!0});return}f(`/projects/${L}/issues`,{replace:!0});return}f(`/projects/${L}`,{replace:!0})}},[A,w,L,_,n,f]),y.useEffect(()=>(a(),()=>a()),[a]),y.useEffect(()=>()=>{Object.values(v.current).forEach(ee=>{ee&&clearTimeout(ee)})},[]);const W=y.useCallback((ee,de)=>{g(ve=>({...ve,[ee]:de}))},[]),F=y.useCallback((ee,de)=>{const ve=v.current[ee];ve&&clearTimeout(ve),v.current[ee]=setTimeout(()=>{g(Te=>{const Fe={...Te};return delete Fe[ee],Fe}),delete v.current[ee]},de)},[]),le=y.useCallback(async(ee,de)=>{const ve=(b.current[ee]??0)+1;b.current[ee]=ve,W(ee,"saving");try{if(await vs.update(D,de,P??C),O(),b.current[ee]!==ve)return;W(ee,"saved"),F(ee,1800)}catch(Te){if(b.current[ee]!==ve)return;throw W(ee,"error"),F(ee,3e3),Te}},[O,C,D,P,F,W]),ie=y.useMemo(()=>{const ee=G==null?void 0:G.policies.find(de=>de.scopeType==="project"&&de.scopeId===((A==null?void 0:A.id)??w));return ee||{policyId:"",companyId:P??"",scopeType:"project",scopeId:(A==null?void 0:A.id)??w,scopeName:(A==null?void 0:A.name)??"Project",metric:"billed_cents",windowKind:"lifetime",amount:0,observedAmount:0,remainingAmount:0,utilizationPercent:0,warnPercent:80,hardStopEnabled:!0,notifyEnabled:!0,isActive:!1,status:"ok",paused:!!(A!=null&&A.pausedAt),pauseReason:(A==null?void 0:A.pauseReason)??null,windowStart:new Date,windowEnd:new Date}},[G==null?void 0:G.policies,A,P,w]),ne=Xe({mutationFn:ee=>pp.upsertPolicy(P,{scopeType:"project",scopeId:(A==null?void 0:A.id)??w,amount:ee,windowKind:"lifetime"}),onSuccess:()=>{P&&(u.invalidateQueries({queryKey:J.budgets.overview(P)}),u.invalidateQueries({queryKey:J.projects.detail(w)}),u.invalidateQueries({queryKey:J.projects.detail(D)}),u.invalidateQueries({queryKey:J.projects.list(P)}),u.invalidateQueries({queryKey:J.dashboard(P)}))}});if(T&&!Z&&!q)return o.jsx(zr,{to:`/projects/${L}/issues`,replace:!0});if(w&&_===null){let ee=null;if(A!=null&&A.id)try{ee=localStorage.getItem(`fidelios:project-tab:${A.id}`)}catch{}return ee==="overview"?o.jsx(zr,{to:`/projects/${L}/overview`,replace:!0}):ee==="configuration"?o.jsx(zr,{to:`/projects/${L}/configuration`,replace:!0}):ee==="budget"?o.jsx(zr,{to:`/projects/${L}/budget`,replace:!0}):E2(ee)?o.jsx(zr,{to:`/projects/${L}?tab=${encodeURIComponent(ee)}`,replace:!0}):o.jsx(zr,{to:`/projects/${L}/issues`,replace:!0})}if(M)return o.jsx(is,{variant:"detail"});if(I)return o.jsx("p",{className:"text-sm text-destructive",children:I.message});if(!A)return null;const X=ee=>{if(A!=null&&A.id)try{localStorage.setItem(`fidelios:project-tab:${A.id}`,ee)}catch{}if(E2(ee)){f(`/projects/${L}?tab=${encodeURIComponent(ee)}`);return}f(ee==="overview"?`/projects/${L}/overview`:ee==="budget"?`/projects/${L}/budget`:ee==="configuration"?`/projects/${L}/configuration`:`/projects/${L}/issues`)};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"h-7 flex items-center",children:o.jsx(Art,{currentColor:A.color??"#6366f1",onSelect:ee=>z.mutate({color:ee})})}),o.jsxs("div",{className:"min-w-0 space-y-2",children:[o.jsx(ou,{value:A.name,onSave:ee=>z.mutate({name:ee}),as:"h2",className:"text-xl font-bold"}),A.pauseReason==="budget"?o.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-red-500/30 bg-red-500/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-red-200",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-red-400"}),"Paused by budget hard stop"]}):null]})]}),o.jsx(Rd,{slotTypes:["toolbarButton","contextMenuItem"],entityType:"project",context:{companyId:P??null,companyPrefix:t??null,projectId:A.id,projectRef:L,entityId:A.id,entityType:"project"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex",missingBehavior:"placeholder"}),o.jsx(L6,{placementZones:["toolbarButton"],entityType:"project",context:{companyId:P??null,companyPrefix:t??null,projectId:A.id,projectRef:L,entityId:A.id,entityType:"project"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex"}),o.jsx(ha,{value:_??"list",onValueChange:ee=>X(ee),children:o.jsx(Wh,{items:[{value:"list",label:"Issues"},{value:"overview",label:"Overview"},{value:"configuration",label:"Configuration"},{value:"budget",label:"Budget"},...Q.map(ee=>({value:ee.value,label:ee.label}))],align:"start",value:_??"list",onValueChange:ee=>X(ee)})}),_==="overview"&&o.jsx(Ert,{project:A,onUpdate:ee=>z.mutate(ee),imageUploadHandler:async ee=>(await $.mutateAsync(ee)).contentPath}),_==="list"&&(A==null?void 0:A.id)&&P&&o.jsx(Trt,{projectId:A.id,companyId:P}),_==="configuration"&&o.jsx("div",{className:"max-w-4xl",children:o.jsx(mrt,{project:A,onUpdate:ee=>z.mutate(ee),onFieldUpdate:le,getFieldSaveState:ee=>p[ee]??"idle",onArchive:ee=>V.mutate(ee),archivePending:V.isPending})}),_==="budget"&&P?o.jsx("div",{className:"max-w-3xl",children:o.jsx(K9,{summary:ie,variant:"plain",isSaving:ne.isPending,onSave:ee=>ne.mutate(ee)})}):null,q&&o.jsx(a0,{slot:q.slot,context:{companyId:P,companyPrefix:t??null,projectId:A.id,projectRef:L,entityId:A.id,entityType:"project"},missingBehavior:"placeholder"})]})}function Mrt(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.label=="string"&&typeof e.href=="string"}function phe(t,e){return{issueDetailBreadcrumb:{label:t,href:e}}}function Irt(t){if(typeof t!="object"||t===null)return null;const e=t.issueDetailBreadcrumb;return Mrt(e)?e:null}function Rrt(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),n=er(),[r]=Yy(),s=hn(),i=r.get("q")??"",a=r.get("participantAgentId")??void 0,l=y.useCallback(j=>{const C=j.trim();if((new URLSearchParams(window.location.search).get("q")??"")===C)return;const S=new URL(window.location.href);C?S.searchParams.set("q",C):S.searchParams.delete("q");const T=`${S.pathname}${S.search}${S.hash}`;window.history.replaceState(window.history.state,"",T)},[]),{data:c}=_e({queryKey:J.agents.list(t),queryFn:()=>Mt.list(t),enabled:!!t}),{data:u}=_e({queryKey:J.projects.list(t),queryFn:()=>vs.list(t),enabled:!!t}),{data:f}=_e({queryKey:J.liveRuns(t),queryFn:()=>qr.liveRunsForCompany(t),enabled:!!t,refetchInterval:5e3}),h=y.useMemo(()=>{const j=new Set;for(const C of f??[])C.issueId&&j.add(C.issueId);return j},[f]),p=y.useMemo(()=>phe("Issues",`${n.pathname}${n.search}${n.hash}`),[n.pathname,n.search,n.hash]);y.useEffect(()=>{e([{label:"Issues"}])},[e]);const{data:g,isLoading:b,error:v}=_e({queryKey:[...J.issues.list(t),"participant-agent",a??"__all__"],queryFn:()=>wn.list(t,{participantAgentId:a}),enabled:!!t}),w=Xe({mutationFn:({id:j,data:C})=>wn.update(j,C),onSuccess:()=>{s.invalidateQueries({queryKey:J.issues.list(t)})}});return t?o.jsx(mhe,{issues:g??[],isLoading:b,error:v,agents:c,projects:u,liveIssueIds:h,viewStateKey:"fidelios:issues-view",issueLinkState:p,initialAssignees:r.get("assignee")?[r.get("assignee")]:void 0,initialSearch:i,onSearchChange:l,onUpdateIssue:(j,C)=>w.mutate({id:j,data:C}),searchFilters:a?{participantAgentId:a}:void 0}):o.jsx(Ar,{icon:oa,message:"Select a company to view issues."})}const Ort=800;function Drt(t){try{return localStorage.getItem(t)??""}catch{return""}}function Prt(t,e){try{e.trim()?localStorage.setItem(t,e):localStorage.removeItem(t)}catch{}}function Lrt(t){try{localStorage.removeItem(t)}catch{}}function $rt(t){if(!t||t==="__none__")return{assigneeAgentId:null,assigneeUserId:null};if(t.startsWith("agent:")){const e=t.slice(6);return e?{assigneeAgentId:e,assigneeUserId:null}:null}if(t.startsWith("user:")){const e=t.slice(5);return e?{assigneeAgentId:null,assigneeUserId:e}:null}return null}function Frt({text:t}){const[e,n]=y.useState(!1);return o.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground transition-colors",title:"Copy as markdown",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)})},children:e?o.jsx($s,{className:"h-3 w-3"}):o.jsx(uc,{className:"h-3 w-3"})})}const Brt=y.memo(function({timeline:e,agentMap:n,companyId:r,projectId:s,highlightCommentId:i}){return e.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No comments or runs yet."}):o.jsx("div",{className:"space-y-3",children:e.map(a=>{var u,f;if(a.kind==="run"){const h=a.run;return o.jsxs("div",{className:"border border-border bg-accent/20 p-3 overflow-hidden min-w-0 rounded-sm",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx(qm,{to:`/agents/${h.agentId}`,className:"hover:underline",children:o.jsx(lr,{name:((u=n==null?void 0:n.get(h.agentId))==null?void 0:u.name)??h.agentId.slice(0,8),size:"sm"})}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Ap(h.startedAt??h.createdAt)})]}),o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:"Run"}),o.jsx(qm,{to:`/agents/${h.agentId}/runs/${h.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/40 px-2 py-1 font-mono text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors",children:h.runId.slice(0,8)}),o.jsx(sr,{status:h.status})]})]},`run:${h.runId}`)}const l=a.comment,c=i===l.id;return o.jsxs("div",{id:`comment-${l.id}`,className:`border p-3 overflow-hidden min-w-0 rounded-sm transition-colors duration-1000 ${c?"border-primary/50 bg-primary/5":"border-border"}`,children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.authorAgentId?o.jsx(qm,{to:`/agents/${l.authorAgentId}`,className:"hover:underline",children:o.jsx(lr,{name:((f=n==null?void 0:n.get(l.authorAgentId))==null?void 0:f.name)??l.authorAgentId.slice(0,8),size:"sm"})}):o.jsx(lr,{name:"You",size:"sm"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[r?o.jsx(Rd,{slotTypes:["commentContextMenuItem"],entityType:"comment",context:{companyId:r,projectId:s??null,entityId:l.id,entityType:"comment",parentEntityId:l.issueId},className:"flex flex-wrap items-center gap-1.5",itemClassName:"inline-flex",missingBehavior:"placeholder"}):null,o.jsx("a",{href:`#comment-${l.id}`,className:"text-xs text-muted-foreground hover:text-foreground hover:underline transition-colors",children:Ap(l.createdAt)}),o.jsx(Frt,{text:l.body})]})]}),o.jsx(Al,{className:"text-sm",children:l.body}),r?o.jsx("div",{className:"mt-2 space-y-2",children:o.jsx(Rd,{slotTypes:["commentAnnotation"],entityType:"comment",context:{companyId:r,projectId:s??null,entityId:l.id,entityType:"comment",parentEntityId:l.issueId},className:"space-y-2",itemClassName:"rounded-md",missingBehavior:"placeholder"})}):null,l.runId&&o.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:l.runAgentId?o.jsxs(qm,{to:`/agents/${l.runAgentId}/runs/${l.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors",children:["run ",l.runId.slice(0,8)]}):o.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground",children:["run ",l.runId.slice(0,8)]})})]},l.id)})})});function zrt({comments:t,linkedRuns:e=[],companyId:n,projectId:r,onAdd:s,agentMap:i,imageUploadHandler:a,onAttachImage:l,draftKey:c,liveRunSlot:u,enableReassign:f=!1,reassignOptions:h=[],currentAssigneeValue:p="",suggestedAssigneeValue:g,mentions:b}){const[v,w]=y.useState(""),[j,C]=y.useState(!0),[N,S]=y.useState(!1),[T,_]=y.useState(!1),A=g??p,[M,I]=y.useState(A),[L,D]=y.useState(null),P=y.useRef(null),B=y.useRef(null),Z=y.useRef(null),Q=er(),q=y.useRef(!1),O=y.useMemo(()=>{const W=t.map(le=>({kind:"comment",id:le.id,createdAtMs:new Date(le.createdAt).getTime(),comment:le})),F=e.map(le=>({kind:"run",id:le.runId,createdAtMs:new Date(le.startedAt??le.createdAt).getTime(),run:le}));return[...W,...F].sort((le,ie)=>le.createdAtMs!==ie.createdAtMs?le.createdAtMs-ie.createdAtMs:le.kind===ie.kind?le.id.localeCompare(ie.id):le.kind==="comment"?-1:1)},[t,e]),z=y.useMemo(()=>b||(i?Array.from(i.values()).filter(W=>W.status!=="terminated").map(W=>({id:`agent:${W.id}`,name:W.name,kind:"agent",agentId:W.id,agentIcon:W.icon})):[]),[i,b]);y.useEffect(()=>{c&&w(Drt(c))},[c]),y.useEffect(()=>{c&&(Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>{Prt(c,v)},Ort))},[v,c]),y.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current)},[]),y.useEffect(()=>{I(A)},[A]),y.useEffect(()=>{const W=Q.hash;if(!W.startsWith("#comment-")||t.length===0)return;const F=W.slice(9);if(q.current)return;const le=document.getElementById(`comment-${F}`);if(le){q.current=!0,D(F),le.scrollIntoView({behavior:"smooth",block:"center"});const ie=setTimeout(()=>D(null),3e3);return()=>clearTimeout(ie)}},[Q.hash,t]);async function V(){const W=v.trim();if(!W)return;const le=f&&M!==p?$rt(M):null;S(!0);try{await s(W,j?!0:void 0,le??void 0),w(""),c&&Lrt(c),C(!0),I(A)}finally{S(!1)}}async function $(W){var le;const F=(le=W.target.files)==null?void 0:le[0];if(F){_(!0);try{if(a){const ie=await a(F),X=`![${F.name.replace(/[[\]]/g,"\\$&")}](${ie})`;w(ee=>ee?`${ee}
1086
1086
 
1087
- ${X}`:X)}else l&&await l(F)}finally{_(!1),B.current&&(B.current.value="")}}}const G=!N&&!!v.trim();return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",O.length,")"]}),o.jsx(Brt,{timeline:O,agentMap:i,companyId:n,projectId:r,highlightCommentId:L}),u,o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ao,{ref:P,value:v,onChange:w,placeholder:"Leave a comment...",mentions:z,onSubmit:V,imageUploadHandler:a,contentClassName:"min-h-[60px] text-sm"}),o.jsxs("div",{className:"flex items-center justify-end gap-3",children:[(a||l)&&o.jsxs("div",{className:"mr-auto flex items-center gap-3",children:[o.jsx("input",{ref:B,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:$}),o.jsx(ue,{variant:"ghost",size:"icon-sm",onClick:()=>{var W;return(W=B.current)==null?void 0:W.click()},disabled:T,title:"Attach image",children:o.jsx(Uj,{className:"h-4 w-4"})})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:j,onChange:W=>C(W.target.checked),className:"rounded border-border"}),"Re-open"]}),f&&h.length>0&&o.jsx(kh,{value:M,options:h,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:I,className:"text-xs h-8",renderTriggerValue:W=>{if(!W)return o.jsx("span",{className:"text-muted-foreground",children:"Assignee"});const F=W.id.startsWith("agent:")?W.id.slice(6):null,le=F?i==null?void 0:i.get(F):null;return o.jsxs(o.Fragment,{children:[le?o.jsx(Gi,{icon:le.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:W.label})]})},renderOption:W=>{if(!W.id)return o.jsx("span",{className:"truncate",children:W.label});const F=W.id.startsWith("agent:")?W.id.slice(6):null,le=F?i==null?void 0:i.get(F):null;return o.jsxs(o.Fragment,{children:[le?o.jsx(Gi,{icon:le.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:W.label})]})}}),o.jsx(ue,{size:"sm",disabled:!G,onClick:V,children:N?"Posting...":"Comment"})]})]})]})}const Urt=900,EG=/^[a-z0-9][a-z0-9_-]*$/,ghe=t=>`fidelios:issue-document-folds:${t}`;function AG(t){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(ghe(t));if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function TG(t,e){typeof window>"u"||window.localStorage.setItem(ghe(t),JSON.stringify(e))}function MG(t,e){return o.jsx(Al,{className:e,children:t})}function Lm(t){return t.trim().toLowerCase()==="plan"}function Vrt(t,e){return(t??"").trim().toLowerCase()===e.trim().toLowerCase()}function Hrt(t){return t instanceof Hd&&t.status===409}function qrt(t,e){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=`${t}.md`,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r)}function Krt({issue:t,canDeleteDocuments:e,mentions:n,imageUploadHandler:r,extraActions:s}){const i=hn(),a=er(),[l,c]=y.useState(null),[u,f]=y.useState(null),[h,p]=y.useState(null),[g,b]=y.useState(null),[v,w]=y.useState(()=>AG(t.id)),[j,C]=y.useState(null),[N,S]=y.useState(null),[T,_]=y.useState(null),A=y.useRef(null),M=y.useRef(null),I=y.useRef(!1),{state:L,markDirty:D,reset:P,runSave:B}=dhe(),{data:Z}=_e({queryKey:J.issues.documents(t.id),queryFn:()=>wn.listDocuments(t.id)}),Q=()=>{i.invalidateQueries({queryKey:J.issues.detail(t.id)}),i.invalidateQueries({queryKey:J.issues.documents(t.id)})},q=Xe({mutationFn:async H=>wn.upsertDocument(t.id,H.key,{title:Lm(H.key)?null:H.title.trim()||null,format:"markdown",body:H.body,baseRevisionId:H.baseRevisionId})}),O=Xe({mutationFn:H=>wn.deleteDocument(t.id,H),onSuccess:()=>{f(null),c(null),Q()},onError:H=>{f(H instanceof Error?H.message:"Failed to delete document")}}),z=y.useMemo(()=>[...Z??[]].sort((H,U)=>H.key==="plan"&&U.key!=="plan"?-1:H.key!=="plan"&&U.key==="plan"?1:new Date(U.updatedAt).getTime()-new Date(H.updatedAt).getTime()),[Z]),V=z.some(H=>H.key==="plan"),$=z.length===0&&!t.legacyPlanDocument,G=h!=null&&h.isNew&&h.key.trim().length>0&&!EG.test(h.key.trim())?"Use lowercase letters, numbers, -, or _, and start with a letter or number.":null,W=y.useCallback(()=>{C(null),P()},[P]),F=y.useCallback(H=>{C(H),D()},[D]),le=()=>{W(),b(null),p({key:"",title:"",body:"",baseRevisionId:null,isNew:!0}),f(null)},ie=H=>{const U=z.find(oe=>oe.key===H);if(!U)return;const me=(g==null?void 0:g.key)===H?g.localDraft:null;w(oe=>oe.filter(pe=>pe!==H)),W(),b(oe=>(oe==null?void 0:oe.key)===H?oe:null),p({key:(me==null?void 0:me.key)??U.key,title:(me==null?void 0:me.title)??U.title??"",body:(me==null?void 0:me.body)??U.body,baseRevisionId:(me==null?void 0:me.baseRevisionId)??U.latestRevisionId,isNew:!1}),f(null)},ne=()=>{A.current&&clearTimeout(A.current),W(),b(null),p(null),f(null)},X=y.useCallback(async(H,U)=>{if(!H||q.isPending)return!1;const me=H.key.trim().toLowerCase(),oe=H.body.trim(),pe=H.title.trim(),Ne=(g==null?void 0:g.key)===me?g:null;if(Ne&&!(U!=null&&U.overrideConflict))return U!=null&&U.trackAutosave&&W(),!1;if(!me||!oe)return H.isNew?f("Document key and body are required"):oe||f("Document body cannot be empty"),U!=null&&U.trackAutosave&&W(),!1;if(!EG.test(me))return f("Document key must start with a letter or number and use only lowercase letters, numbers, -, or _."),U!=null&&U.trackAutosave&&W(),!1;const fe=z.find(ce=>ce.key===me);if(!H.isNew&&fe&&fe.body===H.body&&(fe.title??"")===H.title)return U!=null&&U.clearAfterSave&&p(ce=>(ce==null?void 0:ce.key)===me?null:ce),U!=null&&U.trackAutosave&&W(),!0;const ke=async()=>{const ce=await q.mutateAsync({...H,key:me,title:Lm(me)?"":pe,body:H.body,baseRevisionId:U!=null&&U.overrideConflict?(Ne==null?void 0:Ne.serverDocument.latestRevisionId)??H.baseRevisionId:H.baseRevisionId});f(null),b(ye=>(ye==null?void 0:ye.key)===me?null:ye),p(ye=>!ye||ye.key!==me?ye:U!=null&&U.clearAfterSave?null:{key:ce.key,title:ce.title??"",body:ce.body,baseRevisionId:ce.latestRevisionId,isNew:!1}),Q()};try{return U!=null&&U.trackAutosave?(C(me),await B(ke)):await ke(),!0}catch(ce){if(Hrt(ce))try{const ye=await wn.getDocument(t.id,me);return b({key:me,serverDocument:ye,localDraft:{key:me,title:Lm(me)?"":pe,body:H.body,baseRevisionId:H.baseRevisionId,isNew:!1},showRemote:!0}),w(re=>re.filter(Ye=>Ye!==me)),f(null),W(),!1}catch{return f("Document changed remotely and the latest version could not be loaded"),!1}return f(ce instanceof Error?ce.message:"Failed to save document"),!1}},[g,Q,t.id,W,B,z,q]),ee=y.useCallback(H=>{if((g==null?void 0:g.key)!==H)return;const U=g.serverDocument;p({key:U.key,title:U.title??"",body:U.body,baseRevisionId:U.latestRevisionId,isNew:!1}),b(null),W(),f(null)},[g,W]),de=y.useCallback(async H=>{if((g==null?void 0:g.key)!==H)return;const U=h&&h.key===H&&!h.isNew?h:g.localDraft;await X({...U,baseRevisionId:g.serverDocument.latestRevisionId},{clearAfterSave:!1,trackAutosave:!0,overrideConflict:!0})},[X,g,h]),ve=y.useCallback(H=>{(g==null?void 0:g.key)===H&&(p(g.localDraft),b(U=>(U==null?void 0:U.key)===H?{...U,showRemote:!1}:U),f(null))},[g]),Te=y.useCallback(async(H,U)=>{try{await navigator.clipboard.writeText(U),S(H),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{S(me=>me===H?null:me)},1400)}catch{f("Could not copy document")}},[]),Fe=async H=>{H.currentTarget.contains(H.relatedTarget)||(A.current&&clearTimeout(A.current),await X(h,{clearAfterSave:!0,trackAutosave:!0}))},Ee=async H=>{if(H.key==="Escape"){H.preventDefault(),ne();return}(H.metaKey||H.ctrlKey)&&H.key==="Enter"&&(H.preventDefault(),A.current&&clearTimeout(A.current),await X(h,{clearAfterSave:!1,trackAutosave:!0}))};y.useEffect(()=>{w(AG(t.id))},[t.id]),y.useEffect(()=>{I.current=!1},[t.id,a.hash]),y.useEffect(()=>{const H=new Set(z.map(U=>U.key));w(U=>{const me=U.filter(oe=>H.has(oe));return me.length!==U.length&&TG(t.id,me),me})},[t.id,z]),y.useEffect(()=>{TG(t.id,v)},[v,t.id]),y.useEffect(()=>{if(!g)return;const H=z.find(U=>U.key===g.key);!H||H.latestRevisionId===g.serverDocument.latestRevisionId||b(U=>(U==null?void 0:U.key)===H.key?{...U,serverDocument:H}:U)},[g,z]),y.useEffect(()=>{const H=a.hash;if(!H.startsWith("#document-"))return;const U=decodeURIComponent(H.slice(10));if(!(z.some(Ne=>Ne.key===U)||U==="plan"&&!!t.legacyPlanDocument)||I.current)return;w(Ne=>Ne.filter(fe=>fe!==U));const oe=document.getElementById(`document-${U}`);if(!oe)return;I.current=!0,_(U),oe.scrollIntoView({behavior:"smooth",block:"center"});const pe=setTimeout(()=>_(Ne=>Ne===U?null:Ne),3e3);return()=>clearTimeout(pe)},[t.legacyPlanDocument,a.hash,z]),y.useEffect(()=>()=>{A.current&&clearTimeout(A.current),M.current&&clearTimeout(M.current)},[]),y.useEffect(()=>{if(!h||h.isNew||(g==null?void 0:g.key)===h.key)return;const H=z.find(me=>me.key===h.key);if(!H)return;if(!(H.body!==h.body||(H.title??"")!==h.title)){L!=="saved"&&W();return}return F(h.key),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{X(h,{clearAfterSave:!1,trackAutosave:!0})},Urt),()=>{A.current&&clearTimeout(A.current)}},[L,X,g,h,F,W,z]);const tt="mt-3 overflow-hidden rounded-md",ot="",Ie="fidelios-edit-in-place-content min-h-[220px] text-[15px] leading-7",rt=H=>{w(U=>U.includes(H)?U.filter(me=>me!==H):[...U,H])};return o.jsxs("div",{className:"space-y-3",children:[$&&!(h!=null&&h.isNew)?o.jsxs("div",{className:"flex items-center justify-end gap-2 min-w-0",children:[s,o.jsxs(ue,{variant:"outline",size:"sm",onClick:le,className:"shrink-0",children:[o.jsx(Er,{className:"mr-1.5 h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:"New document"}),o.jsx("span",{className:"sm:hidden",children:"New"})]})]}):o.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[o.jsx("h3",{className:"text-sm font-medium text-muted-foreground shrink-0",children:"Documents"}),o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s,o.jsxs(ue,{variant:"outline",size:"sm",onClick:le,className:"shrink-0",children:[o.jsx(Er,{className:"mr-1.5 h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:"New document"}),o.jsx("span",{className:"sm:hidden",children:"New"})]})]})]}),u&&o.jsx("p",{className:"text-xs text-destructive",children:u}),(h==null?void 0:h.isNew)&&o.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-accent/10 p-3",onBlurCapture:Fe,onKeyDown:Ee,children:[o.jsx(_r,{autoFocus:!0,value:h.key,onChange:H=>p(U=>U&&{...U,key:H.target.value.toLowerCase()}),placeholder:"Document key"}),G&&o.jsx("p",{className:"text-xs text-destructive",children:G}),!Lm(h.key)&&o.jsx(_r,{value:h.title,onChange:H=>p(U=>U&&{...U,title:H.target.value}),placeholder:"Optional title"}),o.jsx(Ao,{value:h.body,onChange:H=>p(U=>U&&{...U,body:H}),placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:"min-h-[220px] text-[15px] leading-7",mentions:n,imageUploadHandler:r,onSubmit:()=>void X(h,{clearAfterSave:!1,trackAutosave:!1})}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsxs(ue,{variant:"outline",size:"sm",onClick:ne,children:[o.jsx(ps,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}),o.jsx(ue,{size:"sm",onClick:()=>void X(h,{clearAfterSave:!1,trackAutosave:!1}),disabled:q.isPending,children:q.isPending?"Saving...":"Create document"})]})]}),!V&&t.legacyPlanDocument?o.jsxs("div",{id:"document-plan",className:se("rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 transition-colors duration-1000",T==="plan"&&"border-primary/50 bg-primary/5"),children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[o.jsx(k_,{className:"h-4 w-4 text-amber-600"}),o.jsx("span",{className:"rounded-full border border-amber-500/30 px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-amber-700 dark:text-amber-300",children:"PLAN"})]}),o.jsx("div",{className:ot,children:MG(t.legacyPlanDocument.body,Ie)})]}):null,o.jsx("div",{className:"space-y-3",children:z.map(H=>{var Ne;const U=(h==null?void 0:h.key)===H.key&&!h.isNew?h:null,me=(g==null?void 0:g.key)===H.key?g:null,oe=v.includes(H.key),pe=!Lm(H.key)&&!!((Ne=H.title)!=null&&Ne.trim())&&!Vrt(H.title,H.key);return o.jsxs("div",{id:`document-${H.key}`,className:se("rounded-lg border border-border p-3 transition-colors duration-1000",T===H.key&&"border-primary/50 bg-primary/5"),children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground",onClick:()=>rt(H.key),"aria-label":oe?`Expand ${H.key} document`:`Collapse ${H.key} document`,"aria-expanded":!oe,children:oe?o.jsx($r,{className:"h-3.5 w-3.5"}):o.jsx(ns,{className:"h-3.5 w-3.5"})}),o.jsx("span",{className:"shrink-0 rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:H.key}),o.jsxs("a",{href:`#document-${encodeURIComponent(H.key)}`,className:"truncate text-[11px] text-muted-foreground transition-colors hover:text-foreground hover:underline",children:["rev ",H.latestRevisionNumber," • updated ",mo(H.updatedAt)]})]}),pe&&o.jsx("p",{className:"mt-2 text-sm font-medium",children:H.title})]}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"icon-xs",className:se("text-muted-foreground transition-colors",N===H.key&&"text-foreground"),title:N===H.key?"Copied":"Copy document",onClick:()=>void Te(H.key,(U==null?void 0:U.body)??H.body),children:N===H.key?o.jsx($s,{className:"h-3.5 w-3.5"}):o.jsx(uc,{className:"h-3.5 w-3.5"})}),o.jsxs(L5,{children:[o.jsx($5,{asChild:!0,children:o.jsx(ue,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",title:"Document actions",children:o.jsx(t0,{className:"h-3.5 w-3.5"})})}),o.jsxs(F5,{align:"end",children:[o.jsxs(Xl,{onClick:()=>qrt(H.key,(U==null?void 0:U.body)??H.body),children:[o.jsx(Cy,{className:"h-3.5 w-3.5"}),"Download document"]}),e?o.jsx(B5,{}):null,e?o.jsxs(Xl,{variant:"destructive",onClick:()=>c(H.key),children:[o.jsx(Fa,{className:"h-3.5 w-3.5"}),"Delete document"]}):null]})]})]})]}),oe?null:o.jsxs("div",{className:"mt-3 space-y-3",onFocusCapture:()=>{U||ie(H.key)},onBlurCapture:async fe=>{U&&await Fe(fe)},onKeyDown:async fe=>{U&&await Ee(fe)},children:[me&&o.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-3",children:[o.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("p",{className:"text-sm font-medium text-amber-200",children:"Out of date"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This document changed while you were editing. Your local draft is preserved and autosave is paused."})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>b(fe=>(fe==null?void 0:fe.key)===H.key?{...fe,showRemote:!fe.showRemote}:fe),children:me.showRemote?"Hide remote":"Review remote"}),o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>ve(H.key),children:"Keep my draft"}),o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>ee(H.key),children:"Reload remote"}),o.jsx(ue,{size:"sm",onClick:()=>void de(H.key),disabled:q.isPending,children:q.isPending?"Saving...":"Overwrite remote"})]})]}),me.showRemote&&o.jsxs("div",{className:"mt-3 rounded-md border border-border/70 bg-background/60 p-3",children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:[o.jsxs("span",{children:["Remote revision ",me.serverDocument.latestRevisionNumber]}),o.jsx("span",{children:"•"}),o.jsxs("span",{children:["updated ",mo(me.serverDocument.updatedAt)]})]}),!Lm(H.key)&&me.serverDocument.title?o.jsx("p",{className:"mb-2 text-sm font-medium",children:me.serverDocument.title}):null,MG(me.serverDocument.body,"text-[14px] leading-7")]})]}),U&&!Lm(H.key)&&o.jsx(_r,{value:U.title,onChange:fe=>{F(H.key),p(ke=>ke&&{...ke,title:fe.target.value})},placeholder:"Optional title"}),o.jsx("div",{className:`${tt} ${ot} ${U?"":"hover:bg-accent/10"}`,children:o.jsx(Ao,{value:(U==null?void 0:U.body)??H.body,onChange:fe=>{F(H.key),p(ke=>ke&&ke.key===H.key&&!ke.isNew?{...ke,body:fe}:{key:H.key,title:H.title??"",body:fe,baseRevisionId:H.latestRevisionId,isNew:!1})},placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:Ie,mentions:n,imageUploadHandler:r,onSubmit:()=>void X(U??h,{clearAfterSave:!1,trackAutosave:!0})})}),o.jsx("div",{className:"flex min-h-4 items-center justify-end px-1",children:o.jsx("span",{className:`text-[11px] transition-opacity duration-150 ${me?"text-amber-300":L==="error"?"text-destructive":"text-muted-foreground"} ${U?"opacity-100":"opacity-0"}`,children:U?me?"Out of date":j===H.key?L==="saving"?"Autosaving...":L==="saved"?"Saved":L==="error"?"Could not save":"":"":""})})]}),l===H.key&&o.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-md border border-destructive/20 bg-destructive/5 px-4 py-3",children:[o.jsx("p",{className:"text-sm text-destructive font-medium",children:"Delete this document? This cannot be undone."}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"sm",onClick:()=>c(null),disabled:O.isPending,children:"Cancel"}),o.jsx(ue,{variant:"destructive",size:"sm",onClick:()=>O.mutate(H.key),disabled:O.isPending,children:O.isPending?"Deleting...":"Delete"})]})]})]},H.id)})})]})}function Wrt(t){var e,n,r,s,i;return t?((e=t.executionWorkspacePolicy)==null?void 0:e.defaultProjectWorkspaceId)??((r=(n=t.workspaces)==null?void 0:n.find(a=>a.isPrimary))==null?void 0:r.id)??((i=(s=t.workspaces)==null?void 0:s[0])==null?void 0:i.id)??null:null}function Grt(t){var n;const e=(n=t==null?void 0:t.executionWorkspacePolicy)!=null&&n.enabled?t.executionWorkspacePolicy.defaultMode:null;return e==="isolated_workspace"||e==="operator_branch"?e:e==="adapter_default"?"agent_default":"shared_workspace"}function Bl({label:t,children:e}){return o.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:t}),o.jsx("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:e})]})}function OM({inline:t,label:e,open:n,onOpenChange:r,triggerContent:s,triggerClassName:i,popoverClassName:a,popoverAlign:l="end",extra:c,children:u}){const f=se("inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",i);return t?o.jsxs("div",{children:[o.jsxs(Bl,{label:e,children:[o.jsx("button",{className:f,onClick:()=>r(!n),children:s}),c]}),n&&o.jsx("div",{className:se("rounded-md border border-border bg-popover p-1 mb-2",a),children:u})]}):o.jsxs(Bl,{label:e,children:[o.jsxs(wr,{open:n,onOpenChange:r,children:[o.jsx(kr,{asChild:!0,children:o.jsx("button",{className:f,children:s})}),o.jsx(Cr,{className:se("p-1",a),align:l,collisionPadding:16,children:u})]}),c]})}function IG({issue:t,onUpdate:e,inline:n}){var Te,Fe,Ee,tt,ot,Ie,rt;const{selectedCompanyId:r}=Xt(),s=hn(),i=t.companyId??r,[a,l]=y.useState(!1),[c,u]=y.useState(""),[f,h]=y.useState(!1),[p,g]=y.useState(""),[b,v]=y.useState(!1),[w,j]=y.useState(""),[C,N]=y.useState(""),[S,T]=y.useState("#6366f1"),{data:_}=_e({queryKey:J.auth.session,queryFn:()=>fi.getSession()}),A=((Te=_==null?void 0:_.user)==null?void 0:Te.id)??((Fe=_==null?void 0:_.session)==null?void 0:Fe.userId),{data:M}=_e({queryKey:J.agents.list(i),queryFn:()=>Mt.list(i),enabled:!!i}),{data:I}=_e({queryKey:J.projects.list(i),queryFn:()=>vs.list(i),enabled:!!i}),L=y.useMemo(()=>(I??[]).filter(H=>!H.archivedAt||H.id===t.projectId),[I,t.projectId]),{orderedProjects:D}=vw({projects:L,companyId:i,userId:A}),{data:P}=_e({queryKey:J.issues.labels(i),queryFn:()=>wn.listLabels(i),enabled:!!i}),B=Xe({mutationFn:H=>wn.createLabel(i,H),onSuccess:async H=>{await s.invalidateQueries({queryKey:J.issues.labels(i)}),e({labelIds:[...t.labelIds??[],H.id]}),N("")}}),Z=Xe({mutationFn:H=>wn.deleteLabel(H),onSuccess:()=>{s.invalidateQueries({queryKey:J.issues.labels(i)}),s.invalidateQueries({queryKey:J.issues.list(i)}),s.invalidateQueries({queryKey:J.issues.detail(t.id)})}}),Q=H=>{const U=t.labelIds??[],me=U.includes(H)?U.filter(oe=>oe!==H):[...U,H];e({labelIds:me})},q=H=>{if(!H||!M)return null;const U=M.find(me=>me.id===H);return(U==null?void 0:U.name)??H.slice(0,8)},O=H=>{if(!H)return(H==null?void 0:H.slice(0,8))??"None";const U=D.find(me=>me.id===H);return(U==null?void 0:U.name)??H.slice(0,8)};t.projectId&&D.find(H=>H.id===t.projectId);const z=H=>{if(!H)return null;const U=(I==null?void 0:I.find(me=>me.id===H))??null;return U?y_(U):`/projects/${H}`},V=y.useMemo(()=>kw(),[a]),$=y.useMemo(()=>L_((M??[]).filter(H=>H.status!=="terminated"),V),[M,V]),G=t.assigneeAgentId?M==null?void 0:M.find(H=>H.id===t.assigneeAgentId):null,W=H=>sI(H,A),F=W(t.assigneeUserId),le=W(t.createdByUserId),ie=(t.labels??[]).length>0?o.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[(t.labels??[]).slice(0,3).map(H=>o.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium border",style:{borderColor:H.color,backgroundColor:`${H.color}22`,color:D_(H.color,.13)},children:H.name},H.id)),(t.labels??[]).length>3&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",(t.labels??[]).length-3]})]}):o.jsxs(o.Fragment,{children:[o.jsx(xte,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"No labels"})]}),ne=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:w,onChange:H=>j(H.target.value),autoFocus:!n}),o.jsx("div",{className:"max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:(P??[]).filter(H=>w.trim()?H.name.toLowerCase().includes(w.toLowerCase()):!0).map(H=>{const U=(t.labelIds??[]).includes(H.id);return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("button",{className:se("flex items-center gap-2 flex-1 px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",U&&"bg-accent"),onClick:()=>Q(H.id),children:[o.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:H.color}}),o.jsx("span",{className:"truncate",children:H.name})]}),o.jsx("button",{type:"button",className:"p-1 text-muted-foreground hover:text-destructive rounded",onClick:()=>Z.mutate(H.id),title:`Delete ${H.name}`,children:o.jsx(Fa,{className:"h-3 w-3"})})]},H.id)})}),o.jsxs("div",{className:"mt-2 border-t border-border pt-2 space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{className:"h-7 w-7 p-0 rounded bg-transparent",type:"color",value:S,onChange:H=>T(H.target.value)}),o.jsx("input",{className:"flex-1 px-2 py-1.5 text-xs bg-transparent outline-none rounded placeholder:text-muted-foreground/50",placeholder:"New label",value:C,onChange:H=>N(H.target.value)})]}),o.jsxs("button",{className:"flex items-center justify-center gap-1.5 w-full px-2 py-1.5 text-xs rounded border border-border hover:bg-accent/50 disabled:opacity-50",disabled:!C.trim()||B.isPending,onClick:()=>B.mutate({name:C.trim(),color:S}),children:[o.jsx(Er,{className:"h-3 w-3"}),B.isPending?"Creating…":"Create label"]})]})]}),X=G?o.jsx(lr,{name:G.name,size:"sm"}):F?o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm",children:F})]}):o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"Unassigned"})]}),ee=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:c,onChange:H=>u(H.target.value),autoFocus:!n}),o.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[o.jsx("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!t.assigneeAgentId&&!t.assigneeUserId&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:null}),l(!1)},children:"No assignee"}),A&&o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===A&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:A}),l(!1)},children:[o.jsx(Ra,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),"Assign to me"]}),t.createdByUserId&&t.createdByUserId!==A&&o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===t.createdByUserId&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:t.createdByUserId}),l(!1)},children:[o.jsx(Ra,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),le?`Assign to ${le}`:"Assign to requester"]}),$.filter(H=>{if(!c.trim())return!0;const U=c.toLowerCase();return H.name.toLowerCase().includes(U)}).map(H=>o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",H.id===t.assigneeAgentId&&"bg-accent"),onClick:()=>{P_(H.id),e({assigneeAgentId:H.id,assigneeUserId:null}),l(!1)},children:[o.jsx(Gi,{icon:H.icon,className:"shrink-0 h-3 w-3 text-muted-foreground"}),H.name]},H.id))]})]}),de=t.projectId?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:((Ee=D.find(H=>H.id===t.projectId))==null?void 0:Ee.color)??"#6366f1"}}),o.jsx("span",{className:"text-sm truncate",children:O(t.projectId)})]}):o.jsxs(o.Fragment,{children:[o.jsx(cu,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"No project"})]}),ve=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search projects...",value:p,onChange:H=>g(H.target.value),autoFocus:!n}),o.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[o.jsx("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",!t.projectId&&"bg-accent"),onClick:()=>{e({projectId:null,projectWorkspaceId:null,executionWorkspaceId:null,executionWorkspacePreference:null,executionWorkspaceSettings:null}),h(!1)},children:"No project"}),D.filter(H=>{if(!p.trim())return!0;const U=p.toLowerCase();return H.name.toLowerCase().includes(U)}).map(H=>o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",H.id===t.projectId&&"bg-accent"),onClick:()=>{var me;const U=Grt(H);e({projectId:H.id,projectWorkspaceId:Wrt(H),executionWorkspaceId:null,executionWorkspacePreference:U,executionWorkspaceSettings:(me=H.executionWorkspacePolicy)!=null&&me.enabled?{mode:U}:null}),h(!1)},children:[o.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:H.color??"#6366f1"}}),H.name]},H.id))]})]});return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Bl,{label:"Status",children:o.jsx(Js,{status:t.status,onChange:H=>e({status:H}),showLabel:!0})}),o.jsx(Bl,{label:"Priority",children:o.jsx(ea,{priority:t.priority,onChange:H=>e({priority:H}),showLabel:!0})}),o.jsx(OM,{inline:n,label:"Labels",open:b,onOpenChange:H=>{v(H),H||j("")},triggerContent:ie,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-64",children:ne}),o.jsx(OM,{inline:n,label:"Assignee",open:a,onOpenChange:H=>{l(H),H||u("")},triggerContent:X,popoverClassName:"w-52",extra:t.assigneeAgentId?o.jsx(jt,{to:`/agents/${t.assigneeAgentId}`,className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:H=>H.stopPropagation(),children:o.jsx(wy,{className:"h-3 w-3"})}):void 0,children:ee}),o.jsx(OM,{inline:n,label:"Project",open:f,onOpenChange:H=>{h(H),H||g("")},triggerContent:de,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-fit min-w-[11rem]",extra:t.projectId?o.jsx(jt,{to:z(t.projectId),className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:H=>H.stopPropagation(),children:o.jsx(wy,{className:"h-3 w-3"})}):void 0,children:ve}),t.parentId&&o.jsx(Bl,{label:"Parent",children:o.jsx(jt,{to:`/issues/${((ot=(tt=t.ancestors)==null?void 0:tt[0])==null?void 0:ot.identifier)??t.parentId}`,className:"text-sm hover:underline",children:((rt=(Ie=t.ancestors)==null?void 0:Ie[0])==null?void 0:rt.title)??t.parentId.slice(0,8)})}),t.requestDepth>0&&o.jsx(Bl,{label:"Depth",children:o.jsx("span",{className:"text-sm font-mono",children:t.requestDepth})})]}),o.jsx(Ro,{}),o.jsxs("div",{className:"space-y-1",children:[(t.createdByAgentId||t.createdByUserId)&&o.jsx(Bl,{label:"Created by",children:t.createdByAgentId?o.jsx(jt,{to:`/agents/${t.createdByAgentId}`,className:"hover:underline",children:o.jsx(lr,{name:q(t.createdByAgentId)??t.createdByAgentId.slice(0,8),size:"sm"})}):o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm",children:le??"User"})]})}),t.startedAt&&o.jsx(Bl,{label:"Started",children:o.jsx("span",{className:"text-sm",children:To(t.startedAt)})}),t.completedAt&&o.jsx(Bl,{label:"Completed",children:o.jsx("span",{className:"text-sm",children:To(t.completedAt)})}),o.jsx(Bl,{label:"Created",children:o.jsx("span",{className:"text-sm",children:To(t.createdAt)})}),o.jsx(Bl,{label:"Updated",children:o.jsx("span",{className:"text-sm",children:ca(t.updatedAt)})})]})]})}const Yrt=[{value:"shared_workspace",label:"Project default"},{value:"isolated_workspace",label:"New isolated workspace"},{value:"reuse_existing",label:"Reuse existing workspace"}];function Jrt(t){return t==="isolated_workspace"||t==="operator_branch"||t==="shared_workspace"?t:t==="adapter_managed"||t==="cloud_sandbox"?"agent_default":"shared_workspace"}function Qrt(t){var n,r;const e=((n=t.currentExecutionWorkspace)==null?void 0:n.mode)??((r=t.executionWorkspaceSettings)==null?void 0:r.mode)??t.executionWorkspacePreference;return!!(t.executionWorkspaceId&&(e==="isolated_workspace"||e==="operator_branch"))}function Zrt(t){var n;const e=(n=t==null?void 0:t.executionWorkspacePolicy)!=null&&n.enabled?t.executionWorkspacePolicy.defaultMode:null;return e==="isolated_workspace"||e==="operator_branch"?e:e==="adapter_default"?"agent_default":"shared_workspace"}function EO({text:t}){const e=[],n=t.split(new RegExp("(?<=[\\/-])"));for(let r=0;r<n.length;r++)r>0&&e.push(o.jsx("wbr",{},r)),e.push(n[r]);return o.jsx(o.Fragment,{children:e})}function DM({value:t,label:e,mono:n}){const[r,s]=y.useState(!1),i=y.useRef(void 0),a=y.useCallback(async()=>{try{await navigator.clipboard.writeText(t),s(!0),clearTimeout(i.current),i.current=setTimeout(()=>s(!1),1500)}catch{}},[t]);return o.jsxs("span",{className:"inline-flex items-center gap-1 group/copy",children:[e&&o.jsx("span",{className:"text-muted-foreground",children:e}),o.jsx("span",{className:se("min-w-0",n&&"font-mono"),style:{overflowWrap:"anywhere"},children:o.jsx(EO,{text:t})}),o.jsx("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground opacity-0 group-hover/copy:opacity-100 focus:opacity-100",onClick:a,title:r?"Copied!":"Copy",children:r?o.jsx($s,{className:"h-3 w-3 text-green-500"}):o.jsx(uc,{className:"h-3 w-3"})})]})}function Xrt(t){switch(t){case"isolated_workspace":return"Isolated workspace";case"operator_branch":return"Operator branch";case"cloud_sandbox":return"Cloud sandbox";case"adapter_managed":return"Adapter managed";default:return"Workspace"}}function est(t,e){switch(t){case"isolated_workspace":return"New isolated workspace";case"reuse_existing":return(e==null?void 0:e.mode)==="isolated_workspace"?"Existing isolated workspace":"Reuse existing workspace";default:return"Project default"}}function RG(t){const e={active:"bg-green-500/15 text-green-700 dark:text-green-400",idle:"bg-muted text-muted-foreground",in_review:"bg-blue-500/15 text-blue-700 dark:text-blue-400",archived:"bg-muted text-muted-foreground"};return o.jsx("span",{className:se("text-[10px] px-1.5 py-0.5 rounded-full font-medium",e[t]??e.idle),children:t.replace(/_/g," ")})}function tst({issue:t,project:e,onUpdate:n}){var A,M;const{selectedCompanyId:r}=Xt(),s=t.companyId??r,[i,a]=y.useState(!1),{data:l}=_e({queryKey:J.instance.experimentalSettings,queryFn:()=>Od.getExperimental()}),c=(l==null?void 0:l.enableIsolatedWorkspaces)===!0&&!!((A=e==null?void 0:e.executionWorkspacePolicy)!=null&&A.enabled),u=t.currentExecutionWorkspace,{data:f}=_e({queryKey:J.executionWorkspaces.list(s,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),queryFn:()=>z6.list(s,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),enabled:!!s&&!!t.projectId&&i}),h=y.useMemo(()=>{const I=f??[],L=new Map;for(const D of I){const P=D.cwd??D.id,B=L.get(P);(!B||new Date(D.lastUsedAt)>new Date(B.lastUsedAt))&&L.set(P,D)}return Array.from(L.values())},[f]),p=h.find(I=>I.id===t.executionWorkspaceId)??u??null,g=Qrt(t)?"reuse_existing":t.executionWorkspacePreference??((M=t.executionWorkspaceSettings)==null?void 0:M.mode)??Zrt(e),[b,v]=y.useState(g),[w,j]=y.useState(t.executionWorkspaceId??"");y.useEffect(()=>{i||(v(g),j(t.executionWorkspaceId??""))},[g,i,t.executionWorkspaceId]);const C=!!(u&&u.mode!=="shared_workspace"),N=h.find(I=>I.id===w)??(w===t.executionWorkspaceId?p:null),S=b!=="reuse_existing"||w.length>0,T=y.useCallback(()=>{S&&(n({executionWorkspacePreference:b,executionWorkspaceId:b==="reuse_existing"&&w||null,executionWorkspaceSettings:{mode:b==="reuse_existing"?Jrt(N==null?void 0:N.mode):b}}),a(!1))},[S,N==null?void 0:N.mode,w,b,n]),_=y.useCallback(()=>{v(g),j(t.executionWorkspaceId??""),a(!1)},[g,t.executionWorkspaceId]);return!c||!e?null:o.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[o.jsx(Bj,{className:"h-3.5 w-3.5 text-muted-foreground"}),C&&u?Xrt(u.mode):est(g,p),RG(u?u.status:"idle")]}),o.jsx("div",{className:"flex items-center gap-1",children:i?o.jsxs(o.Fragment,{children:[o.jsxs(ue,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:_,children:[o.jsx(ps,{className:"h-3 w-3 mr-1"}),"Cancel"]}),o.jsx(ue,{size:"sm",className:"h-6 px-2 text-xs",onClick:T,disabled:!S,children:"Save"})]}):o.jsxs(ue,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:()=>a(!0),children:[o.jsx(Vj,{className:"h-3 w-3 mr-1"}),"Edit"]})})]}),!i&&o.jsxs("div",{className:"space-y-1.5 text-xs",children:[(u==null?void 0:u.branchName)&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Bj,{className:"h-3 w-3 text-muted-foreground shrink-0"}),o.jsx(DM,{value:u.branchName,mono:!0})]}),(u==null?void 0:u.cwd)&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(mw,{className:"h-3 w-3 text-muted-foreground shrink-0"}),o.jsx(DM,{value:u.cwd,mono:!0})]}),(u==null?void 0:u.repoUrl)&&o.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[o.jsx("span",{className:"text-[11px]",children:"Repo:"}),o.jsx(DM,{value:u.repoUrl,mono:!0})]}),!u&&o.jsx("div",{className:"text-muted-foreground",children:g==="isolated_workspace"?"A fresh isolated workspace will be created when this issue runs.":g==="reuse_existing"?"This issue will reuse an existing workspace when it runs.":"This issue will use the project default workspace configuration when it runs."}),g==="reuse_existing"&&p&&o.jsxs("div",{className:"text-muted-foreground",style:{overflowWrap:"anywhere"},children:["Reusing:"," ",o.jsx(jt,{to:`/execution-workspaces/${p.id}`,className:"hover:text-foreground hover:underline",children:o.jsx(EO,{text:p.name})})]}),u&&o.jsx("div",{className:"pt-0.5",children:o.jsx(jt,{to:`/execution-workspaces/${u.id}`,className:"text-[11px] text-muted-foreground hover:text-foreground hover:underline",children:"View workspace details →"})})]}),i&&o.jsxs("div",{className:"space-y-2 pt-1",children:[o.jsx("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:b,onChange:I=>{const L=I.target.value;v(L),L!=="reuse_existing"?j(""):!w&&t.executionWorkspaceId&&j(t.executionWorkspaceId)},children:Yrt.map(I=>o.jsx("option",{value:I.value,children:I.value==="reuse_existing"&&(N==null?void 0:N.mode)==="isolated_workspace"?"Existing isolated workspace":I.label},I.value))}),b==="reuse_existing"&&o.jsxs("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:w,onChange:I=>{j(I.target.value)},children:[o.jsx("option",{value:"",children:"Choose an existing workspace"}),h.map(I=>o.jsxs("option",{value:I.id,children:[I.name," · ",I.status," · ",I.branchName??I.cwd??I.id.slice(0,8)]},I.id))]}),u&&o.jsx("div",{className:"text-[11px] text-muted-foreground space-y-0.5 pt-1 border-t border-border/50",children:o.jsxs("div",{style:{overflowWrap:"anywhere"},children:["Current:"," ",o.jsx(jt,{to:`/execution-workspaces/${u.id}`,className:"hover:text-foreground hover:underline",children:o.jsx(EO,{text:u.name})})," · ",u.status]})})]})]})}function PM(t){return t?typeof t=="string"?t:t.toISOString():null}function nst(t){return t==="queued"||t==="running"}function xhe({issueId:t,companyId:e}){const n=hn(),[r,s]=y.useState(new Set),{data:i}=_e({queryKey:J.issues.liveRuns(t),queryFn:()=>qr.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:a}=_e({queryKey:J.issues.activeRun(t),queryFn:()=>qr.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),l=y.useMemo(()=>{const h=new Map;for(const p of i??[])h.set(p.id,p);return a&&h.set(a.id,{id:a.id,status:a.status,invocationSource:a.invocationSource,triggerDetail:a.triggerDetail,startedAt:PM(a.startedAt),finishedAt:PM(a.finishedAt),createdAt:PM(a.createdAt)??new Date().toISOString(),agentId:a.agentId,agentName:a.agentName,adapterType:a.adapterType,issueId:t}),[...h.values()].sort((p,g)=>new Date(g.createdAt).getTime()-new Date(p.createdAt).getTime())},[a,t,i]),{transcriptByRun:c,hasOutputForRun:u}=qfe({runs:l,companyId:e}),f=async h=>{s(p=>new Set(p).add(h));try{await qr.cancel(h),n.invalidateQueries({queryKey:J.issues.liveRuns(t)}),n.invalidateQueries({queryKey:J.issues.activeRun(t)})}finally{s(p=>{const g=new Set(p);return g.delete(h),g})}};return l.length===0?null:o.jsxs("div",{className:"overflow-hidden rounded-xl border border-cyan-500/25 bg-background/80 shadow-[0_18px_50px_rgba(6,182,212,0.08)]",children:[o.jsxs("div",{className:"border-b border-border/60 bg-cyan-500/[0.04] px-4 py-3",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700 dark:text-cyan-300",children:"Live Runs"}),o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"Streamed with the same transcript UI used on the full run detail page."})]}),o.jsx("div",{className:"divide-y divide-border/60",children:l.map(h=>{const p=nst(h.status),g=c.get(h.id)??[];return o.jsxs("section",{className:"px-4 py-4",children:[o.jsxs("div",{className:"mb-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(jt,{to:`/agents/${h.agentId}`,className:"inline-flex hover:underline",children:o.jsx(lr,{name:h.agentName,size:"sm"})}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[o.jsx(jt,{to:`/agents/${h.agentId}/runs/${h.id}`,className:"inline-flex items-center rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono hover:border-cyan-500/30 hover:text-foreground",children:h.id.slice(0,8)}),o.jsx(sr,{status:h.status}),o.jsx("span",{children:Ap(h.startedAt??h.createdAt)})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[p&&o.jsxs("button",{onClick:()=>f(h.id),disabled:r.has(h.id),className:"inline-flex items-center gap-1 rounded-full border border-red-500/20 bg-red-500/[0.06] px-2.5 py-1 text-[11px] font-medium text-red-700 transition-colors hover:bg-red-500/[0.12] dark:text-red-300 disabled:opacity-50",children:[o.jsx(U5e,{className:"h-2.5 w-2.5",fill:"currentColor"}),r.has(h.id)?"Stopping…":"Stop"]}),o.jsxs(jt,{to:`/agents/${h.agentId}/runs/${h.id}`,className:"inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] font-medium text-cyan-700 transition-colors hover:border-cyan-500/30 hover:text-cyan-600 dark:text-cyan-300",children:["Open run",o.jsx(Md,{className:"h-3 w-3"})]})]})]}),o.jsx("div",{className:"max-h-[320px] overflow-y-auto pr-1",children:o.jsx(T0,{entries:g,density:"compact",limit:8,streaming:p,collapseStdout:!0,emptyMessage:u(h.id)?"Waiting for transcript parsing...":"Waiting for run output..."})})]},h.id)})})]})}function yhe({...t}){return o.jsx(US,{"data-slot":"sheet",...t})}function rst({...t}){return o.jsx(XJ,{"data-slot":"sheet-trigger",...t})}function sst({...t}){return o.jsx(VS,{"data-slot":"sheet-portal",...t})}function ist({className:t,...e}){return o.jsx(HS,{"data-slot":"sheet-overlay",className:se("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function bhe({className:t,children:e,side:n="right",showCloseButton:r=!0,...s}){return o.jsxs(sst,{children:[o.jsx(ist,{}),o.jsxs(qS,{"data-slot":"sheet-content",className:se("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",n==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",n==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",n==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",n==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...s,children:[e,r&&o.jsxs(nw,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[o.jsx(ps,{className:"size-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vhe({className:t,...e}){return o.jsx("div",{"data-slot":"sheet-header",className:se("flex flex-col gap-1.5 p-4",t),...e})}function ost({className:t,...e}){return o.jsx("div",{"data-slot":"sheet-footer",className:se("mt-auto flex flex-col gap-2 p-4",t),...e})}function whe({className:t,...e}){return o.jsx(lD,{"data-slot":"sheet-title",className:se("text-foreground font-semibold",t),...e})}function ast({className:t,...e}){return o.jsx(eQ,{"data-slot":"sheet-description",className:se("text-muted-foreground text-sm",t),...e})}const OG={"issue.created":"created the issue","issue.updated":"updated the issue","issue.checked_out":"checked out the issue","issue.released":"released the issue","issue.comment_added":"added a comment","issue.attachment_added":"added an attachment","issue.attachment_removed":"removed an attachment","issue.document_created":"created a document","issue.document_updated":"updated a document","issue.document_deleted":"deleted a document","issue.deleted":"deleted the issue","agent.created":"created an agent","agent.updated":"updated the agent","agent.paused":"paused the agent","agent.resumed":"resumed the agent","agent.terminated":"terminated the agent","heartbeat.invoked":"invoked a heartbeat","heartbeat.cancelled":"cancelled a heartbeat","approval.created":"requested approval","approval.approved":"approved","approval.rejected":"rejected"};function fx(t){return typeof t!="string"?String(t??"none"):t.replace(/_/g," ")}function DG(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function LM(t,...e){if(!t)return 0;for(const n of e){const r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r}return 0}function PG(t){const e=t.name.toLowerCase();return e.endsWith(".md")||e.endsWith(".markdown")||t.type==="text/markdown"}function lst(t){return t.replace(/\.[^.]+$/,"")}function cst(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"document"}function ust(t){return t.split(/[-_ ]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function dst(t,e){if(t==="issue.updated"&&e){const n=e._previous??{},r=[];if(e.status!==void 0){const s=n.status;r.push(s?`changed the status from ${fx(s)} to ${fx(e.status)}`:`changed the status to ${fx(e.status)}`)}if(e.priority!==void 0){const s=n.priority;r.push(s?`changed the priority from ${fx(s)} to ${fx(e.priority)}`:`changed the priority to ${fx(e.priority)}`)}if((e.assigneeAgentId!==void 0||e.assigneeUserId!==void 0)&&r.push(e.assigneeAgentId||e.assigneeUserId?"assigned the issue":"unassigned the issue"),e.title!==void 0&&r.push("updated the title"),e.description!==void 0&&r.push("updated the description"),r.length>0)return r.join(", ")}if((t==="issue.document_created"||t==="issue.document_updated"||t==="issue.document_deleted")&&e){const n=typeof e.key=="string"?e.key:"document",r=typeof e.title=="string"&&e.title?` (${e.title})`:"";return`${OG[t]??t} ${n}${r}`}return OG[t]??t.replace(/[._]/g," ")}function fst({evt:t,agentMap:e}){const n=t.actorId;if(t.actorType==="agent"){const r=e.get(n);return o.jsx(lr,{name:(r==null?void 0:r.name)??n.slice(0,8),size:"sm"})}return t.actorType==="system"?o.jsx(lr,{name:"System",size:"sm"}):t.actorType==="user"?o.jsx(lr,{name:"Board",size:"sm"}):o.jsx(lr,{name:n||"Unknown",size:"sm"})}function hst(){var at,Gt,ln,Dn;const{issueId:t}=Zi(),{selectedCompanyId:e}=Xt(),{openPanel:n,closePanel:r,panelVisible:s,setPanelVisible:i}=l0(),{setBreadcrumbs:a}=yr(),l=hn(),c=As(),u=er(),{pushToast:f}=Bo(),[h,p]=y.useState(!1),[g,b]=y.useState(!1),[v,w]=y.useState(!1),[j,C]=y.useState("comments"),[N,S]=y.useState({approvals:!1}),[T,_]=y.useState(null),[A,M]=y.useState(!1),I=y.useRef(null),L=y.useRef(null),{data:D,isLoading:P,error:B}=_e({queryKey:J.issues.detail(t),queryFn:()=>wn.get(t),enabled:!!t}),Z=(D==null?void 0:D.companyId)??e,{data:Q}=_e({queryKey:J.issues.comments(t),queryFn:()=>wn.listComments(t),enabled:!!t}),{data:q}=_e({queryKey:J.issues.activity(t),queryFn:()=>Ch.forIssue(t),enabled:!!t}),{data:O}=_e({queryKey:J.issues.runs(t),queryFn:()=>Ch.runsForIssue(t),enabled:!!t,refetchInterval:5e3}),{data:z}=_e({queryKey:J.issues.approvals(t),queryFn:()=>wn.listApprovals(t),enabled:!!t}),{data:V}=_e({queryKey:J.issues.attachments(t),queryFn:()=>wn.listAttachments(t),enabled:!!t}),{data:$}=_e({queryKey:J.issues.liveRuns(t),queryFn:()=>qr.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:G}=_e({queryKey:J.issues.activeRun(t),queryFn:()=>qr.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),W=($??[]).length>0||!!G,F=y.useMemo(()=>Irt(u.state)??{label:"Issues",href:"/issues"},[u.state]),le=y.useMemo(()=>{const be=new Set;for(const dt of $??[])be.add(dt.id);return G&&be.add(G.id),be.size===0?O??[]:(O??[]).filter(dt=>!be.has(dt.runId))},[O,$,G]),{data:ie}=_e({queryKey:J.issues.list(e),queryFn:()=>wn.list(e),enabled:!!e}),{data:ne}=_e({queryKey:J.agents.list(e),queryFn:()=>Mt.list(e),enabled:!!e}),{data:X}=_e({queryKey:J.auth.session,queryFn:()=>fi.getSession()}),{data:ee}=_e({queryKey:J.projects.list(e),queryFn:()=>vs.list(e),enabled:!!e}),de=((at=X==null?void 0:X.user)==null?void 0:at.id)??((Gt=X==null?void 0:X.session)==null?void 0:Gt.userId)??null,{orderedProjects:ve}=vw({projects:ee??[],companyId:e,userId:de}),{slots:Te}=o0({slotTypes:["detailTab"],entityType:"issue",enabled:!!Z}),Fe=y.useMemo(()=>Te.map(be=>({value:`plugin:${be.pluginKey}:${be.id}`,label:be.displayName,slot:be})),[Te]),Ee=Fe.find(be=>be.value===j)??null,tt=y.useMemo(()=>{const be=new Map;for(const dt of ne??[])be.set(dt.id,dt);return be},[ne]),ot=y.useMemo(()=>{const be=[],dt=[...ne??[]].filter(nt=>nt.status!=="terminated").sort((nt,en)=>nt.name.localeCompare(en.name));for(const nt of dt)be.push({id:`agent:${nt.id}`,name:nt.name,kind:"agent",agentId:nt.id,agentIcon:nt.icon});for(const nt of ve)be.push({id:`project:${nt.id}`,name:nt.name,kind:"project",projectId:nt.id,projectColor:nt.color});return be},[ne,ve]),Ie=y.useMemo(()=>!ie||!D?[]:ie.filter(be=>be.parentId===D.id).sort((be,dt)=>new Date(be.createdAt).getTime()-new Date(dt.createdAt).getTime()),[ie,D]),rt=y.useMemo(()=>{const be=[],dt=[...ne??[]].filter(nt=>nt.status!=="terminated").sort((nt,en)=>nt.name.localeCompare(en.name));for(const nt of dt)be.push({id:`agent:${nt.id}`,label:nt.name});return de&&be.push({id:`user:${de}`,label:"Me"}),be},[ne,de]),H=y.useMemo(()=>md(D??{}),[D]),U=y.useMemo(()=>AMe(D??{},Q,de),[D,Q,de]),me=y.useMemo(()=>{const be=new Map,dt=new Map;for(const nt of O??[])dt.set(nt.runId,nt.agentId);for(const nt of q??[]){if(nt.action!=="issue.comment_added"||!nt.runId)continue;const en=nt.details??{},on=typeof en.commentId=="string"?en.commentId:null;!on||be.has(on)||be.set(on,{runId:nt.runId,runAgentId:nt.agentId??dt.get(nt.runId)??null})}return(Q??[]).map(nt=>{const en=be.get(nt.id);return en?{...nt,...en}:nt})},[q,Q,O]),oe=y.useMemo(()=>{let be=0,dt=0,nt=0,en=0,on=!1,cr=!1;for(const ur of O??[]){const dr=DG(ur.usageJson),Oe=DG(ur.resultJson),bt=LM(dr,"inputTokens","input_tokens"),wt=LM(dr,"outputTokens","output_tokens"),En=LM(dr,"cachedInputTokens","cached_input_tokens","cache_read_input_tokens"),tr=nte(dr,Oe);tr>0&&(on=!0),bt+wt+En>0&&(cr=!0),be+=bt,dt+=wt,nt+=En,en+=tr}return{input:be,output:dt,cached:nt,cost:en,totalTokens:be+dt,hasCost:on,hasTokens:cr}},[O]),pe=()=>{l.invalidateQueries({queryKey:J.issues.detail(t)}),l.invalidateQueries({queryKey:J.issues.activity(t)}),l.invalidateQueries({queryKey:J.issues.runs(t)}),l.invalidateQueries({queryKey:J.issues.approvals(t)}),l.invalidateQueries({queryKey:J.issues.attachments(t)}),l.invalidateQueries({queryKey:J.issues.documents(t)}),l.invalidateQueries({queryKey:J.issues.liveRuns(t)}),l.invalidateQueries({queryKey:J.issues.activeRun(t)}),e&&(l.invalidateQueries({queryKey:J.issues.list(e)}),l.invalidateQueries({queryKey:J.issues.listMineByMe(e)}),l.invalidateQueries({queryKey:J.issues.listTouchedByMe(e)}),l.invalidateQueries({queryKey:J.issues.listUnreadTouchedByMe(e)}),l.invalidateQueries({queryKey:J.sidebarBadges(e)}))},Ne=Xe({mutationFn:be=>wn.markRead(be),onSuccess:()=>{e&&(l.invalidateQueries({queryKey:J.issues.listMineByMe(e)}),l.invalidateQueries({queryKey:J.issues.listTouchedByMe(e)}),l.invalidateQueries({queryKey:J.issues.listUnreadTouchedByMe(e)}),l.invalidateQueries({queryKey:J.sidebarBadges(e)}))}}),fe=Xe({mutationFn:be=>wn.update(t,be),onSuccess:()=>{pe()}}),ke=Xe({mutationFn:({body:be,reopen:dt})=>wn.addComment(t,be,dt),onSuccess:()=>{pe(),l.invalidateQueries({queryKey:J.issues.comments(t)})}}),ce=Xe({mutationFn:({body:be,reopen:dt,reassignment:nt})=>wn.update(t,{comment:be,assigneeAgentId:nt.assigneeAgentId,assigneeUserId:nt.assigneeUserId,...dt?{status:"todo"}:{}}),onSuccess:()=>{pe(),l.invalidateQueries({queryKey:J.issues.comments(t)})}}),ye=Xe({mutationFn:async be=>{if(!e)throw new Error("No company selected");return wn.uploadAttachment(e,t,be)},onSuccess:()=>{_(null),l.invalidateQueries({queryKey:J.issues.attachments(t)}),pe()},onError:be=>{_(be instanceof Error?be.message:"Upload failed")}}),re=Xe({mutationFn:async be=>{const dt=lst(be.name),nt=cst(dt),en=((D==null?void 0:D.documentSummaries)??[]).find(dr=>dr.key===nt)??null,on=await be.text(),cr=ust(dt),ur=(en==null?void 0:en.title)??cr??null;return wn.upsertDocument(t,nt,{title:nt==="plan"?null:ur,format:"markdown",body:on,baseRevisionId:(en==null?void 0:en.latestRevisionId)??null})},onSuccess:()=>{_(null),pe()},onError:be=>{_(be instanceof Error?be.message:"Document import failed")}}),Ye=Xe({mutationFn:be=>wn.deleteAttachment(be),onSuccess:()=>{_(null),l.invalidateQueries({queryKey:J.issues.attachments(t)}),pe()},onError:be=>{_(be instanceof Error?be.message:"Delete failed")}});y.useEffect(()=>{const be=(D==null?void 0:D.title)??t??"Issue";a([F,{label:W?`🔵 ${be}`:be}])},[a,F,D,t,W]),y.useEffect(()=>{D!=null&&D.identifier&&t!==D.identifier&&c(`/issues/${D.identifier}`,{replace:!0,state:u.state})},[D,t,c,u.state]),y.useEffect(()=>{D!=null&&D.id&&L.current!==D.id&&(L.current=D.id,Ne.mutate(D.id))},[D==null?void 0:D.id]),y.useEffect(()=>(D&&n(o.jsx(IG,{issue:D,onUpdate:be=>fe.mutate(be)})),()=>r()),[D]);const gt=async()=>{if(!D)return;const be=on=>{const cr=document.createElement("textarea");return cr.innerHTML=on,cr.value},dt=be(D.title),nt=be(D.description??""),en=`# ${D.identifier}: ${dt}
1087
+ ${X}`:X)}else l&&await l(F)}finally{_(!1),B.current&&(B.current.value="")}}}const G=!N&&!!v.trim();return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",O.length,")"]}),o.jsx(Brt,{timeline:O,agentMap:i,companyId:n,projectId:r,highlightCommentId:L}),u,o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ao,{ref:P,value:v,onChange:w,placeholder:"Leave a comment...",mentions:z,onSubmit:V,imageUploadHandler:a,contentClassName:"min-h-[60px] text-sm"}),o.jsxs("div",{className:"flex items-center justify-end gap-3",children:[(a||l)&&o.jsxs("div",{className:"mr-auto flex items-center gap-3",children:[o.jsx("input",{ref:B,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:$}),o.jsx(ue,{variant:"ghost",size:"icon-sm",onClick:()=>{var W;return(W=B.current)==null?void 0:W.click()},disabled:T,title:"Attach image",children:o.jsx(Uj,{className:"h-4 w-4"})})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:j,onChange:W=>C(W.target.checked),className:"rounded border-border"}),"Re-open"]}),f&&h.length>0&&o.jsx(kh,{value:M,options:h,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:I,className:"text-xs h-8",renderTriggerValue:W=>{if(!W)return o.jsx("span",{className:"text-muted-foreground",children:"Assignee"});const F=W.id.startsWith("agent:")?W.id.slice(6):null,le=F?i==null?void 0:i.get(F):null;return o.jsxs(o.Fragment,{children:[le?o.jsx(Gi,{icon:le.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:W.label})]})},renderOption:W=>{if(!W.id)return o.jsx("span",{className:"truncate",children:W.label});const F=W.id.startsWith("agent:")?W.id.slice(6):null,le=F?i==null?void 0:i.get(F):null;return o.jsxs(o.Fragment,{children:[le?o.jsx(Gi,{icon:le.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:W.label})]})}}),o.jsx(ue,{size:"sm",disabled:!G,onClick:V,children:N?"Posting...":"Comment"})]})]})]})}const Urt=900,EG=/^[a-z0-9][a-z0-9_-]*$/,ghe=t=>`fidelios:issue-document-folds:${t}`;function AG(t){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(ghe(t));if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function TG(t,e){typeof window>"u"||window.localStorage.setItem(ghe(t),JSON.stringify(e))}function MG(t,e){return o.jsx(Al,{className:e,children:t})}function Lm(t){return t.trim().toLowerCase()==="plan"}function Vrt(t,e){return(t??"").trim().toLowerCase()===e.trim().toLowerCase()}function Hrt(t){return t instanceof Hd&&t.status===409}function qrt(t,e){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=`${t}.md`,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r)}function Krt({issue:t,canDeleteDocuments:e,mentions:n,imageUploadHandler:r,extraActions:s}){const i=hn(),a=er(),[l,c]=y.useState(null),[u,f]=y.useState(null),[h,p]=y.useState(null),[g,b]=y.useState(null),[v,w]=y.useState(()=>AG(t.id)),[j,C]=y.useState(null),[N,S]=y.useState(null),[T,_]=y.useState(null),A=y.useRef(null),M=y.useRef(null),I=y.useRef(!1),{state:L,markDirty:D,reset:P,runSave:B}=dhe(),{data:Z}=_e({queryKey:J.issues.documents(t.id),queryFn:()=>wn.listDocuments(t.id)}),Q=()=>{i.invalidateQueries({queryKey:J.issues.detail(t.id)}),i.invalidateQueries({queryKey:J.issues.documents(t.id)})},q=Xe({mutationFn:async H=>wn.upsertDocument(t.id,H.key,{title:Lm(H.key)?null:H.title.trim()||null,format:"markdown",body:H.body,baseRevisionId:H.baseRevisionId})}),O=Xe({mutationFn:H=>wn.deleteDocument(t.id,H),onSuccess:()=>{f(null),c(null),Q()},onError:H=>{f(H instanceof Error?H.message:"Failed to delete document")}}),z=y.useMemo(()=>[...Z??[]].sort((H,U)=>H.key==="plan"&&U.key!=="plan"?-1:H.key!=="plan"&&U.key==="plan"?1:new Date(U.updatedAt).getTime()-new Date(H.updatedAt).getTime()),[Z]),V=z.some(H=>H.key==="plan"),$=z.length===0&&!t.legacyPlanDocument,G=h!=null&&h.isNew&&h.key.trim().length>0&&!EG.test(h.key.trim())?"Use lowercase letters, numbers, -, or _, and start with a letter or number.":null,W=y.useCallback(()=>{C(null),P()},[P]),F=y.useCallback(H=>{C(H),D()},[D]),le=()=>{W(),b(null),p({key:"",title:"",body:"",baseRevisionId:null,isNew:!0}),f(null)},ie=H=>{const U=z.find(oe=>oe.key===H);if(!U)return;const me=(g==null?void 0:g.key)===H?g.localDraft:null;w(oe=>oe.filter(pe=>pe!==H)),W(),b(oe=>(oe==null?void 0:oe.key)===H?oe:null),p({key:(me==null?void 0:me.key)??U.key,title:(me==null?void 0:me.title)??U.title??"",body:(me==null?void 0:me.body)??U.body,baseRevisionId:(me==null?void 0:me.baseRevisionId)??U.latestRevisionId,isNew:!1}),f(null)},ne=()=>{A.current&&clearTimeout(A.current),W(),b(null),p(null),f(null)},X=y.useCallback(async(H,U)=>{if(!H||q.isPending)return!1;const me=H.key.trim().toLowerCase(),oe=H.body.trim(),pe=H.title.trim(),Ne=(g==null?void 0:g.key)===me?g:null;if(Ne&&!(U!=null&&U.overrideConflict))return U!=null&&U.trackAutosave&&W(),!1;if(!me||!oe)return H.isNew?f("Document key and body are required"):oe||f("Document body cannot be empty"),U!=null&&U.trackAutosave&&W(),!1;if(!EG.test(me))return f("Document key must start with a letter or number and use only lowercase letters, numbers, -, or _."),U!=null&&U.trackAutosave&&W(),!1;const fe=z.find(ce=>ce.key===me);if(!H.isNew&&fe&&fe.body===H.body&&(fe.title??"")===H.title)return U!=null&&U.clearAfterSave&&p(ce=>(ce==null?void 0:ce.key)===me?null:ce),U!=null&&U.trackAutosave&&W(),!0;const ke=async()=>{const ce=await q.mutateAsync({...H,key:me,title:Lm(me)?"":pe,body:H.body,baseRevisionId:U!=null&&U.overrideConflict?(Ne==null?void 0:Ne.serverDocument.latestRevisionId)??H.baseRevisionId:H.baseRevisionId});f(null),b(ye=>(ye==null?void 0:ye.key)===me?null:ye),p(ye=>!ye||ye.key!==me?ye:U!=null&&U.clearAfterSave?null:{key:ce.key,title:ce.title??"",body:ce.body,baseRevisionId:ce.latestRevisionId,isNew:!1}),Q()};try{return U!=null&&U.trackAutosave?(C(me),await B(ke)):await ke(),!0}catch(ce){if(Hrt(ce))try{const ye=await wn.getDocument(t.id,me);return b({key:me,serverDocument:ye,localDraft:{key:me,title:Lm(me)?"":pe,body:H.body,baseRevisionId:H.baseRevisionId,isNew:!1},showRemote:!0}),w(re=>re.filter(Ye=>Ye!==me)),f(null),W(),!1}catch{return f("Document changed remotely and the latest version could not be loaded"),!1}return f(ce instanceof Error?ce.message:"Failed to save document"),!1}},[g,Q,t.id,W,B,z,q]),ee=y.useCallback(H=>{if((g==null?void 0:g.key)!==H)return;const U=g.serverDocument;p({key:U.key,title:U.title??"",body:U.body,baseRevisionId:U.latestRevisionId,isNew:!1}),b(null),W(),f(null)},[g,W]),de=y.useCallback(async H=>{if((g==null?void 0:g.key)!==H)return;const U=h&&h.key===H&&!h.isNew?h:g.localDraft;await X({...U,baseRevisionId:g.serverDocument.latestRevisionId},{clearAfterSave:!1,trackAutosave:!0,overrideConflict:!0})},[X,g,h]),ve=y.useCallback(H=>{(g==null?void 0:g.key)===H&&(p(g.localDraft),b(U=>(U==null?void 0:U.key)===H?{...U,showRemote:!1}:U),f(null))},[g]),Te=y.useCallback(async(H,U)=>{try{await navigator.clipboard.writeText(U),S(H),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{S(me=>me===H?null:me)},1400)}catch{f("Could not copy document")}},[]),Fe=async H=>{H.currentTarget.contains(H.relatedTarget)||(A.current&&clearTimeout(A.current),await X(h,{clearAfterSave:!0,trackAutosave:!0}))},Ee=async H=>{if(H.key==="Escape"){H.preventDefault(),ne();return}(H.metaKey||H.ctrlKey)&&H.key==="Enter"&&(H.preventDefault(),A.current&&clearTimeout(A.current),await X(h,{clearAfterSave:!1,trackAutosave:!0}))};y.useEffect(()=>{w(AG(t.id))},[t.id]),y.useEffect(()=>{I.current=!1},[t.id,a.hash]),y.useEffect(()=>{const H=new Set(z.map(U=>U.key));w(U=>{const me=U.filter(oe=>H.has(oe));return me.length!==U.length&&TG(t.id,me),me})},[t.id,z]),y.useEffect(()=>{TG(t.id,v)},[v,t.id]),y.useEffect(()=>{if(!g)return;const H=z.find(U=>U.key===g.key);!H||H.latestRevisionId===g.serverDocument.latestRevisionId||b(U=>(U==null?void 0:U.key)===H.key?{...U,serverDocument:H}:U)},[g,z]),y.useEffect(()=>{const H=a.hash;if(!H.startsWith("#document-"))return;const U=decodeURIComponent(H.slice(10));if(!(z.some(Ne=>Ne.key===U)||U==="plan"&&!!t.legacyPlanDocument)||I.current)return;w(Ne=>Ne.filter(fe=>fe!==U));const oe=document.getElementById(`document-${U}`);if(!oe)return;I.current=!0,_(U),oe.scrollIntoView({behavior:"smooth",block:"center"});const pe=setTimeout(()=>_(Ne=>Ne===U?null:Ne),3e3);return()=>clearTimeout(pe)},[t.legacyPlanDocument,a.hash,z]),y.useEffect(()=>()=>{A.current&&clearTimeout(A.current),M.current&&clearTimeout(M.current)},[]),y.useEffect(()=>{if(!h||h.isNew||(g==null?void 0:g.key)===h.key)return;const H=z.find(me=>me.key===h.key);if(!H)return;if(!(H.body!==h.body||(H.title??"")!==h.title)){L!=="saved"&&W();return}return F(h.key),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{X(h,{clearAfterSave:!1,trackAutosave:!0})},Urt),()=>{A.current&&clearTimeout(A.current)}},[L,X,g,h,F,W,z]);const tt="mt-3 overflow-hidden rounded-md",ot="",Ie="fidelios-edit-in-place-content min-h-[220px] text-[15px] leading-7",rt=H=>{w(U=>U.includes(H)?U.filter(me=>me!==H):[...U,H])};return o.jsxs("div",{className:"space-y-3",children:[$&&!(h!=null&&h.isNew)?o.jsxs("div",{className:"flex items-center justify-end gap-2 min-w-0",children:[s,o.jsxs(ue,{variant:"outline",size:"sm",onClick:le,className:"shrink-0",children:[o.jsx(Er,{className:"mr-1.5 h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:"New document"}),o.jsx("span",{className:"sm:hidden",children:"New"})]})]}):o.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[o.jsx("h3",{className:"text-sm font-medium text-muted-foreground shrink-0",children:"Documents"}),o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s,o.jsxs(ue,{variant:"outline",size:"sm",onClick:le,className:"shrink-0",children:[o.jsx(Er,{className:"mr-1.5 h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:"New document"}),o.jsx("span",{className:"sm:hidden",children:"New"})]})]})]}),u&&o.jsx("p",{className:"text-xs text-destructive",children:u}),(h==null?void 0:h.isNew)&&o.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-accent/10 p-3",onBlurCapture:Fe,onKeyDown:Ee,children:[o.jsx(_r,{autoFocus:!0,value:h.key,onChange:H=>p(U=>U&&{...U,key:H.target.value.toLowerCase()}),placeholder:"Document key"}),G&&o.jsx("p",{className:"text-xs text-destructive",children:G}),!Lm(h.key)&&o.jsx(_r,{value:h.title,onChange:H=>p(U=>U&&{...U,title:H.target.value}),placeholder:"Optional title"}),o.jsx(Ao,{value:h.body,onChange:H=>p(U=>U&&{...U,body:H}),placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:"min-h-[220px] text-[15px] leading-7",mentions:n,imageUploadHandler:r,onSubmit:()=>void X(h,{clearAfterSave:!1,trackAutosave:!1})}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsxs(ue,{variant:"outline",size:"sm",onClick:ne,children:[o.jsx(ps,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}),o.jsx(ue,{size:"sm",onClick:()=>void X(h,{clearAfterSave:!1,trackAutosave:!1}),disabled:q.isPending,children:q.isPending?"Saving...":"Create document"})]})]}),!V&&t.legacyPlanDocument?o.jsxs("div",{id:"document-plan",className:se("rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 transition-colors duration-1000",T==="plan"&&"border-primary/50 bg-primary/5"),children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[o.jsx(k_,{className:"h-4 w-4 text-amber-600"}),o.jsx("span",{className:"rounded-full border border-amber-500/30 px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-amber-700 dark:text-amber-300",children:"PLAN"})]}),o.jsx("div",{className:ot,children:MG(t.legacyPlanDocument.body,Ie)})]}):null,o.jsx("div",{className:"space-y-3",children:z.map(H=>{var Ne;const U=(h==null?void 0:h.key)===H.key&&!h.isNew?h:null,me=(g==null?void 0:g.key)===H.key?g:null,oe=v.includes(H.key),pe=!Lm(H.key)&&!!((Ne=H.title)!=null&&Ne.trim())&&!Vrt(H.title,H.key);return o.jsxs("div",{id:`document-${H.key}`,className:se("rounded-lg border border-border p-3 transition-colors duration-1000",T===H.key&&"border-primary/50 bg-primary/5"),children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground",onClick:()=>rt(H.key),"aria-label":oe?`Expand ${H.key} document`:`Collapse ${H.key} document`,"aria-expanded":!oe,children:oe?o.jsx($r,{className:"h-3.5 w-3.5"}):o.jsx(ns,{className:"h-3.5 w-3.5"})}),o.jsx("span",{className:"shrink-0 rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:H.key}),o.jsxs("a",{href:`#document-${encodeURIComponent(H.key)}`,className:"truncate text-[11px] text-muted-foreground transition-colors hover:text-foreground hover:underline",children:["rev ",H.latestRevisionNumber," • updated ",mo(H.updatedAt)]})]}),pe&&o.jsx("p",{className:"mt-2 text-sm font-medium",children:H.title})]}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"icon-xs",className:se("text-muted-foreground transition-colors",N===H.key&&"text-foreground"),title:N===H.key?"Copied":"Copy document",onClick:()=>void Te(H.key,(U==null?void 0:U.body)??H.body),children:N===H.key?o.jsx($s,{className:"h-3.5 w-3.5"}):o.jsx(uc,{className:"h-3.5 w-3.5"})}),o.jsxs(L5,{children:[o.jsx($5,{asChild:!0,children:o.jsx(ue,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",title:"Document actions",children:o.jsx(t0,{className:"h-3.5 w-3.5"})})}),o.jsxs(F5,{align:"end",children:[o.jsxs(Xl,{onClick:()=>qrt(H.key,(U==null?void 0:U.body)??H.body),children:[o.jsx(Cy,{className:"h-3.5 w-3.5"}),"Download document"]}),e?o.jsx(B5,{}):null,e?o.jsxs(Xl,{variant:"destructive",onClick:()=>c(H.key),children:[o.jsx(Fa,{className:"h-3.5 w-3.5"}),"Delete document"]}):null]})]})]})]}),oe?null:o.jsxs("div",{className:"mt-3 space-y-3",onFocusCapture:()=>{U||ie(H.key)},onBlurCapture:async fe=>{U&&await Fe(fe)},onKeyDown:async fe=>{U&&await Ee(fe)},children:[me&&o.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-3",children:[o.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("p",{className:"text-sm font-medium text-amber-200",children:"Out of date"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This document changed while you were editing. Your local draft is preserved and autosave is paused."})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>b(fe=>(fe==null?void 0:fe.key)===H.key?{...fe,showRemote:!fe.showRemote}:fe),children:me.showRemote?"Hide remote":"Review remote"}),o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>ve(H.key),children:"Keep my draft"}),o.jsx(ue,{variant:"outline",size:"sm",onClick:()=>ee(H.key),children:"Reload remote"}),o.jsx(ue,{size:"sm",onClick:()=>void de(H.key),disabled:q.isPending,children:q.isPending?"Saving...":"Overwrite remote"})]})]}),me.showRemote&&o.jsxs("div",{className:"mt-3 rounded-md border border-border/70 bg-background/60 p-3",children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:[o.jsxs("span",{children:["Remote revision ",me.serverDocument.latestRevisionNumber]}),o.jsx("span",{children:"•"}),o.jsxs("span",{children:["updated ",mo(me.serverDocument.updatedAt)]})]}),!Lm(H.key)&&me.serverDocument.title?o.jsx("p",{className:"mb-2 text-sm font-medium",children:me.serverDocument.title}):null,MG(me.serverDocument.body,"text-[14px] leading-7")]})]}),U&&!Lm(H.key)&&o.jsx(_r,{value:U.title,onChange:fe=>{F(H.key),p(ke=>ke&&{...ke,title:fe.target.value})},placeholder:"Optional title"}),o.jsx("div",{className:`${tt} ${ot} ${U?"":"hover:bg-accent/10"}`,children:o.jsx(Ao,{value:(U==null?void 0:U.body)??H.body,onChange:fe=>{F(H.key),p(ke=>ke&&ke.key===H.key&&!ke.isNew?{...ke,body:fe}:{key:H.key,title:H.title??"",body:fe,baseRevisionId:H.latestRevisionId,isNew:!1})},placeholder:"Markdown body",bordered:!1,className:"bg-transparent",contentClassName:Ie,mentions:n,imageUploadHandler:r,onSubmit:()=>void X(U??h,{clearAfterSave:!1,trackAutosave:!0})})}),o.jsx("div",{className:"flex min-h-4 items-center justify-end px-1",children:o.jsx("span",{className:`text-[11px] transition-opacity duration-150 ${me?"text-amber-300":L==="error"?"text-destructive":"text-muted-foreground"} ${U?"opacity-100":"opacity-0"}`,children:U?me?"Out of date":j===H.key?L==="saving"?"Autosaving...":L==="saved"?"Saved":L==="error"?"Could not save":"":"":""})})]}),l===H.key&&o.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-md border border-destructive/20 bg-destructive/5 px-4 py-3",children:[o.jsx("p",{className:"text-sm text-destructive font-medium",children:"Delete this document? This cannot be undone."}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"sm",onClick:()=>c(null),disabled:O.isPending,children:"Cancel"}),o.jsx(ue,{variant:"destructive",size:"sm",onClick:()=>O.mutate(H.key),disabled:O.isPending,children:O.isPending?"Deleting...":"Delete"})]})]})]},H.id)})})]})}function Wrt(t){var e,n,r,s,i;return t?((e=t.executionWorkspacePolicy)==null?void 0:e.defaultProjectWorkspaceId)??((r=(n=t.workspaces)==null?void 0:n.find(a=>a.isPrimary))==null?void 0:r.id)??((i=(s=t.workspaces)==null?void 0:s[0])==null?void 0:i.id)??null:null}function Grt(t){var n;const e=(n=t==null?void 0:t.executionWorkspacePolicy)!=null&&n.enabled?t.executionWorkspacePolicy.defaultMode:null;return e==="isolated_workspace"||e==="operator_branch"?e:e==="adapter_default"?"agent_default":"shared_workspace"}function Bl({label:t,children:e}){return o.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:t}),o.jsx("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:e})]})}function OM({inline:t,label:e,open:n,onOpenChange:r,triggerContent:s,triggerClassName:i,popoverClassName:a,popoverAlign:l="end",extra:c,children:u}){const f=se("inline-flex items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",i);return t?o.jsxs("div",{children:[o.jsxs(Bl,{label:e,children:[o.jsx("button",{className:f,onClick:()=>r(!n),children:s}),c]}),n&&o.jsx("div",{className:se("rounded-md border border-border bg-popover p-1 mb-2",a),children:u})]}):o.jsxs(Bl,{label:e,children:[o.jsxs(wr,{open:n,onOpenChange:r,children:[o.jsx(kr,{asChild:!0,children:o.jsx("button",{className:f,children:s})}),o.jsx(Cr,{className:se("p-1",a),align:l,collisionPadding:16,children:u})]}),c]})}function IG({issue:t,onUpdate:e,inline:n}){var Te,Fe,Ee,tt,ot,Ie,rt;const{selectedCompanyId:r}=Xt(),s=hn(),i=t.companyId??r,[a,l]=y.useState(!1),[c,u]=y.useState(""),[f,h]=y.useState(!1),[p,g]=y.useState(""),[b,v]=y.useState(!1),[w,j]=y.useState(""),[C,N]=y.useState(""),[S,T]=y.useState("#6366f1"),{data:_}=_e({queryKey:J.auth.session,queryFn:()=>fi.getSession()}),A=((Te=_==null?void 0:_.user)==null?void 0:Te.id)??((Fe=_==null?void 0:_.session)==null?void 0:Fe.userId),{data:M}=_e({queryKey:J.agents.list(i),queryFn:()=>Mt.list(i),enabled:!!i}),{data:I}=_e({queryKey:J.projects.list(i),queryFn:()=>vs.list(i),enabled:!!i}),L=y.useMemo(()=>(I??[]).filter(H=>!H.archivedAt||H.id===t.projectId),[I,t.projectId]),{orderedProjects:D}=vw({projects:L,companyId:i,userId:A}),{data:P}=_e({queryKey:J.issues.labels(i),queryFn:()=>wn.listLabels(i),enabled:!!i}),B=Xe({mutationFn:H=>wn.createLabel(i,H),onSuccess:async H=>{await s.invalidateQueries({queryKey:J.issues.labels(i)}),e({labelIds:[...t.labelIds??[],H.id]}),N("")}}),Z=Xe({mutationFn:H=>wn.deleteLabel(H),onSuccess:()=>{s.invalidateQueries({queryKey:J.issues.labels(i)}),s.invalidateQueries({queryKey:J.issues.list(i)}),s.invalidateQueries({queryKey:J.issues.detail(t.id)})}}),Q=H=>{const U=t.labelIds??[],me=U.includes(H)?U.filter(oe=>oe!==H):[...U,H];e({labelIds:me})},q=H=>{if(!H||!M)return null;const U=M.find(me=>me.id===H);return(U==null?void 0:U.name)??H.slice(0,8)},O=H=>{if(!H)return(H==null?void 0:H.slice(0,8))??"None";const U=D.find(me=>me.id===H);return(U==null?void 0:U.name)??H.slice(0,8)};t.projectId&&D.find(H=>H.id===t.projectId);const z=H=>{if(!H)return null;const U=(I==null?void 0:I.find(me=>me.id===H))??null;return U?y_(U):`/projects/${H}`},V=y.useMemo(()=>kw(),[a]),$=y.useMemo(()=>L_((M??[]).filter(H=>H.status!=="terminated"),V),[M,V]),G=t.assigneeAgentId?M==null?void 0:M.find(H=>H.id===t.assigneeAgentId):null,W=H=>sI(H,A),F=W(t.assigneeUserId),le=W(t.createdByUserId),ie=(t.labels??[]).length>0?o.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[(t.labels??[]).slice(0,3).map(H=>o.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium border",style:{borderColor:H.color,backgroundColor:`${H.color}22`,color:D_(H.color,.13)},children:H.name},H.id)),(t.labels??[]).length>3&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",(t.labels??[]).length-3]})]}):o.jsxs(o.Fragment,{children:[o.jsx(xte,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"No labels"})]}),ne=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:w,onChange:H=>j(H.target.value),autoFocus:!n}),o.jsx("div",{className:"max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:(P??[]).filter(H=>w.trim()?H.name.toLowerCase().includes(w.toLowerCase()):!0).map(H=>{const U=(t.labelIds??[]).includes(H.id);return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("button",{className:se("flex items-center gap-2 flex-1 px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",U&&"bg-accent"),onClick:()=>Q(H.id),children:[o.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:H.color}}),o.jsx("span",{className:"truncate",children:H.name})]}),o.jsx("button",{type:"button",className:"p-1 text-muted-foreground hover:text-destructive rounded",onClick:()=>Z.mutate(H.id),title:`Delete ${H.name}`,children:o.jsx(Fa,{className:"h-3 w-3"})})]},H.id)})}),o.jsxs("div",{className:"mt-2 border-t border-border pt-2 space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{className:"h-7 w-7 p-0 rounded bg-transparent",type:"color",value:S,onChange:H=>T(H.target.value)}),o.jsx("input",{className:"flex-1 px-2 py-1.5 text-xs bg-transparent outline-none rounded placeholder:text-muted-foreground/50",placeholder:"New label",value:C,onChange:H=>N(H.target.value)})]}),o.jsxs("button",{className:"flex items-center justify-center gap-1.5 w-full px-2 py-1.5 text-xs rounded border border-border hover:bg-accent/50 disabled:opacity-50",disabled:!C.trim()||B.isPending,onClick:()=>B.mutate({name:C.trim(),color:S}),children:[o.jsx(Er,{className:"h-3 w-3"}),B.isPending?"Creating…":"Create label"]})]})]}),X=G?o.jsx(lr,{name:G.name,size:"sm"}):F?o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm",children:F})]}):o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"Unassigned"})]}),ee=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:c,onChange:H=>u(H.target.value),autoFocus:!n}),o.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[o.jsx("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!t.assigneeAgentId&&!t.assigneeUserId&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:null}),l(!1)},children:"No assignee"}),A&&o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===A&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:A}),l(!1)},children:[o.jsx(Ra,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),"Assign to me"]}),t.createdByUserId&&t.createdByUserId!==A&&o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",t.assigneeUserId===t.createdByUserId&&"bg-accent"),onClick:()=>{e({assigneeAgentId:null,assigneeUserId:t.createdByUserId}),l(!1)},children:[o.jsx(Ra,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),le?`Assign to ${le}`:"Assign to requester"]}),$.filter(H=>{if(!c.trim())return!0;const U=c.toLowerCase();return H.name.toLowerCase().includes(U)}).map(H=>o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",H.id===t.assigneeAgentId&&"bg-accent"),onClick:()=>{P_(H.id),e({assigneeAgentId:H.id,assigneeUserId:null}),l(!1)},children:[o.jsx(Gi,{icon:H.icon,className:"shrink-0 h-3 w-3 text-muted-foreground"}),H.name]},H.id))]})]}),de=t.projectId?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:((Ee=D.find(H=>H.id===t.projectId))==null?void 0:Ee.color)??"#6366f1"}}),o.jsx("span",{className:"text-sm truncate",children:O(t.projectId)})]}):o.jsxs(o.Fragment,{children:[o.jsx(cu,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"No project"})]}),ve=o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search projects...",value:p,onChange:H=>g(H.target.value),autoFocus:!n}),o.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[o.jsx("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",!t.projectId&&"bg-accent"),onClick:()=>{e({projectId:null,projectWorkspaceId:null,executionWorkspaceId:null,executionWorkspacePreference:null,executionWorkspaceSettings:null}),h(!1)},children:"No project"}),D.filter(H=>{if(!p.trim())return!0;const U=p.toLowerCase();return H.name.toLowerCase().includes(U)}).map(H=>o.jsxs("button",{className:se("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",H.id===t.projectId&&"bg-accent"),onClick:()=>{var me;const U=Grt(H);e({projectId:H.id,projectWorkspaceId:Wrt(H),executionWorkspaceId:null,executionWorkspacePreference:U,executionWorkspaceSettings:(me=H.executionWorkspacePolicy)!=null&&me.enabled?{mode:U}:null}),h(!1)},children:[o.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:H.color??"#6366f1"}}),H.name]},H.id))]})]});return o.jsxs("div",{className:"space-y-4",children:[t.identifier&&o.jsx("div",{className:"font-mono text-sm font-semibold text-foreground",children:t.identifier}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Bl,{label:"Status",children:o.jsx(Js,{status:t.status,onChange:H=>e({status:H}),showLabel:!0})}),o.jsx(Bl,{label:"Priority",children:o.jsx(ea,{priority:t.priority,onChange:H=>e({priority:H}),showLabel:!0})}),o.jsx(OM,{inline:n,label:"Labels",open:b,onOpenChange:H=>{v(H),H||j("")},triggerContent:ie,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-64",children:ne}),o.jsx(OM,{inline:n,label:"Assignee",open:a,onOpenChange:H=>{l(H),H||u("")},triggerContent:X,popoverClassName:"w-52",extra:t.assigneeAgentId?o.jsx(jt,{to:`/agents/${t.assigneeAgentId}`,className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:H=>H.stopPropagation(),children:o.jsx(wy,{className:"h-3 w-3"})}):void 0,children:ee}),o.jsx(OM,{inline:n,label:"Project",open:f,onOpenChange:H=>{h(H),H||g("")},triggerContent:de,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-fit min-w-[11rem]",extra:t.projectId?o.jsx(jt,{to:z(t.projectId),className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:H=>H.stopPropagation(),children:o.jsx(wy,{className:"h-3 w-3"})}):void 0,children:ve}),t.parentId&&o.jsx(Bl,{label:"Parent",children:o.jsx(jt,{to:`/issues/${((ot=(tt=t.ancestors)==null?void 0:tt[0])==null?void 0:ot.identifier)??t.parentId}`,className:"text-sm hover:underline",children:((rt=(Ie=t.ancestors)==null?void 0:Ie[0])==null?void 0:rt.title)??t.parentId.slice(0,8)})}),t.requestDepth>0&&o.jsx(Bl,{label:"Depth",children:o.jsx("span",{className:"text-sm font-mono",children:t.requestDepth})})]}),o.jsx(Ro,{}),o.jsxs("div",{className:"space-y-1",children:[(t.createdByAgentId||t.createdByUserId)&&o.jsx(Bl,{label:"Created by",children:t.createdByAgentId?o.jsx(jt,{to:`/agents/${t.createdByAgentId}`,className:"hover:underline",children:o.jsx(lr,{name:q(t.createdByAgentId)??t.createdByAgentId.slice(0,8),size:"sm"})}):o.jsxs(o.Fragment,{children:[o.jsx(Ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"text-sm",children:le??"User"})]})}),t.startedAt&&o.jsx(Bl,{label:"Started",children:o.jsx("span",{className:"text-sm",children:To(t.startedAt)})}),t.completedAt&&o.jsx(Bl,{label:"Completed",children:o.jsx("span",{className:"text-sm",children:To(t.completedAt)})}),o.jsx(Bl,{label:"Created",children:o.jsx("span",{className:"text-sm",children:To(t.createdAt)})}),o.jsx(Bl,{label:"Updated",children:o.jsx("span",{className:"text-sm",children:ca(t.updatedAt)})})]})]})}const Yrt=[{value:"shared_workspace",label:"Project default"},{value:"isolated_workspace",label:"New isolated workspace"},{value:"reuse_existing",label:"Reuse existing workspace"}];function Jrt(t){return t==="isolated_workspace"||t==="operator_branch"||t==="shared_workspace"?t:t==="adapter_managed"||t==="cloud_sandbox"?"agent_default":"shared_workspace"}function Qrt(t){var n,r;const e=((n=t.currentExecutionWorkspace)==null?void 0:n.mode)??((r=t.executionWorkspaceSettings)==null?void 0:r.mode)??t.executionWorkspacePreference;return!!(t.executionWorkspaceId&&(e==="isolated_workspace"||e==="operator_branch"))}function Zrt(t){var n;const e=(n=t==null?void 0:t.executionWorkspacePolicy)!=null&&n.enabled?t.executionWorkspacePolicy.defaultMode:null;return e==="isolated_workspace"||e==="operator_branch"?e:e==="adapter_default"?"agent_default":"shared_workspace"}function EO({text:t}){const e=[],n=t.split(new RegExp("(?<=[\\/-])"));for(let r=0;r<n.length;r++)r>0&&e.push(o.jsx("wbr",{},r)),e.push(n[r]);return o.jsx(o.Fragment,{children:e})}function DM({value:t,label:e,mono:n}){const[r,s]=y.useState(!1),i=y.useRef(void 0),a=y.useCallback(async()=>{try{await navigator.clipboard.writeText(t),s(!0),clearTimeout(i.current),i.current=setTimeout(()=>s(!1),1500)}catch{}},[t]);return o.jsxs("span",{className:"inline-flex items-center gap-1 group/copy",children:[e&&o.jsx("span",{className:"text-muted-foreground",children:e}),o.jsx("span",{className:se("min-w-0",n&&"font-mono"),style:{overflowWrap:"anywhere"},children:o.jsx(EO,{text:t})}),o.jsx("button",{type:"button",className:"shrink-0 p-0.5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground opacity-0 group-hover/copy:opacity-100 focus:opacity-100",onClick:a,title:r?"Copied!":"Copy",children:r?o.jsx($s,{className:"h-3 w-3 text-green-500"}):o.jsx(uc,{className:"h-3 w-3"})})]})}function Xrt(t){switch(t){case"isolated_workspace":return"Isolated workspace";case"operator_branch":return"Operator branch";case"cloud_sandbox":return"Cloud sandbox";case"adapter_managed":return"Adapter managed";default:return"Workspace"}}function est(t,e){switch(t){case"isolated_workspace":return"New isolated workspace";case"reuse_existing":return(e==null?void 0:e.mode)==="isolated_workspace"?"Existing isolated workspace":"Reuse existing workspace";default:return"Project default"}}function RG(t){const e={active:"bg-green-500/15 text-green-700 dark:text-green-400",idle:"bg-muted text-muted-foreground",in_review:"bg-blue-500/15 text-blue-700 dark:text-blue-400",archived:"bg-muted text-muted-foreground"};return o.jsx("span",{className:se("text-[10px] px-1.5 py-0.5 rounded-full font-medium",e[t]??e.idle),children:t.replace(/_/g," ")})}function tst({issue:t,project:e,onUpdate:n}){var A,M;const{selectedCompanyId:r}=Xt(),s=t.companyId??r,[i,a]=y.useState(!1),{data:l}=_e({queryKey:J.instance.experimentalSettings,queryFn:()=>Od.getExperimental()}),c=(l==null?void 0:l.enableIsolatedWorkspaces)===!0&&!!((A=e==null?void 0:e.executionWorkspacePolicy)!=null&&A.enabled),u=t.currentExecutionWorkspace,{data:f}=_e({queryKey:J.executionWorkspaces.list(s,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),queryFn:()=>z6.list(s,{projectId:t.projectId??void 0,projectWorkspaceId:t.projectWorkspaceId??void 0,reuseEligible:!0}),enabled:!!s&&!!t.projectId&&i}),h=y.useMemo(()=>{const I=f??[],L=new Map;for(const D of I){const P=D.cwd??D.id,B=L.get(P);(!B||new Date(D.lastUsedAt)>new Date(B.lastUsedAt))&&L.set(P,D)}return Array.from(L.values())},[f]),p=h.find(I=>I.id===t.executionWorkspaceId)??u??null,g=Qrt(t)?"reuse_existing":t.executionWorkspacePreference??((M=t.executionWorkspaceSettings)==null?void 0:M.mode)??Zrt(e),[b,v]=y.useState(g),[w,j]=y.useState(t.executionWorkspaceId??"");y.useEffect(()=>{i||(v(g),j(t.executionWorkspaceId??""))},[g,i,t.executionWorkspaceId]);const C=!!(u&&u.mode!=="shared_workspace"),N=h.find(I=>I.id===w)??(w===t.executionWorkspaceId?p:null),S=b!=="reuse_existing"||w.length>0,T=y.useCallback(()=>{S&&(n({executionWorkspacePreference:b,executionWorkspaceId:b==="reuse_existing"&&w||null,executionWorkspaceSettings:{mode:b==="reuse_existing"?Jrt(N==null?void 0:N.mode):b}}),a(!1))},[S,N==null?void 0:N.mode,w,b,n]),_=y.useCallback(()=>{v(g),j(t.executionWorkspaceId??""),a(!1)},[g,t.executionWorkspaceId]);return!c||!e?null:o.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[o.jsx(Bj,{className:"h-3.5 w-3.5 text-muted-foreground"}),C&&u?Xrt(u.mode):est(g,p),RG(u?u.status:"idle")]}),o.jsx("div",{className:"flex items-center gap-1",children:i?o.jsxs(o.Fragment,{children:[o.jsxs(ue,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:_,children:[o.jsx(ps,{className:"h-3 w-3 mr-1"}),"Cancel"]}),o.jsx(ue,{size:"sm",className:"h-6 px-2 text-xs",onClick:T,disabled:!S,children:"Save"})]}):o.jsxs(ue,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground",onClick:()=>a(!0),children:[o.jsx(Vj,{className:"h-3 w-3 mr-1"}),"Edit"]})})]}),!i&&o.jsxs("div",{className:"space-y-1.5 text-xs",children:[(u==null?void 0:u.branchName)&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Bj,{className:"h-3 w-3 text-muted-foreground shrink-0"}),o.jsx(DM,{value:u.branchName,mono:!0})]}),(u==null?void 0:u.cwd)&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(mw,{className:"h-3 w-3 text-muted-foreground shrink-0"}),o.jsx(DM,{value:u.cwd,mono:!0})]}),(u==null?void 0:u.repoUrl)&&o.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[o.jsx("span",{className:"text-[11px]",children:"Repo:"}),o.jsx(DM,{value:u.repoUrl,mono:!0})]}),!u&&o.jsx("div",{className:"text-muted-foreground",children:g==="isolated_workspace"?"A fresh isolated workspace will be created when this issue runs.":g==="reuse_existing"?"This issue will reuse an existing workspace when it runs.":"This issue will use the project default workspace configuration when it runs."}),g==="reuse_existing"&&p&&o.jsxs("div",{className:"text-muted-foreground",style:{overflowWrap:"anywhere"},children:["Reusing:"," ",o.jsx(jt,{to:`/execution-workspaces/${p.id}`,className:"hover:text-foreground hover:underline",children:o.jsx(EO,{text:p.name})})]}),u&&o.jsx("div",{className:"pt-0.5",children:o.jsx(jt,{to:`/execution-workspaces/${u.id}`,className:"text-[11px] text-muted-foreground hover:text-foreground hover:underline",children:"View workspace details →"})})]}),i&&o.jsxs("div",{className:"space-y-2 pt-1",children:[o.jsx("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:b,onChange:I=>{const L=I.target.value;v(L),L!=="reuse_existing"?j(""):!w&&t.executionWorkspaceId&&j(t.executionWorkspaceId)},children:Yrt.map(I=>o.jsx("option",{value:I.value,children:I.value==="reuse_existing"&&(N==null?void 0:N.mode)==="isolated_workspace"?"Existing isolated workspace":I.label},I.value))}),b==="reuse_existing"&&o.jsxs("select",{className:"w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none",value:w,onChange:I=>{j(I.target.value)},children:[o.jsx("option",{value:"",children:"Choose an existing workspace"}),h.map(I=>o.jsxs("option",{value:I.id,children:[I.name," · ",I.status," · ",I.branchName??I.cwd??I.id.slice(0,8)]},I.id))]}),u&&o.jsx("div",{className:"text-[11px] text-muted-foreground space-y-0.5 pt-1 border-t border-border/50",children:o.jsxs("div",{style:{overflowWrap:"anywhere"},children:["Current:"," ",o.jsx(jt,{to:`/execution-workspaces/${u.id}`,className:"hover:text-foreground hover:underline",children:o.jsx(EO,{text:u.name})})," · ",u.status]})})]})]})}function PM(t){return t?typeof t=="string"?t:t.toISOString():null}function nst(t){return t==="queued"||t==="running"}function xhe({issueId:t,companyId:e}){const n=hn(),[r,s]=y.useState(new Set),{data:i}=_e({queryKey:J.issues.liveRuns(t),queryFn:()=>qr.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:a}=_e({queryKey:J.issues.activeRun(t),queryFn:()=>qr.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),l=y.useMemo(()=>{const h=new Map;for(const p of i??[])h.set(p.id,p);return a&&h.set(a.id,{id:a.id,status:a.status,invocationSource:a.invocationSource,triggerDetail:a.triggerDetail,startedAt:PM(a.startedAt),finishedAt:PM(a.finishedAt),createdAt:PM(a.createdAt)??new Date().toISOString(),agentId:a.agentId,agentName:a.agentName,adapterType:a.adapterType,issueId:t}),[...h.values()].sort((p,g)=>new Date(g.createdAt).getTime()-new Date(p.createdAt).getTime())},[a,t,i]),{transcriptByRun:c,hasOutputForRun:u}=qfe({runs:l,companyId:e}),f=async h=>{s(p=>new Set(p).add(h));try{await qr.cancel(h),n.invalidateQueries({queryKey:J.issues.liveRuns(t)}),n.invalidateQueries({queryKey:J.issues.activeRun(t)})}finally{s(p=>{const g=new Set(p);return g.delete(h),g})}};return l.length===0?null:o.jsxs("div",{className:"overflow-hidden rounded-xl border border-cyan-500/25 bg-background/80 shadow-[0_18px_50px_rgba(6,182,212,0.08)]",children:[o.jsxs("div",{className:"border-b border-border/60 bg-cyan-500/[0.04] px-4 py-3",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700 dark:text-cyan-300",children:"Live Runs"}),o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"Streamed with the same transcript UI used on the full run detail page."})]}),o.jsx("div",{className:"divide-y divide-border/60",children:l.map(h=>{const p=nst(h.status),g=c.get(h.id)??[];return o.jsxs("section",{className:"px-4 py-4",children:[o.jsxs("div",{className:"mb-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(jt,{to:`/agents/${h.agentId}`,className:"inline-flex hover:underline",children:o.jsx(lr,{name:h.agentName,size:"sm"})}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[o.jsx(jt,{to:`/agents/${h.agentId}/runs/${h.id}`,className:"inline-flex items-center rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono hover:border-cyan-500/30 hover:text-foreground",children:h.id.slice(0,8)}),o.jsx(sr,{status:h.status}),o.jsx("span",{children:Ap(h.startedAt??h.createdAt)})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[p&&o.jsxs("button",{onClick:()=>f(h.id),disabled:r.has(h.id),className:"inline-flex items-center gap-1 rounded-full border border-red-500/20 bg-red-500/[0.06] px-2.5 py-1 text-[11px] font-medium text-red-700 transition-colors hover:bg-red-500/[0.12] dark:text-red-300 disabled:opacity-50",children:[o.jsx(U5e,{className:"h-2.5 w-2.5",fill:"currentColor"}),r.has(h.id)?"Stopping…":"Stop"]}),o.jsxs(jt,{to:`/agents/${h.agentId}/runs/${h.id}`,className:"inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] font-medium text-cyan-700 transition-colors hover:border-cyan-500/30 hover:text-cyan-600 dark:text-cyan-300",children:["Open run",o.jsx(Md,{className:"h-3 w-3"})]})]})]}),o.jsx("div",{className:"max-h-[320px] overflow-y-auto pr-1",children:o.jsx(T0,{entries:g,density:"compact",limit:8,streaming:p,collapseStdout:!0,emptyMessage:u(h.id)?"Waiting for transcript parsing...":"Waiting for run output..."})})]},h.id)})})]})}function yhe({...t}){return o.jsx(US,{"data-slot":"sheet",...t})}function rst({...t}){return o.jsx(XJ,{"data-slot":"sheet-trigger",...t})}function sst({...t}){return o.jsx(VS,{"data-slot":"sheet-portal",...t})}function ist({className:t,...e}){return o.jsx(HS,{"data-slot":"sheet-overlay",className:se("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function bhe({className:t,children:e,side:n="right",showCloseButton:r=!0,...s}){return o.jsxs(sst,{children:[o.jsx(ist,{}),o.jsxs(qS,{"data-slot":"sheet-content",className:se("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",n==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",n==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",n==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",n==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...s,children:[e,r&&o.jsxs(nw,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[o.jsx(ps,{className:"size-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vhe({className:t,...e}){return o.jsx("div",{"data-slot":"sheet-header",className:se("flex flex-col gap-1.5 p-4",t),...e})}function ost({className:t,...e}){return o.jsx("div",{"data-slot":"sheet-footer",className:se("mt-auto flex flex-col gap-2 p-4",t),...e})}function whe({className:t,...e}){return o.jsx(lD,{"data-slot":"sheet-title",className:se("text-foreground font-semibold",t),...e})}function ast({className:t,...e}){return o.jsx(eQ,{"data-slot":"sheet-description",className:se("text-muted-foreground text-sm",t),...e})}const OG={"issue.created":"created the issue","issue.updated":"updated the issue","issue.checked_out":"checked out the issue","issue.released":"released the issue","issue.comment_added":"added a comment","issue.attachment_added":"added an attachment","issue.attachment_removed":"removed an attachment","issue.document_created":"created a document","issue.document_updated":"updated a document","issue.document_deleted":"deleted a document","issue.deleted":"deleted the issue","agent.created":"created an agent","agent.updated":"updated the agent","agent.paused":"paused the agent","agent.resumed":"resumed the agent","agent.terminated":"terminated the agent","heartbeat.invoked":"invoked a heartbeat","heartbeat.cancelled":"cancelled a heartbeat","approval.created":"requested approval","approval.approved":"approved","approval.rejected":"rejected"};function fx(t){return typeof t!="string"?String(t??"none"):t.replace(/_/g," ")}function DG(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function LM(t,...e){if(!t)return 0;for(const n of e){const r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r}return 0}function PG(t){const e=t.name.toLowerCase();return e.endsWith(".md")||e.endsWith(".markdown")||t.type==="text/markdown"}function lst(t){return t.replace(/\.[^.]+$/,"")}function cst(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"document"}function ust(t){return t.split(/[-_ ]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function dst(t,e){if(t==="issue.updated"&&e){const n=e._previous??{},r=[];if(e.status!==void 0){const s=n.status;r.push(s?`changed the status from ${fx(s)} to ${fx(e.status)}`:`changed the status to ${fx(e.status)}`)}if(e.priority!==void 0){const s=n.priority;r.push(s?`changed the priority from ${fx(s)} to ${fx(e.priority)}`:`changed the priority to ${fx(e.priority)}`)}if((e.assigneeAgentId!==void 0||e.assigneeUserId!==void 0)&&r.push(e.assigneeAgentId||e.assigneeUserId?"assigned the issue":"unassigned the issue"),e.title!==void 0&&r.push("updated the title"),e.description!==void 0&&r.push("updated the description"),r.length>0)return r.join(", ")}if((t==="issue.document_created"||t==="issue.document_updated"||t==="issue.document_deleted")&&e){const n=typeof e.key=="string"?e.key:"document",r=typeof e.title=="string"&&e.title?` (${e.title})`:"";return`${OG[t]??t} ${n}${r}`}return OG[t]??t.replace(/[._]/g," ")}function fst({evt:t,agentMap:e}){const n=t.actorId;if(t.actorType==="agent"){const r=e.get(n);return o.jsx(lr,{name:(r==null?void 0:r.name)??n.slice(0,8),size:"sm"})}return t.actorType==="system"?o.jsx(lr,{name:"System",size:"sm"}):t.actorType==="user"?o.jsx(lr,{name:"Board",size:"sm"}):o.jsx(lr,{name:n||"Unknown",size:"sm"})}function hst(){var at,Gt,ln,Dn;const{issueId:t}=Zi(),{selectedCompanyId:e}=Xt(),{openPanel:n,closePanel:r,panelVisible:s,setPanelVisible:i}=l0(),{setBreadcrumbs:a}=yr(),l=hn(),c=As(),u=er(),{pushToast:f}=Bo(),[h,p]=y.useState(!1),[g,b]=y.useState(!1),[v,w]=y.useState(!1),[j,C]=y.useState("comments"),[N,S]=y.useState({approvals:!1}),[T,_]=y.useState(null),[A,M]=y.useState(!1),I=y.useRef(null),L=y.useRef(null),{data:D,isLoading:P,error:B}=_e({queryKey:J.issues.detail(t),queryFn:()=>wn.get(t),enabled:!!t}),Z=(D==null?void 0:D.companyId)??e,{data:Q}=_e({queryKey:J.issues.comments(t),queryFn:()=>wn.listComments(t),enabled:!!t}),{data:q}=_e({queryKey:J.issues.activity(t),queryFn:()=>Ch.forIssue(t),enabled:!!t}),{data:O}=_e({queryKey:J.issues.runs(t),queryFn:()=>Ch.runsForIssue(t),enabled:!!t,refetchInterval:5e3}),{data:z}=_e({queryKey:J.issues.approvals(t),queryFn:()=>wn.listApprovals(t),enabled:!!t}),{data:V}=_e({queryKey:J.issues.attachments(t),queryFn:()=>wn.listAttachments(t),enabled:!!t}),{data:$}=_e({queryKey:J.issues.liveRuns(t),queryFn:()=>qr.liveRunsForIssue(t),enabled:!!t,refetchInterval:3e3}),{data:G}=_e({queryKey:J.issues.activeRun(t),queryFn:()=>qr.activeRunForIssue(t),enabled:!!t,refetchInterval:3e3}),W=($??[]).length>0||!!G,F=y.useMemo(()=>Irt(u.state)??{label:"Issues",href:"/issues"},[u.state]),le=y.useMemo(()=>{const be=new Set;for(const dt of $??[])be.add(dt.id);return G&&be.add(G.id),be.size===0?O??[]:(O??[]).filter(dt=>!be.has(dt.runId))},[O,$,G]),{data:ie}=_e({queryKey:J.issues.list(e),queryFn:()=>wn.list(e),enabled:!!e}),{data:ne}=_e({queryKey:J.agents.list(e),queryFn:()=>Mt.list(e),enabled:!!e}),{data:X}=_e({queryKey:J.auth.session,queryFn:()=>fi.getSession()}),{data:ee}=_e({queryKey:J.projects.list(e),queryFn:()=>vs.list(e),enabled:!!e}),de=((at=X==null?void 0:X.user)==null?void 0:at.id)??((Gt=X==null?void 0:X.session)==null?void 0:Gt.userId)??null,{orderedProjects:ve}=vw({projects:ee??[],companyId:e,userId:de}),{slots:Te}=o0({slotTypes:["detailTab"],entityType:"issue",enabled:!!Z}),Fe=y.useMemo(()=>Te.map(be=>({value:`plugin:${be.pluginKey}:${be.id}`,label:be.displayName,slot:be})),[Te]),Ee=Fe.find(be=>be.value===j)??null,tt=y.useMemo(()=>{const be=new Map;for(const dt of ne??[])be.set(dt.id,dt);return be},[ne]),ot=y.useMemo(()=>{const be=[],dt=[...ne??[]].filter(nt=>nt.status!=="terminated").sort((nt,en)=>nt.name.localeCompare(en.name));for(const nt of dt)be.push({id:`agent:${nt.id}`,name:nt.name,kind:"agent",agentId:nt.id,agentIcon:nt.icon});for(const nt of ve)be.push({id:`project:${nt.id}`,name:nt.name,kind:"project",projectId:nt.id,projectColor:nt.color});return be},[ne,ve]),Ie=y.useMemo(()=>!ie||!D?[]:ie.filter(be=>be.parentId===D.id).sort((be,dt)=>new Date(be.createdAt).getTime()-new Date(dt.createdAt).getTime()),[ie,D]),rt=y.useMemo(()=>{const be=[],dt=[...ne??[]].filter(nt=>nt.status!=="terminated").sort((nt,en)=>nt.name.localeCompare(en.name));for(const nt of dt)be.push({id:`agent:${nt.id}`,label:nt.name});return de&&be.push({id:`user:${de}`,label:"Me"}),be},[ne,de]),H=y.useMemo(()=>md(D??{}),[D]),U=y.useMemo(()=>AMe(D??{},Q,de),[D,Q,de]),me=y.useMemo(()=>{const be=new Map,dt=new Map;for(const nt of O??[])dt.set(nt.runId,nt.agentId);for(const nt of q??[]){if(nt.action!=="issue.comment_added"||!nt.runId)continue;const en=nt.details??{},on=typeof en.commentId=="string"?en.commentId:null;!on||be.has(on)||be.set(on,{runId:nt.runId,runAgentId:nt.agentId??dt.get(nt.runId)??null})}return(Q??[]).map(nt=>{const en=be.get(nt.id);return en?{...nt,...en}:nt})},[q,Q,O]),oe=y.useMemo(()=>{let be=0,dt=0,nt=0,en=0,on=!1,cr=!1;for(const ur of O??[]){const dr=DG(ur.usageJson),Oe=DG(ur.resultJson),bt=LM(dr,"inputTokens","input_tokens"),wt=LM(dr,"outputTokens","output_tokens"),En=LM(dr,"cachedInputTokens","cached_input_tokens","cache_read_input_tokens"),tr=nte(dr,Oe);tr>0&&(on=!0),bt+wt+En>0&&(cr=!0),be+=bt,dt+=wt,nt+=En,en+=tr}return{input:be,output:dt,cached:nt,cost:en,totalTokens:be+dt,hasCost:on,hasTokens:cr}},[O]),pe=()=>{l.invalidateQueries({queryKey:J.issues.detail(t)}),l.invalidateQueries({queryKey:J.issues.activity(t)}),l.invalidateQueries({queryKey:J.issues.runs(t)}),l.invalidateQueries({queryKey:J.issues.approvals(t)}),l.invalidateQueries({queryKey:J.issues.attachments(t)}),l.invalidateQueries({queryKey:J.issues.documents(t)}),l.invalidateQueries({queryKey:J.issues.liveRuns(t)}),l.invalidateQueries({queryKey:J.issues.activeRun(t)}),e&&(l.invalidateQueries({queryKey:J.issues.list(e)}),l.invalidateQueries({queryKey:J.issues.listMineByMe(e)}),l.invalidateQueries({queryKey:J.issues.listTouchedByMe(e)}),l.invalidateQueries({queryKey:J.issues.listUnreadTouchedByMe(e)}),l.invalidateQueries({queryKey:J.sidebarBadges(e)}))},Ne=Xe({mutationFn:be=>wn.markRead(be),onSuccess:()=>{e&&(l.invalidateQueries({queryKey:J.issues.listMineByMe(e)}),l.invalidateQueries({queryKey:J.issues.listTouchedByMe(e)}),l.invalidateQueries({queryKey:J.issues.listUnreadTouchedByMe(e)}),l.invalidateQueries({queryKey:J.sidebarBadges(e)}))}}),fe=Xe({mutationFn:be=>wn.update(t,be),onSuccess:()=>{pe()}}),ke=Xe({mutationFn:({body:be,reopen:dt})=>wn.addComment(t,be,dt),onSuccess:()=>{pe(),l.invalidateQueries({queryKey:J.issues.comments(t)})}}),ce=Xe({mutationFn:({body:be,reopen:dt,reassignment:nt})=>wn.update(t,{comment:be,assigneeAgentId:nt.assigneeAgentId,assigneeUserId:nt.assigneeUserId,...dt?{status:"todo"}:{}}),onSuccess:()=>{pe(),l.invalidateQueries({queryKey:J.issues.comments(t)})}}),ye=Xe({mutationFn:async be=>{if(!e)throw new Error("No company selected");return wn.uploadAttachment(e,t,be)},onSuccess:()=>{_(null),l.invalidateQueries({queryKey:J.issues.attachments(t)}),pe()},onError:be=>{_(be instanceof Error?be.message:"Upload failed")}}),re=Xe({mutationFn:async be=>{const dt=lst(be.name),nt=cst(dt),en=((D==null?void 0:D.documentSummaries)??[]).find(dr=>dr.key===nt)??null,on=await be.text(),cr=ust(dt),ur=(en==null?void 0:en.title)??cr??null;return wn.upsertDocument(t,nt,{title:nt==="plan"?null:ur,format:"markdown",body:on,baseRevisionId:(en==null?void 0:en.latestRevisionId)??null})},onSuccess:()=>{_(null),pe()},onError:be=>{_(be instanceof Error?be.message:"Document import failed")}}),Ye=Xe({mutationFn:be=>wn.deleteAttachment(be),onSuccess:()=>{_(null),l.invalidateQueries({queryKey:J.issues.attachments(t)}),pe()},onError:be=>{_(be instanceof Error?be.message:"Delete failed")}});y.useEffect(()=>{const be=(D==null?void 0:D.title)??t??"Issue";a([F,{label:W?`🔵 ${be}`:be}])},[a,F,D,t,W]),y.useEffect(()=>{D!=null&&D.identifier&&t!==D.identifier&&c(`/issues/${D.identifier}`,{replace:!0,state:u.state})},[D,t,c,u.state]),y.useEffect(()=>{D!=null&&D.id&&L.current!==D.id&&(L.current=D.id,Ne.mutate(D.id))},[D==null?void 0:D.id]),y.useEffect(()=>(D&&n(o.jsx(IG,{issue:D,onUpdate:be=>fe.mutate(be)})),()=>r()),[D]);const gt=async()=>{if(!D)return;const be=on=>{const cr=document.createElement("textarea");return cr.innerHTML=on,cr.value},dt=be(D.title),nt=be(D.description??""),en=`# ${D.identifier}: ${dt}
1088
1088
 
1089
1089
  ${nt}`.trimEnd();await navigator.clipboard.writeText(en),b(!0),f({title:"Copied to clipboard",tone:"success"}),setTimeout(()=>b(!1),2e3)};if(P)return o.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."});if(B)return o.jsx("p",{className:"text-sm text-destructive",children:B.message});if(!D)return null;const Et=D.ancestors??[],bn=async be=>{const dt=be.target.files;if(!(!dt||dt.length===0)){for(const nt of Array.from(dt))PG(nt)?await re.mutateAsync(nt):await ye.mutateAsync(nt);I.current&&(I.current.value="")}},we=async be=>{be.preventDefault(),M(!1);const dt=be.dataTransfer.files;if(!(!dt||dt.length===0))for(const nt of Array.from(dt))PG(nt)?await re.mutateAsync(nt):await ye.mutateAsync(nt)},qe=be=>be.contentType.startsWith("image/"),yt=V??[],Se=yt.length>0,Ge=o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:I,type:"file",accept:"image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown",className:"hidden",onChange:bn,multiple:!0}),o.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>{var be;return(be=I.current)==null?void 0:be.click()},disabled:ye.isPending||re.isPending,className:se("shadow-none",A&&"border-primary bg-primary/5"),children:[o.jsx(Uj,{className:"h-3.5 w-3.5 mr-1.5"}),ye.isPending||re.isPending?"Uploading...":o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden sm:inline",children:"Upload attachment"}),o.jsx("span",{className:"sm:hidden",children:"Upload"})]})]})]});return o.jsxs("div",{className:"max-w-2xl space-y-6",children:[Et.length>0&&o.jsxs("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground flex-wrap",children:[[...Et].reverse().map((be,dt)=>o.jsxs("span",{className:"flex items-center gap-1",children:[dt>0&&o.jsx($r,{className:"h-3 w-3 shrink-0"}),o.jsx(jt,{to:`/issues/${be.identifier??be.id}`,state:u.state,className:"hover:text-foreground transition-colors truncate max-w-[200px]",title:be.title,children:be.title})]},be.id)),o.jsx($r,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"text-foreground/60 truncate max-w-[200px]",children:D.title})]}),D.hiddenAt&&o.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[o.jsx(Vv,{className:"h-4 w-4 shrink-0"}),"This issue is hidden"]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-wrap",children:[o.jsx(Js,{status:D.status,onChange:be=>fe.mutate({status:be})}),o.jsx(ea,{priority:D.priority,onChange:be=>fe.mutate({priority:be})}),o.jsx("span",{className:"text-sm font-mono text-muted-foreground shrink-0",children:D.identifier??D.id.slice(0,8)}),W&&o.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-cyan-500/10 border border-cyan-500/30 px-2 py-0.5 text-[10px] font-medium text-cyan-600 dark:text-cyan-400 shrink-0",children:[o.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[o.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-cyan-400"})]}),"Live"]}),D.originKind==="routine_execution"&&D.originId&&o.jsxs(jt,{to:`/routines/${D.originId}`,className:"inline-flex items-center gap-1 rounded-full bg-violet-500/10 border border-violet-500/30 px-2 py-0.5 text-[10px] font-medium text-violet-600 dark:text-violet-400 shrink-0 hover:bg-violet-500/20 transition-colors",children:[o.jsx(Wv,{className:"h-3 w-3"}),"Routine"]}),D.projectId?o.jsxs(jt,{to:`/projects/${D.projectId}`,className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors rounded px-1 -mx-1 py-0.5 min-w-0",children:[o.jsx(cu,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:((ln=(ee??[]).find(be=>be.id===D.projectId))==null?void 0:ln.name)??D.projectId.slice(0,8)})]}):o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground opacity-50 px-1 -mx-1 py-0.5",children:[o.jsx(cu,{className:"h-3 w-3 shrink-0"}),"No project"]}),(D.labels??[]).length>0&&o.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[(D.labels??[]).slice(0,4).map(be=>o.jsx("span",{className:"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",style:{borderColor:be.color,color:D_(be.color,.12),backgroundColor:`${be.color}1f`},children:be.name},be.id)),(D.labels??[]).length>4&&o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",(D.labels??[]).length-4]})]}),o.jsxs("div",{className:"ml-auto flex items-center gap-0.5 md:hidden shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"icon-xs",onClick:gt,title:"Copy issue as markdown",children:g?o.jsx($s,{className:"h-4 w-4 text-green-500"}):o.jsx(uc,{className:"h-4 w-4"})}),o.jsx(ue,{variant:"ghost",size:"icon-xs",onClick:()=>w(!0),title:"Properties",children:o.jsx(Gv,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"hidden md:flex items-center md:ml-auto shrink-0",children:[o.jsx(ue,{variant:"ghost",size:"icon-xs",onClick:gt,title:"Copy issue as markdown",children:g?o.jsx($s,{className:"h-4 w-4 text-green-500"}):o.jsx(uc,{className:"h-4 w-4"})}),o.jsx(ue,{variant:"ghost",size:"icon-xs",className:se("shrink-0 transition-opacity duration-200",s?"opacity-0 pointer-events-none w-0 overflow-hidden":"opacity-100"),onClick:()=>i(!0),title:"Show properties",children:o.jsx(Gv,{className:"h-4 w-4"})}),o.jsxs(wr,{open:h,onOpenChange:p,children:[o.jsx(kr,{asChild:!0,children:o.jsx(ue,{variant:"ghost",size:"icon-xs",className:"shrink-0",children:o.jsx(t0,{className:"h-4 w-4"})})}),o.jsx(Cr,{className:"w-44 p-1",align:"end",children:o.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive",onClick:()=>{fe.mutate({hiddenAt:new Date().toISOString()},{onSuccess:()=>c("/issues/all")}),p(!1)},children:[o.jsx(Vv,{className:"h-3 w-3"}),"Hide this Issue"]})})]})]})]}),o.jsx(ou,{value:D.title,onSave:be=>fe.mutateAsync({title:be}),as:"h2",className:"text-xl font-bold"}),o.jsx(ou,{value:D.description??"",onSave:be=>fe.mutateAsync({description:be}),as:"p",className:"text-[15px] leading-7 text-foreground",placeholder:"Add a description...",multiline:!0,mentions:ot,imageUploadHandler:async be=>(await ye.mutateAsync(be)).contentPath})]}),o.jsx(Rd,{slotTypes:["toolbarButton","contextMenuItem"],entityType:"issue",context:{companyId:D.companyId,projectId:D.projectId??null,entityId:D.id,entityType:"issue"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex",missingBehavior:"placeholder"}),o.jsx(L6,{placementZones:["toolbarButton"],entityType:"issue",context:{companyId:D.companyId,projectId:D.projectId??null,entityId:D.id,entityType:"issue"},className:"flex flex-wrap gap-2",itemClassName:"inline-flex"}),o.jsx(Rd,{slotTypes:["taskDetailView"],entityType:"issue",context:{companyId:D.companyId,projectId:D.projectId??null,entityId:D.id,entityType:"issue"},className:"space-y-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"}),o.jsx(Krt,{issue:D,canDeleteDocuments:!!((Dn=X==null?void 0:X.user)!=null&&Dn.id),mentions:ot,imageUploadHandler:async be=>(await ye.mutateAsync(be)).contentPath,extraActions:Se?void 0:Ge}),Se?o.jsxs("div",{className:se("space-y-3 rounded-lg transition-colors"),onDragEnter:be=>{be.preventDefault(),M(!0)},onDragOver:be=>{be.preventDefault(),M(!0)},onDragLeave:be=>{be.currentTarget.contains(be.relatedTarget)||M(!1)},onDrop:be=>void we(be),children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Attachments"}),Ge]}),T&&o.jsx("p",{className:"text-xs text-destructive",children:T}),o.jsx("div",{className:"space-y-2",children:yt.map(be=>o.jsxs("div",{className:"border border-border rounded-md p-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("a",{href:be.contentPath,target:"_blank",rel:"noreferrer",className:"text-xs hover:underline truncate",title:be.originalFilename??be.id,children:be.originalFilename??be.id}),o.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:()=>Ye.mutate(be.id),disabled:Ye.isPending,title:"Delete attachment",children:o.jsx(Fa,{className:"h-3.5 w-3.5"})})]}),o.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[be.contentType," · ",(be.byteSize/1024).toFixed(1)," KB"]}),qe(be)&&o.jsx("a",{href:be.contentPath,target:"_blank",rel:"noreferrer",children:o.jsx("img",{src:be.contentPath,alt:be.originalFilename??"attachment",className:"mt-2 max-h-56 rounded border border-border object-contain bg-accent/10",loading:"lazy"})})]},be.id))})]}):null,o.jsx(tst,{issue:D,project:ve.find(be=>be.id===D.projectId)??null,onUpdate:be=>fe.mutate(be)}),o.jsx(Ro,{}),o.jsxs(ha,{value:j,onValueChange:C,className:"space-y-3",children:[o.jsxs(tg,{variant:"line",className:"w-full justify-start gap-1",children:[o.jsxs(_s,{value:"comments",className:"gap-1.5",children:[o.jsx(mte,{className:"h-3.5 w-3.5"}),"Comments"]}),o.jsxs(_s,{value:"subissues",className:"gap-1.5",children:[o.jsx(P_e,{className:"h-3.5 w-3.5"}),"Sub-issues"]}),o.jsxs(_s,{value:"activity",className:"gap-1.5",children:[o.jsx(ote,{className:"h-3.5 w-3.5"}),"Activity"]}),Fe.map(be=>o.jsx(_s,{value:be.value,children:be.label},be.value))]}),o.jsx(Vr,{value:"comments",children:o.jsx(zrt,{comments:me,linkedRuns:le,companyId:D.companyId,projectId:D.projectId,issueStatus:D.status,agentMap:tt,draftKey:`fidelios:issue-comment-draft:${D.id}`,enableReassign:!0,reassignOptions:rt,currentAssigneeValue:H,suggestedAssigneeValue:U,mentions:ot,onAdd:async(be,dt,nt)=>{if(nt){await ce.mutateAsync({body:be,reopen:dt,reassignment:nt});return}await ke.mutateAsync({body:be,reopen:dt})},imageUploadHandler:async be=>(await ye.mutateAsync(be)).contentPath,onAttachImage:async be=>{await ye.mutateAsync(be)},liveRunSlot:o.jsx(xhe,{issueId:t,companyId:D.companyId})})}),o.jsx(Vr,{value:"subissues",children:Ie.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No sub-issues."}):o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:Ie.map(be=>o.jsxs(jt,{to:`/issues/${be.identifier??be.id}`,state:u.state,className:"flex items-center justify-between px-3 py-2 text-sm hover:bg-accent/20 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(Js,{status:be.status}),o.jsx(ea,{priority:be.priority}),o.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:be.identifier??be.id.slice(0,8)}),o.jsx("span",{className:"truncate",children:be.title})]}),be.assigneeAgentId&&(()=>{var nt;const dt=(nt=tt.get(be.assigneeAgentId))==null?void 0:nt.name;return dt?o.jsx(lr,{name:dt,size:"sm"}):o.jsx("span",{className:"text-muted-foreground font-mono",children:be.assigneeAgentId.slice(0,8)})})()]},be.id))})}),o.jsxs(Vr,{value:"activity",children:[O&&O.length>0&&o.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg border border-border",children:[o.jsx("div",{className:"text-sm font-medium text-muted-foreground mb-1",children:"Cost Summary"}),!oe.hasCost&&!oe.hasTokens?o.jsx("div",{className:"text-xs text-muted-foreground",children:"No cost data yet."}):o.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground tabular-nums",children:[oe.hasCost&&o.jsxs("span",{className:"font-medium text-foreground",children:["$",oe.cost.toFixed(4)]}),oe.hasTokens&&o.jsxs("span",{children:["Tokens ",Kn(oe.totalTokens),oe.cached>0?` (in ${Kn(oe.input)}, out ${Kn(oe.output)}, cached ${Kn(oe.cached)})`:` (in ${Kn(oe.input)}, out ${Kn(oe.output)})`]})]})]}),!q||q.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):o.jsx("div",{className:"space-y-1.5",children:q.slice(0,20).map(be=>o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[o.jsx(fst,{evt:be,agentMap:tt}),o.jsx("span",{children:dst(be.action,be.details)}),o.jsx("span",{className:"ml-auto shrink-0",children:mo(be.createdAt)})]},be.id))})]}),Ee&&o.jsx(Vr,{value:Ee.value,children:o.jsx(a0,{slot:Ee.slot,context:{companyId:D.companyId,projectId:D.projectId??null,entityId:D.id,entityType:"issue"},missingBehavior:"placeholder"})})]}),z&&z.length>0&&o.jsxs(tm,{open:N.approvals,onOpenChange:be=>S(dt=>({...dt,approvals:be})),className:"rounded-lg border border-border",children:[o.jsxs(nm,{className:"flex w-full items-center justify-between px-3 py-2 text-left",children:[o.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Linked Approvals (",z.length,")"]}),o.jsx(ns,{className:se("h-4 w-4 text-muted-foreground transition-transform",N.approvals&&"rotate-180")})]}),o.jsx(rm,{children:o.jsx("div",{className:"border-t border-border divide-y divide-border",children:z.map(be=>o.jsxs(jt,{to:`/approvals/${be.id}`,className:"flex items-center justify-between px-3 py-2 text-xs hover:bg-accent/20 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(sr,{status:be.status}),o.jsx("span",{className:"font-medium",children:be.type.replace(/_/g," ").replace(/\b\w/g,dt=>dt.toUpperCase())}),o.jsx("span",{className:"font-mono text-muted-foreground",children:be.id.slice(0,8)})]}),o.jsx("span",{className:"text-muted-foreground",children:mo(be.createdAt)})]},be.id))})})]}),o.jsx(yhe,{open:v,onOpenChange:w,children:o.jsxs(bhe,{side:"bottom",className:"max-h-[85dvh] pb-[env(safe-area-inset-bottom)]",children:[o.jsx(vhe,{children:o.jsx(whe,{className:"text-sm",children:"Properties"})}),o.jsx($6,{className:"flex-1 overflow-y-auto",children:o.jsx("div",{className:"px-4 pb-4",children:o.jsx(IG,{issue:D,onUpdate:be=>fe.mutate(be),inline:!0})})})]})}),o.jsx(ohe,{})]})}const Xo={list:t=>Ce.get(`/companies/${t}/routines`),create:(t,e)=>Ce.post(`/companies/${t}/routines`,e),get:t=>Ce.get(`/routines/${t}`),update:(t,e)=>Ce.patch(`/routines/${t}`,e),listRuns:(t,e=50)=>Ce.get(`/routines/${t}/runs?limit=${e}`),createTrigger:(t,e)=>Ce.post(`/routines/${t}/triggers`,e),updateTrigger:(t,e)=>Ce.patch(`/routine-triggers/${t}`,e),deleteTrigger:t=>Ce.delete(`/routine-triggers/${t}`),rotateTriggerSecret:t=>Ce.post(`/routine-triggers/${t}/rotate-secret`,{}),run:(t,e)=>Ce.post(`/routines/${t}/run`,e??{}),activity:async(t,e,n)=>{const r=[Ch.list(t,{entityType:"routine",entityId:e}),...((n==null?void 0:n.triggerIds)??[]).map(a=>Ch.list(t,{entityType:"routine_trigger",entityId:a})),...((n==null?void 0:n.runIds)??[]).map(a=>Ch.list(t,{entityType:"routine_run",entityId:a}))],s=(await Promise.all(r)).flat();return[...new Map(s.map(a=>[a.id,a])).values()].sort((a,l)=>new Date(l.createdAt).getTime()-new Date(a.createdAt).getTime())}};function Ni({...t}){return o.jsx(wX,{"data-slot":"select",...t})}function Si({...t}){return o.jsx(CX,{"data-slot":"select-value",...t})}function _i({className:t,size:e="default",children:n,...r}){return o.jsxs(kX,{"data-slot":"select-trigger","data-size":e,className:se("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r,children:[n,o.jsx(jX,{asChild:!0,children:o.jsx(ns,{className:"size-4 opacity-50"})})]})}function Ei({className:t,children:e,position:n="item-aligned",align:r="center",...s}){return o.jsx(NX,{children:o.jsxs(SX,{"data-slot":"select-content",className:se("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,align:r,...s,children:[o.jsx(mst,{}),o.jsx(_X,{className:se("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),o.jsx(pst,{})]})})}function nr({className:t,children:e,...n}){return o.jsxs(EX,{"data-slot":"select-item",className:se("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...n,children:[o.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:o.jsx(xke,{children:o.jsx($s,{className:"size-4"})})}),o.jsx(AX,{children:e})]})}function mst({className:t,...e}){return o.jsx(yke,{"data-slot":"select-scroll-up-button",className:se("flex cursor-default items-center justify-center py-1",t),...e,children:o.jsx(ySe,{className:"size-4"})})}function pst({className:t,...e}){return o.jsx(bke,{"data-slot":"select-scroll-down-button",className:se("flex cursor-default items-center justify-center py-1",t),...e,children:o.jsx(ns,{className:"size-4"})})}const gst=["coalesce_if_active","always_enqueue","skip_if_active"],xst=["skip_missed","enqueue_missed_with_cap"],yst={coalesce_if_active:"If a run is already active, keep just one follow-up run queued.",always_enqueue:"Queue every trigger occurrence, even if the routine is already running.",skip_if_active:"Drop new trigger occurrences while a run is still active."},bst={skip_missed:"Ignore windows that were missed while the scheduler or routine was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows in capped batches after recovery."};function LG(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)}function vst(t){return t?new Date(t).toLocaleString():"Never"}function wst(t,e){return t==="archived"&&e||e?"active":"paused"}function kst(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),n=hn(),r=As(),{pushToast:s}=Bo(),i=y.useRef(null),a=y.useRef(null),l=y.useRef(null),c=y.useRef(null),[u,f]=y.useState(null),[h,p]=y.useState(null),[g,b]=y.useState(!1),[v,w]=y.useState(!1),[j,C]=y.useState({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"});y.useEffect(()=>{e([{label:"Routines"}])},[e]);const{data:N,isLoading:S,error:T}=_e({queryKey:J.routines.list(t),queryFn:()=>Xo.list(t),enabled:!!t}),{data:_}=_e({queryKey:J.agents.list(t),queryFn:()=>Mt.list(t),enabled:!!t}),{data:A}=_e({queryKey:J.projects.list(t),queryFn:()=>vs.list(t),enabled:!!t});y.useEffect(()=>{LG(a.current)},[j.title,g]);const M=Xe({mutationFn:()=>Xo.create(t,{...j,description:j.description.trim()||null}),onSuccess:async z=>{C({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"}),b(!1),w(!1),await n.invalidateQueries({queryKey:J.routines.list(t)}),s({title:"Routine created",body:"Add the first trigger to turn it into a live workflow.",tone:"success"}),r(`/routines/${z.id}?tab=triggers`)}}),I=Xe({mutationFn:({id:z,status:V})=>Xo.update(z,{status:V}),onMutate:({id:z})=>{p(z)},onSuccess:async(z,V)=>{await Promise.all([n.invalidateQueries({queryKey:J.routines.list(t)}),n.invalidateQueries({queryKey:J.routines.detail(V.id)})])},onSettled:()=>{p(null)},onError:z=>{s({title:"Failed to update routine",body:z instanceof Error?z.message:"FideliOS could not update the routine.",tone:"error"})}}),L=Xe({mutationFn:z=>Xo.run(z),onMutate:z=>{f(z)},onSuccess:async(z,V)=>{await Promise.all([n.invalidateQueries({queryKey:J.routines.list(t)}),n.invalidateQueries({queryKey:J.routines.detail(V)})])},onSettled:()=>{f(null)},onError:z=>{s({title:"Routine run failed",body:z instanceof Error?z.message:"FideliOS could not start the routine run.",tone:"error"})}}),D=y.useMemo(()=>kw(),[g]),P=y.useMemo(()=>L_((_??[]).filter(z=>z.status!=="terminated"),D).map(z=>({id:z.id,label:z.name,searchText:`${z.name} ${z.role} ${z.title??""}`})),[_,D]),B=y.useMemo(()=>(A??[]).map(z=>({id:z.id,label:z.name,searchText:z.description??""})),[A]),Z=y.useMemo(()=>new Map((_??[]).map(z=>[z.id,z])),[_]),Q=y.useMemo(()=>new Map((A??[]).map(z=>[z.id,z])),[A]),q=j.assigneeAgentId?Z.get(j.assigneeAgentId)??null:null,O=j.projectId?Q.get(j.projectId)??null:null;return t?S?o.jsx(is,{variant:"issues-list"}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("h1",{className:"text-2xl font-semibold tracking-tight flex items-center gap-2",children:["Routines",o.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Beta"})]}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Recurring work definitions that materialize into auditable execution issues."})]}),o.jsxs(ue,{onClick:()=>b(!0),children:[o.jsx(Er,{className:"mr-2 h-4 w-4"}),"Create routine"]})]}),o.jsx(da,{open:g,onOpenChange:z=>{M.isPending||b(z)},children:o.jsxs(Ba,{showCloseButton:!1,className:"max-w-3xl gap-0 overflow-hidden p-0",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-border/60 px-5 py-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"New routine"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Define the recurring work first. Trigger setup comes next on the detail page."})]}),o.jsx(ue,{variant:"ghost",size:"sm",onClick:()=>{b(!1),w(!1)},disabled:M.isPending,children:"Cancel"})]}),o.jsx("div",{className:"px-5 pt-5 pb-3",children:o.jsx("textarea",{ref:a,className:"w-full resize-none overflow-hidden bg-transparent text-xl font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:j.title,onChange:z=>{C(V=>({...V,title:z.target.value})),LG(z.target)},onKeyDown:z=>{var V,$,G,W;if(z.key==="Enter"&&!z.metaKey&&!z.ctrlKey&&!z.nativeEvent.isComposing){z.preventDefault(),(V=i.current)==null||V.focus();return}z.key==="Tab"&&!z.shiftKey&&(z.preventDefault(),j.assigneeAgentId?j.projectId?($=i.current)==null||$.focus():(G=c.current)==null||G.focus():(W=l.current)==null||W.focus())},autoFocus:!0})}),o.jsx("div",{className:"px-5 pb-3",children:o.jsx("div",{className:"overflow-x-auto overscroll-x-contain",children:o.jsxs("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[o.jsx("span",{children:"For"}),o.jsx(kh,{ref:l,value:j.assigneeAgentId,options:P,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:z=>{z&&P_(z),C(V=>({...V,assigneeAgentId:z}))},onConfirm:()=>{var z,V;j.projectId?(z=i.current)==null||z.focus():(V=c.current)==null||V.focus()},renderTriggerValue:z=>z?q?o.jsxs(o.Fragment,{children:[o.jsx(Gi,{icon:q.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"truncate",children:z.label})]}):o.jsx("span",{className:"truncate",children:z.label}):o.jsx("span",{className:"text-muted-foreground",children:"Assignee"}),renderOption:z=>{if(!z.id)return o.jsx("span",{className:"truncate",children:z.label});const V=Z.get(z.id);return o.jsxs(o.Fragment,{children:[V?o.jsx(Gi,{icon:V.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:z.label})]})}}),o.jsx("span",{children:"in"}),o.jsx(kh,{ref:c,value:j.projectId,options:B,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:z=>C(V=>({...V,projectId:z})),onConfirm:()=>{var z;return(z=i.current)==null?void 0:z.focus()},renderTriggerValue:z=>z&&O?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:O.color??"#64748b"}}),o.jsx("span",{className:"truncate",children:z.label})]}):o.jsx("span",{className:"text-muted-foreground",children:"Project"}),renderOption:z=>{if(!z.id)return o.jsx("span",{className:"truncate",children:z.label});const V=Q.get(z.id);return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:(V==null?void 0:V.color)??"#64748b"}}),o.jsx("span",{className:"truncate",children:z.label})]})}})]})})}),o.jsx("div",{className:"border-t border-border/60 px-5 py-4",children:o.jsx(Ao,{ref:i,value:j.description,onChange:z=>C(V=>({...V,description:z})),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-[160px] text-sm text-muted-foreground",onSubmit:()=>{!M.isPending&&j.title.trim()&&j.projectId&&j.assigneeAgentId&&M.mutate()}})}),o.jsx("div",{className:"border-t border-border/60 px-5 py-3",children:o.jsxs(tm,{open:v,onOpenChange:w,children:[o.jsxs(nm,{className:"flex w-full items-center justify-between text-left",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium",children:"Advanced delivery settings"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Keep policy controls secondary to the work definition."})]}),v?o.jsx(ns,{className:"h-4 w-4 text-muted-foreground"}):o.jsx($r,{className:"h-4 w-4 text-muted-foreground"})]}),o.jsx(rm,{className:"pt-3",children:o.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Concurrency"}),o.jsxs(Ni,{value:j.concurrencyPolicy,onValueChange:z=>C(V=>({...V,concurrencyPolicy:z})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:gst.map(z=>o.jsx(nr,{value:z,children:z.replaceAll("_"," ")},z))})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:yst[j.concurrencyPolicy]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Catch-up"}),o.jsxs(Ni,{value:j.catchUpPolicy,onValueChange:z=>C(V=>({...V,catchUpPolicy:z})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:xst.map(z=>o.jsx(nr,{value:z,children:z.replaceAll("_"," ")},z))})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:bst[j.catchUpPolicy]})]})]})})]})}),o.jsxs("div",{className:"flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between",children:[o.jsx("div",{className:"text-sm text-muted-foreground",children:"After creation, FideliOS takes you straight to trigger setup for schedules, webhooks, or internal runs."}),o.jsxs("div",{className:"flex flex-col gap-2 sm:items-end",children:[o.jsxs(ue,{onClick:()=>M.mutate(),disabled:M.isPending||!j.title.trim()||!j.projectId||!j.assigneeAgentId,children:[o.jsx(Er,{className:"mr-2 h-4 w-4"}),M.isPending?"Creating...":"Create routine"]}),M.isError?o.jsx("p",{className:"text-sm text-destructive",children:M.error instanceof Error?M.error.message:"Failed to create routine"}):null]})]})]})}),T?o.jsx(ys,{children:o.jsx(bs,{className:"pt-6 text-sm text-destructive",children:T instanceof Error?T.message:"Failed to load routines"})}):null,o.jsx("div",{children:(N??[]).length===0?o.jsx("div",{className:"py-12",children:o.jsx(Ar,{icon:Wv,message:"No routines yet. Use Create routine to define the first recurring workflow."})}):o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"min-w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-left text-xs text-muted-foreground border-b border-border",children:[o.jsx("th",{className:"px-3 py-2 font-medium",children:"Name"}),o.jsx("th",{className:"px-3 py-2 font-medium",children:"Project"}),o.jsx("th",{className:"px-3 py-2 font-medium",children:"Agent"}),o.jsx("th",{className:"px-3 py-2 font-medium",children:"Last run"}),o.jsx("th",{className:"px-3 py-2 font-medium",children:"Enabled"}),o.jsx("th",{className:"w-12 px-3 py-2"})]})}),o.jsx("tbody",{children:(N??[]).map(z=>{var W,F,le;const V=z.status==="active",$=z.status==="archived",G=h===z.id;return o.jsxs("tr",{className:"align-middle border-b border-border transition-colors hover:bg-accent/50 last:border-b-0 cursor-pointer",onClick:()=>r(`/routines/${z.id}`),children:[o.jsx("td",{className:"px-3 py-2.5",children:o.jsxs("div",{className:"min-w-[180px]",children:[o.jsx("span",{className:"font-medium",children:z.title}),($||z.status==="paused")&&o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:$?"archived":"paused"})]})}),o.jsx("td",{className:"px-3 py-2.5",children:z.projectId?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[o.jsx("span",{className:"shrink-0 h-3 w-3 rounded-sm",style:{backgroundColor:((W=Q.get(z.projectId))==null?void 0:W.color)??"#6366f1"}}),o.jsx("span",{className:"truncate",children:((F=Q.get(z.projectId))==null?void 0:F.name)??"Unknown"})]}):o.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),o.jsx("td",{className:"px-3 py-2.5",children:z.assigneeAgentId?(()=>{const ie=Z.get(z.assigneeAgentId);return ie?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[o.jsx(Gi,{icon:ie.icon,className:"h-4 w-4 shrink-0"}),o.jsx("span",{className:"truncate",children:ie.name})]}):o.jsx("span",{className:"text-xs text-muted-foreground",children:"Unknown"})})():o.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),o.jsxs("td",{className:"px-3 py-2.5 text-muted-foreground",children:[o.jsx("div",{children:vst((le=z.lastRun)==null?void 0:le.triggeredAt)}),z.lastRun?o.jsx("div",{className:"mt-1 text-xs",children:z.lastRun.status.replaceAll("_"," ")}):null]}),o.jsx("td",{className:"px-3 py-2.5",onClick:ie=>ie.stopPropagation(),children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":V,"aria-label":V?`Disable ${z.title}`:`Enable ${z.title}`,disabled:G||$,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${V?"bg-foreground":"bg-muted"} ${G||$?"cursor-not-allowed opacity-50":""}`,onClick:()=>I.mutate({id:z.id,status:wst(z.status,!V)}),children:o.jsx("span",{className:`inline-block h-5 w-5 rounded-full bg-background shadow-sm transition-transform ${V?"translate-x-5":"translate-x-0.5"}`})}),o.jsx("span",{className:"text-xs text-muted-foreground",children:$?"Archived":V?"On":"Off"})]})}),o.jsx("td",{className:"px-3 py-2.5 text-right",onClick:ie=>ie.stopPropagation(),children:o.jsxs(L5,{children:[o.jsx($5,{asChild:!0,children:o.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":`More actions for ${z.title}`,children:o.jsx(t0,{className:"h-4 w-4"})})}),o.jsxs(F5,{align:"end",children:[o.jsx(Xl,{onClick:()=>r(`/routines/${z.id}`),children:"Edit"}),o.jsx(Xl,{disabled:u===z.id||$,onClick:()=>L.mutate(z.id),children:u===z.id?"Running...":"Run now"}),o.jsx(B5,{}),o.jsx(Xl,{onClick:()=>I.mutate({id:z.id,status:V?"paused":"active"}),disabled:G||$,children:V?"Pause":"Enable"}),o.jsx(Xl,{onClick:()=>I.mutate({id:z.id,status:z.status==="archived"?"active":"archived"}),disabled:G,children:z.status==="archived"?"Restore":"Archive"})]})]})})]},z.id)})})]})})})]}):o.jsx(Ar,{icon:Wv,message:"Select a company to view routines."})}function Cst(t,e,n){const r={label:e.label.trim()||null};return t.kind==="schedule"&&(r.cronExpression=e.cronExpression.trim(),r.timezone=t.timezone??n),t.kind==="webhook"&&(r.signingMode=e.signingMode,r.replayWindowSec=Number(e.replayWindowSec||"300")),r}const jst=[{value:"every_minute",label:"Every minute"},{value:"every_hour",label:"Every hour"},{value:"every_day",label:"Every day"},{value:"weekdays",label:"Weekdays"},{value:"weekly",label:"Weekly"},{value:"monthly",label:"Monthly"},{value:"custom",label:"Custom (cron)"}],Nst=Array.from({length:24},(t,e)=>({value:String(e),label:e===0?"12 AM":e<12?`${e} AM`:e===12?"12 PM":`${e-12} PM`})),$G=Array.from({length:12},(t,e)=>({value:String(e*5),label:String(e*5).padStart(2,"0")})),Sst=[{value:"1",label:"Mon"},{value:"2",label:"Tue"},{value:"3",label:"Wed"},{value:"4",label:"Thu"},{value:"5",label:"Fri"},{value:"6",label:"Sat"},{value:"0",label:"Sun"}],_st=Array.from({length:31},(t,e)=>({value:String(e+1),label:String(e+1)}));function FG(t){const e={hour:"10",minute:"0",dayOfWeek:"1",dayOfMonth:"1"};if(!t||!t.trim())return{preset:"every_day",...e};const n=t.trim().split(/\s+/);if(n.length!==5)return{preset:"custom",...e};const[r,s,i,,a]=n;return r==="*"&&s==="*"&&i==="*"&&a==="*"?{preset:"every_minute",...e}:s==="*"&&i==="*"&&a==="*"?{preset:"every_hour",...e,minute:r==="*"?"0":r}:i==="*"&&a==="*"&&s!=="*"?{preset:"every_day",...e,hour:s,minute:r==="*"?"0":r}:i==="*"&&a==="1-5"&&s!=="*"?{preset:"weekdays",...e,hour:s,minute:r==="*"?"0":r}:i==="*"&&/^\d$/.test(a)&&s!=="*"?{preset:"weekly",...e,hour:s,minute:r==="*"?"0":r,dayOfWeek:a}:/^\d{1,2}$/.test(i)&&a==="*"&&s!=="*"?{preset:"monthly",...e,hour:s,minute:r==="*"?"0":r,dayOfMonth:i}:{preset:"custom",...e}}function Est(t,e,n,r,s){switch(t){case"every_minute":return"* * * * *";case"every_hour":return`${n} * * * *`;case"every_day":return`${n} ${e} * * *`;case"weekdays":return`${n} ${e} * * 1-5`;case"weekly":return`${n} ${e} * * ${r}`;case"monthly":return`${n} ${e} ${s} * *`;case"custom":return""}}function khe({value:t,onChange:e}){const n=y.useMemo(()=>FG(t),[t]),[r,s]=y.useState(n.preset),[i,a]=y.useState(n.hour),[l,c]=y.useState(n.minute),[u,f]=y.useState(n.dayOfWeek),[h,p]=y.useState(n.dayOfMonth),[g,b]=y.useState(r==="custom"?t:"");y.useEffect(()=>{const j=FG(t);s(j.preset),a(j.hour),c(j.minute),f(j.dayOfWeek),p(j.dayOfMonth),j.preset==="custom"&&b(t)},[t]);const v=y.useCallback((j,C,N,S,T,_)=>{e(j==="custom"?_:Est(j,C,N,S,T))},[e]),w=j=>{s(j),j==="custom"?b(t):v(j,i,l,u,h,g)};return o.jsxs("div",{className:"space-y-3",children:[o.jsxs(Ni,{value:r,onValueChange:j=>w(j),children:[o.jsx(_i,{className:"w-full",children:o.jsx(Si,{placeholder:"Choose frequency..."})}),o.jsx(Ei,{children:jst.map(j=>o.jsx(nr,{value:j.value,children:j.label},j.value))})]}),r==="custom"?o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(_r,{value:g,onChange:j=>{b(j.target.value),v("custom",i,l,u,h,j.target.value)},placeholder:"0 10 * * *",className:"font-mono text-sm"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Five fields: minute hour day-of-month month day-of-week"})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r!=="every_minute"&&r!=="every_hour"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"at"}),o.jsxs(Ni,{value:i,onValueChange:j=>{a(j),v(r,j,l,u,h,g)},children:[o.jsx(_i,{className:"w-[120px]",children:o.jsx(Si,{})}),o.jsx(Ei,{children:Nst.map(j=>o.jsx(nr,{value:j.value,children:j.label},j.value))})]}),o.jsx("span",{className:"text-sm text-muted-foreground",children:":"}),o.jsxs(Ni,{value:l,onValueChange:j=>{c(j),v(r,i,j,u,h,g)},children:[o.jsx(_i,{className:"w-[80px]",children:o.jsx(Si,{})}),o.jsx(Ei,{children:$G.map(j=>o.jsx(nr,{value:j.value,children:j.label},j.value))})]})]}),r==="every_hour"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"at minute"}),o.jsxs(Ni,{value:l,onValueChange:j=>{c(j),v(r,i,j,u,h,g)},children:[o.jsx(_i,{className:"w-[80px]",children:o.jsx(Si,{})}),o.jsx(Ei,{children:$G.map(j=>o.jsxs(nr,{value:j.value,children:[":",j.label]},j.value))})]})]}),r==="weekly"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"on"}),o.jsx("div",{className:"flex gap-1",children:Sst.map(j=>o.jsx(ue,{type:"button",variant:u===j.value?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{f(j.value),v(r,i,l,j.value,h,g)},children:j.label},j.value))})]}),r==="monthly"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"on day"}),o.jsxs(Ni,{value:h,onValueChange:j=>{p(j),v(r,i,l,u,j,g)},children:[o.jsx(_i,{className:"w-[80px]",children:o.jsx(Si,{})}),o.jsx(Ei,{children:_st.map(j=>o.jsx(nr,{value:j.value,children:j.label},j.value))})]})]})]})]})}function Ls({className:t,...e}){return o.jsx(jwe,{"data-slot":"label",className:se("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...e})}const Ast=XO("inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",ghost:"[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",link:"text-primary underline-offset-4 [a&]:hover:underline"}},defaultVariants:{variant:"default"}});function vr({className:t,variant:e="default",asChild:n=!1,...r}){const s=n?eD:"span";return o.jsx(s,{"data-slot":"badge","data-variant":e,className:se(Ast({variant:e}),t),...r})}const Tst=["coalesce_if_active","always_enqueue","skip_if_active"],Mst=["skip_missed","enqueue_missed_with_cap"],Ist=["schedule","webhook"],Che=["bearer","hmac_sha256"],Rst=["triggers","runs","activity"],Ost={coalesce_if_active:"Keep one follow-up run queued while an active run is still working.",always_enqueue:"Queue every trigger occurrence, even if several runs stack up.",skip_if_active:"Drop overlapping trigger occurrences while the routine is already active."},Dst={skip_missed:"Ignore schedule windows that were missed while the routine or scheduler was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows in capped batches after recovery."},Pst={bearer:"Expect a shared bearer token in the Authorization header.",hmac_sha256:"Expect an HMAC SHA-256 signature over the request using the shared secret."};function BG(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)}function jhe(t){return t!==null&&Rst.includes(t)}function Lst(t){const e=new URLSearchParams(t).get("tab");return jhe(e)?e:"triggers"}function Nhe(t){if(t===null)return"null";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":t.map(e=>Nhe(e)).join(", ");try{return JSON.stringify(t)}catch{return"[unserializable]"}}function She(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function $st({trigger:t,onSave:e,onRotate:n,onDelete:r}){const[s,i]=y.useState({label:t.label??"",cronExpression:t.cronExpression??"",signingMode:t.signingMode??"bearer",replayWindowSec:String(t.replayWindowSec??300)});return y.useEffect(()=>{i({label:t.label??"",cronExpression:t.cronExpression??"",signingMode:t.signingMode??"bearer",replayWindowSec:String(t.replayWindowSec??300)})},[t]),o.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[t.kind==="schedule"?o.jsx(w_,{className:"h-3.5 w-3.5"}):t.kind==="webhook"?o.jsx(vte,{className:"h-3.5 w-3.5"}):o.jsx(qj,{className:"h-3.5 w-3.5"}),t.label??t.kind]}),o.jsx("span",{className:"text-xs text-muted-foreground",children:t.kind==="schedule"&&t.nextRunAt?`Next: ${new Date(t.nextRunAt).toLocaleString()}`:t.kind==="webhook"?"Webhook":"API"})]}),o.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Label"}),o.jsx(_r,{value:s.label,onChange:a=>i(l=>({...l,label:a.target.value}))})]}),t.kind==="schedule"&&o.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Schedule"}),o.jsx(khe,{value:s.cronExpression,onChange:a=>i(l=>({...l,cronExpression:a}))})]}),t.kind==="webhook"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Signing mode"}),o.jsxs(Ni,{value:s.signingMode,onValueChange:a=>i(l=>({...l,signingMode:a})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:Che.map(a=>o.jsx(nr,{value:a,children:a},a))})]})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Replay window (seconds)"}),o.jsx(_r,{value:s.replayWindowSec,onChange:a=>i(l=>({...l,replayWindowSec:a.target.value}))})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.lastResult&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last: ",t.lastResult]}),o.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[t.kind==="webhook"&&o.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>n(t.id),children:[o.jsx(Kv,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),o.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>e(t.id,Cst(t,s,She())),children:[o.jsx(g6,{className:"mr-1.5 h-3.5 w-3.5"}),"Save"]}),o.jsx(ue,{variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-destructive",onClick:()=>r(t.id),children:o.jsx(Fa,{className:"h-3.5 w-3.5"})})]})]})]})}function Fst(){var H;const{routineId:t}=Zi(),{selectedCompanyId:e}=Xt(),{setBreadcrumbs:n}=yr(),r=hn(),s=As(),i=er(),{pushToast:a}=Bo(),l=y.useRef(null),c=y.useRef(null),u=y.useRef(null),f=y.useRef(null),h=y.useRef(null),[p,g]=y.useState(null),[b,v]=y.useState(!1),[w,j]=y.useState({kind:"schedule",cronExpression:"0 10 * * *",signingMode:"bearer",replayWindowSec:"300"}),[C,N]=y.useState({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed"}),S=y.useMemo(()=>Lst(i.search),[i.search]),{data:T,isLoading:_,error:A}=_e({queryKey:J.routines.detail(t),queryFn:()=>Xo.get(t),enabled:!!t}),M=(H=T==null?void 0:T.activeIssue)==null?void 0:H.id,{data:I}=_e({queryKey:J.issues.liveRuns(M),queryFn:()=>qr.liveRunsForIssue(M),enabled:!!M,refetchInterval:3e3}),L=(I??[]).length>0,{data:D}=_e({queryKey:J.routines.runs(t),queryFn:()=>Xo.listRuns(t),enabled:!!t,refetchInterval:L?3e3:!1}),P=y.useMemo(()=>({triggerIds:(T==null?void 0:T.triggers.map(U=>U.id))??[],runIds:(D==null?void 0:D.map(U=>U.id))??[]}),[T==null?void 0:T.triggers,D]),{data:B}=_e({queryKey:[...J.routines.activity(e,t),P.triggerIds.join(","),P.runIds.join(",")],queryFn:()=>Xo.activity(e,t,P),enabled:!!e&&!!t&&!!T}),{data:Z}=_e({queryKey:J.agents.list(e),queryFn:()=>Mt.list(e),enabled:!!e}),{data:Q}=_e({queryKey:J.projects.list(e),queryFn:()=>vs.list(e),enabled:!!e}),q=y.useMemo(()=>T?{title:T.title,description:T.description??"",projectId:T.projectId,assigneeAgentId:T.assigneeAgentId,priority:T.priority,concurrencyPolicy:T.concurrencyPolicy,catchUpPolicy:T.catchUpPolicy}:null,[T]),O=y.useMemo(()=>q?C.title!==q.title||C.description!==q.description||C.projectId!==q.projectId||C.assigneeAgentId!==q.assigneeAgentId||C.priority!==q.priority||C.concurrencyPolicy!==q.concurrencyPolicy||C.catchUpPolicy!==q.catchUpPolicy:!1,[C,q]);y.useEffect(()=>{if(!T||(n([{label:"Routines",href:"/routines"},{label:T.title}]),!q))return;(l.current!==T.id||!O)&&(N(q),l.current=T.id)},[T,q,O,n]),y.useEffect(()=>{BG(c.current)},[C.title,T==null?void 0:T.id]);const z=async(U,me)=>{try{await navigator.clipboard.writeText(me),a({title:`${U} copied`,tone:"success"})}catch(oe){a({title:`Failed to copy ${U.toLowerCase()}`,body:oe instanceof Error?oe.message:"Clipboard access was denied.",tone:"error"})}},V=U=>{if(!t||!jhe(U))return;const me=new URLSearchParams(i.search);U==="triggers"?me.delete("tab"):me.set("tab",U);const oe=me.toString();s({pathname:i.pathname,search:oe?`?${oe}`:""},{replace:!0})},$=Xe({mutationFn:()=>Xo.update(t,{...C,description:C.description.trim()||null}),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.list(e)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Failed to save routine",body:U instanceof Error?U.message:"FideliOS could not save the routine.",tone:"error"})}}),G=Xe({mutationFn:()=>Xo.run(t),onSuccess:async()=>{a({title:"Routine run started",tone:"success"}),V("runs"),await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.runs(t)}),r.invalidateQueries({queryKey:J.routines.list(e)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Routine run failed",body:U instanceof Error?U.message:"FideliOS could not start the routine run.",tone:"error"})}}),W=Xe({mutationFn:U=>Xo.update(t,{status:U}),onSuccess:async(U,me)=>{a({title:"Routine saved",body:me==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.list(e)})])},onError:U=>{a({title:"Failed to update routine",body:U instanceof Error?U.message:"FideliOS could not update the routine.",tone:"error"})}}),F=Xe({mutationFn:async()=>{const U=((T==null?void 0:T.triggers)??[]).filter(oe=>oe.kind===w.kind).length,me=U>0?`${w.kind}-${U+1}`:w.kind;return Xo.createTrigger(t,{kind:w.kind,label:me,...w.kind==="schedule"?{cronExpression:w.cronExpression.trim(),timezone:She()}:{},...w.kind==="webhook"?{signingMode:w.signingMode,replayWindowSec:Number(w.replayWindowSec||"300")}:{}})},onSuccess:async U=>{U.secretMaterial&&g({title:"Webhook trigger created",webhookUrl:U.secretMaterial.webhookUrl,webhookSecret:U.secretMaterial.webhookSecret}),await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.list(e)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Failed to add trigger",body:U instanceof Error?U.message:"FideliOS could not create the trigger.",tone:"error"})}}),le=Xe({mutationFn:({id:U,patch:me})=>Xo.updateTrigger(U,me),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.list(e)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Failed to update trigger",body:U instanceof Error?U.message:"FideliOS could not update the trigger.",tone:"error"})}}),ie=Xe({mutationFn:U=>Xo.deleteTrigger(U),onSuccess:async()=>{await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.list(e)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Failed to delete trigger",body:U instanceof Error?U.message:"FideliOS could not delete the trigger.",tone:"error"})}}),ne=Xe({mutationFn:U=>Xo.rotateTriggerSecret(U),onSuccess:async U=>{g({title:"Webhook secret rotated",webhookUrl:U.secretMaterial.webhookUrl,webhookSecret:U.secretMaterial.webhookSecret}),await Promise.all([r.invalidateQueries({queryKey:J.routines.detail(t)}),r.invalidateQueries({queryKey:J.routines.activity(e,t)})])},onError:U=>{a({title:"Failed to rotate webhook secret",body:U instanceof Error?U.message:"FideliOS could not rotate the webhook secret.",tone:"error"})}}),X=y.useMemo(()=>new Map((Z??[]).map(U=>[U.id,U])),[Z]),ee=y.useMemo(()=>new Map((Q??[]).map(U=>[U.id,U])),[Q]),de=y.useMemo(()=>kw(),[T==null?void 0:T.id]),ve=y.useMemo(()=>L_((Z??[]).filter(U=>U.status!=="terminated"),de).map(U=>({id:U.id,label:U.name,searchText:`${U.name} ${U.role} ${U.title??""}`})),[Z,de]),Te=y.useMemo(()=>(Q??[]).map(U=>({id:U.id,label:U.name,searchText:U.description??""})),[Q]),Fe=C.assigneeAgentId?X.get(C.assigneeAgentId)??null:null,Ee=C.projectId?ee.get(C.projectId)??null:null;if(!e)return o.jsx(Ar,{icon:Wv,message:"Select a company to view routines."});if(_)return o.jsx(is,{variant:"issues-list"});if(A||!T)return o.jsx("p",{className:"pt-6 text-sm text-destructive",children:A instanceof Error?A.message:"Routine not found"});const tt=T.status==="active",ot=W.isPending||T.status==="archived",Ie=T.status==="archived"?"Archived":tt?"Active":"Paused",rt=T.status==="archived"?"text-muted-foreground":tt?"text-emerald-400":"text-muted-foreground";return o.jsxs("div",{className:"max-w-2xl space-y-6",children:[o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("textarea",{ref:c,className:"flex-1 min-w-0 resize-none overflow-hidden bg-transparent text-xl font-bold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:C.title,onChange:U=>{N(me=>({...me,title:U.target.value})),BG(U.target)},onKeyDown:U=>{var me,oe,pe,Ne;if(U.key==="Enter"&&!U.metaKey&&!U.ctrlKey&&!U.nativeEvent.isComposing){U.preventDefault(),(me=u.current)==null||me.focus();return}U.key==="Tab"&&!U.shiftKey&&(U.preventDefault(),C.assigneeAgentId?C.projectId?(oe=u.current)==null||oe.focus():(pe=h.current)==null||pe.focus():(Ne=f.current)==null||Ne.focus())}}),o.jsxs("div",{className:"flex shrink-0 items-center gap-3 pt-1",children:[o.jsx(rhe,{onClick:()=>G.mutate(),disabled:G.isPending}),o.jsx("button",{type:"button",role:"switch","data-slot":"toggle","aria-checked":tt,"aria-label":tt?"Pause automatic triggers":"Enable automatic triggers",disabled:ot,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${tt?"bg-emerald-500":"bg-muted"} ${ot?"cursor-not-allowed opacity-50":""}`,onClick:()=>W.mutate(tt?"paused":"active"),children:o.jsx("span",{className:`inline-block h-5 w-5 rounded-full bg-background shadow-sm transition-transform ${tt?"translate-x-5":"translate-x-0.5"}`})}),o.jsx("span",{className:`min-w-[3.75rem] text-sm font-medium ${rt}`,children:Ie})]})]}),p&&o.jsxs("div",{className:"rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 space-y-3 text-sm",children:[o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:p.title}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Save this now. FideliOS will not show the secret value again."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_r,{value:p.webhookUrl,readOnly:!0,className:"flex-1"}),o.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>z("Webhook URL",p.webhookUrl),children:[o.jsx(uc,{className:"h-3.5 w-3.5 mr-1"}),"URL"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_r,{value:p.webhookSecret,readOnly:!0,className:"flex-1"}),o.jsxs(ue,{variant:"outline",size:"sm",onClick:()=>z("Webhook secret",p.webhookSecret),children:[o.jsx(uc,{className:"h-3.5 w-3.5 mr-1"}),"Secret"]})]})]})]}),o.jsx("div",{className:"overflow-x-auto overscroll-x-contain",children:o.jsxs("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[o.jsx("span",{children:"For"}),o.jsx(kh,{ref:f,value:C.assigneeAgentId,options:ve,placeholder:"Assignee",noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",onChange:U=>{U&&P_(U),N(me=>({...me,assigneeAgentId:U}))},onConfirm:()=>{var U,me;C.projectId?(U=u.current)==null||U.focus():(me=h.current)==null||me.focus()},renderTriggerValue:U=>U?Fe?o.jsxs(o.Fragment,{children:[o.jsx(Gi,{icon:Fe.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"truncate",children:U.label})]}):o.jsx("span",{className:"truncate",children:U.label}):o.jsx("span",{className:"text-muted-foreground",children:"Assignee"}),renderOption:U=>{if(!U.id)return o.jsx("span",{className:"truncate",children:U.label});const me=X.get(U.id);return o.jsxs(o.Fragment,{children:[me?o.jsx(Gi,{icon:me.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,o.jsx("span",{className:"truncate",children:U.label})]})}}),o.jsx("span",{children:"in"}),o.jsx(kh,{ref:h,value:C.projectId,options:Te,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:U=>N(me=>({...me,projectId:U})),onConfirm:()=>{var U;return(U=u.current)==null?void 0:U.focus()},renderTriggerValue:U=>U&&Ee?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:Ee.color??"#64748b"}}),o.jsx("span",{className:"truncate",children:U.label})]}):o.jsx("span",{className:"text-muted-foreground",children:"Project"}),renderOption:U=>{if(!U.id)return o.jsx("span",{className:"truncate",children:U.label});const me=ee.get(U.id);return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:(me==null?void 0:me.color)??"#64748b"}}),o.jsx("span",{className:"truncate",children:U.label})]})}})]})}),o.jsx(Ao,{ref:u,value:C.description,onChange:U=>N(me=>({...me,description:U})),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-[120px] text-[15px] leading-7",onSubmit:()=>{!$.isPending&&C.title.trim()&&C.projectId&&C.assigneeAgentId&&$.mutate()}}),o.jsxs(tm,{open:b,onOpenChange:v,children:[o.jsxs(nm,{className:"flex w-full items-center justify-between text-left",children:[o.jsx("span",{className:"text-sm font-medium",children:"Advanced delivery settings"}),b?o.jsx(ns,{className:"h-4 w-4 text-muted-foreground"}):o.jsx($r,{className:"h-4 w-4 text-muted-foreground"})]}),o.jsx(rm,{className:"pt-3",children:o.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Concurrency"}),o.jsxs(Ni,{value:C.concurrencyPolicy,onValueChange:U=>N(me=>({...me,concurrencyPolicy:U})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:Tst.map(U=>o.jsx(nr,{value:U,children:U.replaceAll("_"," ")},U))})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:Ost[C.concurrencyPolicy]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground",children:"Catch-up"}),o.jsxs(Ni,{value:C.catchUpPolicy,onValueChange:U=>N(me=>({...me,catchUpPolicy:U})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:Mst.map(U=>o.jsx(nr,{value:U,children:U.replaceAll("_"," ")},U))})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:Dst[C.catchUpPolicy]})]})]})})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[O?o.jsx("span",{className:"text-xs text-amber-600",children:"Unsaved changes"}):o.jsx("span",{}),o.jsxs(ue,{onClick:()=>$.mutate(),disabled:$.isPending||!C.title.trim()||!C.projectId||!C.assigneeAgentId,children:[o.jsx(g6,{className:"mr-2 h-4 w-4"}),"Save routine"]})]}),o.jsx(Ro,{}),o.jsxs(ha,{value:S,onValueChange:V,className:"space-y-3",children:[o.jsxs(tg,{variant:"line",className:"w-full justify-start gap-1",children:[o.jsxs(_s,{value:"triggers",className:"gap-1.5",children:[o.jsx(w_,{className:"h-3.5 w-3.5"}),"Triggers"]}),o.jsxs(_s,{value:"runs",className:"gap-1.5",children:[o.jsx(p6,{className:"h-3.5 w-3.5"}),"Runs",L&&o.jsx("span",{className:"h-2 w-2 rounded-full bg-blue-500 animate-pulse"})]}),o.jsxs(_s,{value:"activity",className:"gap-1.5",children:[o.jsx(ote,{className:"h-3.5 w-3.5"}),"Activity"]})]}),o.jsxs(Vr,{value:"triggers",className:"space-y-4",children:[o.jsxs("div",{className:"rounded-lg border border-border p-4 space-y-3",children:[o.jsx("p",{className:"text-sm font-medium",children:"Add trigger"}),o.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Kind"}),o.jsxs(Ni,{value:w.kind,onValueChange:U=>j(me=>({...me,kind:U})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:Ist.map(U=>o.jsxs(nr,{value:U,disabled:U==="webhook",children:[U,U==="webhook"?" — COMING SOON":""]},U))})]})]}),w.kind==="schedule"&&o.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Schedule"}),o.jsx(khe,{value:w.cronExpression,onChange:U=>j(me=>({...me,cronExpression:U}))})]}),w.kind==="webhook"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Signing mode"}),o.jsxs(Ni,{value:w.signingMode,onValueChange:U=>j(me=>({...me,signingMode:U})),children:[o.jsx(_i,{children:o.jsx(Si,{})}),o.jsx(Ei,{children:Che.map(U=>o.jsx(nr,{value:U,children:U},U))})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:Pst[w.signingMode]})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ls,{className:"text-xs",children:"Replay window (seconds)"}),o.jsx(_r,{value:w.replayWindowSec,onChange:U=>j(me=>({...me,replayWindowSec:U.target.value}))})]})]})]}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ue,{size:"sm",onClick:()=>F.mutate(),disabled:F.isPending,children:F.isPending?"Adding...":"Add trigger"})})]}),T.triggers.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No triggers configured yet."}):o.jsx("div",{className:"space-y-3",children:T.triggers.map(U=>o.jsx($st,{trigger:U,onSave:(me,oe)=>le.mutate({id:me,patch:oe}),onRotate:me=>ne.mutate(me),onDelete:me=>ie.mutate(me)},U.id))})]}),o.jsxs(Vr,{value:"runs",className:"space-y-4",children:[L&&M&&T&&o.jsx(xhe,{issueId:M,companyId:T.companyId}),(D??[]).length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No runs yet."}):o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:(D??[]).map(U=>o.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(vr,{variant:"outline",className:"shrink-0",children:U.source}),o.jsx(vr,{variant:U.status==="failed"?"destructive":"secondary",className:"shrink-0",children:U.status.replaceAll("_"," ")}),U.trigger&&o.jsx("span",{className:"text-muted-foreground truncate",children:U.trigger.label??U.trigger.kind}),U.linkedIssue&&o.jsx(jt,{to:`/issues/${U.linkedIssue.identifier??U.linkedIssue.id}`,className:"text-muted-foreground hover:underline truncate",children:U.linkedIssue.identifier??U.linkedIssue.id.slice(0,8)})]}),o.jsx("span",{className:"text-xs text-muted-foreground shrink-0 ml-2",children:ca(U.triggeredAt)})]},U.id))})]}),o.jsx(Vr,{value:"activity",children:(B??[]).length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):o.jsx("div",{className:"border border-border rounded-lg divide-y divide-border",children:(B??[]).map(U=>o.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-xs gap-4",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium text-foreground/90 shrink-0",children:U.action.replaceAll("."," ")}),U.details&&Object.keys(U.details).length>0&&o.jsx("span",{className:"text-muted-foreground truncate",children:Object.entries(U.details).slice(0,3).map(([me,oe],pe)=>o.jsxs("span",{children:[pe>0&&o.jsx("span",{className:"mx-1 text-border",children:"·"}),o.jsxs("span",{className:"text-muted-foreground/70",children:[me.replaceAll("_"," "),":"]})," ",Nhe(oe)]},me))})]}),o.jsx("span",{className:"text-muted-foreground/60 shrink-0",children:ca(U.createdAt)})]},U.id))})})]})]})}function Bst(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function Rc({label:t,children:e}){return o.jsxs("div",{className:"flex items-start gap-3 py-1.5",children:[o.jsx("div",{className:"w-28 shrink-0 text-xs text-muted-foreground",children:t}),o.jsx("div",{className:"min-w-0 flex-1 text-sm",children:e})]})}function zst(){const{workspaceId:t}=Zi(),{data:e,isLoading:n,error:r}=_e({queryKey:J.executionWorkspaces.detail(t),queryFn:()=>z6.get(t),enabled:!!t});return n?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):r?o.jsx("p",{className:"text-sm text-destructive",children:r instanceof Error?r.message:"Failed to load workspace"}):e?o.jsxs("div",{className:"max-w-2xl space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"Execution workspace"}),o.jsx("h1",{className:"text-2xl font-semibold",children:e.name}),o.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.status," · ",e.mode," · ",e.providerType]})]}),o.jsxs("div",{className:"rounded-lg border border-border p-4",children:[o.jsx(Rc,{label:"Project",children:e.projectId?o.jsx(jt,{to:`/projects/${e.projectId}`,className:"hover:underline",children:e.projectId}):"None"}),o.jsx(Rc,{label:"Source issue",children:e.sourceIssueId?o.jsx(jt,{to:`/issues/${e.sourceIssueId}`,className:"hover:underline",children:e.sourceIssueId}):"None"}),o.jsx(Rc,{label:"Branch",children:e.branchName??"None"}),o.jsx(Rc,{label:"Base ref",children:e.baseRef??"None"}),o.jsx(Rc,{label:"Working dir",children:o.jsx("span",{className:"break-all font-mono text-xs",children:e.cwd??"None"})}),o.jsx(Rc,{label:"Provider ref",children:o.jsx("span",{className:"break-all font-mono text-xs",children:e.providerRef??"None"})}),o.jsx(Rc,{label:"Repo URL",children:e.repoUrl&&Bst(e.repoUrl)?o.jsxs("a",{href:e.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[e.repoUrl,o.jsx(Md,{className:"h-3 w-3"})]}):e.repoUrl?o.jsx("span",{className:"break-all font-mono text-xs",children:e.repoUrl}):"None"}),o.jsx(Rc,{label:"Opened",children:new Date(e.openedAt).toLocaleString()}),o.jsx(Rc,{label:"Last used",children:new Date(e.lastUsedAt).toLocaleString()}),o.jsx(Rc,{label:"Cleanup",children:e.cleanupEligibleAt?`${new Date(e.cleanupEligibleAt).toLocaleString()}${e.cleanupReason?` · ${e.cleanupReason}`:""}`:"Not scheduled"})]})]}):null}function _he({goal:t,children:e,allGoals:n,depth:r,goalLink:s,onSelect:i}){const[a,l]=y.useState(!0),c=e.length>0,u=s==null?void 0:s(t),f=o.jsxs(o.Fragment,{children:[c?o.jsx("button",{className:"p-0.5",onClick:p=>{p.preventDefault(),p.stopPropagation(),l(!a)},children:o.jsx($r,{className:se("h-3 w-3 transition-transform",a&&"rotate-90")})}):o.jsx("span",{className:"w-4"}),o.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:t.level}),o.jsx("span",{className:"flex-1 truncate",children:t.title}),o.jsx(sr,{status:t.status})]}),h=se("flex items-center gap-2 px-3 py-1.5 text-sm transition-colors cursor-pointer hover:bg-accent/50");return o.jsxs("div",{children:[u?o.jsx(jt,{to:u,className:se(h,"no-underline text-inherit"),style:{paddingLeft:`${r*16+12}px`},children:f}):o.jsx("div",{className:h,style:{paddingLeft:`${r*16+12}px`},onClick:()=>i==null?void 0:i(t),children:f}),c&&a&&o.jsx("div",{children:e.map(p=>o.jsx(_he,{goal:p,children:n.filter(g=>g.parentId===p.id),allGoals:n,depth:r+1,goalLink:s,onSelect:i},p.id))})]})}function Ehe({goals:t,goalLink:e,onSelect:n}){const r=new Set(t.map(i=>i.id)),s=t.filter(i=>!i.parentId||!r.has(i.parentId));return t.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No goals."}):o.jsx("div",{className:"border border-border py-1",children:s.map(i=>o.jsx(_he,{goal:i,children:t.filter(a=>a.parentId===i.id),allGoals:t,depth:0,goalLink:e,onSelect:n},i.id))})}function Ust(){const{selectedCompanyId:t}=Xt(),{openNewGoal:e}=Ts(),{setBreadcrumbs:n}=yr();y.useEffect(()=>{n([{label:"Goals"}])},[n]);const{data:r,isLoading:s,error:i}=_e({queryKey:J.goals.list(t),queryFn:()=>jl.list(t),enabled:!!t});return t?s?o.jsx(is,{variant:"list"}):o.jsxs("div",{className:"space-y-4",children:[i&&o.jsx("p",{className:"text-sm text-destructive",children:i.message}),r&&r.length===0&&o.jsx(Ar,{icon:uu,message:"No goals yet.",action:"Add Goal",onAction:()=>e()}),r&&r.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"flex items-center justify-start",children:o.jsxs(ue,{size:"sm",variant:"outline",onClick:()=>e(),children:[o.jsx(Er,{className:"h-3.5 w-3.5 mr-1.5"}),"New Goal"]})}),o.jsx(Ehe,{goals:r,goalLink:a=>`/goals/${a.id}`})]})]}):o.jsx(Ar,{icon:uu,message:"Select a company to view goals."})}function hx({label:t,children:e}){return o.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:t}),o.jsx("div",{className:"flex items-center gap-1.5 min-w-0",children:e})]})}function Vst(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function zG({current:t,options:e,onChange:n,children:r}){const[s,i]=y.useState(!1);return o.jsxs(wr,{open:s,onOpenChange:i,children:[o.jsx(kr,{asChild:!0,children:o.jsx("button",{className:"cursor-pointer hover:opacity-80 transition-opacity",children:r})}),o.jsx(Cr,{className:"w-40 p-1",align:"end",children:e.map(a=>o.jsx(ue,{variant:"ghost",size:"sm",className:se("w-full justify-start text-xs",a===t&&"bg-accent"),onClick:()=>{n(a),i(!1)},children:Vst(a)},a))})]})}function Hst({goal:t,onUpdate:e}){const{selectedCompanyId:n}=Xt(),{data:r}=_e({queryKey:J.agents.list(n),queryFn:()=>Mt.list(n),enabled:!!n}),{data:s}=_e({queryKey:J.goals.list(n),queryFn:()=>jl.list(n),enabled:!!n}),i=t.ownerAgentId?r==null?void 0:r.find(l=>l.id===t.ownerAgentId):null,a=t.parentId?s==null?void 0:s.find(l=>l.id===t.parentId):null;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(hx,{label:"Status",children:e?o.jsx(zG,{current:t.status,options:YD,onChange:l=>e({status:l}),children:o.jsx(sr,{status:t.status})}):o.jsx(sr,{status:t.status})}),o.jsx(hx,{label:"Level",children:e?o.jsx(zG,{current:t.level,options:GD,onChange:l=>e({level:l}),children:o.jsx("span",{className:"text-sm capitalize",children:t.level})}):o.jsx("span",{className:"text-sm capitalize",children:t.level})}),o.jsx(hx,{label:"Owner",children:i?o.jsx(jt,{to:Th(i),className:"text-sm hover:underline",children:i.name}):o.jsx("span",{className:"text-sm text-muted-foreground",children:"None"})}),t.parentId&&o.jsx(hx,{label:"Parent Goal",children:o.jsx(jt,{to:`/goals/${t.parentId}`,className:"text-sm hover:underline",children:(a==null?void 0:a.title)??t.parentId.slice(0,8)})})]}),o.jsx(Ro,{}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(hx,{label:"Created",children:o.jsx("span",{className:"text-sm",children:To(t.createdAt)})}),o.jsx(hx,{label:"Updated",children:o.jsx("span",{className:"text-sm",children:To(t.updatedAt)})})]})]})}function qst(){const{goalId:t}=Zi(),{selectedCompanyId:e,setSelectedCompanyId:n}=Xt(),{openNewGoal:r}=Ts(),{openPanel:s,closePanel:i}=l0(),{setBreadcrumbs:a}=yr(),l=hn(),{data:c,isLoading:u,error:f}=_e({queryKey:J.goals.detail(t),queryFn:()=>jl.get(t),enabled:!!t}),h=(c==null?void 0:c.companyId)??e,{data:p}=_e({queryKey:J.goals.list(h),queryFn:()=>jl.list(h),enabled:!!h}),{data:g}=_e({queryKey:J.projects.list(h),queryFn:()=>vs.list(h),enabled:!!h});y.useEffect(()=>{!(c!=null&&c.companyId)||c.companyId===e||n(c.companyId,{source:"route_sync"})},[c==null?void 0:c.companyId,e,n]);const b=Xe({mutationFn:C=>jl.update(t,C),onSuccess:()=>{l.invalidateQueries({queryKey:J.goals.detail(t)}),h&&l.invalidateQueries({queryKey:J.goals.list(h)})}}),v=Xe({mutationFn:async C=>{if(!h)throw new Error("No company selected");return sm.uploadImage(h,C,`goals/${t??"draft"}`)}}),w=(p??[]).filter(C=>C.parentId===t),j=(g??[]).filter(C=>t?C.goalIds.includes(t)||C.goals.some(N=>N.id===t)?!0:C.goalId===t:!1);return y.useEffect(()=>{a([{label:"Goals",href:"/goals"},{label:(c==null?void 0:c.title)??t??"Goal"}])},[a,c,t]),y.useEffect(()=>(c&&s(o.jsx(Hst,{goal:c,onUpdate:C=>b.mutate(C)})),()=>i()),[c]),u?o.jsx(is,{variant:"detail"}):f?o.jsx("p",{className:"text-sm text-destructive",children:f.message}):c?o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs uppercase text-muted-foreground",children:c.level}),o.jsx(sr,{status:c.status})]}),o.jsx(ou,{value:c.title,onSave:C=>b.mutate({title:C}),as:"h2",className:"text-xl font-bold"}),o.jsx(ou,{value:c.description??"",onSave:C=>b.mutate({description:C}),as:"p",className:"text-sm text-muted-foreground",placeholder:"Add a description...",multiline:!0,imageUploadHandler:async C=>(await v.mutateAsync(C)).contentPath})]}),o.jsxs(ha,{defaultValue:"children",children:[o.jsxs(tg,{children:[o.jsxs(_s,{value:"children",children:["Sub-Goals (",w.length,")"]}),o.jsxs(_s,{value:"projects",children:["Projects (",j.length,")"]})]}),o.jsxs(Vr,{value:"children",className:"mt-4 space-y-3",children:[o.jsx("div",{className:"flex items-center justify-start",children:o.jsxs(ue,{size:"sm",variant:"outline",onClick:()=>r({parentId:t}),children:[o.jsx(Er,{className:"h-3.5 w-3.5 mr-1.5"}),"Sub Goal"]})}),w.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No sub-goals."}):o.jsx(Ehe,{goals:w,goalLink:C=>`/goals/${C.id}`})]}),o.jsx(Vr,{value:"projects",className:"mt-4",children:j.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked projects."}):o.jsx("div",{className:"border border-border",children:j.map(C=>o.jsx(Uc,{title:C.name,subtitle:C.description??void 0,to:y_(C),trailing:o.jsx(sr,{status:C.status})},C.id))})})]})]}):null}const Kst={hire_agent:"Hire Agent",approve_ceo_strategy:"CEO Strategy",budget_override_required:"Budget Override"};function G9(t,e){const n=Kst[t]??t;return t==="hire_agent"&&(e!=null&&e.name)?`${n}: ${String(e.name)}`:n}const Y9={hire_agent:yte,approve_ceo_strategy:dte,budget_override_required:x6},J9=y6;function xp({label:t,value:e}){return e?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:t}),o.jsx("span",{children:String(e)})]}):null}function Wst({values:t}){if(!Array.isArray(t))return null;const e=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return e.length===0?null:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Skills"}),o.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.map(n=>o.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:n},n))})]})}function Gst({payload:t}){return o.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Name"}),o.jsx("span",{className:"font-medium",children:String(t.name??"—")})]}),o.jsx(xp,{label:"Role",value:t.role}),o.jsx(xp,{label:"Title",value:t.title}),o.jsx(xp,{label:"Icon",value:t.icon}),!!t.capabilities&&o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Capabilities"}),o.jsx("span",{className:"text-muted-foreground",children:String(t.capabilities)})]}),!!t.adapterType&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Adapter"}),o.jsx("span",{className:"font-mono text-xs bg-muted px-1.5 py-0.5 rounded",children:String(t.adapterType)})]}),o.jsx(Wst,{values:t.desiredSkills})]})}function Yst({payload:t}){const e=t.plan??t.description??t.strategy??t.text;return o.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[o.jsx(xp,{label:"Title",value:t.title}),!!e&&o.jsx("div",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-sm text-muted-foreground whitespace-pre-wrap font-mono text-xs max-h-48 overflow-y-auto",children:String(e)}),!e&&o.jsx("pre",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground overflow-x-auto max-h-48",children:JSON.stringify(t,null,2)})]})}function Jst({payload:t}){const e=typeof t.budgetAmount=="number"?t.budgetAmount:null,n=typeof t.observedAmount=="number"?t.observedAmount:null;return o.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[o.jsx(xp,{label:"Scope",value:t.scopeName??t.scopeType}),o.jsx(xp,{label:"Window",value:t.windowKind}),o.jsx(xp,{label:"Metric",value:t.metric}),e!==null||n!==null?o.jsxs("div",{className:"rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:["Limit ",e!==null?tn(e):"—"," · Observed ",n!==null?tn(n):"—"]}):null,!!t.guidance&&o.jsx("p",{className:"text-muted-foreground",children:String(t.guidance)})]})}function Ahe({type:t,payload:e}){return t==="hire_agent"?o.jsx(Gst,{payload:e}):t==="budget_override_required"?o.jsx(Jst,{payload:e}):o.jsx(Yst,{payload:e})}function Qst(t){return t==="approved"?o.jsx(a6,{className:"h-3.5 w-3.5 text-green-600 dark:text-green-400"}):t==="rejected"?o.jsx(v_,{className:"h-3.5 w-3.5 text-red-600 dark:text-red-400"}):t==="revision_requested"?o.jsx(ky,{className:"h-3.5 w-3.5 text-amber-600 dark:text-amber-400"}):t==="pending"?o.jsx(ky,{className:"h-3.5 w-3.5 text-yellow-600 dark:text-yellow-400"}):null}function Zst({approval:t,requesterAgent:e,onApprove:n,onReject:r,onOpen:s,detailLink:i,isPending:a}){const l=Y9[t.type]??J9,c=G9(t.type,t.payload),u=t.type!=="budget_override_required"&&(t.status==="pending"||t.status==="revision_requested");return o.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-0",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(l,{className:"h-4 w-4 text-muted-foreground shrink-0"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-sm",children:c}),e&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:["requested by ",o.jsx(lr,{name:e.name,size:"sm",className:"inline-flex"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[Qst(t.status),o.jsx("span",{className:"text-xs text-muted-foreground capitalize",children:t.status}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",ca(t.createdAt)]})]})]}),o.jsx(Ahe,{type:t.type,payload:t.payload}),t.decisionNote&&o.jsxs("div",{className:"mt-3 text-xs text-muted-foreground italic border-t border-border pt-2",children:["Note: ",t.decisionNote]}),u&&o.jsxs("div",{className:"flex gap-2 mt-4 pt-3 border-t border-border",children:[o.jsx(ue,{size:"sm",className:"bg-green-700 hover:bg-green-600 text-white",onClick:n,disabled:a,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",onClick:r,disabled:a,children:"Reject"})]}),o.jsx("div",{className:"mt-3",children:i?o.jsx(ue,{variant:"ghost",size:"sm",className:"text-xs px-0",asChild:!0,children:o.jsx(jt,{to:i,children:"View details"})}):o.jsx(ue,{variant:"ghost",size:"sm",className:"text-xs px-0",onClick:s,children:"View details"})})]})}function UG(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),n=hn(),r=As(),a=(er().pathname.split("/").pop()??"pending")==="all"?"all":"pending",[l,c]=y.useState(null);y.useEffect(()=>{e([{label:"Approvals"}])},[e]);const{data:u,isLoading:f,error:h}=_e({queryKey:J.approvals.list(t),queryFn:()=>ko.list(t),enabled:!!t}),{data:p}=_e({queryKey:J.agents.list(t),queryFn:()=>Mt.list(t),enabled:!!t}),g=Xe({mutationFn:j=>ko.approve(j),onSuccess:(j,C)=>{c(null),n.invalidateQueries({queryKey:J.approvals.list(t)}),r(`/approvals/${C}?resolved=approved`)},onError:j=>{c(j instanceof Error?j.message:"Failed to approve")}}),b=Xe({mutationFn:j=>ko.reject(j),onSuccess:()=>{c(null),n.invalidateQueries({queryKey:J.approvals.list(t)})},onError:j=>{c(j instanceof Error?j.message:"Failed to reject")}}),v=(u??[]).filter(j=>a==="all"||j.status==="pending"||j.status==="revision_requested").sort((j,C)=>new Date(C.createdAt).getTime()-new Date(j.createdAt).getTime()),w=(u??[]).filter(j=>j.status==="pending"||j.status==="revision_requested").length;return t?f?o.jsx(is,{variant:"approvals"}):o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsx(ha,{value:a,onValueChange:j=>r(`/approvals/${j}`),children:o.jsx(Wh,{items:[{value:"pending",label:o.jsxs(o.Fragment,{children:["Pending",w>0&&o.jsx("span",{className:se("ml-1.5 rounded-full px-1.5 py-0.5 text-[10px] font-medium","bg-yellow-500/20 text-yellow-500"),children:w})]})},{value:"all",label:"All"}]})})}),h&&o.jsx("p",{className:"text-sm text-destructive",children:h.message}),l&&o.jsx("p",{className:"text-sm text-destructive",children:l}),v.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[o.jsx(y6,{className:"h-8 w-8 text-muted-foreground/30 mb-3"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:a==="pending"?"No pending approvals.":"No approvals yet."})]}),v.length>0&&o.jsx("div",{className:"grid gap-3",children:v.map(j=>o.jsx(Zst,{approval:j,requesterAgent:j.requestedByAgentId?(p??[]).find(C=>C.id===j.requestedByAgentId)??null:null,onApprove:()=>g.mutate(j.id),onReject:()=>b.mutate(j.id),detailLink:`/approvals/${j.id}`,isPending:g.isPending||b.isPending},j.id))})]}):o.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a company first."})}function fh({className:t,...e}){return o.jsx("textarea",{"data-slot":"textarea",className:se("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),...e})}function Xst(){const{approvalId:t}=Zi(),{selectedCompanyId:e,setSelectedCompanyId:n}=Xt(),{setBreadcrumbs:r}=yr(),s=As(),[i]=Yy(),a=hn(),[l,c]=y.useState(""),[u,f]=y.useState(null),[h,p]=y.useState(!1),{data:g,isLoading:b}=_e({queryKey:J.approvals.detail(t),queryFn:()=>ko.get(t),enabled:!!t}),v=(g==null?void 0:g.companyId)??e,{data:w}=_e({queryKey:J.approvals.comments(t),queryFn:()=>ko.listComments(t),enabled:!!t}),{data:j}=_e({queryKey:J.approvals.issues(t),queryFn:()=>ko.listIssues(t),enabled:!!t}),{data:C}=_e({queryKey:J.agents.list(v??""),queryFn:()=>Mt.list(v??""),enabled:!!v});y.useEffect(()=>{!(g!=null&&g.companyId)||g.companyId===e||n(g.companyId,{source:"route_sync"})},[g==null?void 0:g.companyId,e,n]);const N=y.useMemo(()=>{const V=new Map;for(const $ of C??[])V.set($.id,$.name);return V},[C]);y.useEffect(()=>{var V;r([{label:"Approvals",href:"/approvals"},{label:((V=g==null?void 0:g.id)==null?void 0:V.slice(0,8))??t??"Approval"}])},[r,g,t]);const S=()=>{t&&(a.invalidateQueries({queryKey:J.approvals.detail(t)}),a.invalidateQueries({queryKey:J.approvals.comments(t)}),a.invalidateQueries({queryKey:J.approvals.issues(t)}),g!=null&&g.companyId&&(a.invalidateQueries({queryKey:J.approvals.list(g.companyId)}),a.invalidateQueries({queryKey:J.approvals.list(g.companyId,"pending")}),a.invalidateQueries({queryKey:J.agents.list(g.companyId)})))},T=Xe({mutationFn:()=>ko.approve(t),onSuccess:()=>{f(null),S(),s(`/approvals/${t}?resolved=approved`,{replace:!0})},onError:V=>f(V instanceof Error?V.message:"Approve failed")}),_=Xe({mutationFn:()=>ko.reject(t),onSuccess:()=>{f(null),S()},onError:V=>f(V instanceof Error?V.message:"Reject failed")}),A=Xe({mutationFn:()=>ko.requestRevision(t),onSuccess:()=>{f(null),S()},onError:V=>f(V instanceof Error?V.message:"Revision request failed")}),M=Xe({mutationFn:()=>ko.resubmit(t),onSuccess:()=>{f(null),S()},onError:V=>f(V instanceof Error?V.message:"Resubmit failed")}),I=Xe({mutationFn:()=>ko.addComment(t,l.trim()),onSuccess:()=>{c(""),f(null),S()},onError:V=>f(V instanceof Error?V.message:"Comment failed")}),L=Xe({mutationFn:V=>Mt.remove(V),onSuccess:()=>{f(null),S(),s("/approvals")},onError:V=>f(V instanceof Error?V.message:"Delete failed")});if(b)return o.jsx(is,{variant:"detail"});if(!g)return o.jsx("p",{className:"text-sm text-muted-foreground",children:"Approval not found."});const D=g.payload,P=typeof D.agentId=="string"?D.agentId:null,B=g.status==="pending"||g.status==="revision_requested",Z=g.type==="budget_override_required",Q=Y9[g.type]??J9,q=i.get("resolved")==="approved"&&g.status==="approved",O=(j==null?void 0:j[0])??null,z=O?{label:((j==null?void 0:j.length)??0)>1?"Review linked issues":"Review linked issue",to:`/issues/${O.identifier??O.id}`}:P?{label:"Open hired agent",to:`/agents/${P}`}:{label:"Back to approvals",to:"/approvals"};return o.jsxs("div",{className:"space-y-6 max-w-3xl",children:[q&&o.jsx("div",{className:"border border-green-300 dark:border-green-700/40 bg-green-50 dark:bg-green-900/20 rounded-lg px-4 py-3 animate-in fade-in zoom-in-95 duration-300",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsxs("div",{className:"relative mt-0.5",children:[o.jsx(a6,{className:"h-4 w-4 text-green-600 dark:text-green-300"}),o.jsx(n0,{className:"h-3 w-3 text-green-500 dark:text-green-200 absolute -right-2 -top-1 animate-pulse"})]}),o.jsxs("div",{children:[o.jsx("p",{className:"text-sm text-green-800 dark:text-green-100 font-medium",children:"Approval confirmed"}),o.jsx("p",{className:"text-xs text-green-700 dark:text-green-200/90",children:"Requesting agent was notified to review this approval and linked issues."})]})]}),o.jsx(ue,{size:"sm",variant:"outline",className:"border-green-400 dark:border-green-600/50 text-green-800 dark:text-green-100 hover:bg-green-100 dark:hover:bg-green-900/30",onClick:()=>s(z.to),children:z.label})]})}),o.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Q,{className:"h-5 w-5 text-muted-foreground shrink-0"}),o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold",children:G9(g.type,g.payload)}),o.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:g.id})]})]}),o.jsx(sr,{status:g.status})]}),o.jsxs("div",{className:"text-sm space-y-1",children:[g.requestedByAgentId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:"Requested by"}),o.jsx(lr,{name:N.get(g.requestedByAgentId)??g.requestedByAgentId.slice(0,8),size:"sm"})]}),o.jsx(Ahe,{type:g.type,payload:D}),o.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors mt-2",onClick:()=>p(V=>!V),children:[o.jsx($r,{className:`h-3 w-3 transition-transform ${h?"rotate-90":""}`}),"See full request"]}),h&&o.jsx("pre",{className:"text-xs bg-muted/40 rounded-md p-3 overflow-x-auto",children:JSON.stringify(D,null,2)}),g.decisionNote&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Decision note: ",g.decisionNote]})]}),u&&o.jsx("p",{className:"text-sm text-destructive",children:u}),j&&j.length>0&&o.jsxs("div",{className:"pt-2 border-t border-border/60",children:[o.jsx("p",{className:"text-xs text-muted-foreground mb-1.5",children:"Linked Issues"}),o.jsx("div",{className:"space-y-1.5",children:j.map(V=>o.jsxs(jt,{to:`/issues/${V.identifier??V.id}`,className:"block text-xs rounded border border-border/70 px-2 py-1.5 hover:bg-accent/20",children:[o.jsx("span",{className:"font-mono text-muted-foreground mr-2",children:V.identifier??V.id.slice(0,8)}),o.jsx("span",{children:V.title})]},V.id))}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:"Linked issues remain open until the requesting agent follows up and closes them."})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[B&&!Z&&o.jsxs(o.Fragment,{children:[o.jsx(ue,{size:"sm",className:"bg-green-700 hover:bg-green-600 text-white",onClick:()=>T.mutate(),disabled:T.isPending,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",onClick:()=>_.mutate(),disabled:_.isPending,children:"Reject"})]}),Z&&g.status==="pending"&&o.jsxs("p",{className:"text-sm text-muted-foreground",children:["Resolve this budget stop from the budget controls on ",o.jsx(jt,{to:"/costs",className:"underline underline-offset-2",children:"/costs"}),"."]}),g.status==="pending"&&o.jsx(ue,{size:"sm",variant:"outline",onClick:()=>A.mutate(),disabled:A.isPending,children:"Request revision"}),g.status==="revision_requested"&&o.jsx(ue,{size:"sm",variant:"outline",onClick:()=>M.mutate(),disabled:M.isPending,children:"Mark resubmitted"}),g.status==="rejected"&&g.type==="hire_agent"&&P&&o.jsx(ue,{size:"sm",variant:"outline",className:"text-destructive border-destructive/40",onClick:()=>{window.confirm("Delete this disapproved agent? This cannot be undone.")&&L.mutate(P)},disabled:L.isPending,children:"Delete disapproved agent"})]})]}),o.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[o.jsxs("h3",{className:"text-sm font-medium",children:["Comments (",(w==null?void 0:w.length)??0,")"]}),o.jsx("div",{className:"space-y-2",children:(w??[]).map(V=>o.jsxs("div",{className:"border border-border/60 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[V.authorAgentId?o.jsx(jt,{to:`/agents/${V.authorAgentId}`,className:"hover:underline",children:o.jsx(lr,{name:N.get(V.authorAgentId)??V.authorAgentId.slice(0,8),size:"sm"})}):o.jsx(lr,{name:"Board",size:"sm"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(V.createdAt).toLocaleString()})]}),o.jsx(Al,{className:"text-sm",children:V.body})]},V.id))}),o.jsx(fh,{value:l,onChange:V=>c(V.target.value),placeholder:"Add a comment...",rows:3}),o.jsx("div",{className:"flex justify-end",children:o.jsx(ue,{size:"sm",onClick:()=>I.mutate(),disabled:!l.trim()||I.isPending,children:I.isPending?"Posting…":"Post comment"})})]})]})}function Xu(t,e){const n=new URLSearchParams;t&&n.set("from",t),e&&n.set("to",e);const r=n.toString();return r?`?${r}`:""}const Wo={summary:(t,e,n)=>Ce.get(`/companies/${t}/costs/summary${Xu(e,n)}`),byAgent:(t,e,n)=>Ce.get(`/companies/${t}/costs/by-agent${Xu(e,n)}`),byAgentModel:(t,e,n)=>Ce.get(`/companies/${t}/costs/by-agent-model${Xu(e,n)}`),byProject:(t,e,n)=>Ce.get(`/companies/${t}/costs/by-project${Xu(e,n)}`),byProvider:(t,e,n)=>Ce.get(`/companies/${t}/costs/by-provider${Xu(e,n)}`),byBiller:(t,e,n)=>Ce.get(`/companies/${t}/costs/by-biller${Xu(e,n)}`),financeSummary:(t,e,n)=>Ce.get(`/companies/${t}/costs/finance-summary${Xu(e,n)}`),financeByBiller:(t,e,n)=>Ce.get(`/companies/${t}/costs/finance-by-biller${Xu(e,n)}`),financeByKind:(t,e,n)=>Ce.get(`/companies/${t}/costs/finance-by-kind${Xu(e,n)}`),financeEvents:(t,e,n,r=100)=>Ce.get(`/companies/${t}/costs/finance-events${eit(e,n,r)}`),windowSpend:t=>Ce.get(`/companies/${t}/costs/window-spend`),quotaWindows:t=>Ce.get(`/companies/${t}/costs/quota-windows`)};function eit(t,e,n){const r=new URLSearchParams;t&&r.set("from",t),e&&r.set("to",e),n&&r.set("limit",String(n));const s=r.toString();return s?`?${s}`:""}function tit(t){return t>90?"bg-red-400":t>70?"bg-yellow-400":"bg-green-400"}function AO({label:t,percentUsed:e,leftLabel:n,rightLabel:r,showDeficitNotch:s=!1,className:i}){const a=Math.min(100,Math.max(0,e)),l=Math.min(a,97);return o.jsxs("div",{className:se("space-y-1.5",i),children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:t}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("span",{className:"text-xs font-medium tabular-nums",children:n}),r&&o.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:r})]})]}),o.jsxs("div",{className:"relative h-2 w-full border border-border overflow-hidden",children:[o.jsx("div",{className:se("absolute inset-y-0 left-0 transition-[width,background-color] duration-150",tit(a)),style:{width:`${a}%`}}),s&&a>0&&o.jsx("div",{className:"absolute inset-y-0 w-[2px] bg-destructive z-10",style:{left:`${l}%`}})]})]})}function VG({row:t,weekSpendCents:e,budgetMonthlyCents:n,totalCompanySpendCents:r,providerRows:s}){const i=y.useMemo(()=>{const u=new Map;for(const f of s){const h=u.get(f.provider)??{provider:f.provider,costCents:0,inputTokens:0,outputTokens:0};h.costCents+=f.costCents,h.inputTokens+=f.inputTokens+f.cachedInputTokens,h.outputTokens+=f.outputTokens,u.set(f.provider,h)}return Array.from(u.values()).sort((f,h)=>h.costCents-f.costCents)},[s]),a=y.useMemo(()=>{const u=new Map;for(const f of s)u.set(f.billingType,(u.get(f.billingType)??0)+f.costCents);return Array.from(u.entries()).sort((f,h)=>h[1]-f[1])},[s]),l=n>0&&r>0?t.costCents/r*n:n,c=l>0?Math.min(100,t.costCents/l*100):0;return o.jsxs(ys,{children:[o.jsx(ci,{className:"px-4 pt-4 pb-0 gap-1",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ui,{className:"text-sm font-semibold",children:cc(t.biller)}),o.jsxs(ao,{className:"text-xs mt-0.5",children:[o.jsx("span",{className:"font-mono",children:Kn(t.inputTokens+t.cachedInputTokens)})," in"," · ",o.jsx("span",{className:"font-mono",children:Kn(t.outputTokens)})," out"," · ",t.providerCount," provider",t.providerCount===1?"":"s"," · ",t.modelCount," model",t.modelCount===1?"":"s"]})]}),o.jsx("span",{className:"text-xl font-bold tabular-nums shrink-0",children:tn(t.costCents)})]})}),o.jsxs(bs,{className:"px-4 pb-4 pt-3 space-y-4",children:[n>0&&o.jsx(AO,{label:"Period spend",percentUsed:c,leftLabel:tn(t.costCents),rightLabel:`${Math.round(c)}% of allocation`}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} metered run${t.apiRunCount===1?"":"s"}`:"0 metered runs"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription run${t.subscriptionRunCount===1?"":"s"}`:"0 subscription runs"," · ",tn(e)," this week"]}),a.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Billing types"}),o.jsx("div",{className:"space-y-1.5",children:a.map(([u,f])=>o.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:n6(u)}),o.jsx("span",{className:"font-medium tabular-nums",children:tn(f)})]},u))})]})]}),i.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Upstream providers"}),o.jsx("div",{className:"space-y-1.5",children:i.map(u=>o.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[o.jsx("span",{className:"text-muted-foreground",children:cc(u.provider)}),o.jsxs("div",{className:"text-right tabular-nums",children:[o.jsx("div",{className:"font-medium",children:tn(u.costCents)}),o.jsxs("div",{className:"text-muted-foreground",children:[Kn(u.inputTokens+u.outputTokens)," tok"]})]})]},u.provider))})]})]})]})]})}function nit(t){return(t/100).toFixed(2)}function rit(t){const e=Number(t);return!Number.isFinite(e)||e<0?null:Math.round(e*100)}function HG({incident:t,onRaiseAndResume:e,onKeepPaused:n,isMutating:r}){const[s,i]=y.useState(nit(Math.max(t.amountObserved+1e3,t.amountLimit))),a=rit(s);return o.jsxs(ys,{className:"overflow-hidden border-red-500/20 bg-[linear-gradient(180deg,rgba(255,70,70,0.10),rgba(255,255,255,0.02))]",children:[o.jsx(ci,{className:"px-5 pt-5 pb-3",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"text-[11px] uppercase tracking-[0.22em] text-red-200/80",children:[t.scopeType," hard stop"]}),o.jsx(ui,{className:"mt-1 text-base text-red-50",children:t.scopeName}),o.jsxs(ao,{className:"mt-1 text-red-100/70",children:["Spending reached ",tn(t.amountObserved)," against a limit of ",tn(t.amountLimit),"."]})]}),o.jsx("div",{className:"rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-200",children:o.jsx(s5e,{className:"h-4 w-4"})})]})}),o.jsxs(bs,{className:"space-y-4 px-5 pb-5 pt-0",children:[o.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-50/90",children:[o.jsx(l6,{className:"mt-0.5 h-4 w-4 shrink-0"}),o.jsx("div",{children:t.scopeType==="project"?"Project execution is paused. New work in this project will not start until you resolve the budget incident.":"This scope is paused. New heartbeats will not start until you resolve the budget incident."})]}),o.jsxs("div",{className:"rounded-xl border border-border/60 bg-background/60 p-3",children:[o.jsx("label",{className:"text-[11px] uppercase tracking-[0.18em] text-muted-foreground",children:"New budget (USD)"}),o.jsxs("div",{className:"mt-2 flex flex-col gap-3 sm:flex-row",children:[o.jsx(_r,{value:s,onChange:l=>i(l.target.value),inputMode:"decimal",placeholder:"0.00"}),o.jsxs(ue,{className:"gap-2",disabled:r||a===null||a<=t.amountObserved,onClick:()=>{typeof a=="number"&&e(a)},children:[o.jsx(wy,{className:"h-4 w-4"}),r?"Applying...":"Raise budget & resume"]})]}),a!==null&&a<=t.amountObserved?o.jsx("p",{className:"mt-2 text-xs text-red-200/80",children:"The new budget must exceed current observed spend."}):null]}),o.jsx("div",{className:"flex justify-end",children:o.jsx(ue,{variant:"ghost",className:"text-muted-foreground",disabled:r,onClick:n,children:"Keep paused"})})]})]})}function sit({row:t}){return o.jsxs(ys,{children:[o.jsx(ci,{className:"px-4 pt-4 pb-1",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx(ui,{className:"text-base",children:cc(t.biller)}),o.jsxs(ao,{className:"mt-1 text-xs",children:[t.eventCount," event",t.eventCount===1?"":"s"," across ",t.kindCount," kind",t.kindCount===1?"":"s"]})]}),o.jsxs("div",{className:"text-right",children:[o.jsx("div",{className:"text-lg font-semibold tabular-nums",children:tn(t.netCents)}),o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:"net"})]})]})}),o.jsx(bs,{className:"space-y-3 px-4 pb-4 pt-3",children:o.jsxs("div",{className:"grid gap-2 text-sm sm:grid-cols-3",children:[o.jsxs("div",{className:"border border-border p-3",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"debits"}),o.jsx("div",{className:"mt-1 font-medium tabular-nums",children:tn(t.debitCents)})]}),o.jsxs("div",{className:"border border-border p-3",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"credits"}),o.jsx("div",{className:"mt-1 font-medium tabular-nums",children:tn(t.creditCents)})]}),o.jsxs("div",{className:"border border-border p-3",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"estimated"}),o.jsx("div",{className:"mt-1 font-medium tabular-nums",children:tn(t.estimatedDebitCents)})]})]})})]})}function iit({rows:t}){return o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-4 pt-4 pb-1",children:[o.jsx(ui,{className:"text-base",children:"Financial event mix"}),o.jsx(ao,{children:"Account-level charges grouped by event kind."})]}),o.jsx(bs,{className:"space-y-2 px-4 pb-4 pt-3",children:t.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No finance events in this period."}):t.map(e=>o.jsxs("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate text-sm font-medium",children:rte(e.eventKind)}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.eventCount," event",e.eventCount===1?"":"s"," · ",e.billerCount," biller",e.billerCount===1?"":"s"]})]}),o.jsxs("div",{className:"text-right tabular-nums",children:[o.jsx("div",{className:"text-sm font-medium",children:tn(e.netCents)}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[tn(e.debitCents)," debits"]})]})]},e.eventKind))})]})}function qG({rows:t,emptyMessage:e="No financial events in this period."}){return o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-4 pt-4 pb-1",children:[o.jsx(ui,{className:"text-base",children:"Recent financial events"}),o.jsx(ao,{children:"Top-ups, fees, credits, commitments, and other non-request charges."})]}),o.jsx(bs,{className:"space-y-3 px-4 pb-4 pt-3",children:t.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:e}):t.map(n=>o.jsx("div",{className:"border border-border p-3",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0 space-y-2",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(vr,{variant:"secondary",children:rte(n.eventKind)}),o.jsx(vr,{variant:n.direction==="credit"?"outline":"secondary",children:ONe(n.direction)}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Ap(n.occurredAt)})]}),o.jsxs("div",{className:"text-sm font-medium",children:[cc(n.biller),n.provider?` -> ${cc(n.provider)}`:"",n.model?o.jsx("span",{className:"ml-1 font-mono text-xs text-muted-foreground",children:n.model}):null]}),(n.description||n.externalInvoiceId||n.region||n.pricingTier)&&o.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[n.description?o.jsx("div",{children:n.description}):null,n.externalInvoiceId?o.jsxs("div",{children:["invoice ",n.externalInvoiceId]}):null,n.region?o.jsxs("div",{children:["region ",n.region]}):null,n.pricingTier?o.jsxs("div",{children:["tier ",n.pricingTier]}):null]})]}),o.jsxs("div",{className:"text-right tabular-nums",children:[o.jsx("div",{className:"text-sm font-semibold",children:tn(n.amountCents)}),o.jsx("div",{className:"text-xs text-muted-foreground",children:n.currency}),n.estimated?o.jsx("div",{className:"text-[11px] uppercase tracking-[0.12em] text-amber-600",children:"estimated"}):null]})]})},n.id))})]})}const A2=["currentsession","currentweekallmodels","currentweeksonnetonly","currentweeksonnet","currentweekopusonly","currentweekopus","extrausage"];function TO(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function oit(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}function ait(t){return[...t].sort((e,n)=>{const r=A2.indexOf(TO(e.label)),s=A2.indexOf(TO(n.label));return(r===-1?A2.length:r)-(s===-1?A2.length:s)})}function lit(t){return t==null?"bg-zinc-700":t>=90?"bg-red-400":t>=70?"bg-amber-400":"bg-primary/70"}function cit({windows:t,source:e=null,error:n=null}){const r=ait(t);return o.jsxs("div",{className:"border border-border px-4 py-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground",children:"Anthropic subscription"}),o.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:"Live Claude quota windows."})]}),e?o.jsx("span",{className:"shrink-0 border border-border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r6(e)}):null]}),n?o.jsx("div",{className:"mt-4 border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:n}):null,o.jsx("div",{className:"mt-4 space-y-4",children:r.map(s=>{const i=TO(s.label),a=oit(s);if(i==="extrausage")return o.jsxs("div",{className:"border border-border px-3.5 py-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:s.label}),s.valueLabel?o.jsx("div",{className:"text-sm font-medium text-foreground",children:s.valueLabel}):null]}),a?o.jsx("div",{className:"mt-2 text-sm text-muted-foreground",children:a}):null]},s.label);const l=Math.min(100,Math.max(0,s.usedPercent??0));return o.jsxs("div",{className:"border border-border px-3.5 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:s.label}),a?o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:a}):null]}),s.usedPercent!=null?o.jsxs("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-foreground",children:[s.usedPercent,"% used"]}):null]}),o.jsx("div",{className:"mt-3 h-2 overflow-hidden bg-muted",children:o.jsx("div",{className:se("h-full transition-[width] duration-200",lit(s.usedPercent)),style:{width:`${l}%`}})})]},s.label)})})]})}const T2=["5hlimit","weeklylimit","credits"];function MO(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function uit(t){return[...t].sort((e,n)=>{const r=MO(e.label).replace(/^gpt53codexspark/,""),s=MO(n.label).replace(/^gpt53codexspark/,""),i=T2.indexOf(r),a=T2.indexOf(s);return(i===-1?T2.length:i)-(a===-1?T2.length:a)})}function dit(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}function fit(t){return t==null?"bg-zinc-700":t>=90?"bg-red-400":t>=70?"bg-amber-400":"bg-primary/70"}function KG(t){const e=MO(t);return e.includes("gpt53codexspark")||e.includes("gpt5")}function hit({windows:t,source:e=null,error:n=null}){const r=uit(t),s=r.filter(a=>!KG(a.label)),i=r.filter(a=>KG(a.label));return o.jsxs("div",{className:"border border-border px-4 py-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-muted-foreground",children:"Codex subscription"}),o.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:"Live Codex quota windows."})]}),e?o.jsx("span",{className:"shrink-0 border border-border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r6(e)}):null]}),n?o.jsx("div",{className:"mt-4 border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:n}):null,o.jsxs("div",{className:"mt-4 space-y-5",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Account windows"}),o.jsx("div",{className:"space-y-3",children:s.map(a=>o.jsx(WG,{window:a},a.label))})]}),i.length>0?o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:"Model windows"}),o.jsx("div",{className:"space-y-3",children:i.map(a=>o.jsx(WG,{window:a},a.label))})]}):null]})]})}function WG({window:t}){const e=dit(t);return t.usedPercent==null?o.jsxs("div",{className:"border border-border px-3.5 py-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:t.label}),t.valueLabel?o.jsx("div",{className:"text-sm font-semibold tabular-nums text-foreground",children:t.valueLabel}):null]}),e?o.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:e}):null]}):o.jsxs("div",{className:"border border-border px-3.5 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:t.label}),e?o.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:e}):null]}),o.jsxs("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-foreground",children:[t.usedPercent,"% used"]})]}),o.jsx("div",{className:"mt-3 h-2 overflow-hidden bg-muted",children:o.jsx("div",{className:se("h-full transition-[width] duration-200",fit(t.usedPercent)),style:{width:`${Math.max(0,Math.min(100,t.usedPercent))}%`}})})]})}const mit=["5h","24h","7d"];function GG({provider:t,rows:e,budgetMonthlyCents:n,totalCompanySpendCents:r,weekSpendCents:s,windowRows:i,showDeficitNotch:a,quotaWindows:l=[],quotaError:c=null,quotaSource:u=null,quotaLoading:f=!1}){const h=y.useMemo(()=>{let O=0,z=0,V=0,$=0,G=0,W=0,F=0;for(const X of e)O+=X.inputTokens,z+=X.outputTokens,V+=X.costCents,$+=X.apiRunCount,G+=X.subscriptionRunCount,W+=X.subscriptionInputTokens,F+=X.subscriptionOutputTokens;const le=O+z,ie=W+F,ne=le+ie;return{totalInputTokens:O,totalOutputTokens:z,totalTokens:le,totalCostCents:V,totalApiRuns:$,totalSubRuns:G,totalSubInputTokens:W,totalSubOutputTokens:F,totalSubTokens:ie,subSharePct:ne>0?ie/ne*100:0}},[e]),{totalInputTokens:p,totalOutputTokens:g,totalTokens:b,totalCostCents:v,totalApiRuns:w,totalSubRuns:j,totalSubInputTokens:C,totalSubOutputTokens:N,totalSubTokens:S,subSharePct:T}=h,_=n>0&&r>0?v/r*n:n,A=_>0?Math.min(100,v/_*100):0,M=_>0?_/4.33:0,I=M>0?Math.min(100,s/M*100):0,L=n>0,D=y.useMemo(()=>new Map(i.map(O=>[O.window,O])),[i]),P=y.useMemo(()=>Math.max(...i.map(O=>O.costCents),0),[i]),B=t==="anthropic",Z=t==="openai"&&(u==null?void 0:u.startsWith("codex-")),q=(t==="anthropic"||t==="openai")&&(f||l.length>0||c!=null);return o.jsxs(ys,{children:[o.jsx(ci,{className:"px-4 pt-4 pb-0 gap-1",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ui,{className:"text-sm font-semibold",children:cc(t)}),o.jsxs(ao,{className:"text-xs mt-0.5",children:[o.jsx("span",{className:"font-mono",children:Kn(p)})," in"," · ",o.jsx("span",{className:"font-mono",children:Kn(g)})," out",(w>0||j>0)&&o.jsxs("span",{className:"ml-1.5",children:["·"," ",w>0&&`~${w} api`,w>0&&j>0&&" / ",j>0&&`~${j} sub`," runs"]})]})]}),o.jsx("span",{className:"text-xl font-bold tabular-nums shrink-0",children:tn(v)})]})}),o.jsxs(bs,{className:"px-4 pb-4 pt-3 space-y-4",children:[L&&o.jsxs("div",{className:"space-y-3",children:[o.jsx(AO,{label:"Period spend",percentUsed:A,leftLabel:tn(v),rightLabel:`${Math.round(A)}% of allocation`,showDeficitNotch:a}),o.jsx(AO,{label:"This week",percentUsed:I,leftLabel:tn(s),rightLabel:`~${tn(Math.round(M))} / wk`,showDeficitNotch:I>=100})]}),i.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Rolling windows"}),o.jsx("div",{className:"space-y-2.5",children:mit.map(O=>{const z=D.get(O);if(!z)return null;const V=z.costCents,$=z.inputTokens+z.outputTokens,G=P>0?V/P*100:0;return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[o.jsx("span",{className:"font-mono text-muted-foreground w-6 shrink-0",children:O}),o.jsxs("span",{className:"text-muted-foreground font-mono flex-1",children:[Kn($)," tok"]}),o.jsx("span",{className:"font-medium tabular-nums",children:tn(V)})]}),o.jsx("div",{className:"h-2 w-full border border-border overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary/60 transition-[width] duration-150",style:{width:`${G}%`}})})]},O)})})]})]}),j>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Subscription"}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.jsx("span",{className:"font-mono text-foreground",children:j})," runs"," · ",S>0&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"font-mono text-foreground",children:Kn(S)})," total"," · "]}),o.jsx("span",{className:"font-mono text-foreground",children:Kn(C)})," in"," · ",o.jsx("span",{className:"font-mono text-foreground",children:Kn(N)})," out"]}),T>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"h-1.5 w-full border border-border overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary/60 transition-[width] duration-150",style:{width:`${T}%`}})}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(T),"% of token usage via subscription"]})]})]})]}),e.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsx("div",{className:"space-y-3",children:e.map(O=>{const z=O.inputTokens+O.outputTokens,V=b>0?z/b*100:0,$=v>0?O.costCents/v*100:0;return o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("span",{className:"text-xs text-muted-foreground truncate font-mono block",children:O.model}),o.jsxs("span",{className:"text-[11px] text-muted-foreground truncate block",children:[cc(O.biller)," · ",n6(O.billingType)]})]}),o.jsxs("div",{className:"flex items-center gap-3 shrink-0 tabular-nums text-xs",children:[o.jsxs("span",{className:"text-muted-foreground",children:[Kn(z)," tok"]}),o.jsx("span",{className:"font-medium",children:tn(O.costCents)})]})]}),o.jsxs("div",{className:"relative h-2 w-full border border-border overflow-hidden",children:[o.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/60 transition-[width] duration-150",style:{width:`${V}%`},title:`${Math.round(V)}% of provider tokens`}),o.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/85 transition-[width] duration-150",style:{width:`${$}%`},title:`${Math.round($)}% of provider cost`})]})]},`${O.provider}:${O.model}`)})})]}),q&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-t border-border"}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Subscription quota"}),u&&!B&&!Z?o.jsx("span",{className:"text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:r6(u)}):null]}),f?o.jsx(pit,{}):B?o.jsx(cit,{windows:l,source:u,error:c}):Z?o.jsx(hit,{windows:l,source:u,error:c}):o.jsxs(o.Fragment,{children:[c?o.jsx("p",{className:"text-xs text-destructive",children:c}):null,o.jsx("div",{className:"space-y-2.5",children:l.map(O=>{const z=O.usedPercent==null?null:O.usedPercent>=90?"bg-red-400":O.usedPercent>=70?"bg-yellow-400":"bg-green-400";return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[o.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:O.label}),o.jsx("span",{className:"flex-1"}),O.valueLabel!=null?o.jsx("span",{className:"font-medium tabular-nums",children:O.valueLabel}):O.usedPercent!=null?o.jsxs("span",{className:"font-medium tabular-nums",children:[O.usedPercent,"% used"]}):null]}),O.usedPercent!=null&&z!=null&&o.jsx("div",{className:"h-2 w-full border border-border overflow-hidden",children:o.jsx("div",{className:`h-full transition-[width] duration-150 ${z}`,style:{width:`${O.usedPercent}%`}})}),O.detail?o.jsx("p",{className:"text-xs text-muted-foreground",children:O.detail}):O.resetsAt?o.jsxs("p",{className:"text-xs text-muted-foreground",children:["resets ",new Date(O.resetsAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})]}):null]},O.label)})})]})]})]})]})]})}function pit(){return o.jsxs("div",{className:"border border-border px-4 py-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border pb-3",children:[o.jsxs("div",{className:"min-w-0 space-y-2",children:[o.jsx(zt,{className:"h-3 w-36"}),o.jsx(zt,{className:"h-4 w-64 max-w-full"})]}),o.jsx(zt,{className:"h-7 w-28"})]}),o.jsx("div",{className:"mt-4 space-y-3",children:Array.from({length:3}).map((t,e)=>o.jsxs("div",{className:"border border-border px-3.5 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0 space-y-2",children:[o.jsx(zt,{className:"h-4 w-32"}),o.jsx(zt,{className:"h-3 w-44 max-w-full"})]}),o.jsx(zt,{className:"h-4 w-20"})]}),o.jsx(zt,{className:"mt-3 h-2 w-full"})]},e))})]})}const git={mtd:"Month to Date","7d":"Last 7 Days","30d":"Last 30 Days",ytd:"Year to Date",all:"All Time",custom:"Custom"},xit=["mtd","7d","30d","ytd","all","custom"];function yit(t){const e=new Date,n=e.toISOString();switch(t){case"mtd":return{from:new Date(e.getFullYear(),e.getMonth(),1).toISOString(),to:n};case"7d":return{from:new Date(e.getFullYear(),e.getMonth(),e.getDate()-7,0,0,0,0).toISOString(),to:n};case"30d":return{from:new Date(e.getFullYear(),e.getMonth(),e.getDate()-30,0,0,0,0).toISOString(),to:n};case"ytd":return{from:new Date(e.getFullYear(),0,1).toISOString(),to:n};case"all":case"custom":return{from:"",to:""}}}function $M(t){const e=new Date(t);return e.setSeconds(0,0),e.toISOString()}function bit(){const[t,e]=y.useState("mtd"),[n,r]=y.useState(""),[s,i]=y.useState(""),a=y.useRef(null),[l,c]=y.useState(()=>$M(new Date));y.useEffect(()=>{const p=new Date,g=(60-p.getSeconds())*1e3-p.getMilliseconds(),b=setTimeout(()=>{c($M(new Date)),a.current=setInterval(()=>c($M(new Date)),6e4)},g);return()=>{clearTimeout(b),a.current!=null&&clearInterval(a.current)}},[]);const{from:u,to:f}=y.useMemo(()=>{if(t!=="custom")return yit(t);const p=n?new Date(n+"T00:00:00"):null,g=s?new Date(s+"T23:59:59.999"):null;return{from:p?p.toISOString():"",to:g?g.toISOString():""}},[t,n,s,l]);return{preset:t,setPreset:e,customFrom:n,setCustomFrom:r,customTo:s,setCustomTo:i,from:u,to:f,customReady:t!=="custom"||!!n&&!!s}}const vit="__none__";function wit(){const t=new Date,e=t.getDay(),n=e===0?-6:1-e,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+n,0,0,0,0),s=new Date(r.getFullYear(),r.getMonth(),r.getDate()+6,23,59,59,999);return{from:r.toISOString(),to:s.toISOString()}}function kit({provider:t,rows:e}){const n=e.reduce((s,i)=>s+i.inputTokens+i.cachedInputTokens+i.outputTokens,0),r=e.reduce((s,i)=>s+i.costCents,0);return o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{children:cc(t)}),o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Kn(n)}),o.jsx("span",{className:"text-xs text-muted-foreground",children:tn(r)})]})}function Cit({biller:t,rows:e}){const n=e.reduce((s,i)=>s+i.inputTokens+i.cachedInputTokens+i.outputTokens,0),r=e.reduce((s,i)=>s+i.costCents,0);return o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{children:cc(t)}),o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Kn(n)}),o.jsx("span",{className:"text-xs text-muted-foreground",children:tn(r)})]})}function cl({label:t,value:e,subtitle:n,icon:r}){return o.jsx("div",{className:"border border-border p-4",children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground",children:t}),o.jsx("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:e}),o.jsx("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:n})]}),o.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center border border-border",children:o.jsx(r,{className:"h-4 w-4 text-muted-foreground"})})]})})}function YG({debitCents:t,creditCents:e,netCents:n,estimatedDebitCents:r,eventCount:s}){return o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-5 pt-5 pb-2",children:[o.jsx(ui,{className:"text-base",children:"Finance ledger"}),o.jsx(ao,{children:"Account-level charges that do not map to a single inference request."})]}),o.jsxs(bs,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[o.jsx(cl,{label:"Debits",value:tn(t),subtitle:`${s} total event${s===1?"":"s"} in range`,icon:wy}),o.jsx(cl,{label:"Credits",value:tn(e),subtitle:"Refunds, offsets, and credit returns",icon:WNe}),o.jsx(cl,{label:"Net",value:tn(n),subtitle:"Debit minus credit for the selected period",icon:U4}),o.jsx(cl,{label:"Estimated",value:tn(r),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:F4})]})]})}function jit(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),n=hn(),[r,s]=y.useState("overview"),[i,a]=y.useState("all"),[l,c]=y.useState("all"),{preset:u,setPreset:f,customFrom:h,setCustomFrom:p,customTo:g,setCustomTo:b,from:v,to:w,customReady:j}=bit();y.useEffect(()=>{e([{label:"Costs"}])},[e]);const[C,N]=y.useState(()=>new Date().toDateString()),S=y.useRef(null);y.useEffect(()=>{const we=()=>{const qe=new Date,yt=new Date(qe.getFullYear(),qe.getMonth(),qe.getDate()+1).getTime()-qe.getTime();S.current=setTimeout(()=>{N(new Date().toDateString()),we()},yt)};return we(),()=>{S.current!=null&&clearTimeout(S.current)}},[]);const T=y.useMemo(()=>wit(),[C]),_=t??vit,{data:A,isLoading:M,error:I}=_e({queryKey:J.budgets.overview(_),queryFn:()=>pp.overview(_),enabled:!!t&&j,refetchInterval:3e4,staleTime:5e3}),L=()=>{t&&(n.invalidateQueries({queryKey:J.budgets.overview(t)}),n.invalidateQueries({queryKey:J.dashboard(t)}),n.invalidateQueries({queryKey:J.agents.list(t)}),n.invalidateQueries({queryKey:J.projects.list(t)}))},D=Xe({mutationFn:we=>pp.upsertPolicy(_,{scopeType:we.scopeType,scopeId:we.scopeId,amount:we.amount,windowKind:we.windowKind}),onSuccess:L}),P=Xe({mutationFn:we=>pp.resolveIncident(_,we.incidentId,we),onSuccess:L}),{data:B,isLoading:Z,error:Q}=_e({queryKey:J.costs(_,v||void 0,w||void 0),queryFn:async()=>{const[we,qe,yt,Se]=await Promise.all([Wo.summary(_,v||void 0,w||void 0),Wo.byAgent(_,v||void 0,w||void 0),Wo.byProject(_,v||void 0,w||void 0),Wo.byAgentModel(_,v||void 0,w||void 0)]);return{summary:we,byAgent:qe,byProject:yt,byAgentModel:Se}},enabled:!!t&&j}),{data:q,isLoading:O,error:z}=_e({queryKey:[J.financeSummary(_,v||void 0,w||void 0),J.financeByBiller(_,v||void 0,w||void 0),J.financeByKind(_,v||void 0,w||void 0),J.financeEvents(_,v||void 0,w||void 0,18)],queryFn:async()=>{const[we,qe,yt,Se]=await Promise.all([Wo.financeSummary(_,v||void 0,w||void 0),Wo.financeByBiller(_,v||void 0,w||void 0),Wo.financeByKind(_,v||void 0,w||void 0),Wo.financeEvents(_,v||void 0,w||void 0,18)]);return{summary:we,byBiller:qe,byKind:yt,events:Se}},enabled:!!t&&j}),[V,$]=y.useState(new Set);y.useEffect(()=>{$(new Set)},[_,v,w]);function G(we){$(qe=>{const yt=new Set(qe);return yt.has(we)?yt.delete(we):yt.add(we),yt})}const W=y.useMemo(()=>{const we=new Map;for(const qe of(B==null?void 0:B.byAgentModel)??[]){const yt=we.get(qe.agentId)??[];yt.push(qe),we.set(qe.agentId,yt)}for(const[qe,yt]of we)we.set(qe,yt.slice().sort((Se,Ge)=>Ge.costCents-Se.costCents));return we},[B==null?void 0:B.byAgentModel]),{data:F}=_e({queryKey:J.usageByProvider(_,v||void 0,w||void 0),queryFn:()=>Wo.byProvider(_,v||void 0,w||void 0),enabled:!!t&&j&&(r==="providers"||r==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:le}=_e({queryKey:J.usageByBiller(_,v||void 0,w||void 0),queryFn:()=>Wo.byBiller(_,v||void 0,w||void 0),enabled:!!t&&j&&r==="billers",refetchInterval:3e4,staleTime:1e4}),{data:ie}=_e({queryKey:J.usageByProvider(_,T.from,T.to),queryFn:()=>Wo.byProvider(_,T.from,T.to),enabled:!!t&&(r==="providers"||r==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:ne}=_e({queryKey:J.usageByBiller(_,T.from,T.to),queryFn:()=>Wo.byBiller(_,T.from,T.to),enabled:!!t&&r==="billers",refetchInterval:3e4,staleTime:1e4}),{data:X}=_e({queryKey:J.usageWindowSpend(_),queryFn:()=>Wo.windowSpend(_),enabled:!!t&&r==="providers",refetchInterval:3e4,staleTime:1e4}),{data:ee,isLoading:de}=_e({queryKey:J.usageQuotaWindows(_),queryFn:()=>Wo.quotaWindows(_),enabled:!!t&&r==="providers",refetchInterval:3e5,staleTime:6e4}),ve=y.useMemo(()=>{const we=new Map;for(const qe of F??[]){const yt=we.get(qe.provider)??[];yt.push(qe),we.set(qe.provider,yt)}return we},[F]),Te=y.useMemo(()=>{const we=new Map;for(const qe of le??[]){const yt=we.get(qe.biller)??[];yt.push(qe),we.set(qe.biller,yt)}return we},[le]),Fe=y.useMemo(()=>{const we=new Map;for(const qe of ie??[])we.set(qe.provider,(we.get(qe.provider)??0)+qe.costCents);return we},[ie]),Ee=y.useMemo(()=>{const we=new Map;for(const qe of ne??[])we.set(qe.biller,(we.get(qe.biller)??0)+qe.costCents);return we},[ne]),tt=y.useMemo(()=>{const we=new Map;for(const qe of X??[]){const yt=we.get(qe.provider)??[];yt.push(qe),we.set(qe.provider,yt)}return we},[X]),ot=y.useMemo(()=>{const we=new Map;for(const qe of ee??[])qe.ok&&qe.windows.length>0&&we.set(qe.provider,qe.windows);return we},[ee]),Ie=y.useMemo(()=>{const we=new Map;for(const qe of ee??[])!qe.ok&&qe.error&&we.set(qe.provider,qe.error);return we},[ee]),rt=y.useMemo(()=>{const we=new Map;for(const qe of ee??[])typeof qe.source=="string"&&qe.source.length>0&&we.set(qe.provider,qe.source);return we},[ee]),H=y.useMemo(()=>{const we=new Map;if(u!=="mtd")return we;const qe=(B==null?void 0:B.summary.budgetCents)??0;if(qe<=0)return we;const yt=(B==null?void 0:B.summary.spendCents)??0,Se=new Date,Ge=Se.getDate(),at=new Date(Se.getFullYear(),Se.getMonth()+1,0).getDate();for(const[Gt,ln]of ve){const Dn=ln.reduce((en,on)=>en+on.costCents,0),be=yt>0?Dn/yt:0,dt=qe*be;if(dt<=0){we.set(Gt,!1);continue}const nt=Dn/Math.max(Ge,1);we.set(Gt,Dn+nt*(at-Ge)>dt)}return we},[u,B,ve]),U=y.useMemo(()=>Array.from(ve.keys()),[ve]),me=y.useMemo(()=>Array.from(Te.keys()),[Te]),oe=i==="all"||U.includes(i)?i:"all";y.useEffect(()=>{oe!==i&&a("all")},[oe,i]);const pe=l==="all"||me.includes(l)?l:"all";y.useEffect(()=>{pe!==l&&c("all")},[pe,l]);const Ne=y.useMemo(()=>{const we=Array.from(ve.keys()),qe=we.reduce((Se,Ge)=>{var at;return Se+(((at=ve.get(Ge))==null?void 0:at.reduce((Gt,ln)=>Gt+ln.inputTokens+ln.cachedInputTokens+ln.outputTokens,0))??0)},0),yt=we.reduce((Se,Ge)=>{var at;return Se+(((at=ve.get(Ge))==null?void 0:at.reduce((Gt,ln)=>Gt+ln.costCents,0))??0)},0);return[{value:"all",label:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{children:"All providers"}),we.length>0?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Kn(qe)}),o.jsx("span",{className:"text-xs text-muted-foreground",children:tn(yt)})]}):null]})},...we.map(Se=>({value:Se,label:o.jsx(kit,{provider:Se,rows:ve.get(Se)??[]})}))]},[ve]),fe=y.useMemo(()=>{const we=Array.from(Te.keys()),qe=we.reduce((Se,Ge)=>{var at;return Se+(((at=Te.get(Ge))==null?void 0:at.reduce((Gt,ln)=>Gt+ln.inputTokens+ln.cachedInputTokens+ln.outputTokens,0))??0)},0),yt=we.reduce((Se,Ge)=>{var at;return Se+(((at=Te.get(Ge))==null?void 0:at.reduce((Gt,ln)=>Gt+ln.costCents,0))??0)},0);return[{value:"all",label:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{children:"All billers"}),we.length>0?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:Kn(qe)}),o.jsx("span",{className:"text-xs text-muted-foreground",children:tn(yt)})]}):null]})},...we.map(Se=>({value:Se,label:o.jsx(Cit,{biller:Se,rows:Te.get(Se)??[]})}))]},[Te]),ke=((B==null?void 0:B.byAgent)??[]).reduce((we,qe)=>we+qe.inputTokens+qe.cachedInputTokens+qe.outputTokens,0),ce=(q==null?void 0:q.events)??[],ye=(A==null?void 0:A.policies)??[],re=(A==null?void 0:A.activeIncidents)??[],Ye=y.useMemo(()=>({company:ye.filter(we=>we.scopeType==="company"),agent:ye.filter(we=>we.scopeType==="agent"),project:ye.filter(we=>we.scopeType==="project")}),[ye]);if(!t)return o.jsx(Ar,{icon:ru,message:"Select a company to view costs."});const gt=u==="custom"&&!j,Et=(Z||O)&&j,bn=Q??z;return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),o.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:xit.map(we=>o.jsx(ue,{variant:u===we?"secondary":"ghost",size:"sm",onClick:()=>f(we),children:git[we]},we))})]}),u==="custom"?o.jsxs("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[o.jsx("input",{type:"date",value:h,onChange:we=>p(we.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),o.jsx("input",{type:"date",value:g,onChange:we=>b(we.target.value),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,o.jsxs("div",{className:"grid gap-3 lg:grid-cols-4",children:[o.jsx(cl,{label:"Inference spend",value:tn((B==null?void 0:B.summary.spendCents)??0),subtitle:`${Kn(ke)} tokens across request-scoped events`,icon:ru}),o.jsx(cl,{label:"Budget",value:re.length>0?String(re.length):B!=null&&B.summary.budgetCents&&B.summary.budgetCents>0?`${B.summary.utilizationPercent}%`:"Open",subtitle:re.length>0?`${(A==null?void 0:A.pausedAgentCount)??0} agents paused · ${(A==null?void 0:A.pausedProjectCount)??0} projects paused`:B!=null&&B.summary.budgetCents&&B.summary.budgetCents>0?`${tn(B.summary.spendCents)} of ${tn(B.summary.budgetCents)}`:"No monthly cap configured",icon:F4}),o.jsx(cl,{label:"Finance net",value:tn((q==null?void 0:q.summary.netCents)??0),subtitle:`${tn((q==null?void 0:q.summary.debitCents)??0)} debits · ${tn((q==null?void 0:q.summary.creditCents)??0)} credits`,icon:U4}),o.jsx(cl,{label:"Finance events",value:String((q==null?void 0:q.summary.eventCount)??0),subtitle:`${tn((q==null?void 0:q.summary.estimatedDebitCents)??0)} estimated in range`,icon:wy})]})]}),o.jsxs(ha,{value:r,onValueChange:we=>s(we),children:[o.jsxs(tg,{variant:"line",className:"justify-start",children:[o.jsx(_s,{value:"overview",children:"Overview"}),o.jsx(_s,{value:"budgets",children:"Budgets"}),o.jsx(_s,{value:"providers",children:"Providers"}),o.jsx(_s,{value:"billers",children:"Billers"}),o.jsx(_s,{value:"finance",children:"Finance"})]}),o.jsx(Vr,{value:"overview",className:"mt-4 space-y-4",children:gt?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):Et?o.jsx(is,{variant:"costs"}):bn?o.jsx("p",{className:"text-sm text-destructive",children:bn.message}):o.jsxs(o.Fragment,{children:[re.length>0?o.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:re.slice(0,2).map(we=>o.jsx(HG,{incident:we,isMutating:P.isPending,onKeepPaused:()=>P.mutate({incidentId:we.id,action:"keep_paused"}),onRaiseAndResume:qe=>P.mutate({incidentId:we.id,action:"raise_budget_and_resume",amount:qe})},we.id))}):null,o.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.3fr,1fr]",children:[o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-5 pt-5 pb-2",children:[o.jsx(ui,{className:"text-base",children:"Inference ledger"}),o.jsx(ao,{children:"Request-scoped inference spend for the selected period."})]}),o.jsxs(bs,{className:"space-y-4 px-5 pb-5 pt-2",children:[o.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-3xl font-semibold tabular-nums",children:tn((B==null?void 0:B.summary.spendCents)??0)}),o.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:B!=null&&B.summary.budgetCents&&B.summary.budgetCents>0?`Budget ${tn(B.summary.budgetCents)}`:"Unlimited budget"})]}),o.jsxs("div",{className:"border border-border px-4 py-3 text-right",children:[o.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:"usage"}),o.jsx("div",{className:"mt-1 text-lg font-medium tabular-nums",children:Kn(ke)})]})]}),B!=null&&B.summary.budgetCents&&B.summary.budgetCents>0?o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"h-2 overflow-hidden bg-muted",children:o.jsx("div",{className:se("h-full transition-[width,background-color] duration-150",B.summary.utilizationPercent>90?"bg-red-400":B.summary.utilizationPercent>70?"bg-yellow-400":"bg-emerald-400"),style:{width:`${Math.min(100,B.summary.utilizationPercent)}%`}})}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[B.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),o.jsx(YG,{debitCents:(q==null?void 0:q.summary.debitCents)??0,creditCents:(q==null?void 0:q.summary.creditCents)??0,netCents:(q==null?void 0:q.summary.netCents)??0,estimatedDebitCents:(q==null?void 0:q.summary.estimatedDebitCents)??0,eventCount:(q==null?void 0:q.summary.eventCount)??0})]}),o.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.25fr,0.95fr]",children:[o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-5 pt-5 pb-2",children:[o.jsx(ui,{className:"text-base",children:"By agent"}),o.jsx(ao,{children:"What each agent consumed in the selected period."})]}),o.jsx(bs,{className:"space-y-2 px-5 pb-5 pt-2",children:((B==null?void 0:B.byAgent.length)??0)===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):B==null?void 0:B.byAgent.map(we=>{const qe=W.get(we.agentId)??[],yt=V.has(we.agentId),Se=qe.length>0;return o.jsxs("div",{className:"border border-border px-4 py-3",children:[o.jsxs("div",{className:se("flex items-start justify-between gap-3",Se?"cursor-pointer select-none":""),onClick:()=>Se&&G(we.agentId),children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Se?yt?o.jsx(ns,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):o.jsx($r,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):o.jsx("span",{className:"h-3 w-3 shrink-0"}),o.jsx(lr,{name:we.agentName??we.agentId,size:"sm"}),we.agentStatus==="terminated"?o.jsx(sr,{status:"terminated"}):null]}),o.jsxs("div",{className:"text-right text-sm tabular-nums",children:[o.jsx("div",{className:"font-medium",children:tn(we.costCents)}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:["in ",Kn(we.inputTokens+we.cachedInputTokens)," · out ",Kn(we.outputTokens)]}),we.apiRunCount>0||we.subscriptionRunCount>0?o.jsxs("div",{className:"text-xs text-muted-foreground",children:[we.apiRunCount>0?`${we.apiRunCount} api`:"0 api"," · ",we.subscriptionRunCount>0?`${we.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),yt&&qe.length>0?o.jsx("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:qe.map(Ge=>{const at=we.costCents>0?Math.round(Ge.costCents/we.costCents*100):0;return o.jsxs("div",{className:"flex items-start justify-between gap-3 text-xs",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"truncate font-medium text-foreground",children:[cc(Ge.provider),o.jsx("span",{className:"mx-1 text-border",children:"/"}),o.jsx("span",{className:"font-mono",children:Ge.model})]}),o.jsxs("div",{className:"truncate text-muted-foreground",children:[cc(Ge.biller)," · ",n6(Ge.billingType)]})]}),o.jsxs("div",{className:"text-right tabular-nums",children:[o.jsxs("div",{className:"font-medium",children:[tn(Ge.costCents),o.jsxs("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",at,"%)"]})]}),o.jsxs("div",{className:"text-muted-foreground",children:[Kn(Ge.inputTokens+Ge.cachedInputTokens+Ge.outputTokens)," tok"]})]})]},`${Ge.provider}:${Ge.model}:${Ge.billingType}`)})}):null]},we.agentId)})})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-5 pt-5 pb-2",children:[o.jsx(ui,{className:"text-base",children:"By project"}),o.jsx(ao,{children:"Run costs attributed through project-linked issues."})]}),o.jsx(bs,{className:"space-y-2 px-5 pb-5 pt-2",children:((B==null?void 0:B.byProject.length)??0)===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):B==null?void 0:B.byProject.map((we,qe)=>o.jsxs("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[o.jsx("span",{className:"truncate",children:we.projectName??we.projectId??"Unattributed"}),o.jsx("span",{className:"font-medium tabular-nums",children:tn(we.costCents)})]},we.projectId??`unattributed-${qe}`))})]}),o.jsx(qG,{rows:ce.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),o.jsx(Vr,{value:"budgets",className:"mt-4 space-y-4",children:M?o.jsx(is,{variant:"costs"}):I?o.jsx("p",{className:"text-sm text-destructive",children:I.message}):o.jsxs(o.Fragment,{children:[o.jsxs(ys,{className:"border-border/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))]",children:[o.jsxs(ci,{className:"px-5 pt-5 pb-3",children:[o.jsx(ui,{className:"text-base",children:"Budget control plane"}),o.jsx(ao,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),o.jsxs(bs,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[o.jsx(cl,{label:"Active incidents",value:String(re.length),subtitle:"Open soft or hard threshold crossings",icon:U4}),o.jsx(cl,{label:"Pending approvals",value:String((A==null?void 0:A.pendingApprovalCount)??0),subtitle:"Budget override approvals awaiting board action",icon:wy}),o.jsx(cl,{label:"Paused agents",value:String((A==null?void 0:A.pausedAgentCount)??0),subtitle:"Agent heartbeats blocked by budget",icon:F4}),o.jsx(cl,{label:"Paused projects",value:String((A==null?void 0:A.pausedProjectCount)??0),subtitle:"Project execution blocked by budget",icon:ru})]})]}),re.length>0?o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Active incidents"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),o.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:re.map(we=>o.jsx(HG,{incident:we,isMutating:P.isPending,onKeepPaused:()=>P.mutate({incidentId:we.id,action:"keep_paused"}),onRaiseAndResume:qe=>P.mutate({incidentId:we.id,action:"raise_budget_and_resume",amount:qe})},we.id))})]}):null,o.jsxs("div",{className:"space-y-5",children:[["company","agent","project"].map(we=>{const qe=Ye[we];return qe.length===0?null:o.jsxs("section",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-lg font-semibold capitalize",children:[we," budgets"]}),o.jsx("p",{className:"text-sm text-muted-foreground",children:we==="company"?"Company-wide monthly policy.":we==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),o.jsx("div",{className:"grid gap-4 xl:grid-cols-2",children:qe.map(yt=>o.jsx(K9,{summary:yt,isSaving:D.isPending,onSave:Se=>D.mutate({scopeType:yt.scopeType,scopeId:yt.scopeId,amount:Se,windowKind:yt.windowKind})},yt.policyId))})]},we)}),ye.length===0?o.jsx(ys,{children:o.jsx(bs,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),o.jsx(Vr,{value:"providers",className:"mt-4 space-y-4",children:gt?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):o.jsx(o.Fragment,{children:o.jsxs(ha,{value:oe,onValueChange:a,children:[o.jsx(Wh,{items:Ne,value:oe}),o.jsx(Vr,{value:"all",className:"mt-4",children:U.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):o.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:U.map(we=>o.jsx(GG,{provider:we,rows:ve.get(we)??[],budgetMonthlyCents:(B==null?void 0:B.summary.budgetCents)??0,totalCompanySpendCents:(B==null?void 0:B.summary.spendCents)??0,weekSpendCents:Fe.get(we)??0,windowRows:tt.get(we)??[],showDeficitNotch:H.get(we)??!1,quotaWindows:ot.get(we)??[],quotaError:Ie.get(we)??null,quotaSource:rt.get(we)??null,quotaLoading:de},we))})}),U.map(we=>o.jsx(Vr,{value:we,className:"mt-4",children:o.jsx(GG,{provider:we,rows:ve.get(we)??[],budgetMonthlyCents:(B==null?void 0:B.summary.budgetCents)??0,totalCompanySpendCents:(B==null?void 0:B.summary.spendCents)??0,weekSpendCents:Fe.get(we)??0,windowRows:tt.get(we)??[],showDeficitNotch:H.get(we)??!1,quotaWindows:ot.get(we)??[],quotaError:Ie.get(we)??null,quotaSource:rt.get(we)??null,quotaLoading:de})},we))]})})}),o.jsx(Vr,{value:"billers",className:"mt-4 space-y-4",children:gt?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):o.jsx(o.Fragment,{children:o.jsxs(ha,{value:pe,onValueChange:c,children:[o.jsx(Wh,{items:fe,value:pe}),o.jsx(Vr,{value:"all",className:"mt-4",children:me.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):o.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:me.map(we=>{const qe=(Te.get(we)??[])[0];if(!qe)return null;const yt=(F??[]).filter(Se=>Se.biller===we);return o.jsx(VG,{row:qe,weekSpendCents:Ee.get(we)??0,budgetMonthlyCents:(B==null?void 0:B.summary.budgetCents)??0,totalCompanySpendCents:(B==null?void 0:B.summary.spendCents)??0,providerRows:yt},we)})})}),me.map(we=>{const qe=(Te.get(we)??[])[0];if(!qe)return null;const yt=(F??[]).filter(Se=>Se.biller===we);return o.jsx(Vr,{value:we,className:"mt-4",children:o.jsx(VG,{row:qe,weekSpendCents:Ee.get(we)??0,budgetMonthlyCents:(B==null?void 0:B.summary.budgetCents)??0,totalCompanySpendCents:(B==null?void 0:B.summary.spendCents)??0,providerRows:yt})},we)})]})})}),o.jsx(Vr,{value:"finance",className:"mt-4 space-y-4",children:gt?o.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):O?o.jsx(is,{variant:"costs"}):z?o.jsx("p",{className:"text-sm text-destructive",children:z.message}):o.jsxs(o.Fragment,{children:[o.jsx(YG,{debitCents:(q==null?void 0:q.summary.debitCents)??0,creditCents:(q==null?void 0:q.summary.creditCents)??0,netCents:(q==null?void 0:q.summary.netCents)??0,estimatedDebitCents:(q==null?void 0:q.summary.estimatedDebitCents)??0,eventCount:(q==null?void 0:q.summary.eventCount)??0}),o.jsxs("div",{className:"grid gap-4 xl:grid-cols-[1.2fr,0.95fr]",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs(ys,{children:[o.jsxs(ci,{className:"px-5 pt-5 pb-2",children:[o.jsx(ui,{className:"text-base",children:"By biller"}),o.jsx(ao,{children:"Account-level financial events grouped by who charged or credited them."})]}),o.jsx(bs,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:((q==null?void 0:q.byBiller.length)??0)===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):q==null?void 0:q.byBiller.map(we=>o.jsx(sit,{row:we},we.biller))})]}),o.jsx(qG,{rows:ce})]}),o.jsx(iit,{rows:(q==null?void 0:q.byKind)??[]})]})]})})]})]})}function Nit(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),[n,r]=y.useState("all");y.useEffect(()=>{e([{label:"Activity"}])},[e]);const{data:s,isLoading:i,error:a}=_e({queryKey:J.activity(t),queryFn:()=>Ch.list(t),enabled:!!t}),{data:l}=_e({queryKey:J.agents.list(t),queryFn:()=>Mt.list(t),enabled:!!t}),{data:c}=_e({queryKey:J.issues.list(t),queryFn:()=>wn.list(t),enabled:!!t}),{data:u}=_e({queryKey:J.projects.list(t),queryFn:()=>vs.list(t),enabled:!!t}),{data:f}=_e({queryKey:J.goals.list(t),queryFn:()=>jl.list(t),enabled:!!t}),h=y.useMemo(()=>{const w=new Map;for(const j of l??[])w.set(j.id,j);return w},[l]),p=y.useMemo(()=>{const w=new Map;for(const j of c??[])w.set(`issue:${j.id}`,j.identifier??j.id.slice(0,8));for(const j of l??[])w.set(`agent:${j.id}`,j.name);for(const j of u??[])w.set(`project:${j.id}`,j.name);for(const j of f??[])w.set(`goal:${j.id}`,j.title);return w},[c,l,u,f]),g=y.useMemo(()=>{const w=new Map;for(const j of c??[])w.set(`issue:${j.id}`,j.title);return w},[c]);if(!t)return o.jsx(Ar,{icon:Hv,message:"Select a company to view activity."});if(i)return o.jsx(is,{variant:"list"});const b=s&&n!=="all"?s.filter(w=>w.entityType===n):s,v=s?[...new Set(s.map(w=>w.entityType))].sort():[];return o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"flex items-center justify-end",children:o.jsxs(Ni,{value:n,onValueChange:r,children:[o.jsx(_i,{className:"w-[140px] h-8 text-xs",children:o.jsx(Si,{placeholder:"Filter by type"})}),o.jsxs(Ei,{children:[o.jsx(nr,{value:"all",children:"All types"}),v.map(w=>o.jsx(nr,{value:w,children:w.charAt(0).toUpperCase()+w.slice(1)},w))]})]})}),a&&o.jsx("p",{className:"text-sm text-destructive",children:a.message}),b&&b.length===0&&o.jsx(Ar,{icon:Hv,message:"No activity yet."}),b&&b.length>0&&o.jsx("div",{className:"border border-border divide-y divide-border",children:b.map(w=>o.jsx(ufe,{event:w,agentMap:h,entityNameMap:p,entityTitleMap:g},w.id))})]})}const Sit=.4,_it=.92,Eit=210;function M2({children:t,onArchive:e,disabled:n=!1,className:r}){const s=y.useRef(null),i=y.useRef(null),a=y.useRef(0),l=y.useRef(null),[c,u]=y.useState(0),[f,h]=y.useState(!1),[p,g]=y.useState(!1),[b,v]=y.useState(null);y.useEffect(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]);const w=()=>{i.current=null,h(!1),u(0)},j=()=>{const _=s.current;if(!_){e();return}h(!1),v(_.offsetHeight),u(-Math.max(a.current,_.offsetWidth)),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{g(!0)})}),l.current=window.setTimeout(()=>{e()},Eit)},C=_=>{if(n||_.touches.length!==1)return;const A=_.touches[0],M=s.current;a.current=(M==null?void 0:M.offsetWidth)??0,v((M==null?void 0:M.offsetHeight)??null),g(!1),i.current={x:A.clientX,y:A.clientY}},N=_=>{if(n||p)return;const A=i.current;if(!A||_.touches.length!==1)return;const M=_.touches[0],I=M.clientX-A.x,L=M.clientY-A.y;if(!f){if(Math.abs(I)<6)return;if(Math.abs(L)>Math.abs(I)){i.current=null;return}}if(I>=0){_.preventDefault(),h(!0),u(0);return}const D=a.current>0?a.current*_it:Number.POSITIVE_INFINITY;_.preventDefault(),h(!0),u(Math.max(I,-D))},S=()=>{if(n||p)return;if(a.current>0&&Math.abs(c)>=a.current*Sit){j();return}w()},T=a.current>0?Math.min(Math.abs(c)/a.current,1):0;return o.jsxs("div",{ref:s,className:se("relative overflow-hidden touch-pan-y",r),style:{height:b===null?void 0:p?0:b,opacity:p?0:1,transition:p?"height 200ms ease, opacity 200ms ease":void 0},onTouchStart:C,onTouchMove:N,onTouchEnd:S,onTouchCancel:S,children:[o.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 flex items-center justify-end bg-emerald-600 px-4 text-white",style:{opacity:Math.max(T,.2)},children:o.jsxs("span",{className:"inline-flex items-center gap-2 text-sm font-medium",children:[o.jsx(ate,{className:"h-4 w-4"}),"Archive"]})}),o.jsx("div",{className:"relative bg-card will-change-transform",style:{transform:`translate3d(${c}px, 0, 0)`,transition:f?"none":"transform 180ms ease-out"},children:t})]})}const JG="backlog,todo,in_progress,in_review,blocked,done";function QG(t){return t?t.split(`
1090
1090
  `).map(n=>n.trim()).find(Boolean)??null:null}function Ait(t){return QG(t.error)??QG(t.stderrExcerpt)??"Run exited with an error."}function Tit(t){return t.replaceAll("_"," ")}function The(t){const e=t.contextSnapshot;if(!e)return null;const n=e.issueId;if(typeof n=="string"&&n.length>0)return n;const r=e.taskId;return typeof r=="string"&&r.length>0?r:null}function Mit({run:t,issueById:e,agentName:n,issueLinkState:r,onDismiss:s,onRetry:i,isRetrying:a,unreadState:l=null,onMarkRead:c,onArchive:u,archiveDisabled:f,className:h}){const p=The(t),g=p?e.get(p)??null:null,b=Ait(t),v=l!==null,w=l==="visible"||l==="fading";return o.jsxs("div",{className:se("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",h),children:[o.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[v?o.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:w?o.jsx("button",{type:"button",onClick:c,className:"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors hover:bg-blue-500/20","aria-label":"Mark as read",children:o.jsx("span",{className:se("block h-2 w-2 rounded-full bg-blue-600 transition-opacity duration-300 dark:bg-blue-400",l==="fading"?"opacity-0":"opacity-100")})}):u?o.jsx("button",{type:"button",onClick:u,disabled:f,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:o.jsx(ps,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,o.jsxs(jt,{to:`/agents/${t.agentId}/runs/${t.id}`,className:"flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors hover:bg-accent/50",children:[!v&&o.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-red-500/20 p-1.5 sm:mt-0",children:o.jsx(v_,{className:"h-4 w-4 text-red-600 dark:text-red-400"})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:g?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"font-mono text-muted-foreground mr-1.5",children:g.identifier??g.id.slice(0,8)}),g.title]}):o.jsxs(o.Fragment,{children:["Failed run",n?` — ${n}`:""]})}),o.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[o.jsx(sr,{status:t.status}),n&&g?o.jsx("span",{children:n}):null,o.jsx("span",{className:"truncate max-w-[300px]",children:b}),o.jsx("span",{children:ca(t.createdAt)})]})]})]}),o.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[o.jsxs(ue,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:i,disabled:a,children:[o.jsx(Ip,{className:"mr-1.5 h-3.5 w-3.5"}),a?"Retrying…":"Retry"]}),!v&&o.jsx("button",{type:"button",onClick:s,className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100","aria-label":"Dismiss",children:o.jsx(ps,{className:"h-4 w-4"})})]})]}),o.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[o.jsxs(ue,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:i,disabled:a,children:[o.jsx(Ip,{className:"mr-1.5 h-3.5 w-3.5"}),a?"Retrying…":"Retry"]}),!v&&o.jsx("button",{type:"button",onClick:s,className:"rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground","aria-label":"Dismiss",children:o.jsx(ps,{className:"h-4 w-4"})})]})]})}function Iit({approval:t,requesterName:e,onApprove:n,onReject:r,isPending:s,unreadState:i=null,onMarkRead:a,onArchive:l,archiveDisabled:c,className:u}){const f=Y9[t.type]??J9,h=G9(t.type,t.payload),p=t.type!=="budget_override_required"&&Zj.has(t.status),g=i!==null,b=i==="visible"||i==="fading";return o.jsxs("div",{className:se("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",u),children:[o.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[g?o.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:b?o.jsx("button",{type:"button",onClick:a,className:"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors hover:bg-blue-500/20","aria-label":"Mark as read",children:o.jsx("span",{className:se("block h-2 w-2 rounded-full bg-blue-600 transition-opacity duration-300 dark:bg-blue-400",i==="fading"?"opacity-0":"opacity-100")})}):l?o.jsx("button",{type:"button",onClick:l,disabled:c,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:o.jsx(ps,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,o.jsxs(jt,{to:`/approvals/${t.id}`,className:"flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors hover:bg-accent/50",children:[!g&&o.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:o.jsx(f,{className:"h-4 w-4 text-muted-foreground"})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:h}),o.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[o.jsx("span",{className:"capitalize",children:Tit(t.status)}),e?o.jsxs("span",{children:["requested by ",e]}):null,o.jsxs("span",{children:["updated ",ca(t.updatedAt)]})]})]})]}),p?o.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[o.jsx(ue,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:n,disabled:s,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:r,disabled:s,children:"Reject"})]}):null]}),p?o.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[o.jsx(ue,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:n,disabled:s,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:r,disabled:s,children:"Reject"})]}):null]})}function Rit({joinRequest:t,onApprove:e,onReject:n,isPending:r,unreadState:s=null,onMarkRead:i,onArchive:a,archiveDisabled:l,className:c}){const u=t.requestType==="human"?"Human join request":`Agent join request${t.agentName?`: ${t.agentName}`:""}`,f=s!==null,h=s==="visible"||s==="fading";return o.jsxs("div",{className:se("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",c),children:[o.jsxs("div",{className:"flex items-start gap-2 sm:items-center",children:[f?o.jsx("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:h?o.jsx("button",{type:"button",onClick:i,className:"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors hover:bg-blue-500/20","aria-label":"Mark as read",children:o.jsx("span",{className:se("block h-2 w-2 rounded-full bg-blue-600 transition-opacity duration-300 dark:bg-blue-400",s==="fading"?"opacity-0":"opacity-100")})}):a?o.jsx("button",{type:"button",onClick:a,disabled:l,className:"inline-flex h-4 w-4 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 disabled:pointer-events-none disabled:opacity-30","aria-label":"Dismiss from inbox",children:o.jsx(ps,{className:"h-3.5 w-3.5"})}):o.jsx("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,o.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-2",children:[!f&&o.jsx("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),o.jsx("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:o.jsx(yte,{className:"h-4 w-4 text-muted-foreground"})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:u}),o.jsxs("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[o.jsxs("span",{children:["requested ",ca(t.createdAt)," from IP ",t.requestIp]}),t.adapterType&&o.jsxs("span",{children:["adapter: ",t.adapterType]})]})]})]}),o.jsxs("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[o.jsx(ue,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:e,disabled:r,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:n,disabled:r,children:"Reject"})]})]}),o.jsxs("div",{className:"mt-3 flex gap-2 sm:hidden",children:[o.jsx(ue,{size:"sm",className:"h-8 bg-green-700 px-3 text-white hover:bg-green-600",onClick:e,disabled:r,children:"Approve"}),o.jsx(ue,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:n,disabled:r,children:"Reject"})]})]})}function I2(){const{selectedCompanyId:t}=Xt(),{setBreadcrumbs:e}=yr(),n=As(),r=er(),s=hn(),[i,a]=y.useState(null),[l,c]=y.useState("everything"),[u,f]=y.useState("all"),{dismissed:h,dismiss:p}=gne(),{readItems:g,markRead:b}=w3e(),v=r.pathname.split("/").pop()??"mine",w=v==="mine"||v==="recent"||v==="all"||v==="unread"?v:"mine",j=y.useMemo(()=>phe("Inbox",`${r.pathname}${r.search}${r.hash}`),[r.pathname,r.search,r.hash]),{data:C}=_e({queryKey:J.agents.list(t),queryFn:()=>Mt.list(t),enabled:!!t});y.useEffect(()=>{e([{label:"Inbox"}])},[e]),y.useEffect(()=>{p3e(w)},[w]);const{data:N,isLoading:S,error:T}=_e({queryKey:J.approvals.list(t),queryFn:()=>ko.list(t),enabled:!!t}),{data:_=[],isLoading:A}=_e({queryKey:J.access.joinRequests(t),queryFn:async()=>{try{return await Eo.listJoinRequests(t,"pending_approval")}catch(Oe){if(Oe instanceof Hd&&(Oe.status===403||Oe.status===401))return[];throw Oe}},enabled:!!t,retry:!1}),{data:M,isLoading:I}=_e({queryKey:J.dashboard(t),queryFn:()=>D6.summary(t),enabled:!!t}),{data:L,isLoading:D}=_e({queryKey:J.issues.list(t),queryFn:()=>wn.list(t),enabled:!!t}),{data:P=[],isLoading:B}=_e({queryKey:J.issues.listMineByMe(t),queryFn:()=>wn.list(t,{touchedByUserId:"me",inboxArchivedByUserId:"me",status:JG}),enabled:!!t}),{data:Z=[],isLoading:Q}=_e({queryKey:J.issues.listTouchedByMe(t),queryFn:()=>wn.list(t,{touchedByUserId:"me",status:JG}),enabled:!!t}),{data:q,isLoading:O}=_e({queryKey:J.heartbeats(t),queryFn:()=>qr.list(t),enabled:!!t}),z=y.useMemo(()=>X4(P),[P]),V=y.useMemo(()=>X4(Z),[Z]),$=y.useMemo(()=>V.filter(Oe=>Oe.isUnreadForMe),[V]),G=y.useMemo(()=>w==="mine"?z:w==="unread"?$:V,[w,z,V,$]),W=y.useMemo(()=>{const Oe=new Map;for(const bt of C??[])Oe.set(bt.id,bt.name);return Oe},[C]),F=y.useMemo(()=>{const Oe=new Map;for(const bt of L??[])Oe.set(bt.id,bt);return Oe},[L]),le=y.useMemo(()=>mne(q??[]).filter(Oe=>!h.has(`run:${Oe.id}`)),[q,h]),ie=y.useMemo(()=>{const Oe=new Set;for(const bt of q??[]){if(bt.status!=="running"&&bt.status!=="queued")continue;const wt=The(bt);wt&&Oe.add(wt)}return Oe},[q]),ne=y.useMemo(()=>{let Oe=g3e(N??[],w,u);return w==="mine"&&(Oe=Oe.filter(bt=>!h.has(`approval:${bt.id}`))),Oe},[N,w,u,h]),X=l==="everything"||l==="join_requests",ee=l==="everything"||l==="issues_i_touched",de=l==="everything"||l==="approvals",ve=l==="everything"||l==="failed_runs",Te=l==="everything"||l==="alerts",Fe=y.useMemo(()=>w==="all"&&!ve?[]:le,[le,w,ve]),Ee=y.useMemo(()=>w==="all"&&!X?[]:w==="mine"?_.filter(Oe=>!h.has(`join:${Oe.id}`)):_,[_,w,X,h]),tt=y.useMemo(()=>x3e({issues:w==="all"&&!ee?[]:G,approvals:w==="all"&&!de?[]:ne,failedRuns:Fe,joinRequests:Ee}),[ne,G,de,ee,w,Fe,Ee]),ot=Oe=>Oe?W.get(Oe)??null:null,Ie=Xe({mutationFn:Oe=>ko.approve(Oe),onSuccess:(Oe,bt)=>{a(null),s.invalidateQueries({queryKey:J.approvals.list(t)}),n(`/approvals/${bt}?resolved=approved`)},onError:Oe=>{a(Oe instanceof Error?Oe.message:"Failed to approve")}}),rt=Xe({mutationFn:Oe=>ko.reject(Oe),onSuccess:()=>{a(null),s.invalidateQueries({queryKey:J.approvals.list(t)})},onError:Oe=>{a(Oe instanceof Error?Oe.message:"Failed to reject")}}),H=Xe({mutationFn:Oe=>Eo.approveJoinRequest(t,Oe.id),onSuccess:()=>{a(null),s.invalidateQueries({queryKey:J.access.joinRequests(t)}),s.invalidateQueries({queryKey:J.sidebarBadges(t)}),s.invalidateQueries({queryKey:J.agents.list(t)}),s.invalidateQueries({queryKey:J.companies.all})},onError:Oe=>{a(Oe instanceof Error?Oe.message:"Failed to approve join request")}}),U=Xe({mutationFn:Oe=>Eo.rejectJoinRequest(t,Oe.id),onSuccess:()=>{a(null),s.invalidateQueries({queryKey:J.access.joinRequests(t)}),s.invalidateQueries({queryKey:J.sidebarBadges(t)})},onError:Oe=>{a(Oe instanceof Error?Oe.message:"Failed to reject join request")}}),[me,oe]=y.useState(new Set),pe=Xe({mutationFn:async Oe=>{const bt={},wt=Oe.contextSnapshot;wt&&(typeof wt.issueId=="string"&&wt.issueId&&(bt.issueId=wt.issueId),typeof wt.taskId=="string"&&wt.taskId&&(bt.taskId=wt.taskId),typeof wt.taskKey=="string"&&wt.taskKey&&(bt.taskKey=wt.taskKey));const En=await Mt.wakeup(Oe.agentId,{source:"on_demand",triggerDetail:"manual",reason:"retry_failed_run",payload:bt});if(!("id"in En))throw new Error("Retry was skipped because the agent is not currently invokable.");return{newRun:En,originalRun:Oe}},onMutate:Oe=>{oe(bt=>new Set(bt).add(Oe.id))},onSuccess:({newRun:Oe,originalRun:bt})=>{s.invalidateQueries({queryKey:J.heartbeats(bt.companyId)}),s.invalidateQueries({queryKey:J.heartbeats(bt.companyId,bt.agentId)}),n(`/agents/${bt.agentId}/runs/${Oe.id}`)},onSettled:(Oe,bt,wt)=>{wt&&oe(En=>{const tr=new Set(En);return tr.delete(wt.id),tr})}}),[Ne,fe]=y.useState(new Set),[ke,ce]=y.useState(new Set),[ye,re]=y.useState(new Set),[Ye,gt]=y.useState(new Set),Et=()=>{t&&(s.invalidateQueries({queryKey:J.issues.listMineByMe(t)}),s.invalidateQueries({queryKey:J.issues.listTouchedByMe(t)}),s.invalidateQueries({queryKey:J.issues.listUnreadTouchedByMe(t)}),s.invalidateQueries({queryKey:J.sidebarBadges(t)}))},bn=Xe({mutationFn:Oe=>wn.archiveFromInbox(Oe),onMutate:Oe=>{a(null),ce(bt=>new Set(bt).add(Oe))},onSuccess:()=>{Et()},onError:(Oe,bt)=>{a(Oe instanceof Error?Oe.message:"Failed to archive issue"),ce(wt=>{const En=new Set(wt);return En.delete(bt),En})},onSettled:(Oe,bt,wt)=>{bt||window.setTimeout(()=>{ce(En=>{const tr=new Set(En);return tr.delete(wt),tr})},500)}}),we=Xe({mutationFn:Oe=>wn.markRead(Oe),onMutate:Oe=>{fe(bt=>new Set(bt).add(Oe))},onSuccess:()=>{Et()},onSettled:(Oe,bt,wt)=>{setTimeout(()=>{fe(En=>{const tr=new Set(En);return tr.delete(wt),tr})},300)}}),qe=Xe({mutationFn:async Oe=>{await Promise.all(Oe.map(bt=>wn.markRead(bt)))},onMutate:Oe=>{fe(bt=>{const wt=new Set(bt);for(const En of Oe)wt.add(En);return wt})},onSuccess:()=>{Et()},onSettled:(Oe,bt,wt)=>{setTimeout(()=>{fe(En=>{const tr=new Set(En);for(const Ms of wt)tr.delete(Ms);return tr})},300)}}),yt=Oe=>{re(bt=>new Set(bt).add(Oe)),b(Oe),setTimeout(()=>{re(bt=>{const wt=new Set(bt);return wt.delete(Oe),wt})},300)},Se=Oe=>{gt(bt=>new Set(bt).add(Oe)),setTimeout(()=>{p(Oe),gt(bt=>{const wt=new Set(bt);return wt.delete(Oe),wt})},200)},Ge=Oe=>{if(w!=="mine")return null;const bt=g.has(Oe);return ye.has(Oe)?"fading":bt?"hidden":"visible"};if(!t)return o.jsx(Ar,{icon:Mp,message:"Select a company to view inbox."});const at=le.length>0,Gt=!!M&&M.agents.error>0&&!at&&!h.has("alert:agent-errors"),ln=!!M&&M.costs.monthBudgetCents>0&&M.costs.monthUtilizationPercent>=80&&!h.has("alert:budget"),Dn=Gt||ln,be=tt.length>0,dt=y3e({tab:w,hasItems:Dn,showOnMine:Dn,showOnRecent:Dn,showOnUnread:Dn,showOnAll:Te&&Dn}),nt=[dt?"alerts":null,be?"work_items":null].filter(Oe=>Oe!==null),en=!A&&!S&&!I&&!D&&!B&&!Q&&!O,on=Oe=>nt.indexOf(Oe)>0,ur=(w==="mine"?z:$).filter(Oe=>Oe.isUnreadForMe&&!Ne.has(Oe.id)&&!ke.has(Oe.id)).map(Oe=>Oe.id),dr=ur.length>0;return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(ha,{value:w,onValueChange:Oe=>n(`/inbox/${Oe}`),children:o.jsx(Wh,{items:[{value:"mine",label:"Mine"},{value:"recent",label:"Recent"},{value:"unread",label:"Unread"},{value:"all",label:"All"}]})}),dr&&o.jsx(ue,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0",onClick:()=>qe.mutate(ur),disabled:qe.isPending,children:qe.isPending?"Marking…":"Mark all as read"})]}),w==="all"&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:justify-end",children:[o.jsxs(Ni,{value:l,onValueChange:Oe=>c(Oe),children:[o.jsx(_i,{className:"h-8 w-[170px] text-xs",children:o.jsx(Si,{placeholder:"Category"})}),o.jsxs(Ei,{children:[o.jsx(nr,{value:"everything",children:"All categories"}),o.jsx(nr,{value:"issues_i_touched",children:"My recent issues"}),o.jsx(nr,{value:"join_requests",children:"Join requests"}),o.jsx(nr,{value:"approvals",children:"Approvals"}),o.jsx(nr,{value:"failed_runs",children:"Failed runs"}),o.jsx(nr,{value:"alerts",children:"Alerts"})]})]}),de&&o.jsxs(Ni,{value:u,onValueChange:Oe=>f(Oe),children:[o.jsx(_i,{className:"h-8 w-[170px] text-xs",children:o.jsx(Si,{placeholder:"Approval status"})}),o.jsxs(Ei,{children:[o.jsx(nr,{value:"all",children:"All approval statuses"}),o.jsx(nr,{value:"actionable",children:"Needs action"}),o.jsx(nr,{value:"resolved",children:"Resolved"})]})]})]})]}),T&&o.jsx("p",{className:"text-sm text-destructive",children:T.message}),i&&o.jsx("p",{className:"text-sm text-destructive",children:i}),!en&&nt.length===0&&o.jsx(is,{variant:"inbox"}),en&&nt.length===0&&o.jsx(Ar,{icon:Mp,message:w==="mine"?"Inbox zero.":w==="unread"?"No new inbox items.":w==="recent"?"No recent inbox items.":"No inbox items match these filters."}),be&&o.jsxs(o.Fragment,{children:[on("work_items")&&o.jsx(Ro,{}),o.jsx("div",{children:o.jsx("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:tt.map(Oe=>{const bt=w==="mine";if(Oe.kind==="approval"){const An=`approval:${Oe.approval.id}`,Ve=Ye.has(An),st=o.jsx(Iit,{approval:Oe.approval,requesterName:ot(Oe.approval.requestedByAgentId),onApprove:()=>Ie.mutate(Oe.approval.id),onReject:()=>rt.mutate(Oe.approval.id),isPending:Ie.isPending||rt.isPending,unreadState:Ge(An),onMarkRead:()=>yt(An),onArchive:bt?()=>Se(An):void 0,archiveDisabled:Ve,className:Ve?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},An);return bt?o.jsx(M2,{disabled:Ve,onArchive:()=>Se(An),children:st},An):st}if(Oe.kind==="failed_run"){const An=`run:${Oe.run.id}`,Ve=Ye.has(An),st=o.jsx(Mit,{run:Oe.run,issueById:F,agentName:ot(Oe.run.agentId),issueLinkState:j,onDismiss:()=>p(An),onRetry:()=>pe.mutate(Oe.run),isRetrying:me.has(Oe.run.id),unreadState:Ge(An),onMarkRead:()=>yt(An),onArchive:bt?()=>Se(An):void 0,archiveDisabled:Ve,className:Ve?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},An);return bt?o.jsx(M2,{disabled:Ve,onArchive:()=>Se(An),children:st},An):st}if(Oe.kind==="join_request"){const An=`join:${Oe.joinRequest.id}`,Ve=Ye.has(An),st=o.jsx(Rit,{joinRequest:Oe.joinRequest,onApprove:()=>H.mutate(Oe.joinRequest),onReject:()=>U.mutate(Oe.joinRequest),isPending:H.isPending||U.isPending,unreadState:Ge(An),onMarkRead:()=>yt(An),onArchive:bt?()=>Se(An):void 0,archiveDisabled:Ve,className:Ve?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},An);return bt?o.jsx(M2,{disabled:Ve,onArchive:()=>Se(An),children:st},An):st}const wt=Oe.issue,En=wt.isUnreadForMe&&!Ne.has(wt.id),tr=Ne.has(wt.id),Ms=ke.has(wt.id),os=o.jsx(fhe,{issue:wt,issueLinkState:j,className:Ms?"pointer-events-none -translate-x-4 scale-[0.98] opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out",desktopMetaLeading:o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden shrink-0 sm:inline-flex",children:o.jsx(Js,{status:wt.status})}),o.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:wt.identifier??wt.id.slice(0,8)}),ie.has(wt.id)&&o.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-blue-500/10 px-1.5 py-0.5 sm:gap-1.5 sm:px-2",children:[o.jsxs("span",{className:"relative flex h-2 w-2",children:[o.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-500"})]}),o.jsx("span",{className:"hidden text-[11px] font-medium text-blue-600 dark:text-blue-400 sm:inline",children:"Live"})]})]}),mobileMeta:wt.lastExternalCommentAt?`commented ${ca(wt.lastExternalCommentAt)}`:`updated ${ca(wt.updatedAt)}`,unreadState:En?"visible":tr?"fading":"hidden",onMarkRead:()=>we.mutate(wt.id),onArchive:bt?()=>bn.mutate(wt.id):void 0,archiveDisabled:Ms||bn.isPending,trailingMeta:wt.lastExternalCommentAt?`commented ${ca(wt.lastExternalCommentAt)}`:`updated ${ca(wt.updatedAt)}`},`issue:${wt.id}`);return bt?o.jsx(M2,{disabled:Ms||bn.isPending,onArchive:()=>bn.mutate(wt.id),children:os},`issue:${wt.id}`):os})})})]}),dt&&o.jsxs(o.Fragment,{children:[on("alerts")&&o.jsx(Ro,{}),o.jsxs("div",{children:[o.jsx("h3",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Alerts"}),o.jsxs("div",{className:"divide-y divide-border border border-border",children:[Gt&&o.jsxs("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[o.jsxs(jt,{to:"/agents",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[o.jsx(ec,{className:"h-4 w-4 shrink-0 text-red-600 dark:text-red-400"}),o.jsxs("span",{className:"text-sm",children:[o.jsx("span",{className:"font-medium",children:M.agents.error})," ",M.agents.error===1?"agent has":"agents have"," errors"]})]}),o.jsx("button",{type:"button",onClick:()=>p("alert:agent-errors"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:o.jsx(ps,{className:"h-3.5 w-3.5"})})]}),ln&&o.jsxs("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[o.jsxs(jt,{to:"/costs",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[o.jsx(ec,{className:"h-4 w-4 shrink-0 text-yellow-400"}),o.jsxs("span",{className:"text-sm",children:["Budget at"," ",o.jsxs("span",{className:"font-medium",children:[M.costs.monthUtilizationPercent,"%"]})," ","utilization this month"]})]}),o.jsx("button",{type:"button",onClick:()=>p("alert:budget"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:o.jsx(ps,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}function Oit(){const{companies:t,selectedCompany:e,selectedCompanyId:n,setSelectedCompanyId:r}=Xt(),{setBreadcrumbs:s}=yr(),{pushToast:i}=Bo(),a=hn(),[l,c]=y.useState(""),[u,f]=y.useState(""),[h,p]=y.useState(""),[g,b]=y.useState(""),[v,w]=y.useState(null);y.useEffect(()=>{e&&(c(e.name),f(e.description??""),p(e.brandColor??""),b(e.logoUrl??""))},[e]);const[j,C]=y.useState(null),[N,S]=y.useState(null),[T,_]=y.useState(!1),[A,M]=y.useState(0),I=!!e&&(l!==e.name||u!==(e.description??"")||h!==(e.brandColor??"")),L=Xe({mutationFn:$=>oo.update(n,$),onSuccess:()=>{a.invalidateQueries({queryKey:J.companies.all})}}),D=Xe({mutationFn:$=>oo.update(n,{requireBoardApprovalForNewAgents:$}),onSuccess:()=>{a.invalidateQueries({queryKey:J.companies.all})}}),P=Xe({mutationFn:()=>Eo.createOpenClawInvitePrompt(n),onSuccess:async $=>{var ie,ne,X;C(null);const G=window.location.origin.replace(/\/+$/,""),W=$.onboardingTextUrl??$.onboardingTextPath??`/api/invites/${$.token}/onboarding.txt`,F=W.startsWith("http")?W:`${G}${W}`;_(!1),M(0);let le;try{const ee=await Eo.getInviteOnboarding($.token);le=ZG({onboardingTextUrl:F,connectionCandidates:((ie=ee.onboarding.connectivity)==null?void 0:ie.connectionCandidates)??null,testResolutionUrl:((X=(ne=ee.onboarding.connectivity)==null?void 0:ne.testResolutionEndpoint)==null?void 0:X.url)??null})}catch{le=ZG({onboardingTextUrl:F,connectionCandidates:null,testResolutionUrl:null})}S(le);try{await navigator.clipboard.writeText(le),_(!0),M(ee=>ee+1),setTimeout(()=>_(!1),2e3)}catch{}a.invalidateQueries({queryKey:J.sidebarBadges(n)})},onError:$=>{C($ instanceof Error?$.message:"Failed to create invite")}}),B=$=>{b($??""),a.invalidateQueries({queryKey:J.companies.all})},Z=Xe({mutationFn:$=>sm.uploadCompanyLogo(n,$).then(G=>oo.update(n,{logoAssetId:G.assetId})),onSuccess:$=>{B($.logoUrl),w(null)}}),Q=Xe({mutationFn:()=>oo.update(n,{logoAssetId:null}),onSuccess:$=>{w(null),B($.logoUrl)}});function q($){var W;const G=((W=$.target.files)==null?void 0:W[0])??null;$.currentTarget.value="",G&&(w(null),Z.mutate(G))}function O(){Q.mutate()}y.useEffect(()=>{C(null),S(null),_(!1),M(0)},[n]);const z=Xe({mutationFn:({companyId:$,nextCompanyId:G})=>oo.archive($).then(()=>({nextCompanyId:G})),onSuccess:async({nextCompanyId:$})=>{$&&r($),await a.invalidateQueries({queryKey:J.companies.all}),await a.invalidateQueries({queryKey:J.companies.stats})}});if(y.useEffect(()=>{s([{label:(e==null?void 0:e.name)??"Company",href:"/dashboard"},{label:"Settings"}])},[s,e==null?void 0:e.name]),!e)return o.jsx("div",{className:"text-sm text-muted-foreground",children:"No company selected. Select a company from the switcher above."});function V(){L.mutate({name:l.trim(),description:u.trim()||null,brandColor:h||null})}return o.jsxs("div",{className:"max-w-2xl space-y-6",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Id,{className:"h-5 w-5 text-muted-foreground"}),o.jsx("h1",{className:"text-lg font-semibold",children:"Company Settings"})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"General"}),o.jsxs("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:[o.jsx(un,{label:"Company name",hint:"The display name for your company.",children:o.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:l,onChange:$=>c($.target.value)})}),o.jsx(un,{label:"Description",hint:"Optional description shown in the company profile.",children:o.jsx("input",{className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none",type:"text",value:u,placeholder:"Optional company description",onChange:$=>f($.target.value)})})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Appearance"}),o.jsx("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("div",{className:"shrink-0",children:o.jsx(Jte,{companyName:l||e.name,logoUrl:g||null,brandColor:h||null,className:"rounded-[14px]"})}),o.jsxs("div",{className:"flex-1 space-y-3",children:[o.jsx(un,{label:"Logo",hint:"Upload a PNG, JPEG, WEBP, GIF, or SVG logo image.",children:o.jsxs("div",{className:"space-y-2",children:[o.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp,image/gif,image/svg+xml",onChange:q,className:"w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none file:mr-4 file:rounded-md file:border-0 file:bg-muted file:px-2.5 file:py-1 file:text-xs"}),g&&o.jsx("div",{className:"flex items-center gap-2",children:o.jsx(ue,{size:"sm",variant:"outline",onClick:O,disabled:Q.isPending,children:Q.isPending?"Removing...":"Remove logo"})}),(Z.isError||v)&&o.jsx("span",{className:"text-xs text-destructive",children:v??(Z.error instanceof Error?Z.error.message:"Logo upload failed")}),Q.isError&&o.jsx("span",{className:"text-xs text-destructive",children:Q.error.message}),Z.isPending&&o.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploading logo..."})]})}),o.jsx(un,{label:"Brand color",hint:"Sets the hue for the company icon. Leave empty for auto-generated color.",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",value:h||"#6366f1",onChange:$=>p($.target.value),className:"h-8 w-8 cursor-pointer rounded border border-border bg-transparent p-0"}),o.jsx("input",{type:"text",value:h,onChange:$=>{const G=$.target.value;(G===""||/^#[0-9a-fA-F]{0,6}$/.test(G))&&p(G)},placeholder:"Auto",className:"w-28 rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm font-mono outline-none"}),h&&o.jsx(ue,{size:"sm",variant:"ghost",onClick:()=>p(""),className:"text-xs text-muted-foreground",children:"Clear"})]})})]})]})})]}),I&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ue,{size:"sm",onClick:V,disabled:L.isPending||!l.trim(),children:L.isPending?"Saving...":"Save changes"}),L.isSuccess&&o.jsx("span",{className:"text-xs text-muted-foreground",children:"Saved"}),L.isError&&o.jsx("span",{className:"text-xs text-destructive",children:L.error instanceof Error?L.error.message:"Failed to save"})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Hiring"}),o.jsx("div",{className:"rounded-md border border-border px-4 py-3",children:o.jsx(Qp,{label:"Require board approval for new hires",hint:"New agent hires stay pending until approved by board.",checked:!!e.requireBoardApprovalForNewAgents,onChange:$=>D.mutate($)})})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Invites"}),o.jsxs("div",{className:"space-y-3 rounded-md border border-border px-4 py-4",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"Generate an OpenClaw agent invite snippet."}),o.jsx(L1,{text:"Creates a short-lived OpenClaw agent invite and renders a copy-ready prompt."})]}),o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:o.jsx(ue,{size:"sm",onClick:()=>P.mutate(),disabled:P.isPending,children:P.isPending?"Generating...":"Generate OpenClaw Invite Prompt"})}),j&&o.jsx("p",{className:"text-sm text-destructive",children:j}),N&&o.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"OpenClaw Invite Prompt"}),T&&o.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-600 animate-pulse",children:[o.jsx($s,{className:"h-3 w-3"}),"Copied"]},A)]}),o.jsxs("div",{className:"mt-1 space-y-1.5",children:[o.jsx("textarea",{className:"h-[28rem] w-full rounded-md border border-border bg-background px-2 py-1.5 font-mono text-xs outline-none",value:N,readOnly:!0}),o.jsx("div",{className:"flex justify-end",children:o.jsx(ue,{size:"sm",variant:"ghost",onClick:async()=>{try{await navigator.clipboard.writeText(N),_(!0),M($=>$+1),setTimeout(()=>_(!1),2e3)}catch{}},children:T?"Copied snippet":"Copy snippet"})})]})]})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Company Packages"}),o.jsxs("div",{className:"rounded-md border border-border px-4 py-4",children:[o.jsxs("p",{className:"text-sm text-muted-foreground",children:["Import and export have moved to dedicated pages accessible from the"," ",o.jsx("a",{href:"/org",className:"underline hover:text-foreground",children:"Org Chart"})," header."]}),o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsx(ue,{size:"sm",variant:"outline",asChild:!0,children:o.jsxs("a",{href:"/company/export",children:[o.jsx(Cy,{className:"mr-1.5 h-3.5 w-3.5"}),"Export"]})}),o.jsx(ue,{size:"sm",variant:"outline",asChild:!0,children:o.jsxs("a",{href:"/company/import",children:[o.jsx(Yv,{className:"mr-1.5 h-3.5 w-3.5"}),"Import"]})})]})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsx("div",{className:"text-xs font-medium text-destructive uppercase tracking-wide",children:"Danger Zone"}),o.jsxs("div",{className:"space-y-3 rounded-md border border-destructive/40 bg-destructive/5 px-4 py-4",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"Archive this company to hide it from the sidebar. This persists in the database."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ue,{size:"sm",variant:"destructive",disabled:z.isPending||e.status==="archived",onClick:()=>{var W;if(!n||!window.confirm(`Archive company "${e.name}"? It will be hidden from the sidebar.`))return;const G=((W=t.find(F=>F.id!==n&&F.status!=="archived"))==null?void 0:W.id)??null;z.mutate({companyId:n,nextCompanyId:G})},children:z.isPending?"Archiving...":e.status==="archived"?"Already archived":"Archive company"}),z.isError&&o.jsx("span",{className:"text-xs text-destructive",children:z.error instanceof Error?z.error.message:"Failed to archive company"})]})]})]})]})}function ZG(t){const e=Dit(t),n=Pit(t),r=e.length>0?e.map(a=>`- ${a}`).join(`